Sort by type

@param array|object $collection
@param array $types
@return array
979757
public function sortByType($collection, $types)
    {
        if ($collection instanceof \Traversable) {
            $collection = iterator_to_array($collection);
        }

        // store a map of the original sorting, so the usort can use this to keep the original sorting if the types are
        // equal
        $idToIndexMap = array();
        foreach ($collection as $index => $item) {
            $idToIndexMap[$item->getId()] = $index;
        }

        $numTypes = count($types);

        usort(
            $collection,
            function ($left, $right) use ($types, $idToIndexMap, $numTypes) {
                $localClassNameLeft = Str::classname(get_class($left));
                $localClassNameRight = Str::classname(get_class($right));

                // if same type, use original sorting
                if ($localClassNameRight === $localClassNameLeft) {
                    $indexLeft = $idToIndexMap[$left->getId()];
                    $indexRight = $idToIndexMap[$right->getId()];
                } else {
                    $indexLeft = array_search($localClassNameLeft, $types);
                    $indexRight = array_search($localClassNameRight, $types);

                    // assume that types that aren't defined, should come last.
                    if (false === $indexLeft) {
                        $indexLeft = $numTypes + 1;
                    }
                    if (false === $indexRight) {
                        $indexRight = $numTypes + 1;
                    }
                }

                if ($indexLeft < $indexRight) {
                    return -1;
                }
                if ($indexLeft > $indexRight) {
                    return 1;
                }
                return 0;
            }
        );

        return $collection;
    }
1304351
protected function sortCollection($objects)
    {
        $class = false;

        if ($objects instanceof Arrayable) {
            $class = get_class($objects);

            $objects = $objects->toArray();
        }

        usort($objects, function ($aObj, $bObj) {
            list($aRank, $bRank) = $this->getRanks($aObj, $bObj);

            if ($this->equals($aRank, $bRank)) {
                return $this->sortByName($aObj, $bObj);
            }

            return $this->sortByValue($aRank, $bRank);
        });

        return $class ? $class::make($objects) : $objects;
    }
696656
protected static function getClassFromCollection( array $collection )
    {
        // Make sure everything in this container is of __exactly__ the same type.
        // This is a stronger check than the entity container performs (child entities are ok in the container)
        $classes = array_unique( array_map( 'get_class', $collection ) );

        if( count( $classes ) > 1 ) {
            // TODO this could fallback to persisting every entity individually. That would work.
            throw new \Exception(
                sprintf(
                    "Can't manage entities in a container with multiple types, these are %s.",
                    implode( ", ", $classes )
                )
            );
        }
        return array_pop( $classes );

    }
699355
public function sortBy(array $fields) : self
    {
        if ($this->count() == 0) {
            return clone $this;
        }

        /** @var array|bool[] $isMethod */
        $isMethod = [];
        $values = [];

        foreach ($fields as $name => $options) {
            foreach ($this->elements as $key => $element) {
                if (is_array($element)) {
                    $values[$name][$key] = $element[$name];
                } else {
                    if (!array_key_exists($name, $isMethod)) {
                        $isMethod[$name] = method_exists($element, $name);
                    }

                    if ($isMethod[$name]) {
                        $values[$name][$key] = call_user_func([$element, $name]);
                    } else {
                        $values[$name][$key] = $element->$name;
                    }
                }
            }
        }

        $args = [];

        foreach ($fields as $name => $options) {
            $args[] = $values[$name];
            $args[] = $options;
        }

        $return = $this->elements;
        $args[] = &$return;

        call_user_func_array('array_multisort', $args);

        $clone = clone $this;
        $clone->elements = $return;

        return $clone;
    }
408260
public function lookaheadTypeIsAnyOf(array $types): bool
    {
        return isset($this->tokens[$this->position]) && $this->tokens[$this->position]->typeEqualsAnyOf($types);
    }
808898
protected function computeMergedType(array $types) {
        if (count($types) === 1) {
            return $types[0];
        }
        $same = null;
        foreach ($types as $key => $type) {
            if (!$type instanceof Type) {
                var_dump($types);
                throw new \RuntimeException("Invalid type found");
            }
            if (is_null($same)) {
                $same = $type;
            } elseif ($same && !$same->equals($type)) {
                $same = false;
            }
            if ($type->type === Type::TYPE_UNKNOWN) {
                return false;
            }
        }
        if ($same) {
            return $same;
        }
        return (new Type(Type::TYPE_UNION, $types))->simplify();
    }
974389
protected function sort($items, $type = self::TYPE_BOTH, $by = self::KEY_NAME, $direction = self::ASC)
    {
        $returnArray = array();
        if (count($items) > 0) {
            $tmpArray = array();
            foreach($items as $key => $value) {
                $tmpArray[$key] = $value[$by];
            }

            natcasesort($tmpArray);

            if ($direction == self::DESC) {
                $tmpArray = array_reverse($tmpArray, true);
            }

            foreach($tmpArray as $key => $value) {
                $returnArray[] = $items[$key];
            }

            // If sorting by name, lets seperate the files from the dirs.
            if ($by == self::KEY_NAME && $type == self::TYPE_BOTH) {
                $files = array();
                $dirs  = array();

                foreach ($returnArray as $value) {
                    if ($value[self::KEY_TYPE] == self::TYPE_FILE) {
                        $files[] = $value;
                    } elseif ($value[self::KEY_TYPE] == self::TYPE_DIR) {
                        $dirs[] = $value;
                    }
                }

                if ($direction == self::DESC) {
                    $returnArray = array_merge($files, $dirs);
                } else {
                    $returnArray = array_merge($dirs, $files);
                }
            }
        }
        return $returnArray;
    }
531658
public function flat(array $types = []) {
        if (in_array(get_class($this), $types))
            return [$this];
        $flat = [];
        foreach ($this->children as $c) {
            $flat = array_merge($flat, $c->flat($types));
        }
        return $flat;
    }
224449
protected function postCollectionModifiers(Collection $collection)
    {
        if ($this->getOrderByField() && $this->getOrderByDirection()) {
            $field = $this->getOrderByField();
            $desc  = false;

            if ($this->getOrderByDirection() === 'desc') {
                $desc = true;
            }

            $sorted = $collection->sortBy(function ($entry) use ($field) {
                if (property_exists($entry, $field)) {
                    return $entry->{$field};
                }
            }, SORT_NATURAL, $desc);

            return $sorted;
        }

        return $collection;
    }
803475
public static function namesByType(array $types)
    {
        $names = array();

        foreach ($types as $type) {
            $names[] = self::nameByType($type);
        }

        return $names;
    }
1368204
public function sortCollection(Collection $collection, $orderBy, $orderDir = 'asc', $orderManual = null, $sort_flags = null)
    {
        $items = $collection->toArray();
        if (!$items) {
            return [];
        }

        $lookup = md5(json_encode($items) . json_encode($orderManual) . $orderBy . $orderDir);
        if (!isset($this->sort[$lookup][$orderBy])) {
            $this->buildSort($lookup, $items, $orderBy, $orderManual, $sort_flags);
        }

        $sort = $this->sort[$lookup][$orderBy];

        if ($orderDir !== 'asc') {
            $sort = array_reverse($sort);
        }

        return $sort;

    }
591889
public function getList(array $types = [])
    {
        if (!$types || $types == StorageEntity::getTypes()) {
            return $this->getEntityManager()->createQuery('
                SELECT
                    s
                FROM
                    AnimeDbCatalogBundle:Storage s
                ORDER BY
                    s.id DESC
            ')->getResult();
        }

        return $this->getEntityManager()->createQuery('
            SELECT
                s
            FROM
                AnimeDbCatalogBundle:Storage s
            WHERE
                s.type IN (:types)
            ORDER BY
                s.id DESC
        ')
            ->setParameter(':types', $types)
            ->getResult();
    }
1258141
private function sortCollection()
    {
        if ($this->queryConfiguration->hasOrderColumn()) {
            $order = $this->queryConfiguration->orderColumns();
            $orderFunc = $this->defaultGlobalOrderFunction;
            $this->collection = $this->collection->sort(function ($first, $second) use ($order, $orderFunc) {
                return $orderFunc($first, $second, $order);
            });
        }
    }
873602
public function getBestResponseType(array $types)
    {
        if (empty($types))
            return "";

        $this->sortTypes($types);
        $type = reset($types);
        return $this->accepts($type) ? current($types) : null;
    }
739243
public function getOrdered($collection, $sort = null)
    {
        if (!$sort) {
            return $collection;
        }

        $unordered = [];
        foreach ($collection as $content) {
            $unordered[$content->getId()] = $content;
        }

        $ordered = [];
        foreach ($sort as $id) {
            if (isset($unordered[$id])) {
                $ordered[] = $unordered[$id];
            }
        }

        return $ordered;
    }
290171
public function convert($records)
    {
        if (!is_iterable($records)) {
            throw new TypeError(sprintf('%s() expects argument passed to be iterable, %s given', __METHOD__, gettype($records)));
        }

        if ($this->output_encoding === $this->input_encoding) {
            return $records;
        }

        if (is_array($records)) {
            return array_map($this, $records);
        }

        return new MapIterator($records, $this);
    }
335305
public static function makeTypeChoices(array $types, $section)
    {
        $sectionTypes = [];

        foreach ($types as $type) {
            $sectionTypes[] = new ImageType($section, $type['code'], $type['label'], $type['filter']);
        }

        return $sectionTypes;
    }