ResultOrdering   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 89.47%

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 1
dl 0
loc 71
ccs 17
cts 19
cp 0.8947
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 3
A orderItems() 0 13 4
A isRequired() 0 4 1
A comparePivotValues() 0 4 1
1
<?php
2
namespace EngineWorks\Pivot;
3
4
/**
5
 * Class to sort elements (ordering) of a result
6
 */
7
class ResultOrdering
8
{
9
    /** @var array */
10
    private $orderBy;
11
12
    /** @var bool */
13
    private $required;
14
15
    /**
16
     * ResultOrdering constructor
17
     * The parameter orderBy must contain the list of aggregates and the order they must use
18
     * [$aggregate1 => $order1, $aggregate2 => $order2, ... ]
19
     *
20
     * @param array $orderBy
21
     */
22 9
    public function __construct(array $orderBy)
23
    {
24 9
        $this->orderBy = $orderBy;
25 9
        $this->required = false;
26 9
        foreach ($orderBy as $criteria) {
27 9
            if ($criteria) {
28 4
                $this->required = true;
29 9
                break;
30
            }
31
        }
32 9
    }
33
34
    /**
35
     * Method to make comparisons
36
     *
37
     * @param Result $a
38
     * @param Result $b
39
     * @return int
40
     */
41 3
    public function orderItems(Result $a, Result $b)
42
    {
43
        // compare using every aggregator with its own order type
44 3
        foreach ($this->orderBy as $field => $order) {
45 3
            if ($order === Aggregate::ORDERASC) {
46
                return $this->comparePivotValues($field, $a, $b);
47 3
            } elseif ($order === Aggregate::ORDERDESC) {
48 3
                return $this->comparePivotValues($field, $b, $a);
49
            }
50
        }
51
        // if $a and $b are the same, order alphabetically by caption
52
        return strcasecmp($a->caption, $b->caption);
53
    }
54
55
    /**
56
     * Return if ordering is required based on the orderBy array
57
     *
58
     * @return bool
59
     */
60 9
    public function isRequired()
61
    {
62 9
        return $this->required;
63
    }
64
65
    /**
66
     * Internal method to check two numerical values and return 0, -1 or 1
67
     *
68
     * @param string $field
69
     * @param Result $a
70
     * @param Result $b
71
     * @return int
72
     */
73 3
    protected function comparePivotValues($field, Result $a, Result $b)
74
    {
75 3
        return $a->values[$field] <=> $b->values[$field];
76
    }
77
}
78