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: namespace Jyxo\Spl;
15:
16: /**
17: * Iterator which uses a callback or closure for filtering data.
18: *
19: * @category Jyxo
20: * @package Jyxo\Spl
21: * @copyright Copyright (c) 2005-2011 Jyxo, s.r.o.
22: * @license https://github.com/jyxo/php/blob/master/license.txt
23: * @author Jakub Tománek
24: */
25: class FilterIterator extends \FilterIterator implements \Jyxo\Spl\ArrayCopy
26: {
27: /**
28: * Callback which decides if an item is valid. Returns boolean, has one required parameter.
29: *
30: * @var \Closure|callback
31: */
32: private $callback;
33:
34: /**
35: * Constructor.
36: *
37: * @param \Iterator $iterator Source data
38: * @param \Closure|callback $callback Filter callback
39: * @throws \InvalidArgumentException Supplied callback is not callable
40: */
41: public function __construct(\Iterator $iterator, $callback)
42: {
43: if (!is_callable($callback)) {
44: throw new \InvalidArgumentException('Callback is not callable');
45: }
46:
47: parent::__construct($iterator);
48: $this->callback = $callback;
49: }
50:
51: /**
52: * Decides if an item is valid by calling a callback.
53: *
54: * @return boolean
55: */
56: public function accept()
57: {
58: $callback = $this->callback;
59: return $callback($this->current());
60: }
61:
62: /**
63: * Returns all filtered data as an array.
64: *
65: * @return array
66: */
67: public function toArray()
68: {
69: return iterator_to_array($this);
70: }
71: }
72: