1<?php 2/** 3 * Zend Framework (http://framework.zend.com/) 4 * 5 * @link http://github.com/zendframework/zf2 for the canonical source repository 6 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) 7 * @license http://framework.zend.com/license/new-bsd New BSD License 8 */ 9 10namespace Zend\Filter; 11 12use Traversable; 13 14class Callback extends AbstractFilter 15{ 16 /** 17 * @var array 18 */ 19 protected $options = array( 20 'callback' => null, 21 'callback_params' => array() 22 ); 23 24 /** 25 * @param callable|array|Traversable $callbackOrOptions 26 * @param array $callbackParams 27 */ 28 public function __construct($callbackOrOptions, $callbackParams = array()) 29 { 30 if (is_callable($callbackOrOptions)) { 31 $this->setCallback($callbackOrOptions); 32 $this->setCallbackParams($callbackParams); 33 } else { 34 $this->setOptions($callbackOrOptions); 35 } 36 } 37 38 /** 39 * Sets a new callback for this filter 40 * 41 * @param callable $callback 42 * @throws Exception\InvalidArgumentException 43 * @return self 44 */ 45 public function setCallback($callback) 46 { 47 if (!is_callable($callback)) { 48 throw new Exception\InvalidArgumentException( 49 'Invalid parameter for callback: must be callable' 50 ); 51 } 52 53 $this->options['callback'] = $callback; 54 return $this; 55 } 56 57 /** 58 * Returns the set callback 59 * 60 * @return callable 61 */ 62 public function getCallback() 63 { 64 return $this->options['callback']; 65 } 66 67 /** 68 * Sets parameters for the callback 69 * 70 * @param array $params 71 * @return self 72 */ 73 public function setCallbackParams($params) 74 { 75 $this->options['callback_params'] = (array) $params; 76 return $this; 77 } 78 79 /** 80 * Get parameters for the callback 81 * 82 * @return array 83 */ 84 public function getCallbackParams() 85 { 86 return $this->options['callback_params']; 87 } 88 89 /** 90 * Calls the filter per callback 91 * 92 * @param mixed $value Options for the set callable 93 * @return mixed Result from the filter which was called 94 */ 95 public function filter($value) 96 { 97 $params = (array) $this->options['callback_params']; 98 array_unshift($params, $value); 99 100 return call_user_func_array($this->options['callback'], $params); 101 } 102} 103