| 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 */ |
| 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 | * @phpcs:ignore MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam |
| 40 | * @param array|object $array |
| 41 | */ |
| 42 | public function __construct( $array = [] ) { |
| 43 | if ( is_array( $array ) ) { |
| 44 | $this->array = $array; |
| 45 | } elseif ( is_object( $array ) ) { |
| 46 | $this->array = get_object_vars( $array ); |
| 47 | } else { |
| 48 | throw new InvalidArgumentException( __METHOD__ . ' requires an array or object' ); |
| 49 | } |
| 50 | |
| 51 | $this->rewind(); |
| 52 | } |
| 53 | |
| 54 | #[\ReturnTypeWillChange] |
| 55 | public function current() { |
| 56 | return current( $this->array ); |
| 57 | } |
| 58 | |
| 59 | #[\ReturnTypeWillChange] |
| 60 | public function key() { |
| 61 | return key( $this->array ); |
| 62 | } |
| 63 | |
| 64 | public function next(): void { |
| 65 | prev( $this->array ); |
| 66 | } |
| 67 | |
| 68 | public function rewind(): void { |
| 69 | end( $this->array ); |
| 70 | } |
| 71 | |
| 72 | public function valid(): bool { |
| 73 | return key( $this->array ) !== null; |
| 74 | } |
| 75 | |
| 76 | public function count(): int { |
| 77 | return count( $this->array ); |
| 78 | } |
| 79 | } |