Skip to content

Commit

Permalink
Add takeUntilTimeout method to the lazy collection
Browse files Browse the repository at this point in the history
  • Loading branch information
JosephSilber committed Sep 18, 2020
1 parent 5f78c90 commit 0aabf24
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/Illuminate/Collections/LazyCollection.php
Expand Up @@ -4,6 +4,7 @@

use ArrayIterator;
use Closure;
use DateTime;
use Illuminate\Support\Traits\EnumeratesValues;
use Illuminate\Support\Traits\Macroable;
use IteratorAggregate;
Expand Down Expand Up @@ -1213,6 +1214,21 @@ public function takeUntil($value)
});
}

/**
* Take items in the collection until it reaches the given time.
*
* @param \DateTime $timeout
* @return static
*/
public function takeUntilTimeout(DateTime $timeout)
{
$timeout = $timeout->getTimestamp();

return $this->takeWhile(function () use ($timeout) {
return $this->now() < $timeout;
});
}

/**
* Take items in the collection while the given condition is met.
*
Expand Down Expand Up @@ -1385,4 +1401,14 @@ protected function passthru($method, array $params)
yield from $this->collect()->$method(...$params);
});
}

/**
* Get the current time.
*
* @return int
*/
protected function now()
{
return time();
}
}
32 changes: 32 additions & 0 deletions tests/Support/SupportLazyCollectionTest.php
Expand Up @@ -2,8 +2,10 @@

namespace Illuminate\Tests\Support;

use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\LazyCollection;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class SupportLazyCollectionTest extends TestCase
Expand Down Expand Up @@ -154,6 +156,36 @@ public function testRememberWithDuplicateKeys()
$this->assertSame([['key', 1], ['key', 2]], $results);
}

public function testTakeUntilTimeout()
{
$timeout = Carbon::now();

$mock = m::mock(LazyCollection::class.'[now]');

$results = $mock
->times(10)
->pipe(function ($collection) use ($mock, $timeout) {
tap($collection)
->mockery_init($mock->mockery_getContainer())
->shouldAllowMockingProtectedMethods()
->shouldReceive('now')
->times(3)
->andReturn(
(clone $timeout)->sub(2, 'minute')->getTimestamp(),
(clone $timeout)->sub(1, 'minute')->getTimestamp(),
$timeout->getTimestamp()
);

return $collection;
})
->takeUntilTimeout($timeout)
->all();

$this->assertSame([1, 2], $results);

m::close();
}

public function testTapEach()
{
$data = LazyCollection::times(10);
Expand Down

0 comments on commit 0aabf24

Please sign in to comment.