yii\data\Sort::getAttributeOrders PHP Method

getAttributeOrders() public method

Returns the currently requested sort information.
public getAttributeOrders ( boolean $recalculate = false ) : array
$recalculate boolean whether to recalculate the sort directions
return array sort directions indexed by attribute names. Sort direction can be either `SORT_ASC` for ascending order or `SORT_DESC` for descending order.
    public function getAttributeOrders($recalculate = false)
    {
        if ($this->_attributeOrders === null || $recalculate) {
            $this->_attributeOrders = [];
            if (($params = $this->params) === null) {
                $request = Yii::$app->getRequest();
                $params = $request instanceof Request ? $request->getQueryParams() : [];
            }
            if (isset($params[$this->sortParam]) && is_scalar($params[$this->sortParam])) {
                $attributes = explode($this->separator, $params[$this->sortParam]);
                foreach ($attributes as $attribute) {
                    $descending = false;
                    if (strncmp($attribute, '-', 1) === 0) {
                        $descending = true;
                        $attribute = substr($attribute, 1);
                    }
                    if (isset($this->attributes[$attribute])) {
                        $this->_attributeOrders[$attribute] = $descending ? SORT_DESC : SORT_ASC;
                        if (!$this->enableMultiSort) {
                            return $this->_attributeOrders;
                        }
                    }
                }
            }
            if (empty($this->_attributeOrders) && is_array($this->defaultOrder)) {
                $this->_attributeOrders = $this->defaultOrder;
            }
        }
        return $this->_attributeOrders;
    }

Usage Example

Example #1
0
 public function testGetAttributeOrders()
 {
     $sort = new Sort(['attributes' => ['age', 'name' => ['asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC], 'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC]]], 'params' => ['sort' => 'age,-name'], 'enableMultiSort' => true]);
     $orders = $sort->getAttributeOrders();
     $this->assertEquals(2, count($orders));
     $this->assertEquals(SORT_ASC, $orders['age']);
     $this->assertEquals(SORT_DESC, $orders['name']);
     $sort->enableMultiSort = false;
     $orders = $sort->getAttributeOrders(true);
     $this->assertEquals(1, count($orders));
     $this->assertEquals(SORT_ASC, $orders['age']);
 }