BicValidator.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Validator\Constraints;
  11. use Symfony\Component\Validator\Constraint;
  12. use Symfony\Component\Validator\ConstraintValidator;
  13. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  14. /**
  15. * @author Michael Hirschler <michael.vhirsch@gmail.com>
  16. *
  17. * @see https://en.wikipedia.org/wiki/ISO_9362#Structure
  18. */
  19. class BicValidator extends ConstraintValidator
  20. {
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function validate($value, Constraint $constraint)
  25. {
  26. if (!$constraint instanceof Bic) {
  27. throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Bic');
  28. }
  29. if (null === $value || '' === $value) {
  30. return;
  31. }
  32. $canonicalize = str_replace(' ', '', $value);
  33. // the bic must be either 8 or 11 characters long
  34. if (!\in_array(\strlen($canonicalize), array(8, 11))) {
  35. $this->context->buildViolation($constraint->message)
  36. ->setParameter('{{ value }}', $this->formatValue($value))
  37. ->setCode(Bic::INVALID_LENGTH_ERROR)
  38. ->addViolation();
  39. return;
  40. }
  41. // must contain alphanumeric values only
  42. if (!ctype_alnum($canonicalize)) {
  43. $this->context->buildViolation($constraint->message)
  44. ->setParameter('{{ value }}', $this->formatValue($value))
  45. ->setCode(Bic::INVALID_CHARACTERS_ERROR)
  46. ->addViolation();
  47. return;
  48. }
  49. // first 4 letters must be alphabetic (bank code)
  50. if (!ctype_alpha(substr($canonicalize, 0, 4))) {
  51. $this->context->buildViolation($constraint->message)
  52. ->setParameter('{{ value }}', $this->formatValue($value))
  53. ->setCode(Bic::INVALID_BANK_CODE_ERROR)
  54. ->addViolation();
  55. return;
  56. }
  57. // next 2 letters must be alphabetic (country code)
  58. if (!ctype_alpha(substr($canonicalize, 4, 2))) {
  59. $this->context->buildViolation($constraint->message)
  60. ->setParameter('{{ value }}', $this->formatValue($value))
  61. ->setCode(Bic::INVALID_COUNTRY_CODE_ERROR)
  62. ->addViolation();
  63. return;
  64. }
  65. // should contain uppercase characters only
  66. if (strtoupper($canonicalize) !== $canonicalize) {
  67. $this->context->buildViolation($constraint->message)
  68. ->setParameter('{{ value }}', $this->formatValue($value))
  69. ->setCode(Bic::INVALID_CASE_ERROR)
  70. ->addViolation();
  71. return;
  72. }
  73. }
  74. }