Completed
Pull Request — master (#46)
by Daniel
03:48
created

MappedOrderByAdapter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 6
nc 1
nop 2
crap 1
1
<?php
2
3
namespace KGzocha\Searcher\QueryCriteria\Adapter;
4
5
use KGzocha\Searcher\QueryCriteria\OrderByQueryCriteriaInterface;
6
7
/**
8
 * @author Krzysztof Gzocha <[email protected]>
9
 */
10
class MappedOrderByAdapter implements OrderByQueryCriteriaInterface
11
{
12
    /**
13
     * @var OrderByQueryCriteriaInterface
14
     */
15
    private $orderBy;
16
17
    /**
18
     * @var array|\ArrayAccess
19
     */
20
    private $fieldsMap;
21
22
    /**
23
     * @param OrderByQueryCriteriaInterface $orderBy
24
     * @param array|\ArrayAccess          $fieldsMap
25
     */
26 7
    public function __construct(
27
        OrderByQueryCriteriaInterface $orderBy,
28
        $fieldsMap
29
    ) {
30 7
        $this->checkFieldsMapType($fieldsMap);
31 6
        $this->orderBy = $orderBy;
32 6
        $this->fieldsMap = $fieldsMap;
33 6
    }
34
35
    /**
36
     * @return string|null
37
     */
38 2
    public function getMappedOrderBy()
39
    {
40 2
        if ($this->rawValueExistsInFieldsMap()) {
41 1
            return $this->fieldsMap[$this->getOrderBy()];
42
        }
43
44 1
        return null;
45
    }
46
47
    /**
48
     * @return array|\ArrayAccess
49
     */
50 1
    public function getFieldsMap()
51
    {
52 1
        return $this->fieldsMap;
53
    }
54
55
    /**
56
     * @inheritDoc
57
     */
58 3
    public function getOrderBy()
59
    {
60 3
        return $this->orderBy->getOrderBy();
61
    }
62
63
    /**
64
     * @inheritDoc
65
     */
66 4
    public function setOrderBy($orderBy)
67
    {
68 4
        return $this->orderBy->setOrderBy($orderBy);
69
    }
70
71
    /**
72
     * @inheritDoc
73
     */
74 2
    public function shouldBeApplied()
75
    {
76 2
        return $this->orderBy->shouldBeApplied() && $this->rawValueExistsInFieldsMap();
77
    }
78
79
    /**
80
     * @param $fieldsMap
81
     * @throws \InvalidArgumentException
82
     */
83 7
    private function checkFieldsMapType($fieldsMap)
84
    {
85 7
        if (!is_array($fieldsMap) && !$fieldsMap instanceof \ArrayAccess) {
86 1
            throw new \InvalidArgumentException(sprintf(
87
                'Parameter fieldsMap passed to %s should be an array or \ArrayAccess.'
88 1
                . ' Given: %s',
89 1
                __CLASS__,
90 1
                is_object($fieldsMap) ? get_class($fieldsMap) : gettype($fieldsMap)
91
            ));
92
        }
93 6
    }
94
95
    /**
96
     * @return bool
97
     */
98 3
    private function rawValueExistsInFieldsMap()
99
    {
100 3
        return array_key_exists($this->getOrderBy(), $this->fieldsMap);
101
    }
102
}
103