JsonResponse   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 64
rs 10
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A jsonResponse() 0 10 1
A jsonError() 0 30 2
1
<?php
2
3
namespace LeKoala\Admini\Traits;
4
5
use SilverStripe\Control\HTTPRequest;
6
use SilverStripe\Control\HTTPResponse;
7
use SilverStripe\Control\HTTPResponse_Exception;
8
9
trait JsonResponse
10
{
11
    /**
12
     * @return HTTPRequest
13
     */
14
    abstract public function getRequest();
15
    /**
16
     * @return array
17
     */
18
    abstract public function extend($method, &$a1 = null, &$a2 = null, &$a3 = null, &$a4 = null, &$a5 = null, &$a6 = null, &$a7 = null);
19
20
    /**
21
     * Return an error HTTPResponse encoded as json
22
     *
23
     * @param int $errorCode
24
     * @param string $errorMessage
25
     * @throws HTTPResponse_Exception
26
     */
27
    public function jsonError($errorCode, $errorMessage = null)
28
    {
29
        $request = $this->getRequest();
30
31
        // Build error from message
32
        $error = [
33
            'type' => 'error',
34
            'code' => $errorCode,
35
        ];
36
        if ($errorMessage) {
37
            $error['value'] = $errorMessage;
38
        }
39
40
        // Support explicit error handling with status = error, or generic message handling
41
        // with a message of type = error
42
        $result = [
43
            'status' => 'error',
44
            'errors' => [$error]
45
        ];
46
        $response = HTTPResponse::create(json_encode($result), $errorCode)
47
            ->addHeader('Content-Type', 'application/json');
48
49
        // Call a handler method such as onBeforeHTTPError404
50
        $this->extend("onBeforeJSONError{$errorCode}", $request, $response);
51
52
        // Call a handler method such as onBeforeHTTPError, passing 404 as the first arg
53
        $this->extend('onBeforeJSONError', $errorCode, $request, $response);
54
55
        // Throw a new exception
56
        throw new HTTPResponse_Exception($response);
57
    }
58
59
    /**
60
     * @param array $data
61
     * @return HTTPResponse
62
     */
63
    public function jsonResponse($data)
64
    {
65
        $result = [
66
            'status' => 'success',
67
            'data' => $data
68
        ];
69
        $response = HTTPResponse::create(json_encode($result))
70
            ->addHeader('Content-Type', 'application/json');
71
72
        return $response;
73
    }
74
}
75