Task::afterExecuteRoute()   D
last analyzed

Complexity

Conditions 20
Paths 28

Size

Total Lines 73
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 420

Importance

Changes 0
Metric Value
eloc 47
dl 0
loc 73
ccs 0
cts 45
cp 0
rs 4.1666
c 0
b 0
f 0
cc 20
nc 28
nop 1
crap 420

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\Modules\Cli;
13
14
use Phalcon\Cli\Dispatcher;
15
use Zemit\Exception\CliException;
16
use Zemit\Support\Helper;
17
use Zemit\Support\Utils;
18
19
class Task extends \Zemit\Cli\Task
20
{
21
    
22
    public string $cliDoc = <<<DOC
23
Usage:
24
  zemit cli <task> <action> [<params> ...]
25
26
Options:
27
  task: build,cache,cron,errors,help,scaffold
28
29
30
DOC;
31
    
32
    public function beforeExecuteRoute(): void
33
    {
34
        $argv = array_slice($_SERVER['argv'] ?? [], 1);
35
        $response = (new \Docopt())->handle($this->cliDoc, ['argv' => $argv, 'optionsFirst' => false]);
36
        foreach ($response as $key => $value) {
37
            if (!is_null($value) && preg_match('/(<(.*?)>|\-\-(.*))/', $key, $match)) {
38
                $key = lcfirst(Helper::camelize(Helper::uncamelize(array_pop($match))));
39
                $this->dispatcher->setParam($key, $value);
40
            }
41
        }
42
    }
43
    
44
    public function helpAction(): void
45
    {
46
        echo $this->cliDoc;
47
    }
48
    
49
    public function mainAction(): ?array
50
    {
51
        $this->helpAction();
52
        
53
        return null;
54
    }
55
    
56
    public function normalizeResponse(bool $response = true, ?int $code = null, ?string $status = null): array
57
    {
58
        $debug = $this->config->path('app.debug') ?? false;
59
        $view = $this->view->getParamsToView();
60
        
61
        $ret = [];
62
        $ret['api'] = [];
63
        $ret['api']['version'] = ['0.1']; // @todo
64
        $ret['timestamp'] = date('c');
65
        $ret['status'] = $status;
66
        $ret['code'] = $code;
67
        $ret['response'] = $response;
68
        $ret['view'] = $view;
69
        
70
        if ($debug !== false) {
71
            $ret['api']['php'] = phpversion();
72
            $ret['api']['phalcon'] = $this->config->path('phalcon.version');
73
            $ret['api']['zemit'] = $this->config->path('core.version');
74
            $ret['api']['core'] = $this->config->path('core.name');
75
            $ret['api']['app'] = $this->config->path('app.version');
76
            $ret['api']['name'] = $this->config->path('app.name');
77
            
78
            $ret['identity'] = $this->identity ? $this->identity->getIdentity() : null;
79
            $ret['profiler'] = $this->profiler ? $this->profiler->toArray() : null;
80
            $ret['dispatcher'] = $this->dispatcher ? $this->dispatcher->toArray() : null;
81
            $ret['router'] = $this->router ? $this->router->toArray() : null;
82
            $ret['memory'] = Utils::getMemoryUsage();
83
        }
84
        
85
        return $ret;
86
    }
87
    
88
    /**
89
     * Handle rest response automagically
90
     * @param Dispatcher $dispatcher
91
     * @return void
92
     * @throws CliException
93
     */
94
    public function afterExecuteRoute(Dispatcher $dispatcher): void
95
    {
96
        // Merge response into view variables
97
        $response = $dispatcher->getReturnedValue();
98
        
99
        // Quiet output
100
        $quiet = $this->dispatcher->getParam('quiet');
101
        if ($quiet) {
102
            exit(!$response ? 1 : 0);
103
        }
104
        
105
        // Normalize response
106
        $this->view->setVars((array)$response);
107
        $normalizedResponse = $this->normalizeResponse((bool)$response);
108
        $dispatcher->setReturnedValue($normalizedResponse);
109
        
110
        // Set response
111
        $verbose = $this->dispatcher->getParam('verbose');
112
        $ret = $verbose ? $normalizedResponse : $response;
113
        
114
        // Format response
115
        $format = $this->dispatcher->getParam('format');
116
        $format ??= 'json';
117
        switch (strtolower($format)) {
118
            case 'dump':
119
                dump($ret);
120
                break;
121
                
122
            case 'var_export':
123
                var_export($ret);
124
                break;
125
                
126
            case 'print_r':
127
                print_r($ret);
128
                break;
129
    
130
            case 'serialize':
131
                echo serialize($ret);
132
                break;
133
            
134
            case 'json':
135
                echo json_encode($ret, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL;
136
                break;
137
            
138
            case 'string':
139
                if (is_string($ret)) {
140
                    echo $ret;
141
                }
142
                elseif (is_bool($ret)) {
143
                    echo $ret? 'true' : 'false';
144
                }
145
                elseif (is_null($ret)) {
146
                    echo 'null';
147
                }
148
                elseif (is_numeric($ret)) {
149
                    echo $ret;
150
                }
151
                else {
152
                    echo json_encode($ret, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL;
153
                }
154
                break;
155
                
156
            case 'raw':
157
                if (is_string($ret) || is_bool($ret) || is_null($ret) || is_numeric($ret)) {
158
                    echo $ret;
159
                }
160
                else {
161
                    echo json_encode($ret, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL;
162
                }
163
                break;
164
            
165
            default:
166
                throw new CliException('Unknown output format `' . $format . '` expected one of the string value: `json` `serialize` `dump` `raw`');
167
        }
168
    }
169
}
170