1: <?php
2:
3: /**
4: * Jyxo PHP Library
5: *
6: * LICENSE
7: *
8: * This source file is subject to the new BSD license that is bundled
9: * with this package in the file license.txt.
10: * It is also available through the world-wide-web at this URL:
11: * https://github.com/jyxo/php/blob/master/license.txt
12: */
13:
14: /**
15: * Iterator which uses a callback or closure for filtering data.
16: *
17: * @category Jyxo
18: * @package Jyxo_Spl
19: * @copyright Copyright (c) 2005-2011 Jyxo, s.r.o.
20: * @license https://github.com/jyxo/php/blob/master/license.txt
21: * @author Jakub Tománek
22: */
23: class Jyxo_Spl_FilterIterator extends FilterIterator implements Jyxo_Spl_ArrayCopy
24: {
25: /**
26: * Callback which decides if an item is valid. Returns boolean, has one required parameter.
27: *
28: * @var Closure|callback
29: */
30: private $callback;
31:
32: /**
33: * Constructor.
34: *
35: * @param Iterator $iterator Source data
36: * @param Closure|callback $callback Filter callback
37: * @throws InvalidArgumentException Supplied callback is not callable
38: */
39: public function __construct(Iterator $iterator, $callback)
40: {
41: if (!is_callable($callback)) {
42: throw new InvalidArgumentException('Callback is not callable');
43: }
44:
45: parent::__construct($iterator);
46: $this->callback = $callback;
47: }
48:
49: /**
50: * Decides if an item is valid by calling a callback.
51: *
52: * @return boolean
53: */
54: public function accept()
55: {
56: $callback = $this->callback;
57: return $callback($this->current());
58: }
59:
60: /**
61: * Returns all filtered data as an array.
62: *
63: * @return array
64: */
65: public function toArray()
66: {
67: return iterator_to_array($this);
68: }
69: }
70: