You are here

protected function IsbnValidator::validateIsbn10 in Plug 7

1 call to IsbnValidator::validateIsbn10()
IsbnValidator::validate in lib/Symfony/validator/Symfony/Component/Validator/Constraints/IsbnValidator.php
Checks if the passed value is valid.

File

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

Class

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

Namespace

Symfony\Component\Validator\Constraints

Code

protected function validateIsbn10($isbn) {

  // Choose an algorithm so that ERROR_INVALID_CHARACTERS is preferred
  // over ERROR_TOO_SHORT/ERROR_TOO_LONG
  // Otherwise "0-45122-5244" passes, but "0-45122_5244" reports
  // "too long"
  // Error priority:
  // 1. ERROR_INVALID_CHARACTERS
  // 2. ERROR_TOO_SHORT/ERROR_TOO_LONG
  // 3. ERROR_CHECKSUM_FAILED
  $checkSum = 0;
  for ($i = 0; $i < 10; ++$i) {

    // If we test the length before the loop, we get an ERROR_TOO_SHORT
    // when actually an ERROR_INVALID_CHARACTERS is wanted, e.g. for
    // "0-45122_5244" (typo)
    if (!isset($isbn[$i])) {
      return Isbn::TOO_SHORT_ERROR;
    }
    if ('X' === $isbn[$i]) {
      $digit = 10;
    }
    elseif (ctype_digit($isbn[$i])) {
      $digit = $isbn[$i];
    }
    else {
      return Isbn::INVALID_CHARACTERS_ERROR;
    }
    $checkSum += $digit * (10 - $i);
  }
  if (isset($isbn[$i])) {
    return Isbn::TOO_LONG_ERROR;
  }
  return 0 === $checkSum % 11 ? true : Isbn::CHECKSUM_FAILED_ERROR;
}