1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Controller; |
4
|
|
|
|
5
|
|
|
use Bone\Mvc\Controller; |
6
|
|
|
use InvalidArgumentException; |
7
|
|
|
use JMS\Serializer\Serializer; |
8
|
|
|
use JMS\Serializer\SerializerBuilder; |
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
10
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
11
|
|
|
use Zend\Diactoros\Response\SapiEmitter; |
12
|
|
|
|
13
|
|
|
class BaseController extends Controller |
14
|
|
|
{ |
15
|
|
|
/** @var Serializer */ |
16
|
|
|
protected $serializer; |
17
|
|
|
|
18
|
27 |
|
public function __construct(ServerRequestInterface $request) |
19
|
|
|
{ |
20
|
27 |
|
parent::__construct($request); |
21
|
27 |
|
$this->serializer = SerializerBuilder::create()->build(); |
22
|
27 |
|
$this->disableView(); |
23
|
27 |
|
$this->disableLayout(); |
24
|
27 |
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param $object |
28
|
|
|
* @param int $statusCode |
29
|
|
|
*/ |
30
|
8 |
|
public function sendJsonObjectResponse($object, $statusCode = 200) |
31
|
|
|
{ |
32
|
8 |
|
if (!is_object($object)) { |
33
|
|
|
throw new InvalidArgumentException('You must pass an object.'); |
34
|
|
|
} |
35
|
8 |
|
$this->disableLayout(); |
36
|
8 |
|
$this->disableView(); |
37
|
8 |
|
$this->setHeader('Cache-Control', 'no-cache, must-revalidate'); |
38
|
8 |
|
$this->setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT'); |
39
|
8 |
|
$this->setHeader('Content-Type','application/json'); |
40
|
8 |
|
$json = $this->serializer->serialize($object, 'json'); |
41
|
8 |
|
$this->setBody($json); |
42
|
8 |
|
$this->setStatusCode($statusCode); |
43
|
8 |
|
} |
44
|
|
|
|
45
|
12 |
|
protected function httpMethodCheck($method) |
46
|
|
|
{ |
47
|
12 |
|
if ($this->getRequest()->getMethod() !== $method) { |
48
|
|
|
$this->sendJsonResponse(['error' => 'Method not allowed'], 405); |
49
|
|
|
|
50
|
|
|
return false; |
51
|
|
|
} |
52
|
|
|
|
53
|
12 |
|
return true; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param ResponseInterface $response |
58
|
|
|
*/ |
59
|
6 |
|
protected function sendResponse(ResponseInterface $response) |
60
|
|
|
{ |
61
|
6 |
|
$emitter = new SapiEmitter(); |
|
|
|
|
62
|
6 |
|
$emitter->emit($response); |
63
|
6 |
|
exit; |
|
|
|
|
64
|
|
|
} |
65
|
|
|
} |