/testing/phpQuery/Zend/Validate/Barcode/Ean13.php

http://xtraupload.googlecode.com/ · PHP · 100 lines · 37 code · 14 blank · 49 comment · 5 complexity · 40f61a22b89877b6b37e3b6d475b5be0 MD5 · raw file

  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-2008 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id: Ean13.php 8210 2008-02-20 14:09:05Z andries $
  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-2008 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_Ean13 extends Zend_Validate_Abstract
  32. {
  33. /**
  34. * Validation failure message key for when the value is
  35. * an invalid barcode
  36. */
  37. const INVALID = 'invalid';
  38. /**
  39. * Validation failure message key for when the value is
  40. * not 13 characters long
  41. */
  42. const INVALID_LENGTH = 'invalidLength';
  43. /**
  44. * Validation failure message template definitions
  45. *
  46. * @var array
  47. */
  48. protected $_messageTemplates = array(
  49. self::INVALID => "'%value%' is an invalid EAN-13 barcode",
  50. self::INVALID_LENGTH => "'%value%' should be 13 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. $valueString = (string) $value;
  63. $this->_setValue($valueString);
  64. if (strlen($valueString) !== 13) {
  65. $this->_error(self::INVALID_LENGTH);
  66. return false;
  67. }
  68. $barcode = strrev(substr($valueString, 0, -1));
  69. $oddSum = 0;
  70. $evenSum = 0;
  71. for ($i = 0; $i < 12; $i++) {
  72. if ($i % 2 === 0) {
  73. $oddSum += $barcode[$i] * 3;
  74. } elseif ($i % 2 === 1) {
  75. $evenSum += $barcode[$i];
  76. }
  77. }
  78. $calculation = ($oddSum + $evenSum) % 10;
  79. $checksum = ($calculation === 0) ? 0 : 10 - $calculation;
  80. if ($valueString[12] != $checksum) {
  81. $this->_error(self::INVALID);
  82. return false;
  83. }
  84. return true;
  85. }
  86. }