diff --git a/CHANGELOG.md b/CHANGELOG.md index d2b9917..c51eacd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ * Fixed functions, projections and equality to read array-like objects by their elements. * Fixed list functions and flatten to accept array-like objects. * Fixed empty array-like objects to be falsy. +* Fixed length() and reverse() to read objects with __toString() as strings. * Changed array-like objects that are not Traversable to error when their elements are listed. ## 2.10.0 - 2026-11-17 diff --git a/src/FnDispatcher.php b/src/FnDispatcher.php index 8758fac..d789ee0 100644 --- a/src/FnDispatcher.php +++ b/src/FnDispatcher.php @@ -119,8 +119,8 @@ private function fn_length(array $args) { $this->validateArity('length', count($args), 1); $this->validateType('length:0', $args[0], ['string', 'array', 'object']); - return is_string($args[0]) - ? mb_strlen($args[0], 'UTF-8') + return Utils::type($args[0]) === 'string' + ? mb_strlen((string) $args[0], 'UTF-8') : count($args[0] instanceof \Countable ? $args[0] : (array) $args[0]); } @@ -185,11 +185,9 @@ private function fn_reverse(array $args) $this->validate('reverse', $args, [['array', 'string']]); if (is_array($args[0])) { return array_reverse($args[0]); - } elseif (is_string($args[0])) { - return implode('', array_reverse(mb_str_split($args[0], 1, 'UTF-8'))); - } else { - throw new \RuntimeException('Cannot reverse provided argument'); } + + return implode('', array_reverse(mb_str_split((string) $args[0], 1, 'UTF-8'))); } private function fn_sum(array $args) diff --git a/tests/FnDispatcherTest.php b/tests/FnDispatcherTest.php index b02e034..ce83ce2 100644 --- a/tests/FnDispatcherTest.php +++ b/tests/FnDispatcherTest.php @@ -232,6 +232,15 @@ public function testMaxComparesStringableObjectsByCodePoint(): void $this->assertSame($low, $fn('min', [[$low, $high]])); } + public function testLengthAndReverseReadStringableObjectsAsStrings(): void + { + $fn = new FnDispatcher(); + $value = new _TestComparableString('héllo'); + + $this->assertSame(5, $fn('length', [$value])); + $this->assertSame('olléh', $fn('reverse', [$value])); + } + public function testSortComparesNumbersNumerically(): void { $fn = FnDispatcher::getInstance();