Passed
Push — master ( 265a27...339ea2 )
by Hesham
02:59
created

UpdateCommand::_getCurrentAdminerVersion()   B

Complexity

Conditions 8
Paths 10

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 20
rs 8.4444
c 0
b 0
f 0
cc 8
nc 10
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 String $version
24
     */
25
    protected $version;
26
27
    /**
28
     * @var String $filename
29
     */
30
    protected $filename;
31
32
    /**
33
     * The name and signature of the console command.
34
     *
35
     * @var string
36
     */
37
    protected $signature = 'lumener:update {--force}';
38
39
    public function __construct()
40
    {
41
        parent::__construct();
42
43
        $this->filename = LUMENER_STORAGE.'/adminer.php';
44
    }
45
46
    /**
47
     * Execute the console command.
48
     *
49
     * @return void
50
     */
51
    public function handle()
52
    {
53
        $force = $this->option('force', false);
54
        if ($force) {
55
            $this->error("Force mode active.");
56
        }
57
        $current_version = $this->_getCurrentAdminerVersion();
58
        if ($current_version) {
59
            $this->info("Lumener: Current ".$current_version);
60
        } else {
61
            $this->error("Lumener: Adminer not found.");
62
        }
63
        $version = $this->_getRequiredAdminerVersion();
64
        if ($force || !file_exists($this->filename)
65
            || $version != $current_version) {
66
            $this->_downloadVersion($version);
67
        } else {
68
            $this->info('Lumener: Up to date.');
69
        }
70
    }
71
72
    private function _getCurrentAdminerVersion()
73
    {
74
        $current_version = false;
75
        try {
76
            if (file_exists($this->filename)) {
77
                $fn = fopen($this->filename, "r");
78
                if ($fn !== false) {
79
                    for ($i=0; !$current_version && $i < 20 && !feof($fn); $i++) {
80
                        $line = fgets($fn, 30);
81
                        preg_match_all("/@version ((\d([\.-]|$))+)/", $line, $m);
82
                        if (!empty($m[1])) {
83
                            $current_version = $m[1][0];
84
                        }
85
                    }
86
                }
87
            }
88
        } catch (\Throwable $e) {
89
            // Just return false
90
        }
91
        return $current_version;
92
    }
93
94
    private function _getRequiredAdminerVersion()
95
    {
96
        $vsource = config(
97
            'lumener.adminer_version',
98
            'https://api.github.com/repos/vrana/adminer/releases/latest'
99
        );
100
        if (config('lumener.adminer.version_type', 'url') == 'url') {
101
            $version = $this->_getLatestAdminerVersion($vsource);
102
            $this->info("Lumener: Latest Adminer Version " . $version);
103
        } else {
104
            $version = $vsource;
105
            $this->info("Lumener: Required Adminer Version " . $version);
106
        }
107
        return $version;
108
    }
109
110
    /**
111
     * Rename functions already defined in Laravel/Lumen public helper
112
     */
113
    private function _patchAdminer()
114
    {
115
        foreach (config(
116
            'lumener.adminer.rename_list',
117
            ['redirect','cookie','view', 'exit', 'ob_flush']
118
        ) as $var) {
119
            ShellHelper::rename($var, $this->filename);
120
        }
121
    }
122
123
    /**
124
     * Retreives the most recent adminer release version
125
     * @return string Version
126
     */
127
    private function _getLatestAdminerVersion($vsource)
128
    {
129
        $this->info("Lumener: Checking latest adminer version...");
130
        $response = ShellHelper::get($vsource);
131
        if (!$response || $response->getStatusCode() != '200') {
132
            $this->error(
133
                'Lumener: Could not retrieve version information from url.'
134
                .
135
                (
136
                    $response ? "\r\n[{$response->getStatusCode()}]
137
                    {$response->getReasonPhrase()} {(string)$response->getBody()}"
138
                    : "Connection Failed.\r\n" . ShellHelper::$LastError
139
                )
140
            );
141
            return;
142
        }
143
        return
144
            ltrim(json_decode((string) $response->getBody())->tag_name, 'v');
145
    }
146
147
    /**
148
     * Downloads the speicifed adminer.php version
149
     * @param  string $version
150
     * @return bool Success
151
     */
152
    private function _downloadVersion($version)
153
    {
154
        $this->info("Lumener: Downloading...");
155
        $url = config(
156
            'lumener.adminer.source',
157
            'https://github.com/vrana/adminer/releases/download/v{version}/adminer-{version}.php'
158
        );
159
        $url = str_replace("{version}", ltrim($version, 'v'), $url);
160
        $response = ShellHelper::get($url, ['sink' => $this->filename]);
161
        if ($response && $response->getStatusCode() == '200') {
162
            $this->info("Patching adminer.php...");
163
            $this->_patchAdminer();
164
            $this->info("Lumener: Updated!");
165
            return true;
166
        } else {
167
            $this->error(
168
                'Lumener: Could not download adminer.php.'
169
                .
170
                (
171
                    $response ? "\r\n[{$response->getStatusCode()}]
172
                    {$response->getReasonPhrase()} {(string)$response->getBody()}"
173
                    : "Connection Failed.\r\n" . ShellHelper::$LastError
174
                )
175
            );
176
            return false;
177
        }
178
    }
179
}
180