Created
July 29, 2014 07:33
-
-
Save skrajewski/37108efd4e5f8ca41a09 to your computer and use it in GitHub Desktop.
Class EAN13
This file contains 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
class EAN13 { | |
protected $code; | |
public function __construct($code) | |
{ | |
if (preg_match("/^[0-9]{12}$/", $code)) | |
{ | |
$this->code = $code . $this->calculateChecksumNumber($code); | |
} | |
elseif(preg_match("/^[0-9]{13}$/", $code)) | |
{ | |
if($this->calculateChecksumNumber(substr($code, 0, -1)) != $code[12]) | |
{ | |
throw new \InvalidArgumentException("Invalid EAN code."); | |
} | |
$this->code = $code; | |
} | |
else | |
{ | |
throw new \InvalidArgumentException("Parameter must be 12 or 13 digits."); | |
} | |
} | |
public function toString() | |
{ | |
return $this->code; | |
} | |
protected function calculateChecksumNumber($code) | |
{ | |
$even_sum = $code{1} + $code{3} + $code{5} + $code{7} + $code{9} + $code{11}; | |
$odd_sum = $code{0} + $code{2} + $code{4} + $code{6} + $code{8} + $code{10}; | |
$even_sum_three = $even_sum * 3; | |
$total_sum = $even_sum_three + $odd_sum; | |
$next_ten = (ceil($total_sum/10))*10; | |
return $next_ten - $total_sum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment