Test Failed
Push — master ( 244aa0...8b6dec )
by Julien
10:46 queued 06:25
created

Task   A

Complexity

Total Complexity 33

Size/Duplication

Total Lines 157
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 96
dl 0
loc 157
ccs 0
cts 76
cp 0
rs 9.76
c 2
b 0
f 0
wmc 33

4 Methods

Rating   Name   Duplication   Size   Complexity  
D afterExecuteRoute() 0 82 22
A mainAction() 0 5 1
B normalizeResponse() 0 42 9
A helpAction() 0 3 1
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\Modules\Cli;
13
14
use Phalcon\Cli\Dispatcher;
15
use Phalcon\Version;
16
use Zemit\Exception\CliException;
17
use Zemit\Http\StatusCode;
18
use Zemit\Utils;
19
20
class Task extends \Zemit\Cli\Task
21
{
22
    
23
    public string $cliDoc = <<<DOC
24
Usage:
25
  php zemit cli <task> <action> [<params> ...]
26
27
Options:
28
  task: build,cache,cron,errors,help,scaffold
29
30
31
DOC;
32
    
33
    public function helpAction(): void
34
    {
35
        echo $this->cliDoc;
36
    }
37
    
38
    public function mainAction(): ?array
39
    {
40
        $this->helpAction();
41
        
42
        return null;
43
    }
44
    
45
    public function normalizeResponse(bool $response = true, ?int $code = null, ?string $status = null): array
46
    {
47
        $debug = $this->config->path('app.debug') || $this->dispatcher->getParam('debug');
48
        
49
        // keep forced status code or set our own
50
        $statusCode = $this->response->getStatusCode();
51
        $reasonPhrase = $this->response->getReasonPhrase();
52
        $code ??= (int)$statusCode ?: 200;
53
        $status ??= $reasonPhrase ?: StatusCode::getMessage($code);
54
        
55
        $view = $this->view->getParamsToView();
56
        $hash = hash('sha512', json_encode($view));
57
        
58
        // set response status code
59
        $this->response->setStatusCode($code, $status);
60
        
61
        $ret = [];
62
        $ret['api'] = [];
63
        $ret['api']['version'] = ['0.1'];
64
        $ret['timestamp'] = date('c');
65
        $ret['hash'] = $hash;
66
        $ret['status'] = $status;
67
        $ret['code'] = $code;
68
        $ret['response'] = $response;
69
        $ret['view'] = $view;
70
        
71
        if ($debug) {
72
            $ret['api']['php'] = phpversion();
73
            $ret['api']['phalcon'] = Version::get();
74
            $ret['api']['zemit'] = $this->config->path('core.version');
75
            $ret['api']['core'] = $this->config->path('core.name');
76
            $ret['api']['app'] = $this->config->path('app.version');
77
            $ret['api']['name'] = $this->config->path('app.name');
78
            
79
            $ret['identity'] = $this->identity ? $this->identity->getIdentity() : null;
80
            $ret['profiler'] = $this->profiler ? $this->profiler->toArray() : null;
81
            $ret['dispatcher'] = $this->dispatcher ? $this->dispatcher->toArray() : null;
82
            $ret['router'] = $this->router ? $this->router->toArray() : null;
83
            $ret['memory'] = Utils::getMemoryUsage();
84
        }
85
        
86
        return $ret;
87
    }
88
    
89
    /**
90
     * Handle rest response automagically
91
     * @param Dispatcher $dispatcher
92
     * @return void
93
     * @throws CliException
94
     */
95
    public function afterExecuteRoute(Dispatcher $dispatcher): void
96
    {
97
        // Merge response into view variables
98
        $response = $dispatcher->getReturnedValue();
99
        
100
        // Quiet output
101
        $quiet = $this->dispatcher->getParam('quiet');
102
        if ($quiet) {
103
            exit(!$response ? 1 : 0);
1 ignored issue
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
104
        }
105
        
106
        // Normalize response
107
        if (is_array($response)) {
108
            $this->view->setVars($response, true);
0 ignored issues
show
Bug introduced by
The method setVars() does not exist on Phalcon\Mvc\ViewInterface. Did you maybe mean setVar()? ( Ignorable by Annotation )

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

108
            $this->view->/** @scrutinizer ignore-call */ 
109
                         setVars($response, true);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
109
        }
110
        else {
111
            $this->view->setVars((array)$response, true);
112
        }
113
        $normalizedResponse = $this->normalizeResponse((bool)$response);
114
        $dispatcher->setReturnedValue($normalizedResponse);
115
        
116
        // Set response
117
        $verbose = $this->dispatcher->getParam('verbose');
118
        $ret = $verbose ? $normalizedResponse : $response;
119
        
120
        // Format response
121
        $format = $this->dispatcher->getParam('format');
122
        $format ??= 'json';
123
        switch (strtolower($format)) {
124
            case 'dump':
125
                dump($ret);
126
                break;
127
                
128
            case 'var_dump':
129
                var_dump($ret);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($ret) looks like debug code. Are you sure you do not want to remove it?
Loading history...
130
                break;
131
                
132
            case 'var_export':
133
                var_export($ret);
134
                break;
135
                
136
            case 'print_r':
137
                print_r($ret);
138
                break;
139
    
140
            case 'serialize':
141
                echo serialize($ret);
142
                break;
143
            
144
            case 'json':
145
                echo json_encode($ret, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
146
                break;
147
            
148
            case 'string':
149
                if (is_string($ret)) {
150
                    echo $ret;
151
                }
152
                elseif (is_bool($ret)) {
153
                    echo $ret? 'true' : 'false';
154
                }
155
                elseif (is_null($ret)) {
156
                    echo 'null';
157
                }
158
                elseif (is_numeric($ret)) {
159
                    echo $ret;
160
                }
161
                else {
162
                    echo json_encode($ret, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
163
                }
164
                break;
165
                
166
            case 'raw':
167
                if (is_string($ret) || is_bool($ret) || is_null($ret) || is_numeric($ret)) {
168
                    echo $ret;
169
                }
170
                else {
171
                    echo json_encode($ret, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
172
                }
173
                break;
174
            
175
            default:
176
                throw new CliException('Unknown output format `' . $format . '` expected one of the string value: `json` `serialize` `dump` `raw`');
177
        }
178
    }
179
}
180