18
18
*/
19
19
final class ResourceIteratorAggregate implements IteratorAggregate
20
20
{
21
- /**
22
- * @var null|non-negative-int
23
- */
24
- private ?int $ length = null ;
25
-
26
21
/**
27
22
* @var resource
28
23
*/
29
24
private $ resource ;
30
25
31
26
/**
32
27
* @param false|resource $resource
33
- * @param null|non-negative-int $length
34
28
* @param Closure(resource): T $consumer
35
29
*/
36
- public function __construct ($ resource , private bool $ closeResource = false , ? int $ length = null , private ?Closure $ consumer = null )
30
+ public function __construct ($ resource , private bool $ closeResource = false , private ?Closure $ consumer = null )
37
31
{
38
32
if (!is_resource ($ resource ) || 'stream ' !== get_resource_type ($ resource )) {
39
33
throw new InvalidArgumentException ('Invalid resource type. ' );
40
34
}
41
35
42
36
$ this ->resource = $ resource ;
43
- $ this ->length = $ length ;
37
+ $ this ->consumer ??= static fn ( $ resource ): bool | string => fgetc ( $ resource ) ;
44
38
}
45
39
46
40
/**
@@ -49,25 +43,10 @@ public function __construct($resource, private bool $closeResource = false, ?int
49
43
public function getIterator (): Generator
50
44
{
51
45
$ closeResource = $ this ->closeResource ;
52
- $ length = $ this ->length ;
53
46
$ resource = $ this ->resource ;
54
47
55
- $ fgetc =
56
- /**
57
- * @param resource $resource
58
- */
59
- static fn ($ resource ): false |string => fgetc ($ resource );
60
-
61
- $ fgets =
62
- /**
63
- * @param resource $resource
64
- */
65
- static fn ($ resource ): false |string => fgets ($ resource , $ length );
66
-
67
- $ function = $ this ->consumer ?? ((null === $ length ) ? $ fgetc : $ fgets );
68
-
69
48
try {
70
- while (false !== $ chunk = $ function ($ resource )) {
49
+ while ($ chunk = ( $ this -> consumer ) ($ resource )) {
71
50
yield $ chunk ;
72
51
}
73
52
} finally {
0 commit comments