1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Igni\Http\Controller; |
4
|
|
|
|
5
|
|
|
use Igni\Application\Controller\ControllerAggregate as ControllerAggregateInterface; |
6
|
|
|
use Igni\Application\Exception\ApplicationException; |
7
|
|
|
use Igni\Http\Controller; |
8
|
|
|
use Igni\Http\Route; |
9
|
|
|
use Igni\Http\Router; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Http application's controller aggregate. |
13
|
|
|
* @see \Igni\Application\Controller |
14
|
|
|
* @package Igni\Http\Controller |
15
|
|
|
*/ |
16
|
|
|
class ControllerAggregate implements ControllerAggregateInterface |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @var Router |
20
|
|
|
*/ |
21
|
|
|
private $router; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* ControllerAggregate constructor. |
25
|
|
|
* @param Router $router |
26
|
|
|
*/ |
27
|
16 |
|
public function __construct(Router $router) |
28
|
|
|
{ |
29
|
16 |
|
$this->router = $router; |
30
|
16 |
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Registers new controller and attaches it to passed route. |
34
|
|
|
* |
35
|
|
|
* @param callable|string $controller can be either callable or class implementing Igni\Http\Controller interface or its instance. |
36
|
|
|
* @param Route|null $route must be passed if callable is passed as a controller. |
37
|
|
|
* |
38
|
|
|
* @throws ApplicationException if passed controller is not valid. |
39
|
|
|
*/ |
40
|
12 |
|
public function add($controller, Route $route = null): void |
41
|
|
|
{ |
42
|
12 |
|
if (is_callable($controller) && $route !== null) { |
43
|
10 |
|
$route->delegate($controller); |
44
|
10 |
|
$this->router->addRoute($route); |
45
|
10 |
|
return; |
46
|
|
|
} |
47
|
|
|
|
48
|
2 |
|
if ($controller instanceof Controller) { |
49
|
|
|
/** @var Route $route */ |
50
|
1 |
|
$route = $controller::getRoute(); |
51
|
1 |
|
$route->delegate($controller); |
52
|
1 |
|
$this->router->addRoute($route); |
53
|
1 |
|
return; |
54
|
|
|
} |
55
|
|
|
|
56
|
1 |
|
if (is_string($controller) && |
57
|
1 |
|
class_exists($controller) && |
58
|
1 |
|
in_array(Controller::class, class_implements($controller)) |
59
|
|
|
) { |
60
|
|
|
/** @var Route $route */ |
61
|
1 |
|
$route = $controller::getRoute(); |
62
|
1 |
|
$route->delegate($controller); |
63
|
1 |
|
$this->router->addRoute($route); |
64
|
1 |
|
return; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
throw ApplicationException::forInvalidController($controller); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|