Completed
Push — master ( bbff6f...c51acf )
by Rafał
19:14 queued 09:31
created

Order::camelize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher ElasticSearch Bundle.
7
 *
8
 * Copyright 2017 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2017 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\ElasticSearchBundle\Criteria;
18
19
final class Order
20
{
21
    const DEFAULT_FIELD = 'id';
22
23
    const DEFAULT_DIRECTION = self::ASCENDING_DIRECTION;
24
25
    const ASCENDING_DIRECTION = 'asc';
26
27
    const DESCENDING_DIRECTION = 'desc';
28
29
    /**
30
     * @var string
31
     */
32
    private $field;
33
34
    /**
35
     * @var string
36
     */
37
    private $direction;
38
39
    /**
40
     * @param string $field
41
     * @param string $direction
42
     */
43
    private function __construct($field, $direction)
44
    {
45
        $this->field = $field;
46
        $this->direction = $direction;
47
    }
48
49
    /**
50
     * @param array $parameters
51
     *
52
     * @return Order
53
     */
54
    public static function fromQueryParameters(array $parameters)
55
    {
56
        $sort = isset($parameters['sort']) && is_array($parameters['sort']) ? $parameters['sort'] : [self::DEFAULT_FIELD => self::DEFAULT_DIRECTION];
57
58
        $direction = self::DEFAULT_DIRECTION;
59
        if (self::DESCENDING_DIRECTION === array_values($sort)[0]) {
60
            $direction = self::DESCENDING_DIRECTION;
61
        }
62
63
        $field = self::DEFAULT_FIELD;
64
        if (self::DEFAULT_FIELD !== array_keys($sort)[0]) {
65
            $field = self::camelize(array_keys($sort)[0]);
66
        }
67
68
        return new self($field, $direction);
69
    }
70
71
    private static function camelize(string $value): string
72
    {
73
        return lcfirst(str_replace('_', '', ucwords($value, '_')));
74
    }
75
76
    /**
77
     * @return string
78
     */
79
    public function getField()
80
    {
81
        return $this->field;
82
    }
83
84
    /**
85
     * @return string
86
     */
87
    public function getDirection()
88
    {
89
        return $this->direction;
90
    }
91
}
92