Passed
Branch cake4 (6bfeea)
by n
02:11
created

ControllerFactory::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace N1215\CakeCandle\Controller;
5
6
use Cake\Controller\Controller;
7
use Cake\Http\ServerRequest;
8
use N1215\CakeCandle\ContainerBagInterface;
9
use N1215\CakeCandle\Invoker\Exceptions\InvocationException;
10
use Psr\Container\ContainerExceptionInterface;
11
use Psr\Http\Message\ResponseInterface;
12
use Psr\Http\Message\ServerRequestInterface;
13
use ReflectionClass;
14
use ReflectionException;
15
16
/**
17
 * Factory method for building controllers for request.
18
 */
19
class ControllerFactory extends \Cake\Controller\ControllerFactory
20
{
21
    /**
22
     * @var ContainerBagInterface
23
     */
24
    private $containerBag;
25
26
    /**
27
     * @param ContainerBagInterface $containerBag
28
     */
29 4
    public function __construct(ContainerBagInterface $containerBag)
30
    {
31 4
        $this->containerBag = $containerBag;
32 4
    }
33
34
    /**
35
     * @inheritdoc
36
     * @throws ReflectionException
37
     * @throws ContainerExceptionInterface
38
     */
39 4
    public function create(ServerRequestInterface $request): Controller
40
    {
41 4
        assert($request instanceof ServerRequest);
42 4
        $className = $this->getControllerClass($request);
43 4
        if (!$className) {
44 1
            $this->missingController($request);
45
        }
46
47 3
        $reflection = new ReflectionClass($className);
48 3
        if ($reflection->isAbstract()) {
49 1
            $this->missingController($request);
50
        }
51
52
        /** @var Controller $controller */
53 2
        $controller = $this->containerBag->get($className);
54
55 1
        $controller->setRequest($request);
56
57 1
        return $controller;
58
    }
59
60
    /**
61
     * @inheritDoc
62
     * @throws InvocationException
63
     */
64
    public function invoke($controller): ResponseInterface
65
    {
66
        $result = $controller->startupProcess();
67
        if ($result instanceof ResponseInterface) {
68
            return $result;
69
        }
70
71
        $action = $controller->getAction();
72
        $args = array_values($controller->getRequest()->getParam('pass'));
73
74
        $args = $this->containerBag->complement($action, $args);
75
76
        $controller->invokeAction($action, $args);
77
78
        $result = $controller->shutdownProcess();
79
        if ($result instanceof ResponseInterface) {
80
            return $result;
81
        }
82
83
        return $controller->getResponse();
84
    }
85
}
86