1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of the Simplex package. |
5
|
|
|
* |
6
|
|
|
* (c) Freddie Frantzen <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
namespace Simplex; |
12
|
|
|
|
13
|
|
|
use JMS\Serializer\SerializerInterface; |
14
|
|
|
use Lukasoppermann\Httpstatus\Httpstatuscodes; |
15
|
|
|
use Psr\Http\Message\ResponseInterface; |
16
|
|
|
use Psr\Http\Message\ResponseInterface as Response; |
17
|
|
|
use Symfony\Component\Routing\Generator\UrlGeneratorInterface; |
18
|
|
|
|
19
|
|
|
abstract class BaseController implements Controller |
20
|
|
|
{ |
21
|
|
|
protected const JSON_FORMAT = 'json'; |
22
|
|
|
|
23
|
|
|
/** @var UrlGeneratorInterface */ |
24
|
|
|
protected $urlGenerator; |
25
|
|
|
|
26
|
|
|
/** @var SerializerInterface */ |
27
|
|
|
protected $serializer; |
28
|
|
|
|
29
|
|
|
/** @var ResponseInterface */ |
30
|
|
|
protected $response; |
31
|
|
|
|
32
|
|
|
public function setUrlGenerator(UrlGeneratorInterface $urlGenerator): void |
33
|
|
|
{ |
34
|
|
|
$this->urlGenerator = $urlGenerator; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function setSerializer(SerializerInterface $serializer): void |
38
|
|
|
{ |
39
|
|
|
$this->serializer = $serializer; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function setResponse(ResponseInterface $response): void |
43
|
|
|
{ |
44
|
|
|
$this->response = $response; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public function jsonResponse($data = null, int $status = Httpstatuscodes::HTTP_OK): Response |
48
|
|
|
{ |
49
|
|
|
if ($data !== null) { |
50
|
|
|
|
51
|
|
|
$serialized = $this->serializer->serialize($data, self::JSON_FORMAT); |
52
|
|
|
|
53
|
|
|
$this->response->getBody()->write($serialized); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
return $this->response->withStatus($status); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function setHeader(string $headerName, string $headerValue): void |
60
|
|
|
{ |
61
|
|
|
$this->response = $this->response->withHeader($headerName, $headerValue); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|