ResourceIteratorAggregate::getIterator()   A
last analyzed

Complexity

Conditions 3
Paths 8

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 8
c 1
b 0
f 0
nc 8
nop 0
dl 0
loc 12
ccs 7
cts 7
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
16
use function is_resource;
17
18
/**
19
 * @implements IteratorAggregate<int, string>
20
 */
21
final class ResourceIteratorAggregate implements IteratorAggregate
22
{
23
    /**
24
     * @var resource
25
     */
26
    private $resource;
27
28
    /**
29
     * @param false|resource $resource
30
     */
31 5
    public function __construct($resource, private bool $closeResource = false)
32
    {
33 5
        if (!is_resource($resource) || 'stream' !== get_resource_type($resource)) {
34 2
            throw new InvalidArgumentException('Invalid resource type.');
35
        }
36
37 3
        $this->resource = $resource;
38
    }
39
40
    /**
41
     * @return Generator<int, string>
42
     */
43 3
    public function getIterator(): Generator
44
    {
45 3
        $resource = $this->resource;
46 3
        $closeResource = $this->closeResource;
47
48
        try {
49 3
            while (false !== $chunk = fgetc($resource)) {
50 3
                yield $chunk;
51
            }
52
        } finally {
53 3
            if ($closeResource) {
54 1
                fclose($resource);
55
            }
56
        }
57
    }
58
}
59