Completed
Pull Request — master (#61)
by Tomas
03:17
created

ApiListingControl::handleSelect()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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