4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator\Constraints;
14 use Symfony\Component\Validator\Constraint;
15 use Symfony\Component\Validator\ConstraintValidator;
16 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
19 * Validates whether the value is a valid ISSN.
21 * @author Antonio J. GarcĂa Lagar <aj@garcialagar.es>
22 * @author Bernhard Schussek <bschussek@gmail.com>
24 * @see https://en.wikipedia.org/wiki/Issn
26 class IssnValidator extends ConstraintValidator
31 public function validate($value, Constraint $constraint)
33 if (!$constraint instanceof Issn) {
34 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Issn');
37 if (null === $value || '' === $value) {
41 if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
42 throw new UnexpectedTypeException($value, 'string');
45 $value = (string) $value;
50 if (isset($canonical[4]) && '-' === $canonical[4]) {
52 $canonical = substr($canonical, 0, 4).substr($canonical, 5);
53 } elseif ($constraint->requireHyphen) {
54 $this->context->buildViolation($constraint->message)
55 ->setParameter('{{ value }}', $this->formatValue($value))
56 ->setCode(Issn::MISSING_HYPHEN_ERROR)
62 $length = strlen($canonical);
65 $this->context->buildViolation($constraint->message)
66 ->setParameter('{{ value }}', $this->formatValue($value))
67 ->setCode(Issn::TOO_SHORT_ERROR)
74 $this->context->buildViolation($constraint->message)
75 ->setParameter('{{ value }}', $this->formatValue($value))
76 ->setCode(Issn::TOO_LONG_ERROR)
83 // ^^^^^^^ digits only
84 if (!ctype_digit(substr($canonical, 0, 7))) {
85 $this->context->buildViolation($constraint->message)
86 ->setParameter('{{ value }}', $this->formatValue($value))
87 ->setCode(Issn::INVALID_CHARACTERS_ERROR)
95 if (!ctype_digit($canonical[7]) && 'x' !== $canonical[7] && 'X' !== $canonical[7]) {
96 $this->context->buildViolation($constraint->message)
97 ->setParameter('{{ value }}', $this->formatValue($value))
98 ->setCode(Issn::INVALID_CHARACTERS_ERROR)
106 if ($constraint->caseSensitive && 'x' === $canonical[7]) {
107 $this->context->buildViolation($constraint->message)
108 ->setParameter('{{ value }}', $this->formatValue($value))
109 ->setCode(Issn::INVALID_CASE_ERROR)
115 // Calculate a checksum. "X" equals 10.
116 $checkSum = 'X' === $canonical[7]
117 || 'x' === $canonical[7]
121 for ($i = 0; $i < 7; ++$i) {
122 // Multiply the first digit by 8, the second by 7, etc.
123 $checkSum += (8 - $i) * $canonical[$i];
126 if (0 !== $checkSum % 11) {
127 $this->context->buildViolation($constraint->message)
128 ->setParameter('{{ value }}', $this->formatValue($value))
129 ->setCode(Issn::CHECKSUM_FAILED_ERROR)