AbstractOrder::directionExists()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: siim
5
 * Date: 31.01.19
6
 * Time: 10:45
7
 */
8
9
namespace Sf4\Api\Dto\Order;
10
11
abstract class AbstractOrder implements OrderInterface
12
{
13
14
    public const PROPERTY_DIRECTION = 'direction';
15
    public const PROPERTY_FIELD = 'field';
16
17
    /** @var string $direction */
18
    protected $direction;
19
20
    /** @var string $field */
21
    protected $field;
22
23
    public function populate(array $data): void
24
    {
25
        if (isset($data[static::PROPERTY_DIRECTION], $data[static::PROPERTY_FIELD])) {
26
            $this->setDirection($data[static::PROPERTY_DIRECTION]);
27
            $this->setField($data[static::PROPERTY_FIELD]);
28
        }
29
    }
30
31
    public function toArray(): array
32
    {
33
        return [
34
            static::PROPERTY_DIRECTION => $this->getDirection(),
35
            static::PROPERTY_FIELD => $this->getField()
36
        ];
37
    }
38
39
    /**
40
     * @return string
41
     */
42
    public function getDirection(): string
43
    {
44
        if (!$this->direction) {
45
            $this->direction = static::DIRECTION_ASCENDING;
46
        }
47
        return $this->direction;
48
    }
49
50
    /**
51
     * @param string $direction
52
     */
53
    public function setDirection(string $direction): void
54
    {
55
        if (false === $this->directionExists($direction)) {
56
            $direction = static::DIRECTION_ASCENDING;
57
        }
58
        $this->direction = $direction;
59
    }
60
61
    /**
62
     * @return string
63
     */
64
    public function getField(): string
65
    {
66
        if (!$this->field) {
67
            $this->field = static::DEFAULT_FIELD;
68
        }
69
        return $this->field;
70
    }
71
72
    /**
73
     * @param string $field
74
     */
75
    public function setField(string $field): void
76
    {
77
        if (false === $this->fieldExists($field)) {
78
            $field = static::DEFAULT_FIELD;
79
        }
80
        $this->field = $field;
81
    }
82
83
    /**
84
     * @param string $direction
85
     * @return bool
86
     */
87
    protected function directionExists(string $direction): bool
88
    {
89
        return in_array($direction, [
90
            static::DIRECTION_ASCENDING,
91
            static::DIRECTION_DESCENDING
92
        ], true);
93
    }
94
95
    /**
96
     * @param string $field
97
     * @return bool
98
     */
99
    protected function fieldExists(string $field): bool
100
    {
101
        return in_array($field, $this->getAvailableFields(), true);
102
    }
103
}
104