diff --git a/src/Entity/QRCode/QRCodeMoney.php b/src/Entity/QRCode/QRCodeMoney.php index 3485300..b822f07 100644 --- a/src/Entity/QRCode/QRCodeMoney.php +++ b/src/Entity/QRCode/QRCodeMoney.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace App\Entity\QRCode; use App\Validator\Currency; +use App\Validator\Money; use Symfony\Component\Validator\Constraints as Assert; /** @@ -15,6 +16,7 @@ class QRCodeMoney message: 'messages.not_valid_amount', )] #[Assert\NotBlank(message: 'messages.fill_value')] + #[Money(message: 'messages.not_valid_amount')] private ?string $amount; // TODO: getCurrencies validation diff --git a/src/Validator/Money.php b/src/Validator/Money.php new file mode 100644 index 0000000..b214978 --- /dev/null +++ b/src/Validator/Money.php @@ -0,0 +1,31 @@ + 'NOT_CURRENCY_ERROR', + ]; + + public string $message = 'This value should be currency.'; + + /** + * @param mixed|null $options + * @param string|null $message + * @param array|null $groups + * @param mixed|null $payload + */ + public function __construct(mixed $options = null, string $message = null, array $groups = null, mixed $payload = null) + { + parent::__construct($options ?? [], $groups, $payload); + + $this->message = $message ?? $this->message; + } +} diff --git a/src/Validator/MoneyValidator.php b/src/Validator/MoneyValidator.php new file mode 100644 index 0000000..1a18c04 --- /dev/null +++ b/src/Validator/MoneyValidator.php @@ -0,0 +1,34 @@ +context->buildViolation($constraint->message) + ->setParameter('{{ string }}', $value) + ->addViolation(); + } +} diff --git a/tests/Validator/MoneyValidatorTest.php b/tests/Validator/MoneyValidatorTest.php new file mode 100644 index 0000000..a234620 --- /dev/null +++ b/tests/Validator/MoneyValidatorTest.php @@ -0,0 +1,40 @@ +initialize($this->createExecutionContext(false)); + $moneyValidator->validate($generatedValue, new Money(['message' => 'foo'])); + } + + private function successDp(): array { + return [['122'], ['122.0'], ['122,00'], ['122'], ['2.05'], ['2,04']]; + } + + /** + * @dataProvider failureDp + * @param string $generatedValue + * @return void + */ + public function testFailure(string $generatedValue): void { + $moneyValidator = new MoneyValidator(); + $moneyValidator->initialize($this->createExecutionContext(true)); + $moneyValidator->validate($generatedValue, new Money(['message' => 'foo'])); + } + + private function failureDp(): array { + return [['122.b'], ['a.a'], ['a'], ['2.040'], ['2,a']]; + } +}