Completed
Push — master ( 3528ad...ff9b79 )
by Alexpts
02:31
created

ControllerPoint   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%
Metric Value
wmc 8
lcom 1
cbo 2
dl 0
loc 76
ccs 0
cts 23
cp 0
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 5 1
A getPoint() 0 13 1
A getControllerClass() 0 4 1
A checkController() 0 6 2
A checkAction() 0 6 2
A getAction() 0 4 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
    public function __invoke(Route $route, array $args = [])
18
    {
19
        $endPoint = $this->getPoint($route);
20
        return call_user_func_array($endPoint, $args);
21
    }
22
23
    /**
24
     * @param Route $route
25
     * @return callable
26
     */
27
    protected function getPoint(Route $route)
28
    {
29
        $matches = $route->getMatches();
30
        $controller = $this->getControllerClass();
31
        $this->checkController($controller);
32
33
        $controller = new $controller();
34
35
        $action = $this->getAction($matches);
36
        $this->checkAction($controller, $action);
37
38
        return [$controller, $action];
39
    }
40
41
    /**
42
     * @return string
43
     */
44
    protected function getControllerClass() : string
45
    {
46
        return $this->controller;
47
    }
48
49
    /**
50
     * @param $controller
51
     * @throws \BadMethodCallException
52
     */
53
    protected function checkController($controller)
54
    {
55
        if (!class_exists($controller)) {
56
            throw new \BadMethodCallException('Controller not found');
57
        }
58
    }
59
60
    /**
61
     * @param $controller
62
     * @param string $action
63
     * @throws \BadMethodCallException
64
     */
65
    protected function checkAction($controller, $action)
66
    {
67
        if (!method_exists($controller, $action)) {
68
            throw new \BadMethodCallException('Action not found');
69
        }
70
    }
71
72
    /**
73
     * @param array $matches
74
     * @return string
75
     */
76
    protected function getAction(array $matches = []) : string
77
    {
78
        return $matches['_action'] ?? $this->action ?? 'index';
79
    }
80
81
}
82