ExtendedSortExtension   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 89.47%

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 52
ccs 17
cts 19
cp 0.8947
rs 10
wmc 5
lcom 0
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A implementedEvents() 0 6 1
A findEntities() 0 20 4
1
<?php
2
/**
3
 * Copyright 2016 - 2018, Cake Development Corporation (http://cakedc.com)
4
 *
5
 * Licensed under The MIT License
6
 * Redistributions of files must retain the above copyright notice.
7
 *
8
 * @copyright Copyright 2016 - 2018, Cake Development Corporation (http://cakedc.com)
9
 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
10
 */
11
12
namespace CakeDC\Api\Service\Action\Extension;
13
14
use CakeDC\Api\Service\Action\Action;
15
use Cake\Event\Event;
16
use Cake\Event\EventListenerInterface;
17
use Cake\ORM\Entity;
18
19
class ExtendedSortExtension extends Extension implements EventListenerInterface
20
{
21
22
    /**
23
     * Default settings
24
     *
25
     * @var array
26
     */
27
    protected $_defaultConfig = [
28
        'sortField' => 'sort',
29
    ];
30
31
    /**
32
     * Returns a list of events this object is implementing. When the class is registered
33
     * in an event manager, each individual method will be associated with the respective event.
34
     *
35
     * @return array
36
     */
37 5
    public function implementedEvents()
38
    {
39
        return [
40 5
            'Action.Crud.onFindEntities' => 'findEntities',
41 5
        ];
42
    }
43
44
    /**
45
     * find entities
46
     *
47
     * @param Event $event An Event instance
48
     * @return Entity
49
     */
50 5
    public function findEntities(Event $event)
51
    {
52 5
        $action = $event->getSubject();
53 5
        $query = $event->getData('query');
54 5
        if ($event->result) {
55
            $query = $event->result;
56
        }
57 5
        $data = $action->getData();
58 5
        $sort = null;
59
60 5
        $sortField = $this->getConfig('sortField');
61 5
        if (!empty($data[$sortField])) {
62 4
            $sort = json_decode($data[$sortField], true);
63 4
        }
64 5
        if (is_array($sort)) {
65 4
            $query->order($sort);
66 4
        }
67
68 5
        return $query;
69
    }
70
}
71