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