rosstuck/sort

generic chain sort

Opened this issue · 0 comments

Good job man php is terrible with sorting.
Maybe you should add some general generic method for sorting.
I had to extend your class for ordering collection of objects with:

class Sort extends \Tuck\Sort\Sort {
    const ASC = "asc";
    const DESC = "desc";

    static function chainGeneric(array $keysOrder = []) : SortChain {
        $sortChain = self::chain();
        foreach ($keysOrder as $key => $order) {
            if ($order == self::ASC) {
                $sortChain = $sortChain->asc(function ($item) use ($key) {
                    return $item[$key] ?? null;
                });
            } else if ($order == self::DESC) {
                $sortChain = $sortChain->desc(function ($item) use ($key) {
                    return $item[$key] ?? null;
                });
            }
        }

        return $sortChain;
    }
}

invoke

$sorter = Sort::chainGeneric([ 'apples' => 'asc', 'lemons' => 'desc']);