Passed
Push — master ( e3c67b...98eade )
by Fran
08:10
created

Order::fromArray()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 2
rs 10
1
<?php
2
namespace PSFS\base\dto;
3
4
class Order extends Dto
5
{
6
    const ASC = 'ASC';
7
    const DESC = 'DESC';
8
    /**
9
     * Fields to use to order
10
     * @var array fields
11
     */
12
    protected $fields = array();
13
14
    /**
15
     * Add new order to dto
16
     *
17
     * @param string $field
18
     * @param string $direction
19
     */
20 1
    public function addOrder($field, $direction = self::ASC)
21
    {
22 1
        $this->fields[$field] = $direction;
23 1
    }
24
25
    /**
26
     * Remove existing order
27
     *
28
     * @param string $fieldToRemove
29
     */
30 1
    public function removeOrder($fieldToRemove)
31
    {
32 1
        $order = array();
33 1
        if (count($order) > 0) {
34
            foreach ($this->fields as $field => $direction) {
35
                if (strtolower($fieldToRemove) === strtolower($field)) {
36
                    continue;
37
                }
38
                $order[$field] = $direction;
39
            }
40
        }
41 1
        $this->fields = $order;
42 1
    }
43
44
    /**
45
     * Set an order field
46
     *
47
     * @param string $field
48
     * @param string $direction
49
     */
50
    public function setOrder($field, $direction = self::ASC)
51
    {
52
        $this->fields = [$field => $direction];
53
    }
54
55
    /**
56
     * Parse direction string
57
     * @param string $direction
58
     *
59
     * @return string
60
     */
61
    public static function parseDirection($direction = self::ASC)
62
    {
63
        if (preg_match('/^asc$/i', $direction)) {
64
            return self::ASC;
65
        } else {
66
            return self::DESC;
67
        }
68
    }
69
70
    /**
71
     * Return all order fields
72
     * @return array
73
     */
74
    public function getOrders()
75
    {
76
        return $this->fields;
77
    }
78
79
    /**
80
     * @param array $object
81
     */
82 1
    public function fromArray(array $object = array())
83
    {
84 1
        foreach($object as $field => $order) {
85 1
            $this->addOrder($field, $order);
86
        }
87 1
    }
88
89
    /**
90
     * @return array
91
     */
92 1
    public function toArray()
93
    {
94 1
        return $this->fields;
95
    }
96
}