Passed
Push — scrutinizer-migrate-to-new-eng... ( 58afd6 )
by Alexander
18:11
created

Sort::link()   A

Complexity

Conditions 6
Paths 15

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6.288

Importance

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