Completed
Push — master ( 15f393...42b28c )
by Carlos
03:29 queued 01:06
created

LeaderBoard::getItems()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 8
ccs 3
cts 4
cp 0.75
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
crap 2.0625
1
<?php
2
3
namespace CarlosIO\Geckoboard\Widgets;
4
5
use CarlosIO\Geckoboard\Data\LeaderBoard\Item;
6
7
/**
8
 * Class LeaderBoard.
9
 */
10
class LeaderBoard extends Widget
11
{
12
    const SORT_ASC = 1;
13
    const SORT_DESC = -1;
14
15
    /**
16
     * @var array
17
     */
18
    protected $items = array();
19
20
    /**
21
     * @param null $order
22
     *
23
     * @return Item[]
24
     */
25 4
    public function getItems($order = null)
26
    {
27 4
        if (null === $order) {
28
            return $this->items;
29
        }
30
31 4
        return $this->sort($this->items, $order);
32
    }
33
34
    /**
35
     * @param $item
36
     *
37
     * @return $this
38
     */
39 3
    public function addItem(Item $item)
40
    {
41 3
        $this->items[] = $item;
42
43 3
        return $this;
44
    }
45
46
    /**
47
     * Get data in array format.
48
     *
49
     * @param int $order
50
     *
51
     * @return array
52
     */
53 4
    public function getData($order = self::SORT_DESC)
54
    {
55
        return array(
56 4
            'items' => array_map(
57
                function ($item) {
58
                    /*
59
                     * @var Item $item
60
                     */
61 3
                    return $item->toArray();
62 4
                },
63 4
                array_values($this->getItems($order))
64 4
            ),
65 4
        );
66
    }
67
68
    /**
69
     * @param $items
70
     * @param $order
71
     *
72
     * @return array
73
     */
74
    private function sort($items, $order)
75
    {
76 4
        uasort($items, function (Item $item1, Item $item2) use ($order) {
77 2
            return ($item1->getValue() < $item2->getValue()) ? (-1 * $order) : $order;
78 4
        });
79
80 4
        return $items;
81
    }
82
}
83