Completed
Push — ezp26175-exception_on_non_defa... ( 77d2f3...ca5fc8 )
by
unknown
39:33
created

DataKeyValueObjectClass   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 55
rs 10
wmc 5
lcom 1
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A parse() 0 18 4
1
<?php
2
3
namespace eZ\Publish\Core\REST\Server\Input\Parser\SortClause;
4
5
use eZ\Publish\API\Repository\Values\Content\Query;
6
use eZ\Publish\Core\REST\Common\Input\BaseParser;
7
use eZ\Publish\Core\REST\Common\Input\ParsingDispatcher;
8
use eZ\Publish\Core\REST\Common\Exceptions;
9
10
class DataKeyValueObjectClass extends BaseParser
11
{
12
    /**
13
     * Data key, corresponding to the $valueObjectClass class.
14
     * Example: 'DatePublished'.
15
     * @var string
16
     */
17
    protected $dataKey;
18
19
    /**
20
     * Value object class, corresponding to the $dataKey.
21
     * Example: 'eZ\Publish\API\Repository\Values\Content\Query\SortClause\DatePublished'.
22
     * @var string
23
     */
24
    protected $valueObjectClass;
25
26
    /**
27
     * DataKeyValueObjectClass constructor.
28
     *
29
     * @param string $dataKey
30
     * @param string $valueObjectClass
31
     */
32
    public function __construct($dataKey, $valueObjectClass)
33
    {
34
        $this->dataKey = $dataKey;
35
        $this->valueObjectClass = $valueObjectClass;
36
    }
37
38
    /**
39
     * Parse input structure.
40
     *
41
     * @param array $data
42
     * @param \eZ\Publish\Core\REST\Common\Input\ParsingDispatcher $parsingDispatcher
43
     *
44
     * @return \eZ\Publish\API\Repository\Values\ValueObject
45
     */
46
    public function parse(array $data, ParsingDispatcher $parsingDispatcher)
47
    {
48
        if (!class_exists($this->valueObjectClass)) {
49
            throw new Exceptions\Parser("Value object class <{$this->valueObjectClass}> is not defined");
50
        }
51
52
        if (!array_key_exists($this->dataKey, $data)) {
53
            throw new Exceptions\Parser("The <{$this->dataKey}> sort clause doesn't exist in the input structure");
54
        }
55
56
        $direction = $data[$this->dataKey];
57
58
        if (!in_array($direction, [Query::SORT_ASC, Query::SORT_DESC])) {
59
            throw new Exceptions\Parser("Invalid direction format in <{$this->dataKey}> sort clause");
60
        }
61
62
        return new $this->valueObjectClass($direction);
63
    }
64
}
65