Completed
Pull Request — master (#48)
by Frederik
05:48
created

LineIterator::newIterator()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.5125
c 0
b 0
f 0
cc 6
eloc 14
nc 4
nop 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Genkgo\Mail\Stream;
5
6
use Genkgo\Mail\StreamInterface;
7
8
final class LineIterator extends \IteratorIterator
9
{
10
    /**
11
     * @param StreamInterface $stream
12
     */
13
    public function __construct(StreamInterface $stream)
14
    {
15
        parent::__construct($this->newIterator($stream));
16
    }
17
18
    /**
19
     * @param StreamInterface $stream
20
     * @return \Generator
21
     */
22
    private function newIterator(StreamInterface $stream): \Generator
23
    {
24
        $stream->rewind();
25
26
        $bytes = '';
27
        while (!$stream->eof()) {
28
            $bytes .= $stream->read(1000);
29
30
            $index = 0;
31
            while (isset($bytes[$index])) {
32
                if ($bytes[$index] === "\r" && isset($bytes[$index + 1]) && $bytes[$index + 1] === "\n") {
33
                    $line = \substr($bytes, 0, $index);
34
                    $bytes = \substr($bytes, $index + 2);
35
                    $index = -1;
36
37
                    yield $line;
38
                }
39
40
                $index++;
41
            }
42
        }
43
44
        yield $bytes;
45
    }
46
}
47