SubmissionHandler::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
c 0
b 0
f 0
nc 1
nop 4
dl 0
loc 10
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chinstrap\Core\Http\Handlers;
6
7
use Chinstrap\Core\Contracts\Sources\Source;
8
use Chinstrap\Core\Contracts\Views\Renderer;
9
use Chinstrap\Core\Events\FormSubmitted;
10
use Laminas\Diactoros\Response\EmptyResponse;
11
use Laminas\EventManager\EventManagerInterface;
12
use League\Route\Http\Exception\NotFoundException;
13
use Psr\Http\Message\ResponseInterface;
14
use Psr\Http\Message\ServerRequestInterface;
15
16
final class SubmissionHandler
17
{
18
    private ResponseInterface $response;
19
    private Source $source;
20
    private Renderer $view;
21
    private EventManagerInterface $eventManager;
22
23
    public function __construct(
24
        ResponseInterface $response,
25
        Source $source,
26
        Renderer $view,
27
        EventManagerInterface $eventManager
28
    ) {
29
        $this->response = $response;
30
        $this->source = $source;
31
        $this->view = $view;
32
        $this->eventManager = $eventManager;
33
    }
34
35
    /**
36
     * POST request to content page
37
     *
38
     * @param ServerRequestInterface $request
39
     * @param array{name: ?string} $args
40
     */
41
    public function __invoke(ServerRequestInterface $request, array $args): ResponseInterface
42
    {
43
        $name = isset($args['name']) ? $args['name'] : 'index';
44
        if (!$document = $this->source->find($name)) {
0 ignored issues
show
Bug introduced by
It seems like $name can also be of type null; however, parameter $name of Chinstrap\Core\Contracts\Sources\Source::find() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

44
        if (!$document = $this->source->find(/** @scrutinizer ignore-type */ $name)) {
Loading history...
45
            throw new NotFoundException('Page not found');
46
        }
47
        $data = $document->getFields();
48
        if (!isset($data['forms'])) {
49
            return new EmptyResponse(405);
50
        }
51
        $data['content'] = $document->getContent();
52
        $layout = isset($data['layout']) ? $data['layout'] . '.html' : 'default.html';
53
        $this->eventManager->trigger(FormSubmitted::class);
54
        return $this->view->render($this->response, $layout, $data);
55
    }
56
}
57