Skip to content

Commit

Permalink
feat: add a consumer parameter to constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Nov 24, 2023
1 parent 331dc50 commit 46419a0
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/ResourceIteratorAggregate.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace loophp\iterators;

use Closure;
use Generator;
use InvalidArgumentException;
use IteratorAggregate;
Expand All @@ -28,8 +29,9 @@ final class ResourceIteratorAggregate implements IteratorAggregate
/**
* @param false|resource $resource
* @param null|non-negative-int $length
* @param Closure(resource): string $consumer
*/
public function __construct($resource, private bool $closeResource = false, ?int $length = null)
public function __construct($resource, private bool $closeResource = false, ?int $length = null, private ?Closure $consumer = null)
{
if (!is_resource($resource) || 'stream' !== get_resource_type($resource)) {
throw new InvalidArgumentException('Invalid resource type.');
Expand All @@ -52,15 +54,15 @@ public function getIterator(): Generator
/**
* @param resource $resource
*/
static fn ($resource): string|false => fgetc($resource);
static fn ($resource): false|string => fgetc($resource);

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

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

try {
while (false !== $chunk = $function($resource)) {
Expand Down

0 comments on commit 46419a0

Please sign in to comment.