Skip to content

Commit

Permalink
feat: Add fromFile static constructor.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Sep 22, 2020
1 parent 72df47a commit 7211052
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 0 deletions.
9 changes: 9 additions & 0 deletions docs/pages/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,15 @@ Create a collection from a callable.
$collection = Collection::fromCallable($callback);
fromFile
~~~~~~~~~~~~

Create a collection from a file.

.. code-block:: php
Collection::fromFile('http://loripsum.net/api');
fromIterable
~~~~~~~~~~~~

Expand Down
17 changes: 17 additions & 0 deletions docs/pages/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -894,3 +894,20 @@ Collatz conjecture
);
print_r($c->all()); // [25, 76, 38, 19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
Read a file
~~~~~~~~~~~
.. code-block:: php
<?php
declare(strict_types=1);
include 'vendor/autoload.php';
use loophp\collection\Collection;
$c = Collection::fromFile('/path/to/file')
->lines()
->count();
10 changes: 10 additions & 0 deletions spec/loophp/collection/CollectionSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,16 @@ static function ($carry, $key, $value) {
);
}

public function it_can_be_constructed_from_a_file(): void
{
$this::fromFile(__DIR__ . '/../../fixtures/sample.txt')
->shouldIterateAs([
'a',
'b',
'c',
]);
}

public function it_can_be_constructed_from_a_stream(): void
{
$string = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
Expand Down
10 changes: 10 additions & 0 deletions src/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,16 @@ static function (callable $callable, array $parameters): Generator {
);
}

public static function fromFile(string $filepath): Collection
{
return new self(
static function (string $filepath): Generator {
return yield from new ResourceIterator(fopen($filepath, 'rb'));
},
$filepath
);
}

public static function fromIterable(iterable $iterable): Collection
{
return new self(
Expand Down

0 comments on commit 7211052

Please sign in to comment.