Skip to content

Commit 1109a47

Browse files
committed
Add Collection.size function
1 parent 83e9291 commit 1109a47

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed

src/Collection/size.php

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/*
6+
* This file is part of the SolidWorx Lodash-PHP project.
7+
*
8+
* @author Pierre du Plessis <open-source@solidworx.co>
9+
* @copyright Copyright (c) 2017
10+
*/
11+
12+
namespace _;
13+
14+
/**
15+
* Gets the size of `collection` by returning its length for array
16+
* values or the number of public properties for objects.
17+
*
18+
* @category Collection
19+
*
20+
* @param array|object|string $collection The collection to inspect.
21+
*
22+
* @return int Returns the collection size.
23+
* @example
24+
*
25+
* size([1, 2, 3]);
26+
* // => 3
27+
*
28+
* size(new class { public $a = 1; public $b = 2; private $c = 3; });
29+
* // => 2
30+
*
31+
* size('pebbles');
32+
* // => 7
33+
*/
34+
function size($collection): int
35+
{
36+
if (\is_string($collection)) {
37+
return \strlen($collection);
38+
}
39+
40+
if (\is_array($collection) || $collection instanceof \Countable) {
41+
return \count($collection);
42+
}
43+
44+
if ($collection instanceof \Traversable) {
45+
return \count(\iterator_to_array($collection));
46+
}
47+
48+
if (\is_object($collection)) {
49+
return \count(\get_object_vars($collection));
50+
}
51+
52+
return 0;
53+
}

tests/Collection/SizeTest.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/*
6+
* This file is part of the SolidWorx Lodash-PHP project.
7+
*
8+
* @author Pierre du Plessis <open-source@solidworx.co>
9+
* @copyright Copyright (c) 2017
10+
*/
11+
12+
use PHPUnit\Framework\TestCase;
13+
use function _\size;
14+
15+
class SizeTest extends TestCase
16+
{
17+
public function testSize()
18+
{
19+
$this->assertSame(3, size([1, 2, 3]));
20+
$this->assertSame(2, size(new class
21+
{
22+
public $a = 1;
23+
24+
public $b = 2;
25+
26+
private $c = 3;
27+
}));
28+
29+
$this->assertSame(12, size(new class implements \Countable
30+
{
31+
public function count() { return 12; }
32+
}));
33+
34+
$this->assertSame(4, size(new \ArrayIterator([1, 2, 3, 4])));
35+
36+
$this->assertSame(7, size('pebbles'));
37+
}
38+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy