Skip to content

Commit

Permalink
feat: let this iterator use fgets when needed.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Sep 1, 2023
1 parent b16881d commit 45e1fdf
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions src/ResourceIteratorAggregate.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,33 +20,55 @@
*/
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
*/
public function __construct($resource, private bool $closeResource = false)
public function __construct($resource, private bool $closeResource = false, ?int $length = null)
{
if (!is_resource($resource) || 'stream' !== get_resource_type($resource)) {
throw new InvalidArgumentException('Invalid resource type.');
}

$this->resource = $resource;
$this->length = $length;
}

/**
* @return Generator<int, string>
*/
public function getIterator(): Generator
{
$resource = $this->resource;
$closeResource = $this->closeResource;
$length = $this->length;
$resource = $this->resource;

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

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

$function = (null === $length) ? $fgetc : $fgets;

try {
while (false !== $chunk = fgetc($resource)) {
while (false !== $chunk = $function($resource)) {
yield $chunk;
}
} finally {
Expand Down

0 comments on commit 45e1fdf

Please sign in to comment.