function IsbnValidator::validate
Overrides ConstraintValidatorInterface::validate
File
-
vendor/
symfony/ validator/ Constraints/ IsbnValidator.php, line 30
Class
- IsbnValidator
- Validates whether the value is a valid ISBN-10 or ISBN-13.
Namespace
Symfony\Component\Validator\ConstraintsCode
public function validate(mixed $value, Constraint $constraint) : void {
if (!$constraint instanceof Isbn) {
throw new UnexpectedTypeException($constraint, Isbn::class);
}
if (null === $value || '' === $value) {
return;
}
if (!\is_scalar($value) && !$value instanceof \Stringable) {
throw new UnexpectedValueException($value, 'string');
}
$value = (string) $value;
$canonical = str_replace('-', '', $value);
// Explicitly validate against ISBN-10
if (Isbn::ISBN_10 === $constraint->type) {
if (true !== ($code = $this->validateIsbn10($canonical))) {
$this->context
->buildViolation($this->getMessage($constraint, $constraint->type))
->setParameter('{{ value }}', $this->formatValue($value))
->setCode($code)
->addViolation();
}
return;
}
// Explicitly validate against ISBN-13
if (Isbn::ISBN_13 === $constraint->type) {
if (true !== ($code = $this->validateIsbn13($canonical))) {
$this->context
->buildViolation($this->getMessage($constraint, $constraint->type))
->setParameter('{{ value }}', $this->formatValue($value))
->setCode($code)
->addViolation();
}
return;
}
// Try both ISBNs
// First, try ISBN-10
$code = $this->validateIsbn10($canonical);
// The ISBN can only be an ISBN-13 if the value was too long for ISBN-10
if (Isbn::TOO_LONG_ERROR === $code) {
// Try ISBN-13 now
$code = $this->validateIsbn13($canonical);
// If too short, this means we have 11 or 12 digits
if (Isbn::TOO_SHORT_ERROR === $code) {
$code = Isbn::TYPE_NOT_RECOGNIZED_ERROR;
}
}
if (true !== $code) {
$this->context
->buildViolation($this->getMessage($constraint))
->setParameter('{{ value }}', $this->formatValue($value))
->setCode($code)
->addViolation();
}
}