Completed
Pull Request — master (#61)
by Michal
03:22
created

ApiListingControl::groupApis()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 12
cp 0
rs 9.8666
c 0
b 0
f 0
cc 3
nc 3
nop 1
crap 12
1
<?php
2
3
namespace Tomaj\NetteApi\Component;
4
5
use Nette\Application\UI\Control;
6
use Nette\ComponentModel\IContainer;
7
use Tomaj\NetteApi\ApiDecider;
8
use Closure;
9
use Exception;
10
use Tomaj\NetteApi\Api;
11
12
class ApiListingControl extends Control
13
{
14
    /** @var ApiDecider */
15
    private $apiDecider;
16
17
    /** @var Closure|null */
18
    private $clickCallback;
19
20
    public function __construct(IContainer $parent, $name, ApiDecider $apiDecider)
21
    {
22
        $this->apiDecider = $apiDecider;
23
    }
24
25
    public function onClick(Closure $callback)
26
    {
27
        $this->clickCallback = $callback;
28
    }
29
30
    public function render()
31
    {
32
        $apis = $this->apiDecider->getApis();
33
        $this->getTemplate()->add('apis', $this->groupApis($apis));
34
        $this->getTemplate()->setFile(__DIR__ . '/api_listing.latte');
35
        $this->getTemplate()->render();
36
    }
37
38
    public function handleSelect($method, $version, $package, $apiAction)
39
    {
40
        if (!$this->clickCallback) {
41
            throw new Exception('You have to set onClick callback to component!');
42
        }
43
44
        $this->clickCallback->__invoke($method, $version, $package, $apiAction);
45
    }
46
47
    /**
48
     * @param Api[] $handlers
49
     * @return array
50
     */
51
    private function groupApis($handlers)
52
    {
53
        $versionHandlers = [];
54
        foreach ($handlers as $handler) {
55
            $endPoint = $handler->getEndpoint();
56
            if (!isset($versionHandlers[$endPoint->getVersion()])) {
57
                $versionHandlers[$endPoint->getVersion()] = [];
58
            }
59
            $versionHandlers[$endPoint->getVersion()][] = $handler;
60
        }
61
        return $versionHandlers;
62
    }
63
}
64