From 5014004752b30a57c8e8cb95bdc4b4288e84c64f Mon Sep 17 00:00:00 2001 From: Pol Dellaiera Date: Sat, 8 Aug 2020 08:46:13 +0200 Subject: [PATCH] Simplify the use of the Sort callback in userland. --- docs/pages/api.rst | 1 + spec/loophp/collection/CollectionSpec.php | 4 ++-- src/Operation/Sort.php | 27 ++++++++++++++--------- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/docs/pages/api.rst b/docs/pages/api.rst index 7ca7d004d..b01341a04 100644 --- a/docs/pages/api.rst +++ b/docs/pages/api.rst @@ -1069,6 +1069,7 @@ Signature: ``Collection::sort(?callable $callback = null);`` Operation\Sortable::BY_VALUES, static function ($left, $right): int { // Do the comparison here. + return $left <=> $right; } ); diff --git a/spec/loophp/collection/CollectionSpec.php b/spec/loophp/collection/CollectionSpec.php index f17995022..03c0e1630 100644 --- a/spec/loophp/collection/CollectionSpec.php +++ b/spec/loophp/collection/CollectionSpec.php @@ -1650,8 +1650,8 @@ public function it_can_sort(): void $this::fromIterable($input) ->sort( Operation\Sortable::BY_VALUES, - static function (array $left, array $right): int { - return current($right) <=> current($left); + static function ($left, $right): int { + return $right <=> $left; } ) ->shouldIterateAs(array_combine(range('A', 'E'), range('E', 'A'))); diff --git a/src/Operation/Sort.php b/src/Operation/Sort.php index 03f6f6c96..b1ca891e8 100644 --- a/src/Operation/Sort.php +++ b/src/Operation/Sort.php @@ -37,11 +37,6 @@ public function __invoke(): Closure * @psalm-return \Generator */ static function (Iterator $iterator, int $type, callable $callback): Generator { - $operations = [ - 'before' => [], - 'after' => [], - ]; - switch ($type) { case Operation\Sortable::BY_VALUES: $operations = [ @@ -62,21 +57,31 @@ static function (Iterator $iterator, int $type, callable $callback): Generator { throw new Exception('Invalid sort type.'); } + $callback = + /** + * @psalm-param array{TKey, T} $left + * @psalm-param array{TKey, T} $right + */ + static function (array $left, array $right) use ($callback): int { + return $callback(current($left), current($right)); + }; + $arrayIterator = new ArrayIterator(iterator_to_array((new Run(...$operations['before']))($iterator))); $arrayIterator->uasort($callback); - $arrayIterator = (new Run(...$operations['after']))($arrayIterator); - return yield from $arrayIterator; + return yield from (new Run(...$operations['after']))($arrayIterator); }; } /** - * @psalm-param array{TKey, T} $left + * @psalm-param T $left + * @psalm-param T $right * - * @psalm-param array{TKey, T} $right + * @param mixed $left + * @param mixed $right */ - private function compare(array $left, array $right): int + private function compare($left, $right): int { - return current($left) <=> current($right); + return $left <=> $right; } }