Skip to content

Commit 52f84d0

Browse files
authored
Count collections more efficiently in the length modifier (statamic#5802)
1 parent ba39fed commit 52f84d0

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

src/Modifiers/CoreModifiers.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use ArrayAccess;
66
use Carbon\Carbon;
7+
use Countable;
78
use Illuminate\Contracts\Support\Arrayable;
89
use Illuminate\Support\Collection;
910
use Statamic\Contracts\Assets\Asset as AssetContract;
@@ -1279,7 +1280,7 @@ public function lcfirst($value)
12791280
*/
12801281
public function length($value)
12811282
{
1282-
if (Compare::isQueryBuilder($value)) {
1283+
if (Compare::isQueryBuilder($value) || $value instanceof Countable) {
12831284
return $value->count();
12841285
}
12851286

tests/Modifiers/LengthTest.php

+44
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
namespace Tests\Modifiers;
44

5+
use Illuminate\Contracts\Support\Arrayable;
6+
use Mockery;
7+
use Statamic\Contracts\Query\Builder;
58
use Statamic\Modifiers\Modify;
69
use Tests\TestCase;
710

@@ -19,6 +22,36 @@ public function it_returns_the_numbers_of_items_in_array(): void
1922
$this->assertSame(3, $modified);
2023
}
2124

25+
/** @test */
26+
public function it_returns_the_numbers_of_items_in_collection(): void
27+
{
28+
$arr = collect([
29+
'Taylor Swift',
30+
'Left Shark',
31+
'Leroy Jenkins',
32+
]);
33+
$modified = $this->modify($arr);
34+
$this->assertSame(3, $modified);
35+
}
36+
37+
/** @test */
38+
public function it_returns_the_number_of_items_in_a_query()
39+
{
40+
$builder = Mockery::mock(Builder::class);
41+
$builder->shouldReceive('count')->once()->andReturn(3);
42+
$modified = $this->modify($builder);
43+
$this->assertSame(3, $modified);
44+
}
45+
46+
/** @test */
47+
public function it_returns_the_number_of_items_in_an_arrayable()
48+
{
49+
$arrayable = Mockery::mock(Arrayable::class)->shouldReceive('toArray')->andReturn(['one', 'two'])->getMock();
50+
51+
$modified = $this->modify($arrayable);
52+
$this->assertSame(2, $modified);
53+
}
54+
2255
/** @test */
2356
public function it_returns_the_numbers_of_chars_in_string(): void
2457
{
@@ -27,6 +60,17 @@ public function it_returns_the_numbers_of_chars_in_string(): void
2760
$this->assertSame(27, $modified);
2861
}
2962

63+
/** @test */
64+
public function it_counts_a_collection_instead_of_toarraying_it(): void
65+
{
66+
$itemOne = Mockery::mock(Arrayable::class)->shouldNotReceive('toArray')->getMock();
67+
$itemTwo = Mockery::mock(Arrayable::class)->shouldNotReceive('toArray')->getMock();
68+
69+
$arr = collect([$itemOne, $itemTwo]);
70+
$modified = $this->modify($arr);
71+
$this->assertSame(2, $modified);
72+
}
73+
3074
private function modify($value)
3175
{
3276
return Modify::value($value)->length()->fetch();

0 commit comments

Comments
 (0)