Passed
Push — master ( 5b5c00...4c0c12 )
by Julien
04:52
created

Response::setRestResponse()   B

Complexity

Conditions 11
Paths 99

Size

Total Lines 57
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 39
c 1
b 0
f 0
dl 0
loc 57
ccs 0
cts 39
cp 0
rs 7.3166
cc 11
nc 99
nop 5
crap 132

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * This file is part of the Zemit Framework.
5
 *
6
 * (c) Zemit Team <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE.txt
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Zemit\Mvc\Controller\Rest;
13
14
use Phalcon\Http\ResponseInterface;
15
use Phalcon\Mvc\Dispatcher;
16
use Zemit\Mvc\Controller\AbstractTrait\AbstractInjectable;
17
use Zemit\Http\StatusCode;
18
use Zemit\Support\Utils;
19
20
trait Response {
21
    
22
    use AbstractInjectable;
23
    
24
    /**
25
     * Set the REST response error
26
     *
27
     * @param int $code The HTTP status code (default: 400)
28
     * @param string $status The status message (default: 'Bad Request')
29
     * @param mixed $response The response body (default: null)
30
     * @return ResponseInterface The REST response object
31
     */
32
    public function setRestErrorResponse(int $code = 400, string $status = 'Bad Request', mixed $response = null): ResponseInterface
33
    {
34
        return $this->setRestResponse($response, $code, $status);
35
    }
36
    
37
    /**
38
     * Sending rest response as a http response
39
     *
40
     * @param mixed $response
41
     * @param ?int $code
42
     * @param ?string $status
43
     * @param int $jsonOptions
44
     * @param int $depth
45
     *
46
     * @return ResponseInterface
47
     */
48
    public function setRestResponse(mixed $response = null, int $code = null, string $status = null, int $jsonOptions = 0, int $depth = 512): ResponseInterface
49
    {
50
        $debug = $this->isDebugEnabled();
0 ignored issues
show
Bug introduced by
It seems like isDebugEnabled() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

50
        /** @scrutinizer ignore-call */ 
51
        $debug = $this->isDebugEnabled();
Loading history...
51
        
52
        // keep forced status code or set our own
53
        $statusCode = $this->response->getStatusCode();
0 ignored issues
show
Bug introduced by
The property response does not exist on Zemit\Mvc\Controller\Rest\Response. Did you mean response;?
Loading history...
54
        $reasonPhrase = $this->response->getReasonPhrase();
55
        $code ??= (int)$statusCode ?: 200;
56
        $status ??= $reasonPhrase ?: StatusCode::getMessage($code);
57
        
58
        $view = $this->view->getParamsToView();
0 ignored issues
show
Bug introduced by
The property view does not exist on Zemit\Mvc\Controller\Rest\Response. Did you mean view;?
Loading history...
59
        $hash = hash('sha512', json_encode($view)); // @todo store hash in cache layer with response content
60
        
61
        // set response status code
62
        $this->response->setStatusCode($code, $code . ' ' . $status);
63
        
64
        // @todo handle this correctly
65
        // @todo private vs public cache type
66
        $cache = $this->getCache();
0 ignored issues
show
Bug introduced by
It seems like getCache() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

66
        /** @scrutinizer ignore-call */ 
67
        $cache = $this->getCache();
Loading history...
67
        if (!empty($cache['lifetime'])) {
68
            if ($this->response->getStatusCode() === 200) {
69
                $this->response->setCache($cache['lifetime']);
70
                $this->response->setEtag($hash);
71
            }
72
        }
73
        else {
74
            $this->response->setCache(0);
75
            $this->response->setHeader('Cache-Control', 'no-cache, max-age=0');
76
        }
77
        
78
        $ret = [];
79
        $ret['api'] = [];
80
        $ret['api']['version'] = ['0.1']; // @todo
81
        $ret['timestamp'] = date('c');
82
        $ret['hash'] = $hash;
83
        $ret['status'] = $status;
84
        $ret['code'] = $code;
85
        $ret['response'] = $response;
86
        $ret['view'] = $view;
87
        
88
        if ($debug) {
89
            $ret['api']['php'] = phpversion();
90
            $ret['api']['phalcon'] = $this->config->path('phalcon.version');
91
            $ret['api']['zemit'] = $this->config->path('core.version');
92
            $ret['api']['core'] = $this->config->path('core.name');
93
            $ret['api']['app'] = $this->config->path('app.version');
94
            $ret['api']['name'] = $this->config->path('app.name');
95
            
96
            $ret['identity'] = $this->identity ? $this->identity->getIdentity() : null;
0 ignored issues
show
Bug introduced by
The property identity does not exist on Zemit\Mvc\Controller\Rest\Response. Did you mean identity;?
Loading history...
97
            $ret['profiler'] = $this->profiler ? $this->profiler->toArray() : null;
98
            $ret['request'] = $this->request ? $this->request->toArray() : null;
0 ignored issues
show
Bug introduced by
The property request does not exist on Zemit\Mvc\Controller\Rest\Response. Did you mean request;?
Loading history...
99
            $ret['dispatcher'] = $this->dispatcher ? $this->dispatcher->toArray() : null;
0 ignored issues
show
Bug introduced by
The property dispatcher does not exist on Zemit\Mvc\Controller\Rest\Response. Did you mean dispatcher;?
Loading history...
100
            $ret['router'] = $this->router ? $this->router->toArray() : null;
0 ignored issues
show
Bug introduced by
The property router does not exist on Zemit\Mvc\Controller\Rest\Response. Did you mean router;?
Loading history...
101
            $ret['memory'] = Utils::getMemoryUsage();
102
        }
103
        
104
        return $this->response->setJsonContent($ret, $jsonOptions, $depth);
105
    }
106
    
107
    /**
108
     * Update the Dispatcher after executing the route.
109
     *
110
     * @param Dispatcher $dispatcher The Dispatcher instance.
111
     *
112
     * @return void
113
     */
114
    public function afterExecuteRoute(Dispatcher $dispatcher): void
115
    {
116
        $response = $dispatcher->getReturnedValue();
117
        
118
        // Avoid breaking default phalcon behaviour
119
        if ($response instanceof \Phalcon\Http\Response) {
120
            return;
121
        }
122
        
123
        // Merge response into view variables
124
        if (is_array($response)) {
125
            $this->view->setVars($response, true);
0 ignored issues
show
Bug introduced by
The property view does not exist on Zemit\Mvc\Controller\Rest\Response. Did you mean view;?
Loading history...
126
        }
127
        
128
        // Return our Rest normalized response
129
        $dispatcher->setReturnedValue($this->setRestResponse(is_array($response) ? null : $response));
130
    }
131
    
132
}
133