Athari / YaLinqo

Yet Another LINQ to Objects for PHP [Simplified BSD]
https://athari.github.io/YaLinqo
BSD 2-Clause "Simplified" License
441 stars 39 forks source link

Custom comparer in orderBy is ignored if key selector is cached #59

Open dima-stefantsov opened 2 years ago

dima-stefantsov commented 2 years ago

Using latest "composer require athari/yalinqo", v2.4.2

<?php

require 'vendor/autoload.php';

$qwe = [
    'key3' => 3,
    'key2' => 1,
    'key1' => 2
];

$asd =
    from($qwe)->
    orderBy(
        // #1
        function($v, $k) {
            return $k;
        },

        // #2
        // '$k',

        // #3
        // YaLinqo\Functions::$key,
    function($a, $b) {
        echo "in\n";
        return $b <=> $a;
    })->
    toArray();

var_dump($asd);

Hi Alexander. If I run code like shown, with key_selector#1, I can see "echo in\n" executed, like expected. But If I run code with key_selector#2 or key_selector#3, I never see "echo in\n" executed, $comparer is never executed. Sorting still works, but not with my custom comparer, just by alphabet.

I've digged into the sources, and I've found vendor\athari\yalinqo\YaLinqo\OrderedEnumerable.php:127

trySortBySingleField:
  elseif ($this->keySelector === Functions::$key)
    elseif ($this->sortOrder == SORT_ASC) {
      ksort($array, $this->sortFlags);

If your code found current key selector function is the one from the cache, it never even tries to run provided custom comparer function.

I expect orderBy to always run comparer function if it is present. Thank you.