You are here

public function IsbnValidator::validate in Plug 7

Checks if the passed value is valid.

@api

Parameters

mixed $value The value that should be validated:

Constraint $constraint The constraint for the validation:

Overrides ConstraintValidatorInterface::validate

File

lib/Symfony/validator/Symfony/Component/Validator/Constraints/IsbnValidator.php, line 32

Class

IsbnValidator
Validates whether the value is a valid ISBN-10 or ISBN-13

Namespace

Symfony\Component\Validator\Constraints

Code

public function validate($value, Constraint $constraint) {
  if (!$constraint instanceof Isbn) {
    throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\Isbn');
  }
  if (null === $value || '' === $value) {
    return;
  }
  if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
    throw new UnexpectedTypeException($value, 'string');
  }
  $value = (string) $value;
  $canonical = str_replace('-', '', $value);
  if (null === $constraint->type) {
    if ($constraint->isbn10 && !$constraint->isbn13) {
      $constraint->type = 'isbn10';
    }
    elseif ($constraint->isbn13 && !$constraint->isbn10) {
      $constraint->type = 'isbn13';
    }
  }

  // Explicitly validate against ISBN-10
  if ('isbn10' === $constraint->type) {
    if (true !== ($code = $this
      ->validateIsbn10($canonical))) {
      $this
        ->buildViolation($this
        ->getMessage($constraint, $constraint->type))
        ->setParameter('{{ value }}', $this
        ->formatValue($value))
        ->setCode($code)
        ->addViolation();
    }
    return;
  }

  // Explicitly validate against ISBN-13
  if ('isbn13' === $constraint->type) {
    if (true !== ($code = $this
      ->validateIsbn13($canonical))) {
      $this
        ->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
      ->buildViolation($this
      ->getMessage($constraint))
      ->setParameter('{{ value }}', $this
      ->formatValue($value))
      ->setCode($code)
      ->addViolation();
  }
}