Passed
Push — master ( cc83dd...040056 )
by Julien
05:06
created

Task::beforeExecuteRoute()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 3
nop 0
dl 0
loc 9
ccs 0
cts 8
cp 0
crap 20
rs 10
c 0
b 0
f 0
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 Zemit\Exception\CliException;
16
use Zemit\Http\StatusCode;
17
use Zemit\Support\Helper;
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 beforeExecuteRoute(): void
34
    {
35
        $argv = array_slice($_SERVER['argv'] ?? [], 1);
36
        $response = (new \Docopt())->handle($this->cliDoc, ['argv' => $argv, 'optionsFirst' => false]);
37
        foreach ($response as $key => $value) {
38
            if (!is_null($value) && preg_match('/(<(.*?)>|\-\-(.*))/', $key, $match)) {
39
                $key = lcfirst(Helper::camelize(Helper::uncamelize(array_pop($match))));
40
                $args[$key] = $value;
41
                $this->dispatcher->setParam($key, $value);
42
            }
43
        }
44
    }
45
    
46
    public function helpAction(): void
47
    {
48
        echo $this->cliDoc;
49
    }
50
    
51
    public function mainAction(): ?array
52
    {
53
        $this->helpAction();
54
        
55
        return null;
56
    }
57
    
58
    public function normalizeResponse(bool $response = true, ?int $code = null, ?string $status = null): array
59
    {
60
        $debug = $this->config->path('app.debug') ?? false;
61
        
62
        // keep forced status code or set our own
63
        $statusCode = $this->response->getStatusCode();
64
        $reasonPhrase = $this->response->getReasonPhrase();
65
        $code ??= (int)$statusCode ?: 200;
66
        $status ??= $reasonPhrase ?: StatusCode::getMessage($code);
67
        
68
        $view = $this->view->getParamsToView();
69
        $hash = hash('sha512', json_encode($view));
70
        
71
        // set response status code
72
        $this->response->setStatusCode($code, $status);
73
        
74
        $ret = [];
75
        $ret['api'] = [];
76
        $ret['api']['version'] = ['0.1']; // @todo
77
        $ret['timestamp'] = date('c');
78
        $ret['hash'] = $hash;
79
        $ret['status'] = $status;
80
        $ret['code'] = $code;
81
        $ret['response'] = $response;
82
        $ret['view'] = $view;
83
        
84
        if ($debug) {
85
            $ret['api']['php'] = phpversion();
86
            $ret['api']['phalcon'] = $this->config->path('phalcon.version');
87
            $ret['api']['zemit'] = $this->config->path('core.version');
88
            $ret['api']['core'] = $this->config->path('core.name');
89
            $ret['api']['app'] = $this->config->path('app.version');
90
            $ret['api']['name'] = $this->config->path('app.name');
91
            
92
            $ret['identity'] = $this->identity ? $this->identity->getIdentity() : null;
93
            $ret['profiler'] = $this->profiler ? $this->profiler->toArray() : null;
94
            $ret['dispatcher'] = $this->dispatcher ? $this->dispatcher->toArray() : null;
95
            $ret['router'] = $this->router ? $this->router->toArray() : null;
96
            $ret['memory'] = Utils::getMemoryUsage();
97
        }
98
        
99
        return $ret;
100
    }
101
    
102
    /**
103
     * Handle rest response automagically
104
     * @param Dispatcher $dispatcher
105
     * @return void
106
     * @throws CliException
107
     */
108
    public function afterExecuteRoute(Dispatcher $dispatcher): void
109
    {
110
        // Merge response into view variables
111
        $response = $dispatcher->getReturnedValue();
112
        
113
        // Quiet output
114
        $quiet = $this->dispatcher->getParam('quiet');
115
        if ($quiet) {
116
            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...
117
        }
118
        
119
        // Normalize response
120
        $this->view->setVars((array)$response);
121
        $normalizedResponse = $this->normalizeResponse((bool)$response);
122
        $dispatcher->setReturnedValue($normalizedResponse);
123
        
124
        // Set response
125
        $verbose = $this->dispatcher->getParam('verbose');
126
        $ret = $verbose ? $normalizedResponse : $response;
127
        
128
        // Format response
129
        $format = $this->dispatcher->getParam('format');
130
        $format ??= 'json';
131
        switch (strtolower($format)) {
132
            case 'dump':
133
                dump($ret);
134
                break;
135
                
136
            case 'var_export':
137
                var_export($ret);
138
                break;
139
                
140
            case 'print_r':
141
                print_r($ret);
142
                break;
143
    
144
            case 'serialize':
145
                echo serialize($ret);
146
                break;
147
            
148
            case 'json':
149
                echo json_encode($ret, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL;
150
                break;
151
            
152
            case 'string':
153
                if (is_string($ret)) {
154
                    echo $ret;
155
                }
156
                elseif (is_bool($ret)) {
157
                    echo $ret? 'true' : 'false';
158
                }
159
                elseif (is_null($ret)) {
160
                    echo 'null';
161
                }
162
                elseif (is_numeric($ret)) {
163
                    echo $ret;
164
                }
165
                else {
166
                    echo json_encode($ret, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL;
167
                }
168
                break;
169
                
170
            case 'raw':
171
                if (is_string($ret) || is_bool($ret) || is_null($ret) || is_numeric($ret)) {
172
                    echo $ret;
173
                }
174
                else {
175
                    echo json_encode($ret, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL;
176
                }
177
                break;
178
            
179
            default:
180
                throw new CliException('Unknown output format `' . $format . '` expected one of the string value: `json` `serialize` `dump` `raw`');
181
        }
182
    }
183
}
184