Completed
Push — ezp24315-sorting_in_rest_views ( 4b8804 )
by
unknown
21:51
created

DataKeyValueObjectClass::parse()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 1
Metric Value
cc 3
eloc 7
c 1
b 1
f 1
nc 3
nop 2
dl 0
loc 14
rs 9.4285
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
    /** @var string $dataKey */
13
    protected $dataKey;
14
15
    /** @var string $valueObjectClass */
16
    protected $valueObjectClass;
17
18
    /**
19
     * DataKeyValueObjectClass constructor.
20
     * 
21
     * @param string $dataKey
22
     * @param string $valueObjectClass
23
     */
24
    public function __construct($dataKey, $valueObjectClass)
25
    {
26
        $this->dataKey = $dataKey;
27
        $this->valueObjectClass = $valueObjectClass;
28
    }
29
30
    /**
31
     * Parse input structure.
32
     *
33
     * @param array $data
34
     * @param \eZ\Publish\Core\REST\Common\Input\ParsingDispatcher $parsingDispatcher
35
     *
36
     * @return \eZ\Publish\API\Repository\Values\ValueObject
37
     */
38
    public function parse(array $data, ParsingDispatcher $parsingDispatcher)
39
    {
40
        if (!array_key_exists($this->dataKey, $data)) {
41
            throw new Exceptions\Parser("The <{$this->dataKey}> sort clause doesn't exist in the input structure");
42
        }
43
44
        $direction = $data[$this->dataKey];
45
46
        if (!in_array($direction, [Query::SORT_ASC, Query::SORT_DESC])) {
47
            throw new Exceptions\Parser("Invalid direction format in <{$this->dataKey}> sort clause");
48
        }
49
50
        return new $this->valueObjectClass($direction);
51
    }
52
}
53