Passed
Push — master ( 0017b2...5a58d2 )
by Hesham
02:57
created

UpdateCommand::_getVersion()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 14
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
/**
3
 * Update adminer
4
 *
5
 * @author    Hesham A. Meneisi [email protected]
6
 * @copyright 2019 Hesham Meneisi
7
 * @license   http://www.opensource.org/licenses/mit-license.php MIT
8
 */
9
10
namespace Lumener\Console;
11
12
use Illuminate\Console\Command;
13
use Lumener\Helpers\ShellHelper;
14
15
/**
16
 * A command to update the file for adminer.php
17
 *
18
 * @author Charles A. Peterson <[email protected]>
19
 */
20
class UpdateCommand extends Command
21
{
22
    /**
23
     * @var Filesystem $files
0 ignored issues
show
Bug introduced by
The type Lumener\Console\Filesystem was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
24
     */
25
    protected $files;
26
27
    /**
28
     * @var String $version
29
     */
30
    protected $version;
31
32
    /**
33
     * @var String $filename
34
     */
35
    protected $filename;
36
37
    /**
38
     * The name and signature of the console command.
39
     *
40
     * @var string
41
     */
42
    protected $signature = 'lumener:update {--force}';
43
44
    public function __construct()
45
    {
46
        parent::__construct();
47
48
        $this->filename = LUMENER_STORAGE.'/adminer.php';
49
    }
50
51
    /**
52
     * Execute the console command.
53
     *
54
     * @return void
55
     */
56
    public function handle()
57
    {
58
        $force = $this->option('force', false);
1 ignored issue
show
Unused Code introduced by
The call to Illuminate\Console\Command::option() has too many arguments starting with false. ( Ignorable by Annotation )

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

58
        /** @scrutinizer ignore-call */ 
59
        $force = $this->option('force', false);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
59
        if ($force) {
60
            $this->error("Force mode active.");
61
        }
62
        $current_version = false;
63
        try {
64
            if (file_exists($this->filename)) {
65
                $fn = fopen($this->filename, "r");
66
                if ($fn !== false) {
67
                    for ($i=0; !$current_version && $i < 20 && !feof($fn); $i++) {
68
                        $line = fgets($fn, 30);
69
                        preg_match_all("/@version ((\d([\.-]|$))+)/", $line, $m);
70
                        if (!empty($m[1])) {
71
                            $current_version = $m[1][0];
72
                        }
73
                    }
74
                }
75
            }
76
        } catch (\Throwable $e) {
77
            // current_version is false
78
        }
79
        if ($current_version) {
80
            $this->info("Lumener: Current ".$current_version);
81
        } else {
82
            $this->error("Lumener: Adminer not found.");
83
        }
84
        $version = $this->_getVersion();
85
        if ($force || !file_exists($this->filename)
86
            || $version != $current_version) {
87
            $this->_downloadVersion($version);
88
        } else {
89
            $this->info('Lumener: Up to date.');
90
        }
91
    }
92
93
    private function _getVersion()
94
    {
95
        $vsource = config(
96
            'lumener.adminer_version',
97
            'https://api.github.com/repos/vrana/adminer/releases/latest'
98
        );
99
        if (config('lumener.adminer.version_type', 'url') == 'url') {
100
            $version = $this->_getLatestAdminerVersion($vsource);
101
            $this->info("Lumener: Latest Adminer Version " . $version);
102
        } else {
103
            $version = $vsource;
104
            $this->info("Lumener: Required Adminer Version " . $version);
105
        }
106
        return $verison;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $verison does not exist. Did you maybe mean $version?
Loading history...
107
    }
108
109
    /**
110
     * Rename functions already defined in Laravel/Lumen public helper
111
     */
112
    private function _patchAdminer()
113
    {
114
        foreach (config(
115
            'lumener.adminer.rename_list',
116
            ['redirect','cookie','view', 'exit', 'ob_flush']
117
        ) as $var) {
118
            ShellHelper::rename($var, $this->filename);
119
        }
120
    }
121
122
    /**
123
     * Retreives the most recent adminer release version
124
     * @return string Version
125
     */
126
    private function _getLatestAdminerVersion($vsource)
127
    {
128
        $this->info("Lumener: Checking latest adminer version...");
129
        $response = ShellHelper::get($vsource);
130
        if (!$response || $response->getStatusCode() != '200') {
131
            $this->error(
132
                'Lumener: Could not retrieve version information from url.'
133
                .
134
                (
135
                    $response ? "\r\n[{$response->getStatusCode()}]
136
                    {$response->getReasonPhrase()} {(string)$response->getBody()}"
137
                    : "Connection Failed.\r\n" . ShellHelper::$LastError
138
                )
139
            );
140
            return;
141
        }
142
        return
143
            ltrim(json_decode((string) $response->getBody())->tag_name, 'v');
144
    }
145
146
    /**
147
     * Downloads the speicifed adminer.php version
148
     * @param  string $version
149
     * @return bool Success
150
     */
151
    private function _downloadVersion($version)
152
    {
153
        $this->info("Lumener: Downloading...");
154
        $url = config(
155
            'lumener.adminer.source',
156
            'https://github.com/vrana/adminer/releases/download/v{version}/adminer-{version}.php'
157
        );
158
        $url = str_replace("{version}", ltrim($version, 'v'), $url);
159
        $response = ShellHelper::get($url, ['sink' => $this->filename]);
160
        if ($response && $response->getStatusCode() == '200') {
161
            $this->info("Patching adminer.php...");
162
            $this->_patchAdminer();
163
            $this->info("Lumener: Updated!");
164
            return true;
165
        } else {
166
            $this->error(
167
                'Lumener: Could not download adminer.php.'
168
                .
169
                (
170
                    $response ? "\r\n[{$response->getStatusCode()}]
171
                    {$response->getReasonPhrase()} {(string)$response->getBody()}"
172
                    : "Connection Failed.\r\n" . ShellHelper::$LastError
173
                )
174
            );
175
            return false;
176
        }
177
    }
178
}
179