3 * @copyright Copyright (C) 2021, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Util;
26 * An iterator which returns lines from file in reversed order
28 * original code https://stackoverflow.com/a/10494801
30 class ReversedFileReader implements \Iterator
32 const BUFFER_SIZE = 4096;
33 const SEPARATOR = "\n";
50 public function __construct($filename)
52 $this->_fh = fopen($filename, 'r');
54 // this should use a custom exception.
55 throw \Exception("Unable to open $filename");
57 $this->filesize = filesize($filename);
64 public function _read($size)
67 fseek($this->_fh, $this->pos);
68 return fread($this->_fh, $size);
71 public function _readline()
73 $buffer =& $this->buffer;
75 if ($this->pos == 0) {
76 return array_pop($buffer);
78 if (count($buffer) > 1) {
79 return array_pop($buffer);
81 $buffer = explode(self::SEPARATOR, $this->_read(self::BUFFER_SIZE) . $buffer[0]);
85 public function next()
88 $this->value = $this->_readline();
91 public function rewind()
93 if ($this->filesize > 0) {
94 $this->pos = $this->filesize;
97 $this->buffer = explode(self::SEPARATOR, $this->_read($this->filesize % self::BUFFER_SIZE ?: self::BUFFER_SIZE));
102 public function key()
107 public function current()
112 public function valid()
114 return ! is_null($this->value);