Completed
Push — master ( 73baea...57ba99 )
by Matthias
03:57
created

JsonController::invoke()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
nc 1
1
<?php
2
3
namespace MatthiasMullie\Api\Controllers;
4
5
use League\Route\Http\Exception;
6
use Psr\Http\Message\ResponseInterface;
7
use Psr\Http\Message\ServerRequestInterface;
8
9
/**
10
 * @author Matthias Mullie <[email protected]>
11
 * @copyright Copyright (c) 2016, Matthias Mullie. All rights reserved
12
 * @license LICENSE MIT
13
 */
14
abstract class JsonController implements ControllerInterface
15
{
16
    /**
17
     * @param ServerRequestInterface $request
18
     * @param ResponseInterface      $response
19
     * @param array                  $args
20
     *
21
     * @return array|ResponseInterface
22
     *
23
     * @throws Exception
24
     */
25
    abstract public function invoke(ServerRequestInterface $request, ResponseInterface $response, array $args);
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $args)
31
    {
32
        $result = $this->invoke($request, $response, $args);
33
34
        $response->withAddedHeader('Content-Type', 'application/json');
35
36
        if ($response->getBody()->isWritable()) {
37
            $response->getBody()->write(json_encode($result));
38
        }
39
40
        return $response->withStatus(isset($result['status_code']) ? $result['status_code'] : 200);
41
    }
42
}
43