Completed
Push — master ( 856811...eec34e )
by Siim
12:20
created

AbstractOrder::directionExists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
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
    const PROPERTY_DIRECTION = 'direction';
15
    const PROPERTY_FIELD = 'field';
16
17
    /** @var string $direction */
18
    protected $direction;
19
20
    /** @var string $field */
21
    protected $field;
22
23
    /**
24
     * @param string $direction
25
     */
26
    public function setDirection(string $direction)
27
    {
28
        if(false === $this->directionExists($direction)) {
29
            $direction = static::DIRECTION_ASCENDING;
30
        }
31
        $this->direction = $direction;
32
    }
33
34
    /**
35
     * @return string
36
     */
37
    public function getDirection(): string
38
    {
39
        if(!$this->direction) {
40
            $this->direction = static::DIRECTION_ASCENDING;
41
        }
42
        return $this->direction;
43
    }
44
45
    /**
46
     * @param string $direction
47
     * @return bool
48
     */
49
    protected function directionExists(string $direction): bool
50
    {
51
        return in_array($direction, [
52
            static::DIRECTION_ASCENDING,
53
            static::DIRECTION_DESCENDING
54
        ]);
55
    }
56
57
    /**
58
     * @param string $field
59
     */
60
    public function setField(string $field)
61
    {
62
        if(false === $this->fieldExists($field)) {
63
            $field = static::DEFAULT_FIELD;
64
        }
65
        $this->field = $field;
66
    }
67
68
    /**
69
     * @return string
70
     */
71
    public function getField(): string
72
    {
73
        if(!$this->field) {
74
            $this->field = static::DEFAULT_FIELD;
75
        }
76
        return $this->field;
77
    }
78
79
    /**
80
     * @param string $field
81
     * @return bool
82
     */
83
    protected function fieldExists(string $field): bool
84
    {
85
        return in_array($field, $this->getAvailableFields());
86
    }
87
88
    public function populate(array $data)
89
    {
90
        if(isset($data[static::PROPERTY_DIRECTION]) && isset($data[static::PROPERTY_FIELD])) {
91
            $this->setDirection($data[static::PROPERTY_DIRECTION]);
92
            $this->setField($data[static::PROPERTY_FIELD]);
93
        }
94
    }
95
96
    public function toArray(): array
97
    {
98
        return [
99
            static::PROPERTY_DIRECTION => $this->getDirection(),
100
            static::PROPERTY_FIELD => $this->getField()
101
        ];
102
    }
103
}
104