*prechod na novsiu verziu ZF
[sport-group.git] / library / Zend / Validate / Barcode / Ean13.php
blob068809248c3ccf1b8efbe86772e3b8171fe021b5
1 <?php
3 /**
4 * Zend Framework
6 * LICENSE
8 * This source file is subject to the new BSD license that is bundled
9 * with this package in the file LICENSE.txt.
10 * It is also available through the world-wide-web at this URL:
11 * http://framework.zend.com/license/new-bsd
12 * If you did not receive a copy of the license and are unable to
13 * obtain it through the world-wide-web, please send an email
14 * to license@zend.com so we can send you a copy immediately.
16 * @category Zend
17 * @package Zend_Validate
18 * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
19 * @license http://framework.zend.com/license/new-bsd New BSD License
20 * @version $Id: Ean13.php 16223 2009-06-21 20:04:53Z thomas $
24 /**
25 * @see Zend_Validate_Abstract
27 require_once 'Zend/Validate/Abstract.php';
30 /**
31 * @category Zend
32 * @package Zend_Validate
33 * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
34 * @license http://framework.zend.com/license/new-bsd New BSD License
36 class Zend_Validate_Barcode_Ean13 extends Zend_Validate_Abstract
38 /**
39 * Validation failure message key for when the value is
40 * an invalid barcode
42 const INVALID = 'invalid';
44 /**
45 * Validation failure message key for when the value is
46 * not 13 characters long
48 const INVALID_LENGTH = 'invalidLength';
50 /**
51 * Validation failure message key for when the value
52 * does not only contain numeric characters
54 const NOT_NUMERIC = 'ean13NotNumeric';
56 /**
57 * Validation failure message template definitions
59 * @var array
61 protected $_messageTemplates = array(
62 self::INVALID => "'%value%' is an invalid EAN-13 barcode",
63 self::INVALID_LENGTH => "'%value%' should be 13 characters",
64 self::NOT_NUMERIC => "'%value%' should contain only numeric characters",
67 /**
68 * Defined by Zend_Validate_Interface
70 * Returns true if and only if $value contains a valid barcode
72 * @param string $value
73 * @return boolean
75 public function isValid($value)
77 if (!is_string($value) || !ctype_digit($value)) {
78 $this->_error(self::NOT_NUMERIC);
79 return false;
82 $this->_setValue($value);
83 if (strlen($value) !== 13) {
84 $this->_error(self::INVALID_LENGTH);
85 return false;
88 $barcode = strrev(substr($value, 0, -1));
89 $oddSum = 0;
90 $evenSum = 0;
92 for ($i = 0; $i < 12; $i++) {
93 if ($i % 2 === 0) {
94 $oddSum += $barcode[$i] * 3;
95 } elseif ($i % 2 === 1) {
96 $evenSum += $barcode[$i];
100 $calculation = ($oddSum + $evenSum) % 10;
101 $checksum = ($calculation === 0) ? 0 : 10 - $calculation;
103 if ($value[12] != $checksum) {
104 $this->_error(self::INVALID);
105 return false;
108 return true;