Passed
Push — main ( 076cfe...124d4b )
by Pol
03:34
created

ResourceIteratorAggregate::__construct()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 3
rs 10
1
<?php
2
3
/**
4
 * For the full copyright and license information, please view
5
 * the LICENSE file that was distributed with this source code.
6
 */
7
8
declare(strict_types=1);
9
10
namespace loophp\iterators;
11
12
use Generator;
13
use InvalidArgumentException;
14
use IteratorAggregate;
15
use Traversable;
16
17
use function is_resource;
18
19
/**
20
 * @implements IteratorAggregate<int, string>
21
 */
22
final class ResourceIteratorAggregate implements IteratorAggregate
23
{
24
    private bool $closeResource;
25
26
    /**
27
     * @var resource
28
     */
29
    private $resource;
30
31
    /**
32
     * @param false|resource $resource
33
     */
34 5
    public function __construct($resource, bool $closeResource = false)
35
    {
36 5
        if (!is_resource($resource) || 'stream' !== get_resource_type($resource)) {
37 2
            throw new InvalidArgumentException('Invalid resource type.');
38
        }
39
40 3
        $this->resource = $resource;
41 3
        $this->closeResource = $closeResource;
42 3
    }
43
44 3
    public function getIterator(): Traversable
45
    {
46 3
        yield from new ClosureIteratorAggregate(
47
            /**
48
             * @param resource $resource
49
             *
50
             * @return Generator<int, string, mixed, void>
51
             */
52 3
            static function ($resource, bool $closeResource = false): Generator {
53
                try {
54 3
                    while (false !== $chunk = fgetc($resource)) {
55 3
                        yield $chunk;
56
                    }
57 3
                } finally {
58 3
                    if ($closeResource) {
59 3
                        fclose($resource);
60
                    }
61
                }
62 3
            },
63 3
            [$this->resource, $this->closeResource]
64
        );
65 3
    }
66
}
67