|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Convenience class for iterating over an array in reverse order. |
|
4
|
|
|
* |
|
5
|
|
|
* This program is free software; you can redistribute it and/or modify |
|
6
|
|
|
* it under the terms of the GNU General Public License as published by |
|
7
|
|
|
* the Free Software Foundation; either version 2 of the License, or |
|
8
|
|
|
* (at your option) any later version. |
|
9
|
|
|
* |
|
10
|
|
|
* This program is distributed in the hope that it will be useful, |
|
11
|
|
|
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12
|
|
|
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
13
|
|
|
* GNU General Public License for more details. |
|
14
|
|
|
* |
|
15
|
|
|
* You should have received a copy of the GNU General Public License along |
|
16
|
|
|
* with this program; if not, write to the Free Software Foundation, Inc., |
|
17
|
|
|
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
|
18
|
|
|
* http://www.gnu.org/copyleft/gpl.html |
|
19
|
|
|
* |
|
20
|
|
|
* @file |
|
21
|
|
|
* @since 1.27 |
|
22
|
|
|
*/ |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Convenience class for iterating over an array in reverse order. |
|
26
|
|
|
* |
|
27
|
|
|
* @since 1.27 |
|
28
|
|
|
*/ |
|
29
|
|
|
class ReverseArrayIterator implements Iterator, Countable { |
|
30
|
|
|
/** @var array $array */ |
|
31
|
|
|
protected $array; |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* Creates an iterator which will visit the keys in $array in |
|
35
|
|
|
* reverse order. If given an object, will visit the properties |
|
36
|
|
|
* of the object in reverse order. (Note that the default order |
|
37
|
|
|
* for PHP arrays and objects is declaration/assignment order.) |
|
38
|
|
|
* |
|
39
|
|
|
* @param array|object $array |
|
40
|
|
|
*/ |
|
41
|
|
|
public function __construct( $array = [] ) { |
|
42
|
|
|
if ( is_array( $array ) ) { |
|
43
|
|
|
$this->array = $array; |
|
44
|
|
|
} elseif ( is_object( $array ) ) { |
|
45
|
|
|
$this->array = get_object_vars( $array ); |
|
46
|
|
|
} else { |
|
47
|
|
|
throw new InvalidArgumentException( __METHOD__ . ' requires an array or object' ); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
$this->rewind(); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
public function current() { |
|
54
|
|
|
return current( $this->array ); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
public function key() { |
|
58
|
|
|
return key( $this->array ); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
public function next() { |
|
62
|
|
|
prev( $this->array ); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
public function rewind() { |
|
66
|
|
|
end( $this->array ); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
public function valid() { |
|
70
|
|
|
return key( $this->array ) !== null; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
public function count() { |
|
74
|
|
|
return count( $this->array ); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|