Passed
Pull Request — 2.2 (#20357)
by Wilmer
08:02 queued 17s
created

Sort::hasAttribute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\data;
10
11
use Yii;
12
use yii\base\BaseObject;
13
use yii\base\InvalidConfigException;
14
use yii\helpers\Html;
15
use yii\helpers\Inflector;
16
use yii\web\Request;
17
18
/**
19
 * Sort represents information relevant to sorting.
20
 *
21
 * When data needs to be sorted according to one or several attributes,
22
 * we can use Sort to represent the sorting information and generate
23
 * appropriate hyperlinks that can lead to sort actions.
24
 *
25
 * A typical usage example is as follows,
26
 *
27
 * ```php
28
 * public function actionIndex()
29
 * {
30
 *     $sort = new Sort([
31
 *         'attributes' => [
32
 *             'age',
33
 *             'name' => [
34
 *                 'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
35
 *                 'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
36
 *                 'default' => SORT_DESC,
37
 *                 'label' => 'Name',
38
 *             ],
39
 *         ],
40
 *     ]);
41
 *
42
 *     $models = Article::find()
43
 *         ->where(['status' => 1])
44
 *         ->orderBy($sort->orders)
45
 *         ->all();
46
 *
47
 *     return $this->render('index', [
48
 *          'models' => $models,
49
 *          'sort' => $sort,
50
 *     ]);
51
 * }
52
 * ```
53
 *
54
 * View:
55
 *
56
 * ```php
57
 * // display links leading to sort actions
58
 * echo $sort->link('name') . ' | ' . $sort->link('age');
59
 *
60
 * foreach ($models as $model) {
61
 *     // display $model here
62
 * }
63
 * ```
64
 *
65
 * In the above, we declare two [[attributes]] that support sorting: `name` and `age`.
66
 * We pass the sort information to the Article query so that the query results are
67
 * sorted by the orders specified by the Sort object. In the view, we show two hyperlinks
68
 * that can lead to pages with the data sorted by the corresponding attributes.
69
 *
70
 * For more details and usage information on Sort, see the [guide article on sorting](guide:output-sorting).
71
 *
72
 * @property array $attributeOrders Sort directions indexed by attribute names. Sort direction can be either
73
 * `SORT_ASC` for ascending order or `SORT_DESC` for descending order. Note that the type of this property
74
 * differs in getter and setter. See [[getAttributeOrders()]] and [[setAttributeOrders()]] for details.
75
 * @property-read array $orders The columns (keys) and their corresponding sort directions (values). This can
76
 * be passed to [[\yii\db\Query::orderBy()]] to construct a DB query.
77
 *
78
 * @author Qiang Xue <[email protected]>
79
 * @since 2.0
80
 */
81
class Sort extends BaseObject
82
{
83
    /**
84
     * @var bool whether the sorting can be applied to multiple attributes simultaneously.
85
     * Defaults to `false`, which means each time the data can only be sorted by one attribute.
86
     */
87
    public $enableMultiSort = false;
88
    /**
89
     * @var array list of attributes that are allowed to be sorted. Its syntax can be
90
     * described using the following example:
91
     *
92
     * ```php
93
     * [
94
     *     'age',
95
     *     'name' => [
96
     *         'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
97
     *         'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
98
     *         'default' => SORT_DESC,
99
     *         'label' => 'Name',
100
     *     ],
101
     * ]
102
     * ```
103
     *
104
     * In the above, two attributes are declared: `age` and `name`. The `age` attribute is
105
     * a simple attribute which is equivalent to the following:
106
     *
107
     * ```php
108
     * 'age' => [
109
     *     'asc' => ['age' => SORT_ASC],
110
     *     'desc' => ['age' => SORT_DESC],
111
     *     'default' => SORT_ASC,
112
     *     'label' => Inflector::camel2words('age'),
113
     * ]
114
     * ```
115
     *
116
     * Since 2.0.12 particular sort direction can be also specified as direct sort expression, like following:
117
     *
118
     * ```php
119
     * 'name' => [
120
     *     'asc' => '[[last_name]] ASC NULLS FIRST', // PostgreSQL specific feature
121
     *     'desc' => '[[last_name]] DESC NULLS LAST',
122
     * ]
123
     * ```
124
     *
125
     * The `name` attribute is a composite attribute:
126
     *
127
     * - The `name` key represents the attribute name which will appear in the URLs leading
128
     *   to sort actions.
129
     * - The `asc` and `desc` elements specify how to sort by the attribute in ascending
130
     *   and descending orders, respectively. Their values represent the actual columns and
131
     *   the directions by which the data should be sorted by.
132
     * - The `default` element specifies by which direction the attribute should be sorted
133
     *   if it is not currently sorted (the default value is ascending order).
134
     * - The `label` element specifies what label should be used when calling [[link()]] to create
135
     *   a sort link. If not set, [[Inflector::camel2words()]] will be called to get a label.
136
     *   Note that it will not be HTML-encoded.
137
     *
138
     * Note that if the Sort object is already created, you can only use the full format
139
     * to configure every attribute. Each attribute must include these elements: `asc` and `desc`.
140
     */
141
    public $attributes = [];
142
    /**
143
     * @var string the name of the parameter that specifies which attributes to be sorted
144
     * in which direction. Defaults to `sort`.
145
     * @see params
146
     */
147
    public $sortParam = 'sort';
148
    /**
149
     * @var array|null the order that should be used when the current request does not specify any order.
150
     * The array keys are attribute names and the array values are the corresponding sort directions. For example,
151
     *
152
     * ```php
153
     * [
154
     *     'name' => SORT_ASC,
155
     *     'created_at' => SORT_DESC,
156
     * ]
157
     * ```
158
     *
159
     * @see attributeOrders
160
     */
161
    public $defaultOrder;
162
    /**
163
     * @var string|null the route of the controller action for displaying the sorted contents.
164
     * If not set, it means using the currently requested route.
165
     */
166
    public $route;
167
    /**
168
     * @var string the character used to separate different attributes that need to be sorted by.
169
     */
170
    public $separator = ',';
171
    /**
172
     * @var array|null parameters (name => value) that should be used to obtain the current sort directions
173
     * and to create new sort URLs. If not set, `$_GET` will be used instead.
174
     *
175
     * In order to add hash to all links use `array_merge($_GET, ['#' => 'my-hash'])`.
176
     *
177
     * The array element indexed by [[sortParam]] is considered to be the current sort directions.
178
     * If the element does not exist, the [[defaultOrder|default order]] will be used.
179
     *
180
     * @see sortParam
181
     * @see defaultOrder
182
     */
183
    public $params;
184
    /**
185
     * @var \yii\web\UrlManager|null the URL manager used for creating sort URLs. If not set,
186
     * the `urlManager` application component will be used.
187
     */
188
    public $urlManager;
189
    /**
190
     * @var int Allow to control a value of the fourth parameter which will be
191
     * passed to [[ArrayHelper::multisort()]]
192
     * @since 2.0.33
193
     */
194
    public $sortFlags = SORT_REGULAR;
195
    /**
196
     * @var string|null the name of the [[\yii\base\Model]]-based class used by the [[link()]] method to retrieve
197
     * attributes' labels. See [[link]] method for details.
198
     * @since 2.0.49
199
     */
200
    public $modelClass;
201
202
203
    /**
204
     * Normalizes the [[attributes]] property.
205
     */
206 79
    public function init()
207
    {
208 79
        $attributes = [];
209 79
        foreach ($this->attributes as $name => $attribute) {
210 38
            if (!is_array($attribute)) {
211 33
                $attributes[$attribute] = [
212 33
                    'asc' => [$attribute => SORT_ASC],
213 33
                    'desc' => [$attribute => SORT_DESC],
214 33
                ];
215 24
            } elseif (!isset($attribute['asc'], $attribute['desc'])) {
216
                $attributes[$name] = array_merge([
217
                    'asc' => [$name => SORT_ASC],
218
                    'desc' => [$name => SORT_DESC],
219
                ], $attribute);
220
            } else {
221 24
                $attributes[$name] = $attribute;
222
            }
223
        }
224 79
        $this->attributes = $attributes;
225
    }
226
227
    /**
228
     * Returns the columns and their corresponding sort directions.
229
     * @param bool $recalculate whether to recalculate the sort directions
230
     * @return array the columns (keys) and their corresponding sort directions (values).
231
     * This can be passed to [[\yii\db\Query::orderBy()]] to construct a DB query.
232
     */
233 60
    public function getOrders($recalculate = false)
234
    {
235 60
        $attributeOrders = $this->getAttributeOrders($recalculate);
236 60
        $orders = [];
237 60
        foreach ($attributeOrders as $attribute => $direction) {
238 17
            $definition = $this->attributes[$attribute];
239 17
            $columns = $definition[$direction === SORT_ASC ? 'asc' : 'desc'];
240 17
            if (is_array($columns) || $columns instanceof \Traversable) {
241 16
                foreach ($columns as $name => $dir) {
242 16
                    $orders[$name] = $dir;
243
                }
244
            } else {
245 1
                $orders[] = $columns;
246
            }
247
        }
248
249 60
        return $orders;
250
    }
251
252
    /**
253
     * @var array the currently requested sort order as computed by [[getAttributeOrders]].
254
     */
255
    private $_attributeOrders;
256
257
    /**
258
     * Returns the currently requested sort information.
259
     * @param bool $recalculate whether to recalculate the sort directions
260
     * @return array sort directions indexed by attribute names.
261
     * Sort direction can be either `SORT_ASC` for ascending order or
262
     * `SORT_DESC` for descending order.
263
     */
264 79
    public function getAttributeOrders($recalculate = false)
265
    {
266 79
        if ($this->_attributeOrders === null || $recalculate) {
267 78
            $this->_attributeOrders = [];
268 78
            if (($params = $this->params) === null) {
269 51
                $request = Yii::$app->getRequest();
270 51
                $params = $request instanceof Request ? $request->getQueryParams() : [];
271
            }
272 78
            if (isset($params[$this->sortParam])) {
273 26
                foreach ($this->parseSortParam($params[$this->sortParam]) as $attribute) {
274 26
                    $descending = false;
275 26
                    if (strncmp($attribute, '-', 1) === 0) {
276 21
                        $descending = true;
277 21
                        $attribute = substr($attribute, 1);
278
                    }
279
280 26
                    if (isset($this->attributes[$attribute])) {
281 21
                        $this->_attributeOrders[$attribute] = $descending ? SORT_DESC : SORT_ASC;
282 21
                        if (!$this->enableMultiSort) {
283 15
                            return $this->_attributeOrders;
284
                        }
285
                    }
286
                }
287
288 13
                return $this->_attributeOrders;
289
            }
290 52
            if (empty($this->_attributeOrders) && is_array($this->defaultOrder)) {
291 9
                $this->_attributeOrders = $this->defaultOrder;
292
            }
293
        }
294
295 64
        return $this->_attributeOrders;
296
    }
297
298
    /**
299
     * Parses the value of [[sortParam]] into an array of sort attributes.
300
     *
301
     * The format must be the attribute name only for ascending
302
     * or the attribute name prefixed with `-` for descending.
303
     *
304
     * For example the following return value will result in ascending sort by
305
     * `category` and descending sort by `created_at`:
306
     *
307
     * ```php
308
     * [
309
     *     'category',
310
     *     '-created_at'
311
     * ]
312
     * ```
313
     *
314
     * @param string $param the value of the [[sortParam]].
315
     * @return array the valid sort attributes.
316
     * @since 2.0.12
317
     * @see separator for the attribute name separator.
318
     * @see sortParam
319
     */
320 25
    protected function parseSortParam($param)
321
    {
322 25
        return is_scalar($param) ? explode($this->separator, $param) : [];
0 ignored issues
show
introduced by
The condition is_scalar($param) is always true.
Loading history...
323
    }
324
325
    /**
326
     * Sets up the currently sort information.
327
     * @param array|null $attributeOrders sort directions indexed by attribute names.
328
     * Sort direction can be either `SORT_ASC` for ascending order or
329
     * `SORT_DESC` for descending order.
330
     * @param bool $validate whether to validate given attribute orders against [[attributes]] and [[enableMultiSort]].
331
     * If validation is enabled incorrect entries will be removed.
332
     * @since 2.0.10
333
     */
334 1
    public function setAttributeOrders($attributeOrders, $validate = true)
335
    {
336 1
        if ($attributeOrders === null || !$validate) {
337 1
            $this->_attributeOrders = $attributeOrders;
338
        } else {
339 1
            $this->_attributeOrders = [];
340 1
            foreach ($attributeOrders as $attribute => $order) {
341 1
                if (isset($this->attributes[$attribute])) {
342 1
                    $this->_attributeOrders[$attribute] = $order;
343 1
                    if (!$this->enableMultiSort) {
344 1
                        break;
345
                    }
346
                }
347
            }
348
        }
349
    }
350
351
    /**
352
     * Returns the sort direction of the specified attribute in the current request.
353
     * @param string $attribute the attribute name
354
     * @return int|null Sort direction of the attribute. Can be either `SORT_ASC`
355
     * for ascending order or `SORT_DESC` for descending order. Null is returned
356
     * if the attribute is invalid or does not need to be sorted.
357
     */
358 16
    public function getAttributeOrder($attribute)
359
    {
360 16
        $orders = $this->getAttributeOrders();
361
362 16
        return isset($orders[$attribute]) ? $orders[$attribute] : null;
363
    }
364
365
    /**
366
     * Generates a hyperlink that links to the sort action to sort by the specified attribute.
367
     * Based on the sort direction, the CSS class of the generated hyperlink will be appended
368
     * with "asc" or "desc".
369
     * @param string $attribute the attribute name by which the data should be sorted by.
370
     * @param array $options additional HTML attributes for the hyperlink tag.
371
     * There is one special attribute `label` which will be used as the label of the hyperlink.
372
     * If this is not set, the label defined in [[attributes]] will be used.
373
     * If no label is defined, it will be retrieved from the instance of [[modelClass]] (if [[modelClass]] is not null)
374
     * or generated from attribute name using [[\yii\helpers\Inflector::camel2words()]].
375
     * Note that it will not be HTML-encoded.
376
     * @return string the generated hyperlink
377
     * @throws InvalidConfigException if the attribute is unknown
378
     */
379 14
    public function link($attribute, $options = [])
380
    {
381 14
        if (($direction = $this->getAttributeOrder($attribute)) !== null) {
382 8
            $class = $direction === SORT_DESC ? 'desc' : 'asc';
383 8
            if (isset($options['class'])) {
384
                $options['class'] .= ' ' . $class;
385
            } else {
386 8
                $options['class'] = $class;
387
            }
388
        }
389
390 14
        $url = $this->createUrl($attribute);
391 14
        $options['data-sort'] = $this->createSortParam($attribute);
392
393 14
        if (isset($options['label'])) {
394
            $label = $options['label'];
395
            unset($options['label']);
396
        } else {
397 14
            if (isset($this->attributes[$attribute]['label'])) {
398
                $label = $this->attributes[$attribute]['label'];
399 14
            } elseif ($this->modelClass !== null) {
400
                $modelClass = $this->modelClass;
401
                /** @var \yii\base\Model $model */
402
                $model = $modelClass::instance();
403
                $label = $model->getAttributeLabel($attribute);
404
            } else {
405 14
                $label = Inflector::camel2words($attribute);
406
            }
407
        }
408
409 14
        return Html::a($label, $url, $options);
410
    }
411
412
    /**
413
     * Creates a URL for sorting the data by the specified attribute.
414
     * This method will consider the current sorting status given by [[attributeOrders]].
415
     * For example, if the current page already sorts the data by the specified attribute in ascending order,
416
     * then the URL created will lead to a page that sorts the data by the specified attribute in descending order.
417
     * @param string $attribute the attribute name
418
     * @param bool $absolute whether to create an absolute URL. Defaults to `false`.
419
     * @return string the URL for sorting. False if the attribute is invalid.
420
     * @throws InvalidConfigException if the attribute is unknown
421
     * @see attributeOrders
422
     * @see params
423
     */
424 15
    public function createUrl($attribute, $absolute = false)
425
    {
426 15
        if (($params = $this->params) === null) {
427 7
            $request = Yii::$app->getRequest();
428 7
            $params = $request instanceof Request ? $request->getQueryParams() : [];
429
        }
430 15
        $params[$this->sortParam] = $this->createSortParam($attribute);
431 15
        $params[0] = $this->route === null ? Yii::$app->controller->getRoute() : $this->route;
432 15
        $urlManager = $this->urlManager === null ? Yii::$app->getUrlManager() : $this->urlManager;
433 15
        if ($absolute) {
434
            return $urlManager->createAbsoluteUrl($params);
435
        }
436
437 15
        return $urlManager->createUrl($params);
438
    }
439
440
    /**
441
     * Creates the sort variable for the specified attribute.
442
     * The newly created sort variable can be used to create a URL that will lead to
443
     * sorting by the specified attribute.
444
     * @param string $attribute the attribute name
445
     * @return string the value of the sort variable
446
     * @throws InvalidConfigException if the specified attribute is not defined in [[attributes]]
447
     */
448 16
    public function createSortParam($attribute)
449
    {
450 16
        if (!isset($this->attributes[$attribute])) {
451
            throw new InvalidConfigException("Unknown attribute: $attribute");
452
        }
453 16
        $definition = $this->attributes[$attribute];
454 16
        $directions = $this->getAttributeOrders();
455 16
        if (isset($directions[$attribute])) {
456 10
            if ($this->enableMultiSort) {
457 6
                if ($directions[$attribute] === SORT_ASC) {
458 5
                    $direction = SORT_DESC;
459
                } else {
460 6
                    $direction = null;
461
                }
462
            } else {
463 4
                $direction = $directions[$attribute] === SORT_DESC ? SORT_ASC : SORT_DESC;
464
            }
465
466 10
            unset($directions[$attribute]);
467
        } else {
468 7
            $direction = isset($definition['default']) ? $definition['default'] : SORT_ASC;
469
        }
470
471 16
        if ($this->enableMultiSort) {
472 10
            if ($direction !== null) {
473 10
                $directions = array_merge([$attribute => $direction], $directions);
474
            }
475
        } else {
476 6
            $directions = [$attribute => $direction];
477
        }
478
479 16
        $sorts = [];
480 16
        foreach ($directions as $attribute => $direction) {
0 ignored issues
show
introduced by
$attribute is overwriting one of the parameters of this function.
Loading history...
481 15
            $sorts[] = $direction === SORT_DESC ? '-' . $attribute : $attribute;
482
        }
483
484 16
        return implode($this->separator, $sorts);
485
    }
486
487
    /**
488
     * Returns a value indicating whether the sort definition supports sorting by the named attribute.
489
     * @param string $name the attribute name
490
     * @return bool whether the sort definition supports sorting by the named attribute.
491
     */
492
    public function hasAttribute($name)
493
    {
494
        return isset($this->attributes[$name]);
495
    }
496
}
497