-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathOrderlyBehavior.php
More file actions
84 lines (73 loc) · 2.11 KB
/
Copy pathOrderlyBehavior.php
File metadata and controls
84 lines (73 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
declare(strict_types=1);
namespace Muffin\Orderly\Model\Behavior;
use ArrayObject;
use Cake\Event\EventInterface;
use Cake\ORM\Behavior;
use Cake\ORM\Query\SelectQuery;
class OrderlyBehavior extends Behavior
{
/**
* Initialize behavior
*
* @param array<string, mixed> $config Config
* @return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->_normalizeConfig($config);
}
/**
* Add the default order clause to the query as necessary.
*
* @param \Cake\Event\EventInterface $event Event
* @param \Cake\ORM\Query\SelectQuery $query Query
* @param \ArrayObject $options Options
* @param bool $primary Boolean indicating whether it's primary query.
* @return void
*/
public function beforeFind(EventInterface $event, SelectQuery $query, ArrayObject $options, bool $primary): void
{
if ($query->clause('order')) {
return;
}
$orders = $this->_config['orders'];
foreach ($orders as $config) {
if (
empty($config['callback'])
|| call_user_func($config['callback'], $query, $options, $primary)
) {
$query->orderBy($config['order']);
}
}
}
/**
* Normalize configuration.
*
* @param array<string, mixed> $orders Orders config
* @return void
*/
protected function _normalizeConfig(array $orders): void
{
unset($orders['className']);
if ($orders === []) {
$orders = [[]];
} elseif (isset($orders['order']) || isset($orders['callback'])) {
$orders = [$orders];
}
$default = [
'order' => array_map(
$this->_table->aliasField(...),
(array)$this->_table->getDisplayField(),
),
'callback' => null,
];
foreach ($orders as $key => $value) {
$orders[$key] = $orders[$key] + $default;
}
$this->_config = [
'orders' => $orders,
];
}
}