diff --git a/composer.json b/composer.json index 559d6389f..f6225451c 100644 --- a/composer.json +++ b/composer.json @@ -37,7 +37,7 @@ ], "require": { "php": ">= 8.1", - "loophp/iterators": "^2.4" + "loophp/iterators": "^3" }, "require-dev": { "ext-pcov": "*", diff --git a/docs/pages/api.rst b/docs/pages/api.rst index d93a15ba4..9c471339b 100644 --- a/docs/pages/api.rst +++ b/docs/pages/api.rst @@ -47,11 +47,10 @@ fromFile Create a collection from a file. -Signature: ``Collection::fromIterable(string $filepath): Collection;`` +Signature: ``Collection::fromFile(string $filepath, ?Closure $consumer = null): Collection;`` -.. code-block:: php - - Collection::fromFile('http://loripsum.net/api'); +.. literalinclude:: code/operations/fromFile.php + :language: php fromGenerator ~~~~~~~~~~~~~ diff --git a/docs/pages/code/operations/fromFile.php b/docs/pages/code/operations/fromFile.php new file mode 100644 index 000000000..1e82e0e63 --- /dev/null +++ b/docs/pages/code/operations/fromFile.php @@ -0,0 +1,18 @@ +&self + * @return CollectionInterface&self */ - public static function fromFile(string $filepath, ?int $length = 2): CollectionInterface + public static function fromFile(string $filepath, ?Closure $consumer = null): CollectionInterface { return new self( - static fn (): Generator => yield from new ResourceIteratorAggregate(fopen($filepath, 'rb'), true, $length), + static fn (): Generator => yield from new ResourceIteratorAggregate(fopen($filepath, 'rb'), true, $consumer), ); } diff --git a/src/CollectionDecorator.php b/src/CollectionDecorator.php index fd954b6b8..1356c6e7a 100644 --- a/src/CollectionDecorator.php +++ b/src/CollectionDecorator.php @@ -283,11 +283,11 @@ public static function fromCallable(callable $callable, iterable $parameters = [ } /** - * @param null|non-negative-int $length + * @param Closure(resource): mixed $consumer */ - public static function fromFile(string $filepath, ?int $length = 2): static + public static function fromFile(string $filepath, ?Closure $consumer = null): static { - return new static(Collection::fromFile($filepath, $length)); + return new static(Collection::fromFile($filepath, $consumer)); } public static function fromGenerator(Generator $generator): static diff --git a/tests/fixtures/data.csv b/tests/fixtures/data.csv new file mode 100644 index 000000000..2e8f4cae1 --- /dev/null +++ b/tests/fixtures/data.csv @@ -0,0 +1,2 @@ +a,b,c +d,e,f diff --git a/tests/unit/CollectionConstructorsTest.php b/tests/unit/CollectionConstructorsTest.php index ee0e2a507..11eed99da 100644 --- a/tests/unit/CollectionConstructorsTest.php +++ b/tests/unit/CollectionConstructorsTest.php @@ -107,6 +107,14 @@ public function testFromFileConstructor() ['a', 'b', 'c'], Collection::fromFile(__DIR__ . '/../fixtures/sample.txt') ); + + self::assertIdenticalIterable( + [['a', 'b', 'c'], ['d', 'e', 'f']], + Collection::fromFile( + __DIR__ . '/../fixtures/data.csv', + fgetcsv(...) + ) + ); } public function testFromGeneratorConstructor()