UpcA.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Validate
  17. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id$
  20. */
  21. /**
  22. * @see Zend_Validate_Abstract
  23. */
  24. require_once 'Zend/Validate/Abstract.php';
  25. /**
  26. * @category Zend
  27. * @package Zend_Validate
  28. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  29. * @license http://framework.zend.com/license/new-bsd New BSD License
  30. */
  31. class Zend_Validate_Barcode_UpcA extends Zend_Validate_Abstract
  32. {
  33. /**
  34. * Validation failure message key for when the value is
  35. * an invalid barcode
  36. */
  37. const INVALID = 'upcaInvalid';
  38. /**
  39. * Validation failure message key for when the value is
  40. * not 12 characters long
  41. */
  42. const INVALID_LENGTH = 'upcaInvalidLength';
  43. /**
  44. * Validation failure message template definitions
  45. *
  46. * @var array
  47. */
  48. protected $_messageTemplates = array(
  49. self::INVALID => "'%value%' is an invalid UPC-A barcode",
  50. self::INVALID_LENGTH => "'%value%' should be 12 characters",
  51. );
  52. /**
  53. * Defined by Zend_Validate_Interface
  54. *
  55. * Returns true if and only if $value contains a valid barcode
  56. *
  57. * @param string $value
  58. * @return boolean
  59. */
  60. public function isValid($value)
  61. {
  62. if (!is_string($value)) {
  63. $this->_error(self::INVALID);
  64. return false;
  65. }
  66. $this->_setValue($value);
  67. if (strlen($value) !== 12) {
  68. $this->_error(self::INVALID_LENGTH);
  69. return false;
  70. }
  71. $barcode = substr($value, 0, -1);
  72. $oddSum = 0;
  73. $evenSum = 0;
  74. for ($i = 0; $i < 11; $i++) {
  75. if ($i % 2 === 0) {
  76. $oddSum += $barcode[$i] * 3;
  77. } elseif ($i % 2 === 1) {
  78. $evenSum += $barcode[$i];
  79. }
  80. }
  81. $calculation = ($oddSum + $evenSum) % 10;
  82. $checksum = ($calculation === 0) ? 0 : 10 - $calculation;
  83. if ($value[11] != $checksum) {
  84. $this->_error(self::INVALID);
  85. return false;
  86. }
  87. return true;
  88. }
  89. }