HEX
Server: LiteSpeed
System: Linux premium260.web-hosting.com 4.18.0-553.45.1.lve.el8.x86_64 #1 SMP Wed Mar 26 12:08:09 UTC 2025 x86_64
User: aliazzsr (627)
PHP: 7.4.33
Disabled: NONE
Upload Files
File: /home/aliazzsr/api.crm.vqode.com/components/helpers/SortingHelper.php
<?php
namespace app\components\helpers;

use app\components\BaseModel;
use yii\base\BaseObject;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\Request;

class SortingHelper extends BaseObject
{
    const SEPARATOR = ',';
    const SORT = 'sort';

    /**
     * Adds additional fields into subquery and returns order by
     * @param string $modelClass
     * @param Query $subQuery
     * @return array
     */
    public static function getOrderBy($modelClass, Query $subQuery)
    {
        /** @var BaseModel $modelClass */

        $orderBy = [];

        foreach (static::getSort() as $attribute) {
            $descending = false;
            if (strncmp($attribute, '-', 1) === 0) {
                $descending = true;
                $attribute = substr($attribute, 1);
            }
            if (strpos($attribute, '.')) {
                list($relation, $attribute) = explode('.', $attribute);
                if ($modelClass::hasRelation($relation)) {
                    $aliasName = $relation . '__' . $attribute;
                    $orderBy[$aliasName] = $descending ? SORT_DESC : SORT_ASC;
                    $subQuery->addSelect([$aliasName => $relation . '.' . $attribute]);
                }
            } else {
                if ($modelClass::isValidAttribute($attribute)) {
                    $orderBy[$attribute] = $descending ? SORT_DESC : SORT_ASC;
                }
            }
        }

        return $orderBy;
    }

    protected static function getSort()
    {
        $request = \Yii::$app->getRequest();
        $params = $request instanceof Request ? $request->getQueryParams() : [];

        return explode(self::SEPARATOR, ArrayHelper::getValue($params, self::SORT));
    }
}