Skip to content

Commit

Permalink
refactor: remove length parameter
Browse files Browse the repository at this point in the history
BREAKING CHANGE: yes
  • Loading branch information
drupol committed Nov 25, 2023
1 parent 7142179 commit f9d98cc
Showing 1 changed file with 3 additions and 24 deletions.
27 changes: 3 additions & 24 deletions src/ResourceIteratorAggregate.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,29 +18,23 @@
*/
final class ResourceIteratorAggregate implements IteratorAggregate
{
/**
* @var null|non-negative-int
*/
private ?int $length = null;

/**
* @var resource
*/
private $resource;

/**
* @param false|resource $resource
* @param null|non-negative-int $length
* @param Closure(resource): T $consumer
*/
public function __construct($resource, private bool $closeResource = false, ?int $length = null, private ?Closure $consumer = null)
public function __construct($resource, private bool $closeResource = false, private ?Closure $consumer = null)
{
if (!is_resource($resource) || 'stream' !== get_resource_type($resource)) {
throw new InvalidArgumentException('Invalid resource type.');
}

$this->resource = $resource;
$this->length = $length;
$this->consumer ??= static fn ($resource): bool|string => fgetc($resource);
}

/**
Expand All @@ -49,25 +43,10 @@ public function __construct($resource, private bool $closeResource = false, ?int
public function getIterator(): Generator
{
$closeResource = $this->closeResource;
$length = $this->length;
$resource = $this->resource;

$fgetc =
/**
* @param resource $resource
*/
static fn ($resource): false|string => fgetc($resource);

$fgets =
/**
* @param resource $resource
*/
static fn ($resource): false|string => fgets($resource, $length);

$function = $this->consumer ?? ((null === $length) ? $fgetc : $fgets);

try {
while (false !== $chunk = $function($resource)) {
while ($chunk = ($this->consumer)($resource)) {
yield $chunk;
}
} finally {
Expand Down

0 comments on commit f9d98cc

Please sign in to comment.