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.
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: UpcA.php 16223 2009-06-21 20:04:53Z thomas $
25 * @see Zend_Validate_Abstract
27 require_once 'Zend/Validate/Abstract.php';
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_UpcA
extends Zend_Validate_Abstract
39 * Validation failure message key for when the value is
42 const INVALID
= 'invalid';
45 * Validation failure message key for when the value is
46 * not 12 characters long
48 const INVALID_LENGTH
= 'invalidLength';
51 * Validation failure message template definitions
55 protected $_messageTemplates = array(
56 self
::INVALID
=> "'%value%' is an invalid UPC-A barcode",
57 self
::INVALID_LENGTH
=> "'%value%' should be 12 characters",
61 * Defined by Zend_Validate_Interface
63 * Returns true if and only if $value contains a valid barcode
65 * @param string $value
68 public function isValid($value)
70 if (!is_string($value)) {
71 $this->_error(self
::INVALID
);
75 $this->_setValue($value);
76 if (strlen($value) !== 12) {
77 $this->_error(self
::INVALID_LENGTH
);
81 $barcode = substr($value, 0, -1);
85 for ($i = 0; $i < 11; $i++
) {
87 $oddSum +
= $barcode[$i] * 3;
88 } elseif ($i %
2 === 1) {
89 $evenSum +
= $barcode[$i];
93 $calculation = ($oddSum +
$evenSum) %
10;
94 $checksum = ($calculation === 0) ?
0 : 10 - $calculation;
96 if ($value[11] != $checksum) {
97 $this->_error(self
::INVALID
);