Skip to content

Instantly share code, notes, and snippets.

@simoncoulton
Last active December 11, 2015 09:59
Show Gist options
  • Save simoncoulton/4583948 to your computer and use it in GitHub Desktop.
Save simoncoulton/4583948 to your computer and use it in GitHub Desktop.
use Zend\Filter\Digits as DigitsFilter;
use Zend\Validator\AbstractValidator;
class Abn extends AbstractValidator
{
const INVALID = 'invalidAbn';
const DIGITS = 'digitsOnly';
const INCORRECT_LENGTH = 'lengthMismatch';
protected static $digitsFilter = null;
protected $messageTemplates = [
self::INVALID => 'Invalid ABN number',
self::INCORRECT_LENGTH => 'ABN must be 11 characters long',
self::DIGITS => 'ABN must only contain digits',
];
protected $weights = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
public function isValid($value)
{
if (null === static::$digitsFilter) {
static::$digitsFilter = new DigitsFilter();
}
$value = preg_replace('/\s/', '', (string) $value);
$this->setValue($value);
if ($this->getValue() !== static::$digitsFilter->filter($this->getValue())) {
$this->error(self::DIGITS);
return false;
}
if (strlen($this->getValue()) < 11) {
$this->error(self::INCORRECT_LENGTH);
return false;
}
$newNumber = 0;
for ($i = 0; $i < strlen($value); $i++) {
$number = (int)$value[$i];
if ($i === 0) {
$number--;
}
$newNumber += $number * $this->weights[$i];
}
if (is_int($newNumber/89)) {
return true;
}
$this->error(self::INVALID);
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment