1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Selami; |
5
|
|
|
|
6
|
|
|
use Psr\Container\ContainerInterface; |
7
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
8
|
|
|
use Selami\Stdlib\Resolver; |
9
|
|
|
use ReflectionClass; |
10
|
|
|
|
11
|
|
|
class FrontController |
12
|
|
|
{ |
13
|
|
|
private $container; |
14
|
|
|
private $controller; |
15
|
|
|
private $controllerClass; |
16
|
|
|
private $uriParameters; |
17
|
|
|
private $request; |
18
|
|
|
|
19
|
|
|
public function __construct( |
20
|
|
|
ContainerInterface $container, |
21
|
|
|
ServerRequestInterface $request, |
22
|
|
|
string $controller, |
23
|
|
|
?array $uriParameters = [] |
24
|
|
|
) { |
25
|
|
|
$this->request = $request; |
26
|
|
|
$this->container = $container; |
27
|
|
|
$this->controller = $controller; |
28
|
|
|
$this->uriParameters = $uriParameters; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function getUriParameters() : array |
32
|
|
|
{ |
33
|
|
|
return $this->uriParameters; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function getControllerResponse() : ControllerResponse |
37
|
|
|
{ |
38
|
|
|
$this->controllerClass = $this->controller; |
39
|
|
|
$controllerConstructorArguments = Resolver::getParameterHints($this->controllerClass, '__construct'); |
40
|
|
|
$arguments = []; |
41
|
|
|
foreach ($controllerConstructorArguments as $argumentName => $argumentType) { |
42
|
|
|
$arguments[] = $this->getArgument($argumentName, $argumentType); |
43
|
|
|
} |
44
|
|
|
$controllerClass = new ReflectionClass($this->controllerClass); |
45
|
|
|
/** |
46
|
|
|
* @var $controllerObject \Selami\Interfaces\ApplicationController |
47
|
|
|
*/ |
48
|
|
|
$controllerObject = $controllerClass->newInstanceArgs($arguments); |
49
|
|
|
return $controllerObject(); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
private function getArgument(string $argumentName, string $argumentType) |
53
|
|
|
{ |
54
|
|
|
if ($argumentType === ServerRequestInterface::class) { |
55
|
|
|
return $this->request; |
56
|
|
|
} |
57
|
|
|
if ($argumentType === Resolver::ARRAY && $argumentName === 'uriParameters') { |
58
|
|
|
return $this->getUriParameters(); |
59
|
|
|
} |
60
|
|
|
return $this->container->has($argumentType) ? $this->container->get($argumentType) : |
61
|
|
|
$this->container->get($argumentName); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|