1<?php
2/**
3 * Iterator for arrays requiring filtered values
4 *
5 * @package Requests\Utilities
6 */
7
8namespace WpOrg\Requests\Utility;
9
10use ArrayIterator;
11use ReturnTypeWillChange;
12use WpOrg\Requests\Exception\InvalidArgument;
13use WpOrg\Requests\Utility\InputValidator;
14
15/**
16 * Iterator for arrays requiring filtered values
17 *
18 * @package Requests\Utilities
19 */
20final class FilteredIterator extends ArrayIterator {
21 /**
22 * Callback to run as a filter
23 *
24 * @var callable
25 */
26 private $callback;
27
28 /**
29 * Create a new iterator
30 *
31 * @param array $data The array or object to be iterated on.
32 * @param callable $callback Callback to be called on each value
33 *
34 * @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $data argument is not iterable.
35 */
36 public function __construct($data, $callback) {
37 if (InputValidator::is_iterable($data) === false) {
38 throw InvalidArgument::create(1, '$data', 'iterable', gettype($data));
39 }
40
41 parent::__construct($data);
42
43 if (is_callable($callback)) {
44 $this->callback = $callback;
45 }
46 }
47
48 /**
49 * Prevent unserialization of the object for security reasons.
50 *
51 * @phpcs:disable PHPCompatibility.FunctionNameRestrictions.NewMagicMethods.__unserializeFound
52 *
53 * @param array $data Restored array of data originally serialized.
54 *
55 * @return void
56 */
57 #[ReturnTypeWillChange]
58 public function __unserialize($data) {}
59 // phpcs:enable
60
61 /**
62 * Perform reinitialization tasks.
63 *
64 * Prevents a callback from being injected during unserialization of an object.
65 *
66 * @return void
67 */
68 public function __wakeup() {
69 unset($this->callback);
70 }
71
72 /**
73 * Get the current item's value after filtering
74 *
75 * @return string
76 */
77 #[ReturnTypeWillChange]
78 public function current() {
79 $value = parent::current();
80
81 if (is_callable($this->callback)) {
82 $value = call_user_func($this->callback, $value);
83 }
84
85 return $value;
86 }
87
88 /**
89 * Prevent creating a PHP value from a stored representation of the object for security reasons.
90 *
91 * @param string $data The serialized string.
92 *
93 * @return void
94 */
95 #[ReturnTypeWillChange]
96 public function unserialize($data) {}
97}
98