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)) { |
|
|
|
|
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
|
|
|
|