1 | <?php |
||
31 | trait IsReadable |
||
32 | { |
||
33 | /** |
||
34 | * Read single line. |
||
35 | * Read the next line from the file (moving the internal pointer down a line). |
||
36 | * Returns multiple lines if newline character(s) fall within a quoted string. |
||
37 | * |
||
38 | * @param string|array $eol A string or array of strings to be used as EOL char/sequence |
||
39 | * @param int $maxLength Maximum number of bytes to return (line will be truncated to this -1 if set) |
||
40 | * |
||
41 | * @throws IOException |
||
42 | * |
||
43 | * @return string A single line read from the file. |
||
44 | * |
||
45 | * @todo Should this add a newline if maxlength is reached? |
||
46 | * @todo I could actually buffer this by reading x chars at a time and doing |
||
47 | * the same thing with looping char by char if this is too IO intensive. |
||
48 | */ |
||
49 | 25 | public function readLine($eol = PHP_EOL, $maxLength = null) |
|
50 | { |
||
51 | 25 | $size = 0; |
|
52 | 25 | $buffer = false; |
|
53 | 25 | if (!is_array($eol)) { |
|
54 | 24 | $eol = [$eol]; |
|
55 | 24 | } |
|
56 | 25 | while (!$this->eof()) { |
|
57 | // Using a loose equality here to match on '' and false. |
||
58 | 25 | if (null == ($byte = $this->read(1))) { |
|
59 | 4 | return $buffer; |
|
60 | } |
||
61 | 25 | $buffer .= $byte; |
|
62 | // Break when a new line is found or the max length - 1 is reached |
||
63 | 25 | if (array_reduce($eol, function ($carry, $eol) use ($buffer) { |
|
64 | 25 | if (!$carry) { |
|
65 | 25 | $eollen = 0 - strlen($eol); |
|
66 | |||
67 | 25 | return substr($buffer, $eollen) === $eol; |
|
68 | } |
||
69 | |||
70 | 1 | return true; |
|
71 | 25 | }, false) || ++$size === $maxLength - 1) { |
|
72 | 23 | break; |
|
73 | } |
||
74 | 25 | } |
|
75 | |||
76 | 24 | return $buffer; |
|
77 | } |
||
78 | |||
79 | abstract public function isReadable(); |
||
80 | |||
81 | abstract public function read($length); |
||
82 | |||
83 | abstract public function eof(); |
||
84 | |||
85 | /** |
||
86 | * Assert that this file/stream object is readable. |
||
87 | * |
||
88 | * @throws IOException |
||
89 | */ |
||
90 | 51 | protected function assertIsReadable() |
|
96 | } |
||
97 |