1 <?php
2 /**
3 * Part of the Joomla Framework Compat Package
4 *
5 * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
6 * @license GNU General Public License version 2 or later; see LICENSE
7 */
8
9 /**
10 * CallbackFilterIterator using the callback to determine which items are accepted or rejected.
11 *
12 * @link http://php.net/manual/en/class.callbackfilteriterator.php
13 * @since 1.2.0
14 */
15 class CallbackFilterIterator extends \FilterIterator
16 {
17 /**
18 * The callback to check value.
19 *
20 * @var callable
21 *
22 * @since 1.2.0
23 */
24 protected $callback = null;
25
26 /**
27 * Creates a filtered iterator using the callback to determine
28 * which items are accepted or rejected.
29 *
30 * @param \Iterator $iterator The iterator to be filtered.
31 * @param callable $callback The callback, which should return TRUE to accept the current item
32 * or FALSE otherwise. May be any valid callable value.
33 * The callback should accept up to three arguments: the current item,
34 * the current key and the iterator, respectively.
35 * ``` php
36 * function my_callback($current, $key, $iterator)
37 * ```
38 *
39 * @throws InvalidArgumentException
40 *
41 * @since 1.2.0
42 */
43 public function __construct(\Iterator $iterator, $callback)
44 {
45 if (!is_callable($callback))
46 {
47 throw new \InvalidArgumentException("Argument 2 of CallbackFilterIterator should be callable.");
48 }
49
50 $this->callback = $callback;
51
52 parent::__construct($iterator);
53 }
54
55 /**
56 * This method calls the callback with the current value, current key and the inner iterator.
57 * The callback is expected to return TRUE if the current item is to be accepted, or FALSE otherwise.
58 *
59 * @link http://www.php.net/manual/en/callbackfilteriterator.accept.php
60 *
61 * @return boolean True if the current element is acceptable, otherwise false.
62 *
63 * @since 1.2.0
64 */
65 public function accept()
66 {
67 $inner = $this->getInnerIterator();
68
69 return call_user_func_array(
70 $this->callback,
71 array(
72 $inner->current(),
73 $inner->key(),
74 $inner
75 )
76 );
77 }
78 }
79