Completed
Push — master ( 24cbbe...c65133 )
by Derek Stephen
03:26 queued 01:10
created

BaseController   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 86.96%

Importance

Changes 0
Metric Value
wmc 5
eloc 20
dl 0
loc 41
ccs 20
cts 23
cp 0.8696
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A httpMethodCheck() 0 9 2
A __construct() 0 6 1
A sendJsonObjectResponse() 0 13 2
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\ServerRequestInterface;
10
11
class BaseController extends Controller
12
{
13
    /** @var Serializer */
14
    protected $serializer;
15
16 14
    public function __construct(ServerRequestInterface $request)
17
    {
18 14
        parent::__construct($request);
19 14
        $this->serializer = SerializerBuilder::create()->build();
20 14
        $this->disableView();
21 14
        $this->disableLayout();
22 14
    }
23
24
    /**
25
     * @param $object
26
     * @param int $statusCode
27
     */
28 5
    public function sendJsonObjectResponse($object, $statusCode = 200)
29
    {
30 5
        if (!is_object($object)) {
31
            throw new InvalidArgumentException('You must pass an object.');
32
        }
33 5
        $this->disableLayout();
34 5
        $this->disableView();
35 5
        $this->setHeader('Cache-Control', 'no-cache, must-revalidate');
36 5
        $this->setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT');
37 5
        $this->setHeader('Content-Type','application/json');
38 5
        $json = $this->serializer->serialize($object, 'json');
39 5
        $this->setBody($json);
40 5
        $this->setStatusCode($statusCode);
41 5
    }
42
43 5
    protected function httpMethodCheck($method)
44
    {
45 5
        if ($this->getRequest()->getMethod() !== $method) {
46
            $this->sendJsonResponse(['error' => 'Method not allowed'], 405);
47
48
            return false;
49
        }
50
51 5
        return true;
52
    }
53
}