Page Menu
Home
DevCentral
Search
Configure Global Search
Log In
Files
F4020274
D1632.diff
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
2 KB
Referenced Files
None
Subscribers
None
D1632.diff
View Options
diff --git a/src/Collections/TraversableUtilities.php b/src/Collections/TraversableUtilities.php
new file mode 100644
--- /dev/null
+++ b/src/Collections/TraversableUtilities.php
@@ -0,0 +1,27 @@
+<?php
+declare(strict_types=1);
+
+namespace Keruald\OmniTools\Collections;
+
+use Countable;
+use TypeError;
+
+class TraversableUtilities {
+
+ public static function count ($countable) : int {
+ if (is_array($countable)) {
+ return count($countable);
+ }
+
+ if ($countable instanceof Countable) {
+ return $countable->count();
+ }
+
+ if ($countable === null || $countable === false) {
+ return 0;
+ }
+
+ throw new TypeError;
+ }
+
+}
diff --git a/tests/Collections/TraversableUtilitiesTest.php b/tests/Collections/TraversableUtilitiesTest.php
new file mode 100644
--- /dev/null
+++ b/tests/Collections/TraversableUtilitiesTest.php
@@ -0,0 +1,55 @@
+<?php
+declare(strict_types=1);
+
+namespace Keruald\OmniTools\Tests\Collections;
+
+use Keruald\OmniTools\Collections\TraversableUtilities;
+use PHPUnit\Framework\TestCase;
+
+use Countable;
+
+class TraversableUtilitiesTest extends TestCase {
+
+ /**
+ * @dataProvider provideCountables
+ */
+ public function testCount ($expectedCount, $countable) {
+ $this->assertEquals(
+ $expectedCount, TraversableUtilities::count($countable)
+ );
+ }
+
+ /**
+ * @dataProvider provideNotCountables
+ */
+ public function testCountWithNotCountables ($notCountable) {
+ $this->expectException("TypeError");
+ TraversableUtilities::count($notCountable);
+ }
+
+ ///
+ /// Data providers
+ ///
+
+ public function provideCountables () : iterable {
+ yield [0, null];
+ yield [0, false];
+ yield [0, []];
+ yield [3, ["a", "b", "c"]];
+ yield [42, new class implements Countable {
+ public function count () : int {
+ return 42;
+ }
+ }
+ ];
+ }
+
+ public function provideNotCountables () : iterable {
+ yield [true];
+ yield [new \stdClass];
+ yield [0];
+ yield [""];
+ yield ["abc"];
+ }
+
+}
File Metadata
Details
Attached
Mime Type
text/plain
Expires
Mon, Jan 20, 03:12 (20 h, 46 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2360807
Default Alt Text
D1632.diff (2 KB)
Attached To
Mode
D1632: Allow to count "null" and "false" values
Attached
Detach File
Event Timeline
Log In to Comment