delboy1978uk /
oauth2-api
| 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 | use Zend\Diactoros\Stream; |
||
| 13 | |||
| 14 | class BaseController extends Controller |
||
| 15 | { |
||
| 16 | /** @var Serializer */ |
||
| 17 | protected $serializer; |
||
| 18 | |||
| 19 | 30 | public function __construct(ServerRequestInterface $request) |
|
| 20 | { |
||
| 21 | 30 | parent::__construct($request); |
|
| 22 | 30 | $this->serializer = SerializerBuilder::create()->build(); |
|
| 23 | 30 | $this->disableView(); |
|
| 24 | 30 | $this->disableLayout(); |
|
| 25 | 30 | } |
|
| 26 | |||
| 27 | /** |
||
| 28 | * @param $object |
||
| 29 | * @param int $statusCode |
||
| 30 | */ |
||
| 31 | 10 | public function sendJsonObjectResponse($object, $statusCode = 200) |
|
| 32 | { |
||
| 33 | 10 | if (!is_object($object) && !is_array($object)) { |
|
| 34 | 1 | throw new InvalidArgumentException('You must pass an object or array.'); |
|
| 35 | } |
||
| 36 | 9 | $this->disableLayout(); |
|
| 37 | 9 | $this->disableView(); |
|
| 38 | 9 | $this->setHeader('Cache-Control', 'no-cache, must-revalidate'); |
|
| 39 | 9 | $this->setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT'); |
|
| 40 | 9 | $this->setHeader('Content-Type','application/json'); |
|
| 41 | 9 | $json = $this->serializer->serialize($object, 'json'); |
|
| 42 | 9 | $this->setBody($json); |
|
| 43 | 9 | $this->setStatusCode($statusCode); |
|
| 44 | 9 | } |
|
| 45 | |||
| 46 | 12 | protected function httpMethodCheck($method) |
|
| 47 | { |
||
| 48 | 12 | if ($this->getRequest()->getMethod() !== $method) { |
|
| 49 | $this->sendJsonResponse(['error' => 'Method not allowed'], 405); |
||
| 50 | |||
| 51 | return false; |
||
| 52 | } |
||
| 53 | |||
| 54 | 12 | return true; |
|
| 55 | } |
||
| 56 | |||
| 57 | /** |
||
| 58 | * @param ResponseInterface $response |
||
| 59 | */ |
||
| 60 | 8 | protected function sendResponse(ResponseInterface $response) |
|
| 61 | { |
||
| 62 | 8 | $emitter = new SapiEmitter(); |
|
|
0 ignored issues
–
show
Deprecated Code
introduced
by
Loading history...
|
|||
| 63 | 8 | $emitter->emit($response); |
|
| 64 | 8 | exit; |
|
|
0 ignored issues
–
show
|
|||
| 65 | } |
||
| 66 | |||
| 67 | /** |
||
| 68 | * @param $content |
||
| 69 | * @return Stream |
||
| 70 | */ |
||
| 71 | public function createStreamFromString($content) |
||
| 72 | { |
||
| 73 | $stream = new Stream('php://memory', 'wb+'); |
||
| 74 | $stream->write($content); |
||
| 75 | $stream->rewind(); |
||
| 76 | |||
| 77 | return $stream; |
||
| 78 | } |
||
| 79 | } |