IbanValidator.php in Plug 7
File
lib/Symfony/validator/Symfony/Component/Validator/Constraints/IbanValidator.php
View source
<?php
namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class IbanValidator extends ConstraintValidator {
public function validate($value, Constraint $constraint) {
if (!$constraint instanceof Iban) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\\Iban');
}
if (null === $value || '' === $value) {
return;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
throw new UnexpectedTypeException($value, 'string');
}
$value = (string) $value;
$canonicalized = str_replace(' ', '', $value);
if (strlen($canonicalized) < 4) {
$this
->buildViolation($constraint->message)
->setParameter('{{ value }}', $this
->formatValue($value))
->setCode(Iban::TOO_SHORT_ERROR)
->addViolation();
return;
}
if (!ctype_alpha($canonicalized[0]) || !ctype_alpha($canonicalized[1])) {
$this
->buildViolation($constraint->message)
->setParameter('{{ value }}', $this
->formatValue($value))
->setCode(Iban::INVALID_COUNTRY_CODE_ERROR)
->addViolation();
return;
}
if (!ctype_alnum($canonicalized)) {
$this
->buildViolation($constraint->message)
->setParameter('{{ value }}', $this
->formatValue($value))
->setCode(Iban::INVALID_CHARACTERS_ERROR)
->addViolation();
return;
}
if ($canonicalized !== strtoupper($canonicalized)) {
$this
->buildViolation($constraint->message)
->setParameter('{{ value }}', $this
->formatValue($value))
->setCode(Iban::INVALID_CASE_ERROR)
->addViolation();
return;
}
$canonicalized = substr($canonicalized, 4) . substr($canonicalized, 0, 4);
$checkSum = $this
->toBigInt($canonicalized);
if (1 !== $this
->bigModulo97($checkSum)) {
$this
->buildViolation($constraint->message)
->setParameter('{{ value }}', $this
->formatValue($value))
->setCode(Iban::CHECKSUM_FAILED_ERROR)
->addViolation();
}
}
private function toBigInt($string) {
$chars = str_split($string);
$bigInt = '';
foreach ($chars as $char) {
if (ctype_upper($char)) {
$bigInt .= ord($char) - 55;
continue;
}
$bigInt .= $char;
}
return $bigInt;
}
private function bigModulo97($bigInt) {
$parts = str_split($bigInt, 7);
$rest = 0;
foreach ($parts as $part) {
$rest = ($rest . $part) % 97;
}
return $rest;
}
}