ZF-2269: Zend_Filter_Callback

Description

This new filter provides the flexibility to not have to write a custom ZF filter when filtering is already available from another function.


class Zend_Filter_Callback implements Zend_Filter_Interface {
    /**
     * The callback function/method.
     *
     * @var callback
     */
    protected $_callback;

    /**
     * Additional parameters to send to the callback function/method.
     *
     * @var array
     */
    protected $_params = array();

    /**
     * Instantiates the callback filter.
     *
     * @param   $callback   The callback function/method.
     * @param   $params     Additional parameters to be sent to the callback function/method.
     */
    public function __construct($callback, array $params = array()) {
        $this->setCallback($callback)->_params = $params;
    }

    /**
     * Sets the callback function/method.
     *
     * @param   callback    $callback
     *
     * @return  Zend_Filter_Callback
     */
    public function setCallback($callback) {
        if (!is_callable($callback)) {
            throw new Zend_Filter_Exception('Invalid callback');
        }

        $this->_callback = $callback;

        return $this;
    }

    /**
     * Calls the callback function/method.
     *
     * @param   mixed   $value
     *
     * @return  mixed
     */
    public function filter($value) {
        $params = array_merge(array($value), $this->_params);

        return call_user_func_array($this->_callback, $params);
    }
}

Comments

Please evaluate and categorize/assign as necessary.

Attached a new version.

Ralph, can you find a course of action on this issue, please?

There is already a small Zend_Filter_Callback implemented but it lacks 2 things which are solved in the above code:

  • It does not check if the callback can be called
  • It does not provide default parameters

Both would be a good addition to the existing class.

I'd suggest one of the following approaches:


$params = $this->_params;
call_user_func_array($this->_callback, array($value, $params));

or:


$params = $this->_params;
array_unshift($params, $value);
call_user_func_array($this->_callback, $params);

with preference going to the latter.

The mentioned two improvements have been added to trunk. Additionally there exists now a chapter in the manual which was missing before.