ElasticSearcher\Fragments\Traits\SortableTrait::sortBy PHP Метод

sortBy() публичный Метод

public sortBy ( string $fieldName, string | null $direction = null )
$fieldName string
$direction string | null
    public function sortBy($fieldName, $direction = null)
    {
        $predefinedFields = $this->get('sort');
        $sortingFields = [];
        // Field exists, prioritize and set direction (if any).
        if ($field = $this->findField($fieldName, $predefinedFields)) {
            // Field was defined without options.
            if (!is_array($field)) {
                if ($direction) {
                    $sortingFields[] = [$fieldName => $direction];
                } else {
                    $sortingFields[] = $fieldName;
                }
            } else {
                // Set direction, otherwise it will just use the default definition.
                if ($direction) {
                    // Defined as {"post_date" : {"order" : "asc", "mode": "avg"}}
                    if (is_array($field[$fieldName])) {
                        $field[$fieldName]['order'] = $direction;
                    } else {
                        $field[$fieldName] = $direction;
                    }
                }
                $sortingFields[] = $field;
            }
        } else {
            $sortingFields[] = [$fieldName => $direction];
        }
        // Add the predefined fields but remove the one we are sorting on.
        if ($predefinedFields) {
            foreach ($predefinedFields as $field) {
                if (!is_array($field) && $fieldName == $field) {
                    continue;
                } elseif (is_array($field) && array_key_exists($fieldName, $field)) {
                    continue;
                }
                $sortingFields[] = $field;
            }
        }
        $this->set('sort', $sortingFields);
        return $this;
    }