Completed
Push — master ( ff9b79...7869cf )
by Alexpts
02:33
created

ControllerPoint::__invoke()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
namespace PTS\Routing\Point;
3
4
use PTS\Routing\Route;
5
6
class ControllerPoint extends AbstractPoint
7
{
8
    protected $controller;
9
    protected $action;
10
11
    /**
12
     * @param Route $route
13
     * @param array $args
14
     *
15
     * @return mixed
16
     */
17 5
    public function __invoke(Route $route, array $args = [])
18
    {
19 5
        $endPoint = $this->getPoint($route);
20 3
        return call_user_func_array($endPoint, $args);
21
    }
22
23
    /**
24
     * @param Route $route
25
     * @return callable
26
     */
27 5
    protected function getPoint(Route $route)
28
    {
29 5
        $matches = $route->getMatches();
30 5
        $controller = $this->getControllerClass();
31 5
        $this->checkController($controller);
32
33 4
        $controller = new $controller();
34
35 4
        $action = $this->getAction($matches);
36 4
        $this->checkAction($controller, $action);
37
38 3
        return [$controller, $action];
39
    }
40
41
    /**
42
     * @return string
43
     */
44 5
    protected function getControllerClass() : string
45
    {
46 5
        return $this->controller;
47
    }
48
49
    /**
50
     * @param $controller
51
     * @throws \BadMethodCallException
52
     */
53 5
    protected function checkController($controller)
54
    {
55 5
        if (!class_exists($controller)) {
56 1
            throw new \BadMethodCallException('Controller not found');
57
        }
58 4
    }
59
60
    /**
61
     * @param $controller
62
     * @param string $action
63
     * @throws \BadMethodCallException
64
     */
65 4
    protected function checkAction($controller, $action)
66
    {
67 4
        if (!method_exists($controller, $action)) {
68 1
            throw new \BadMethodCallException('Action not found');
69
        }
70 3
    }
71
72
    /**
73
     * @param array $matches
74
     * @return string
75
     */
76 4
    protected function getAction(array $matches = []) : string
77
    {
78 4
        return $matches['_action'] ?? $this->action ?? 'index';
79
    }
80
81
}
82