Completed
Pull Request — master (#36)
by
unknown
08:48
created

LeaderBoard::addItem()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 1
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 4
                function (Item $item) {
58
                    /*
59
                     * @var Item $item
60
                     */
61 3
                    return $item->toArray();
62 4
                },
63 4
                array_values($this->getItems($order))
64
            ),
65
        );
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
        return $items;
81
    }
82
}
83