Passed
Push — 1.0.x ( 8353d5...3a2c37 )
by Julien
21:28
created

Group::initializeGroup()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 13
c 1
b 0
f 0
nc 12
nop 0
dl 0
loc 23
ccs 0
cts 13
cp 0
crap 30
rs 9.5222
1
<?php
2
3
/**
4
 * This file is part of the Zemit Framework.
5
 *
6
 * (c) Zemit Team <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE.txt
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Zemit\Mvc\Controller\Traits\Query;
13
14
use Phalcon\Filter\Filter;
15
use Phalcon\Support\Collection;
16
use Zemit\Mvc\Controller\Traits\Abstracts\AbstractModel;
17
use Zemit\Mvc\Controller\Traits\Abstracts\AbstractParams;
18
use Zemit\Mvc\Controller\Traits\Abstracts\Query\AbstractGroup;
19
20
trait Group
21
{
22
    use AbstractGroup;
23
    
24
    use AbstractParams;
25
    use AbstractModel;
26
    
27
    protected ?Collection $group;
28
    
29
    // @todo add model name to group attributes
30
    public function initializeGroup(): void
31
    {
32
        $group = $this->getParam('group', [Filter::FILTER_STRING, Filter::FILTER_TRIM], $this->defaultGroup());
33
        
34
        if (!isset($group)) {
35
            $this->setGroup(null);
36
        }
37
        
38
        if (!is_array($group)) {
39
            $group = explode(',', $group);
40
        }
41
        
42
        $collection = new Collection([], false);
43
        foreach ($group as $key => $item) {
44
            $item = trim($item);
45
            if (is_int($key)) {
46
                $collection->set($item, $this->appendModelName($item));
47
            } else {
48
                $collection->set(trim($key), $this->appendModelName($item));
49
            }
50
        }
51
        
52
        $this->setGroup($collection);
53
    }
54
    
55
    public function setGroup(?Collection $group): void
56
    {
57
        $this->group = $group;
58
    }
59
    
60
    public function getGroup(): ?Collection
61
    {
62
        return $this->group;
63
    }
64
    
65
    public function defaultGroup(): array|string|null
66
    {
67
        // @todo use primary keys from model meta data instead
68
        return 'id';
69
    }
70
}
71