Explorar el Código

[PROMOTE] Zend_Validate_Isbn

git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@20229 44c647ce-9c0f-0410-b52a-842ac1e357ba
matthew hace 16 años
padre
commit
0ffd6da057

+ 124 - 0
documentation/manual/en/module_specs/Zend_Validate-Isbn.xml

@@ -0,0 +1,124 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Reviewed: no -->
+<sect2 id="zend.validate.set.isbn">
+    <title>Isbn</title>
+
+    <para>
+        <classname>Zend_Validate_Isbn</classname> allows you to validate an
+        <acronym>ISBN-10</acronym> or <acronym>ISBN-13</acronym> value.
+    </para>
+
+    <sect3 id="zend.validate.set.isbn.basic">
+        <title>Basic usage</title>
+
+        <para>
+            A basic example of usage is below:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+$validator = new Zend_Validate_Isbn();
+if ($validator->isValid($isbn)) {
+    // isbn is valid
+} else {
+    // isbn is not valid
+}
+]]></programlisting>
+
+        <para>
+            This will validate any <acronym>ISBN-10</acronym> and <acronym>ISBN-13</acronym> without
+            separator.
+        </para>
+    </sect3>
+
+    <sect3 id="zend.validate.set.isbn.type-explicit">
+        <title>Setting an explicit ISBN validation type</title>
+
+        <para>
+            An example of an <acronym>ISBN</acronym> type restriction is below:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+$validator = new Zend_Validate_Isbn();
+$validator->setType(Zend_Validate_Isbn::ISBN13);
+// OR
+$validator = new Zend_Validate_Isbn(array(
+    'type' => Zend_Validate_Isbn::ISBN13,
+));
+
+if ($validator->isValid($isbn)) {
+    // this is a valid ISBN-13 value
+} else {
+    // this is an invalid ISBN-13 value
+}
+]]></programlisting>
+
+        <para>
+            The above will validate only <acronym>ISBN-13</acronym> values.
+        </para>
+
+        <para>
+            Valid types include:
+        </para>
+
+        <itemizedlist>
+            <listitem>
+                <para><constant>Zend_Validate_Isbn::AUTO</constant> (default)</para>
+            </listitem>
+
+            <listitem>
+                <para><constant>Zend_Validate_Isbn::ISBN10</constant></para>
+            </listitem>
+
+            <listitem>
+                <para><constant>Zend_Validate_Isbn::ISBN13</constant></para>
+            </listitem>
+        </itemizedlist>
+    </sect3>
+
+    <sect3 id="zend.validate.set.isbn.separator">
+        <title>Specifying a separator restriction</title>
+
+        <para>
+            An example of separator restriction is below:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+$validator = new Zend_Validate_Isbn();
+$validator->setSeparator('-');
+// OR
+$validator = new Zend_Validate_Isbn(array(
+    'separator' => '-',
+));
+
+if ($validator->isValid($isbn)) {
+    // this is a valid ISBN with separator
+} else {
+    // this is an invalid ISBN with separator
+}
+]]></programlisting>
+
+        <para>
+            Note that this will return false if <varname>$isbn</varname> doesn't contain a separator
+            <emphasis>or</emphasis> if it's an invalid <acronym>ISBN</acronym> value.
+        </para>
+
+        <para>
+            Valid separators include:
+        </para>
+
+        <itemizedlist>
+            <listitem>
+                <para>"" (empty) (default)</para>
+            </listitem>
+            <listitem>
+                <para>"-" (hyphen)</para>
+            </listitem>
+            <listitem>
+                <para>" " (space)</para>
+            </listitem>
+        </itemizedlist>
+    </sect3>
+</sect2>
+<!--
+vim:se ts=4 sw=4 et:
+-->

+ 1 - 0
documentation/manual/en/module_specs/Zend_Validate-Set.xml

@@ -178,6 +178,7 @@ if ($validator->isValid($iban)) {
     </sect2>
 
     <xi:include href="Zend_Validate-Ip.xml" />
+    <xi:include href="Zend_Validate-Isbn.xml" />
 
     <sect2 id="zend.validate.set.less_than">
         <title>LessThan</title>

+ 263 - 0
library/Zend/Validate/Isbn.php

@@ -0,0 +1,263 @@
+<?php
+/**
+ * Zend Framework
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://framework.zend.com/license/new-bsd
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@zend.com so we can send you a copy immediately.
+ *
+ * @category   Zend
+ * @package    Zend_Validate
+ * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
+ * @license    http://framework.zend.com/license/new-bsd     New BSD License
+ * @version    $Id$
+ */
+
+/**
+ * @see Zend_Validate_Abstract
+ */
+require_once 'Zend/Validate/Abstract.php';
+
+/**
+ * @category   Zend
+ * @package    Zend_Validate
+ * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
+ * @license    http://framework.zend.com/license/new-bsd     New BSD License
+ */
+class Zend_Validate_Isbn extends Zend_Validate_Abstract
+{
+    const AUTO    = 'auto';
+    const ISBN10  = '10';
+    const ISBN13  = '13';
+    const INVALID = 'isbnInvalid';
+
+    /**
+     * Validation failure message template definitions.
+     *
+     * @var array
+     */
+    protected $_messageTemplates = array(
+        self::INVALID => "'%value%' is an invalid ISBN",
+    );
+
+    /**
+     * Allowed type.
+     *
+     * @var string
+     */
+    protected $_type = self::AUTO;
+
+    /**
+     * Separator character.
+     *
+     * @var string
+     */
+    protected $_separator = '';
+
+    /**
+     * Set up options.
+     *
+     * @param  Zend_Config|array $options
+     * @throws Zend_Validate_Exception When $options is not valid
+     * @return void
+     */
+    public function __construct($options = array())
+    {
+        // prepare options
+        if ($options instanceof Zend_Config) {
+            $options = $options->toArray();
+        }
+        if (!is_array($options)) {
+            /**
+             * @see Zend_Validate_Exception
+             */
+            require_once 'Zend/Validate/Exception.php';
+            throw new Zend_Validate_Exception('Invalid options provided.');
+        }
+
+        // set type
+        if (array_key_exists('type', $options)) {
+            $this->setType($options['type']);
+        }
+
+        // set separator
+        if (array_key_exists('separator', $options)) {
+            $this->setSeparator($options['separator']);
+        }
+    }
+
+    /**
+     * Detect input format.
+     *
+     * @return string
+     */
+    protected function _detectFormat()
+    {
+        // prepare separator and pattern list
+        $sep      = quotemeta($this->_separator);
+        $patterns = array();
+
+        // check for ISBN-10
+        if ($this->_type == self::ISBN10 || $this->_type == self::AUTO) {
+            if (empty($sep)) {
+                $pattern = '^[0-9]{9}[0-9X]{1}$';
+            } else {
+                $pattern = "^[0-9]{1,7}[{$sep}]{1}[0-9]{1,7}[{$sep}]{1}[0-9]{1,7}[{$sep}]{1}[0-9X]{1}\${13}";
+            }
+            $patterns[$pattern] = self::ISBN10;
+        }
+
+        // check for ISBN-13
+        if ($this->_type == self::ISBN13 || $this->_type == self::AUTO) {
+            if (empty($sep)) {
+                $pattern = '^[0-9]{13}$';
+            } else {
+                $pattern = "^[0-9]{1,9}[{$sep}]{1}[0-9]{1,5}[{$sep}]{1}[0-9]{1,9}[{$sep}]{1}[0-9]{1,9}[{$sep}]{1}[0-9]{1}\${17}";
+            }
+            $patterns[$pattern] = self::ISBN13;
+        }
+
+        // check pattern list
+        foreach ($patterns as $pattern => $type) {
+            if (ereg($pattern, $this->_value) == 1) {
+                return $type;
+            }
+        }
+        return null;
+    }
+
+    /**
+     * Defined by Zend_Validate_Interface.
+     *
+     * Returns true if and only if $value contains a valid ISBN.
+     *
+     * @param  string $value
+     * @return boolean
+     */
+    public function isValid($value)
+    {
+        // save value
+        $value = (string) $value;
+        $this->_setValue($value);
+
+        switch ($this->_detectFormat()) {
+            case self::ISBN10:
+                // sum
+                $isbn10 = preg_replace('/[^0-9X]/', '', $value);
+                $sum    = 0;
+                for ($i = 0; $i < 9; $i++) {
+                    $sum += (10 - $i) * $isbn10{$i};
+                }
+
+                // checksum
+                $checksum = 11 - ($sum % 11);
+                if ($checksum == 11) {
+                    $checksum = '0';
+                } elseif ($checksum == 10) {
+                    $checksum = 'X';
+                }
+                break;
+
+            case self::ISBN13:
+                // sum
+                $isbn13 = preg_replace('/[^0-9]/', '', $value);
+                $sum    = 0;
+                for ($i = 0; $i < 12; $i++) {
+                    if ($i % 2 == 0) {
+                        $sum += $isbn13{$i};
+                    } else {
+                        $sum += 3 * $isbn13{$i};
+                    }
+                }
+                // checksum
+                $checksum = 10 - ($sum % 10);
+                if ($checksum == 10) {
+                    $checksum = '0';
+                }
+                break;
+
+            default:
+                $this->_error(self::INVALID);
+                return false;
+        }
+
+        // validate
+        if (substr($this->_value, -1) != $checksum) {
+            $this->_error(self::INVALID);
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Set separator characters.
+     *
+     * It is allowed only empty string, hyphen and space.
+     *
+     * @param  string $separator
+     * @throws Zend_Validate_Exception When $separator is not valid
+     * @return Zend_Validate_Isbn Provides a fluent interface
+     */
+    public function setSeparator($separator)
+    {
+        // check separator
+        if (!in_array($separator, array('-', ' ', ''))) {
+            /**
+             * @see Zend_Validate_Exception
+             */
+            require_once 'Zend/Validate/Exception.php';
+            throw new Zend_Validate_Exception('Invalid ISBN separator.');
+        }
+
+        $this->_separator = $separator;
+        return $this;
+    }
+
+    /**
+     * Get separator characters.
+     *
+     * @return string
+     */
+    public function getSeparator()
+    {
+        return $this->_separator;
+    }
+
+    /**
+     * Set allowed ISBN type.
+     *
+     * @param  string $type
+     * @throws Zend_Validate_Exception When $type is not valid
+     * @return Zend_Validate_Isbn Provides a fluent interface
+     */
+    public function setType($type)
+    {
+        // check type
+        if (!in_array($type, array(self::AUTO, self::ISBN10, self::ISBN13))) {
+            /**
+             * @see Zend_Validate_Exception
+             */
+            require_once 'Zend/Validate/Exception.php';
+            throw new Zend_Validate_Exception('Invalid ISBN type');
+        }
+
+        $this->_type = $type;
+        return $this;
+    }
+
+    /**
+     * Get allowed ISBN type.
+     *
+     * @return string
+     */
+    public function getType()
+    {
+        return $this->_type;
+    }
+}

+ 2 - 0
tests/Zend/Validate/AllTests.php

@@ -45,6 +45,7 @@ require_once 'Zend/Validate/IdenticalTest.php';
 require_once 'Zend/Validate/InArrayTest.php';
 require_once 'Zend/Validate/IntTest.php';
 require_once 'Zend/Validate/IpTest.php';
+require_once 'Zend/Validate/IsbnTest.php';
 require_once 'Zend/Validate/LessThanTest.php';
 require_once 'Zend/Validate/MessageTest.php';
 require_once 'Zend/Validate/NotEmptyTest.php';
@@ -100,6 +101,7 @@ class Zend_Validate_AllTests
         $suite->addTestSuite('Zend_Validate_InArrayTest');
         $suite->addTestSuite('Zend_Validate_IntTest');
         $suite->addTestSuite('Zend_Validate_IpTest');
+        $suite->addTestSuite('Zend_Validate_IsbnTest');
         $suite->addTestSuite('Zend_Validate_LessThanTest');
         $suite->addTestSuite('Zend_Validate_MessageTest');
         $suite->addTestSuite('Zend_Validate_NotEmptyTest');

+ 259 - 0
tests/Zend/Validate/IsbnTest.php

@@ -0,0 +1,259 @@
+<?php
+/**
+ * Zend Framework
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://framework.zend.com/license/new-bsd
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@zend.com so we can send you a copy immediately.
+ *
+ * @category   Zend
+ * @package    Zend_Validate
+ * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
+ * @license    http://framework.zend.com/license/new-bsd     New BSD License
+ * @version    $Id$
+ */
+
+/**
+ * Test helper
+ */
+require_once dirname(__FILE__) . '/../../TestHelper.php';
+
+/**
+ * @see Zend_Validate_Isbn
+ */
+require_once 'Zend/Validate/Isbn.php';
+
+
+/**
+ * @category   Zend
+ * @package    Zend_Validate
+ * @subpackage UnitTests
+ * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
+ * @license    http://framework.zend.com/license/new-bsd     New BSD License
+ */
+class Zend_Validate_IsbnTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * Ensures that the validator follows expected behavior
+     *
+     * @return void
+     */
+    public function testBasic()
+    {
+        $validator = new Zend_Validate_Isbn();
+
+        // Brave New World by Aldous Huxley
+        $this->assertTrue($validator->isValid('0060929871'));
+        $this->assertFalse($validator->isValid('006092987X'));
+
+        // Time Rations by Benjamin Friedlander
+        $this->assertTrue($validator->isValid('188202205X'));
+        $this->assertFalse($validator->isValid('1882022059'));
+
+        // Towards The Primeval Lighting Field by Will Alexander
+        $this->assertTrue($validator->isValid('1882022300'));
+        $this->assertFalse($validator->isValid('1882022301'));
+
+        //  ISBN-13 for dummies by Zoë Wykes
+        $this->assertTrue($validator->isValid('9780555023402'));
+        $this->assertFalse($validator->isValid('97805550234029'));
+
+        // Change Your Brain, Change Your Life Daniel G. Amen
+        $this->assertTrue($validator->isValid('9780812929980'));
+        $this->assertFalse($validator->isValid('9780812929981'));
+    }
+
+    /**
+     * Ensures that setSeparator() works as expected
+     *
+     * @return void
+     */
+    public function testType()
+    {
+        $validator = new Zend_Validate_Isbn();
+
+        try {
+            $validator->setType(Zend_Validate_Isbn::AUTO);
+            $this->assertTrue($validator->getType() == Zend_Validate_Isbn::AUTO);
+        } catch (Exception $e) {
+            $this->fail("Should accept type 'auto'");
+        }
+
+        try {
+            $validator->setType(Zend_Validate_Isbn::ISBN10);
+            $this->assertTrue($validator->getType() == Zend_Validate_Isbn::ISBN10);
+        } catch (Exception $e) {
+            $this->fail("Should accept type 'ISBN-10'");
+        }
+
+        try {
+            $validator->setType(Zend_Validate_Isbn::ISBN13);
+            $this->assertTrue($validator->getType() == Zend_Validate_Isbn::ISBN13);
+        } catch (Exception $e) {
+            $this->fail("Should accept type 'ISBN-13'");
+        }
+
+        try {
+            $validator->setType('X');
+            $this->fail("Should not accept type 'X'");
+        } catch (Exception $e) {
+            // success
+        }
+    }
+
+    /**
+     * Ensures that setSeparator() works as expected
+     *
+     * @return void
+     */
+    public function testSeparator()
+    {
+        $validator = new Zend_Validate_Isbn();
+
+        try {
+            $validator->setSeparator('-');
+            $this->assertTrue($validator->getSeparator() == '-');
+        } catch (Exception $e) {
+            $this->fail("Should accept separator '-'");
+        }
+
+        try {
+            $validator->setSeparator(' ');
+            $this->assertTrue($validator->getSeparator() == ' ');
+        } catch (Exception $e) {
+            $this->fail("Should accept separator ' '");
+        }
+
+        try {
+            $validator->setSeparator('');
+            $this->assertTrue($validator->getSeparator() == '');
+        } catch (Exception $e) {
+            $this->fail("Should accept empty separator");
+        }
+
+        try {
+            $validator->setSeparator('X');
+            $this->fail("Should not accept separator 'X'");
+        } catch (Exception $e) {
+            // success
+        }
+    }
+
+    /**
+     * Ensures that __construct() works as expected
+     *
+     * @return void
+     */
+    public function testInitialization()
+    {
+        $options = array('type'      => Zend_Validate_Isbn::AUTO,
+                         'separator' => ' ');
+        $validator = new Zend_Validate_Isbn($options);
+        $this->assertTrue($validator->getType() == Zend_Validate_Isbn::AUTO);
+        $this->assertTrue($validator->getSeparator() == ' ');
+
+        $options = array('type'      => Zend_Validate_Isbn::ISBN10,
+                         'separator' => '-');
+        $validator = new Zend_Validate_Isbn($options);
+        $this->assertTrue($validator->getType() == Zend_Validate_Isbn::ISBN10);
+        $this->assertTrue($validator->getSeparator() == '-');
+
+        $options = array('type'      => Zend_Validate_Isbn::ISBN13,
+                         'separator' => '');
+        $validator = new Zend_Validate_Isbn($options);
+        $this->assertTrue($validator->getType() == Zend_Validate_Isbn::ISBN13);
+        $this->assertTrue($validator->getSeparator() == '');
+    }
+
+    /**
+     * Ensures that the validator follows expected behavior
+     *
+     * @return void
+     */
+    public function testTypeAuto()
+    {
+        $validator = new Zend_Validate_Isbn();
+
+        $this->assertTrue($validator->isValid('0060929871'));
+        $this->assertFalse($validator->isValid('0-06-092987-1'));
+        $this->assertFalse($validator->isValid('0 06 092987 1'));
+
+        $this->assertTrue($validator->isValid('9780555023402'));
+        $this->assertFalse($validator->isValid('978-0-555023-40-2'));
+        $this->assertFalse($validator->isValid('978 0 555023 40 2'));
+
+        $validator->setSeparator('-');
+
+        $this->assertFalse($validator->isValid('0060929871'));
+        $this->assertTrue($validator->isValid('0-06-092987-1'));
+        $this->assertFalse($validator->isValid('0 06 092987 1'));
+
+        $this->assertFalse($validator->isValid('9780555023402'));
+        $this->assertTrue($validator->isValid('978-0-555023-40-2'));
+        $this->assertFalse($validator->isValid('978 0 555023 40 2'));
+
+        $validator->setSeparator(' ');
+
+        $this->assertFalse($validator->isValid('0060929871'));
+        $this->assertFalse($validator->isValid('0-06-092987-1'));
+        $this->assertTrue($validator->isValid('0 06 092987 1'));
+
+        $this->assertFalse($validator->isValid('9780555023402'));
+        $this->assertFalse($validator->isValid('978-0-555023-40-2'));
+        $this->assertTrue($validator->isValid('978 0 555023 40 2'));
+    }
+
+    /**
+     * Ensures that the validator follows expected behavior
+     *
+     * @return void
+     */
+    public function testType10()
+    {
+        $validator = new Zend_Validate_Isbn();
+        $validator->setType(Zend_Validate_Isbn::ISBN10);
+
+        $this->assertTrue($validator->isValid('0060929871'));
+        $this->assertFalse($validator->isValid('9780555023402'));
+
+        $validator->setSeparator('-');
+
+        $this->assertTrue($validator->isValid('0-06-092987-1'));
+        $this->assertFalse($validator->isValid('978-0-555023-40-2'));
+
+        $validator->setSeparator(' ');
+
+        $this->assertTrue($validator->isValid('0 06 092987 1'));
+        $this->assertFalse($validator->isValid('978 0 555023 40 2'));
+    }
+
+    /**
+     * Ensures that the validator follows expected behavior
+     *
+     * @return void
+     */
+    public function testType13()
+    {
+        $validator = new Zend_Validate_Isbn();
+        $validator->setType(Zend_Validate_Isbn::ISBN13);
+
+        $this->assertFalse($validator->isValid('0060929871'));
+        $this->assertTrue($validator->isValid('9780555023402'));
+
+        $validator->setSeparator('-');
+
+        $this->assertFalse($validator->isValid('0-06-092987-1'));
+        $this->assertTrue($validator->isValid('978-0-555023-40-2'));
+
+        $validator->setSeparator(' ');
+
+        $this->assertFalse($validator->isValid('0 06 092987 1'));
+        $this->assertTrue($validator->isValid('978 0 555023 40 2'));
+    }
+}