Last active
December 11, 2015 09:59
-
-
Save simoncoulton/4583948 to your computer and use it in GitHub Desktop.
Zend Framework 2 Validator for ABN's http://www.ato.gov.au/businesses/content.aspx?doc=/content/13187.htm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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