Jelajahi Sumber

[GENERIC] Zend_Validate_Callback:

- promoted Zend_Validate_Callback to core

git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@18270 44c647ce-9c0f-0410-b52a-842ac1e357ba
thomas 16 tahun lalu
induk
melakukan
e766d978e2

+ 220 - 0
documentation/manual/en/module_specs/Zend_Validate-Callback.xml

@@ -0,0 +1,220 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Reviewed: no -->
+<sect2 id="zend.validate.set.callback">
+
+    <title>Callback</title>
+
+    <para>
+        <classname>Zend_Validate_Callback</classname> allows you to provide a callback with which to
+        validate a given value.
+    </para>
+
+    <sect3 id="zend.validate.set.callback.basic">
+        <title>Basic usage</title>
+
+        <para>
+            The simplest usecase is to have a single function and use it as a callback. Let's expect
+            we have the following function.
+        </para>
+
+        <programlisting language="php"><![CDATA[
+function myMethod($value)
+{
+    // some validation
+    return true;
+}
+]]></programlisting>
+
+        <para>
+            To use it within <classname>Zend_Validate_Callback</classname> you just have to call it
+            this way:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+$valid = new Zend_Validate_Callback('myMethod');
+if ($valid->isValid($input)) {
+    // input appears to be valid
+} else {
+    // input is invalid
+}
+]]></programlisting>
+    </sect3>
+
+    <sect3 id="zend.validate.set.callback.closure">
+        <title>Usage with closures</title>
+
+        <para>
+            PHP 5.3 introduces <ulink url="http://php.net/functions.anonymous">closures</ulink>,
+            which are basically self-contained or <emphasis>anonymous</emphasis> functions. PHP
+            considers closures another form of callback, and, as such, may be used with
+            <classname>Zend_Validate_Callback</classname>.  As an example:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+$valid = new Zend_Validate_Callback(function($value){
+    // some validation
+    return true;
+});
+
+if ($valid->isValid($input)) {
+    // input appears to be valid
+} else {
+    // input is invalid
+}
+]]></programlisting>
+    </sect3>
+
+    <sect3 id="zend.validate.set.callback.class">
+        <title>Usage with class-based callbacks</title>
+
+        <para>
+            Of course it's also possible to use a class method as callback. Let's expect we have
+            the following class method:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+class MyClass
+{
+    public function myMethod($value)
+    {
+        // some validation
+        return true;
+    }
+}
+]]></programlisting>
+
+        <para>
+            The definition of the callback is in this case almost the same. You have just to create
+            an instance of the class before the method and create an array describing the callback:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+$object = new MyClass;
+$valid = new Zend_Validate_Callback(array($object, 'myMethod'));
+if ($valid->isValid($input)) {
+    // input appears to be valid
+} else {
+    // input is invalid
+}
+]]></programlisting>
+
+        <para>
+            You may also define a static method as a callback. Consider the following class
+            definition and validator usage:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+class MyClass
+{
+    public static function test($value)
+    {
+        // some validation
+        return true;
+    }
+}
+
+$valid = new Zend_Validate_Callback(array('MyClass, 'test'));
+if ($valid->isValid($input)) {
+    // input appears to be valid
+} else {
+    // input is invalid
+}
+]]></programlisting>
+
+        <para>
+            Finally, if you are using PHP 5.3, you may define the magic method
+            <methodname>__invoke()</methodname> in your class. If you do so, simply providing an
+            instance of the class as the callback will also work:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+class MyClass
+{
+    public function __invoke($value)
+    {
+        // some validation
+        return true;
+    }
+}
+
+$object = new MyClass();
+$valid = new Zend_Validate_Callback($object);
+if ($valid->isValid($input)) {
+    // input appears to be valid
+} else {
+    // input is invalid
+}
+]]></programlisting>
+    </sect3>
+
+    <sect3 id="zend.validate.set.callback.options">
+        <title>Adding options</title>
+
+        <para>
+            <classname>Zend_Validate_Callback</classname> also allows the usage of options which
+            are provided as additional arguments to the callback.
+        </para>
+
+        <para>
+            Consider the following class and method definition:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+class MyClass
+{
+    function myMethod($value, $option)
+    {
+        // some validation
+        return true;
+    }
+}
+]]></programlisting>
+
+        <para>
+            There are two ways to inform the validator of additional options: pass them in the
+            constructor, or pass them to the <methodname>setOptions()</methodname> method.
+        </para>
+
+        <para>
+            To pass them to the constructor, you would need to pass an array containing two keys,
+            "callback" and "options":
+        </para>
+
+        <programlisting language="php"><![CDATA[
+$valid = new Zend_Validate_Callback(array(
+    'callback' => array('MyClass', 'myMethod'), 
+    'options'  => $option,
+));
+
+if ($valid->isValid($input)) {
+    // input appears to be valid
+} else {
+    // input is invalid
+}
+]]></programlisting>
+
+        <para>
+            Otherwise, you may pass them to the validator after instantiation:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+$valid = new Zend_Validate_Callback(array('MyClass', 'myMethod'));
+$valid->setOptions($option);
+
+if ($valid->isValid($input)) {
+    // input appears to be valid
+} else {
+    // input is invalid
+}
+]]></programlisting>
+
+        <para>
+            When making the call to the callback, the value to be validated will always be passed as
+            the first argument to the callback; all other options will follow it. The amount and
+            type of options which can be used is not limited.
+        </para>
+    </sect3>
+</sect2>
+<!--
+vim:se ts=4 sw=4 et:
+-->

+ 3 - 9
documentation/manual/en/module_specs/Zend_Validate-Set.xml

@@ -1,7 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <!-- Reviewed: no -->
 <sect1 id="zend.validate.set" xmlns:xi="http://www.w3.org/2001/XInclude">
-
     <title>Standard Validation Classes</title>
 
     <para>
@@ -60,6 +59,8 @@
         </para>
     </sect2>
 
+    <xi:include href="Zend_Validate-Callback.xml" />
+
     <sect2 id="zend.validate.set.ccnum">
         <title>Ccnum</title>
         <para>
@@ -193,14 +194,7 @@ if ($validator->isValid(1)) { // token invalid
 ]]></programlisting>
     </sect2>
 
-    <sect2 id="zend.validate.set.in_array">
-        <title>InArray</title>
-        <para>
-            Returns <constant>TRUE</constant> if and only if a "needle" <varname>$value</varname> is contained in
-            a "haystack" array. If the strict option is <constant>TRUE</constant>, then the type of
-            <varname>$value</varname> is also checked.
-        </para>
-    </sect2>
+    <xi:include href="Zend_Validate-InArray.xml" />
 
     <sect2 id="zend.validate.set.int">
         <title>Int</title>

+ 174 - 0
library/Zend/Validate/Callback.php

@@ -0,0 +1,174 @@
+<?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-2009 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-2009 Zend Technologies USA Inc. (http://www.zend.com)
+ * @license    http://framework.zend.com/license/new-bsd     New BSD License
+ */
+class Zend_Validate_Callback extends Zend_Validate_Abstract
+{
+    /**
+     * Invalid callback
+     */
+    const INVALID_CALLBACK = 'callbackInvalid';
+
+    /**
+     * Invalid value
+     */
+    const INVALID_VALUE = 'callbackValue';
+
+    /**
+     * Validation failure message template definitions
+     *
+     * @var array
+     */
+    protected $_messageTemplates = array(
+        self::INVALID_VALUE    => "'%value%' is not valid",
+        self::INVALID_CALLBACK => "Failure within the callback, exception returned",
+    );
+
+    /**
+     * Callback in a call_user_func format
+     *
+     * @var string|array
+     */
+    protected $_callback = null;
+
+    /**
+     * Default options to set for the filter
+     *
+     * @var mixed
+     */
+    protected $_options = array();
+
+    /**
+     * Sets validator options
+     *
+     * @param  string|array $callback
+     * @param  mixed   $max
+     * @param  boolean $inclusive
+     * @return void
+     */
+    public function __construct($callback = null)
+    {
+        if (is_callable($callback)) {
+            $this->setCallback($callback);
+        } elseif (is_array($callback)) {
+            if (isset($callback['callback'])) {
+                $this->setCallback($callback['callback']);
+            }
+            if (isset($callback['options'])) {
+                $this->setOptions($callback['options']);
+            }
+        }
+
+        if (null === ($initializedCallack = $this->getCallback())) {
+            require_once 'Zend/Validate/Exception.php';
+            throw new Zend_Validate_Exception('No callback registered');
+        }
+    }
+
+    /**
+     * Returns the set callback
+     *
+     * @return mixed
+     */
+    public function getCallback()
+    {
+        return $this->_callback;
+    }
+
+    /**
+     * Sets the callback
+     *
+     * @param  string|array $callback
+     * @return Zend_Validate_Callback Provides a fluent interface
+     */
+    public function setCallback($callback)
+    {
+        if (!is_callable($callback)) {
+            require_once 'Zend/Validate/Exception.php';
+            throw new Zend_Validate_Exception('Invalid callback given');
+        }
+        $this->_callback = $callback;
+        return $this;
+    }
+
+    /**
+     * Returns the set options for the callback
+     *
+     * @return mixed
+     */
+    public function getOptions()
+    {
+        return $this->_options;
+    }
+
+    /**
+     * Sets options for the callback
+     *
+     * @param  mixed $max
+     * @return Zend_Validate_Callback Provides a fluent interface
+     */
+    public function setOptions($options)
+    {
+        $this->_options = (array) $options;
+        return $this;
+    }
+
+    /**
+     * Defined by Zend_Validate_Interface
+     *
+     * Returns true if and only if the set callback returns
+     * for the provided $value
+     *
+     * @param  mixed $value
+     * @return boolean
+     */
+    public function isValid($value)
+    {
+        $this->_setValue($value);
+
+        $options = $this->getOptions();
+        array_unshift($options, $value);
+
+        $callback = $this->getCallback();
+
+        try {
+            if (!call_user_func_array($callback, $options)) {
+                $this->_error(self::INVALID_VALUE);
+                return false;
+            }
+        } catch (Exception $e) {
+            $this->_error(self::INVALID_CALLBACK);
+            return false;
+        }
+
+        return true;
+    }
+}

+ 220 - 0
library/Zend/Validate/Zend_Validate-Callback.xml

@@ -0,0 +1,220 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Reviewed: no -->
+<sect2 id="zend.validate.set.callback">
+
+    <title>Callback</title>
+
+    <para>
+        <classname>Zend_Validate_Callback</classname> allows you to provide a callback with which to
+        validate a given value.
+    </para>
+
+    <sect3 id="zend.validate.set.callback.basic">
+        <title>Basic usage</title>
+
+        <para>
+            The simplest usecase is to have a single function and use it as a callback. Let's expect
+            we have the following function.
+        </para>
+
+        <programlisting language="php"><![CDATA[
+function myMethod($value)
+{
+    // some validation
+    return true;
+}
+]]></programlisting>
+
+        <para>
+            To use it within <classname>Zend_Validate_Callback</classname> you just have to call it
+            this way:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+$valid = new Zend_Validate_Callback('myMethod');
+if ($valid->isValid($input)) {
+    // input appears to be valid
+} else {
+    // input is invalid
+}
+]]></programlisting>
+    </sect3>
+
+    <sect3 id="zend.validate.set.callback.closure">
+        <title>Usage with closures</title>
+
+        <para>
+            PHP 5.3 introduces <ulink url="http://php.net/functions.anonymous">closures</ulink>,
+            which are basically self-contained or <emphasis>anonymous</emphasis> functions. PHP
+            considers closures another form of callback, and, as such, may be used with
+            <classname>Zend_Validate_Callback</classname>.  As an example:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+$valid = new Zend_Validate_Callback(function($value){
+    // some validation
+    return true;
+});
+
+if ($valid->isValid($input)) {
+    // input appears to be valid
+} else {
+    // input is invalid
+}
+]]></programlisting>
+    </sect3>
+
+    <sect3 id="zend.validate.set.callback.class">
+        <title>Usage with class-based callbacks</title>
+
+        <para>
+            Of course it's also possible to use a class method as callback. Let's expect we have
+            the following class method:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+class MyClass
+{
+    public function myMethod($value)
+    {
+        // some validation
+        return true;
+    }
+}
+]]></programlisting>
+
+        <para>
+            The definition of the callback is in this case almost the same. You have just to create
+            an instance of the class before the method and create an array describing the callback:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+$object = new MyClass;
+$valid = new Zend_Validate_Callback(array($object, 'myMethod'));
+if ($valid->isValid($input)) {
+    // input appears to be valid
+} else {
+    // input is invalid
+}
+]]></programlisting>
+
+        <para>
+            You may also define a static method as a callback. Consider the following class
+            definition and validator usage:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+class MyClass
+{
+    public static function test($value)
+    {
+        // some validation
+        return true;
+    }
+}
+
+$valid = new Zend_Validate_Callback(array('MyClass, 'test'));
+if ($valid->isValid($input)) {
+    // input appears to be valid
+} else {
+    // input is invalid
+}
+]]></programlisting>
+
+        <para>
+            Finally, if you are using PHP 5.3, you may define the magic method
+            <methodname>__invoke()</methodname> in your class. If you do so, simply providing an
+            instance of the class as the callback will also work:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+class MyClass
+{
+    public function __invoke($value)
+    {
+        // some validation
+        return true;
+    }
+}
+
+$object = new MyClass();
+$valid = new Zend_Validate_Callback($object);
+if ($valid->isValid($input)) {
+    // input appears to be valid
+} else {
+    // input is invalid
+}
+]]></programlisting>
+    </sect3>
+
+    <sect3 id="zend.validate.set.callback.options">
+        <title>Adding options</title>
+
+        <para>
+            <classname>Zend_Validate_Callback</classname> also allows the usage of options which
+            are provided as additional arguments to the callback.
+        </para>
+
+        <para>
+            Consider the following class and method definition:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+class MyClass
+{
+    function myMethod($value, $option)
+    {
+        // some validation
+        return true;
+    }
+}
+]]></programlisting>
+
+        <para>
+            There are two ways to inform the validator of additional options: pass them in the
+            constructor, or pass them to the <methodname>setOptions()</methodname> method.
+        </para>
+
+        <para>
+            To pass them to the constructor, you would need to pass an array containing two keys,
+            "callback" and "options":
+        </para>
+
+        <programlisting language="php"><![CDATA[
+$valid = new Zend_Validate_Callback(array(
+    'callback' => array('MyClass', 'myMethod'), 
+    'options'  => $option,
+));
+
+if ($valid->isValid($input)) {
+    // input appears to be valid
+} else {
+    // input is invalid
+}
+]]></programlisting>
+
+        <para>
+            Otherwise, you may pass them to the validator after instantiation:
+        </para>
+
+        <programlisting language="php"><![CDATA[
+$valid = new Zend_Validate_Callback(array('MyClass', 'myMethod'));
+$valid->setOptions($option);
+
+if ($valid->isValid($input)) {
+    // input appears to be valid
+} else {
+    // input is invalid
+}
+]]></programlisting>
+
+        <para>
+            When making the call to the callback, the value to be validated will always be passed as
+            the first argument to the callback; all other options will follow it. The amount and
+            type of options which can be used is not limited.
+        </para>
+    </sect3>
+</sect2>
+<!--
+vim:se ts=4 sw=4 et:
+-->

+ 122 - 0
tests/Zend/Validate/CallbackTest.php

@@ -0,0 +1,122 @@
+<?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
+ * @subpackage UnitTests
+ * @copyright  Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
+ * @license    http://framework.zend.com/license/new-bsd     New BSD License
+ * @version    $Id$
+ */
+
+if (!defined('PHPUnit_MAIN_METHOD')) {
+    define('PHPUnit_MAIN_METHOD', 'Zend_Validate_CallbackTest::main');
+}
+
+/**
+ * Test helper
+ */
+require_once dirname(__FILE__) . '/../../TestHelper.php';
+
+/**
+ * @see Zend_Validate_Callback
+ */
+require_once 'Zend/Validate/Callback.php';
+
+/**
+ * @category   Zend
+ * @package    Zend_Validate
+ * @subpackage UnitTests
+ * @copyright  Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
+ * @license    http://framework.zend.com/license/new-bsd     New BSD License
+ * @group      Zend_Validate
+ */
+class Zend_Validate_CallbackTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * Runs this test suite
+     *
+     * @return void
+     */
+    public static function main()
+    {
+        $suite  = new PHPUnit_Framework_TestSuite('Zend_Validate_CallbackTest');
+        $result = PHPUnit_TextUI_TestRunner::run($suite);
+    }
+
+    /**
+     * Ensures that the validator follows expected behavior
+     *
+     * @return void
+     */
+    public function testBasic()
+    {
+        $valid = new Zend_Validate_Callback(array($this, 'objectCallback'));
+        $this->assertTrue($valid->isValid('test'));
+    }
+
+    public function testStaticCallback()
+    {
+        $valid = new Zend_Validate_Callback(
+            array('Zend_Validate_CallbackTest', 'staticCallback')
+        );
+        $this->assertTrue($valid->isValid('test'));
+    }
+
+    public function testSettingDefaultOptionsAfterwards()
+    {
+        $valid = new Zend_Validate_Callback(array($this, 'objectCallback'));
+        $valid->setOptions('options');
+        $this->assertEquals(array('options'), $valid->getOptions());
+        $this->assertTrue($valid->isValid('test'));
+    }
+
+    public function testSettingDefaultOptions()
+    {
+        $valid = new Zend_Validate_Callback(array('callback' => array($this, 'objectCallback'), 'options' => 'options'));
+        $this->assertEquals(array('options'), $valid->getOptions());
+        $this->assertTrue($valid->isValid('test'));
+    }
+
+    public function testGettingCallback()
+    {
+        $valid = new Zend_Validate_Callback(array($this, 'objectCallback'));
+        $this->assertEquals(array($this, 'objectCallback'), $valid->getCallback());
+    }
+
+    public function testInvalidCallback()
+    {
+        $valid = new Zend_Validate_Callback(array($this, 'objectCallback'));
+        try {
+            $valid->setCallback('invalidcallback');
+            $this->fail('Exception expected');
+        } catch (Zend_Exception $e) {
+            $this->assertContains('Invalid callback given', $e->getMessage());
+        }
+    }
+
+    public function objectCallback($value)
+    {
+        return true;
+    }
+
+    public static function staticCallback($value)
+    {
+        return true;
+    }
+}
+
+if (PHPUnit_MAIN_METHOD == 'Zend_Validate_CallbackTest::main') {
+    Zend_Validate_CallbackTest::main();
+}