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

ResourceIteratorAggregate   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 42
ccs 16
cts 16
cp 1
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 3
A getIterator() 0 20 3
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