Passed
Push — master ( 76a7e8...d2297b )
by Taha
10:13
created

XdebugToggle::initializeCommand()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 10
rs 10
1
<?php
2
3
namespace Tpaksu\XdebugToggle\Commands;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Support\Str;
7
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
8
use Symfony\Component\Console\Output\OutputInterface;
9
use Symfony\Component\Process\Process;
10
11
class XdebugToggle extends Command
12
{
13
    /**
14
     * The complete line containing "*_extension=*xdebug*".
15
     *
16
     * @var string
17
     */
18
    protected $extensionLine;
19
20
    /**
21
     * Extension active status.
22
     *
23
     * @var bool
24
     */
25
    protected $extensionStatus;
26
27
    /**
28
     * The configuration written in php.ini for XDebug.
29
     *
30
     * @var array
31
     */
32
    protected $extensionSettings;
33
34
    /**
35
     * Path of the Loaded INI file.
36
     *
37
     * @var string
38
     */
39
    protected $iniPath;
40
41
    /**
42
     * Debug mode active flag.
43
     *
44
     * @var bool
45
     */
46
    protected $debug;
47
48
    /**
49
     * The command signature.
50
     *
51
     * @var string
52
     */
53
    protected $signature = 'xdebug {status : "on" or "off" to enable/disable XDebug}';
54
55
    /**
56
     * The command description.
57
     *
58
     * @var string
59
     */
60
    protected $description = 'Enables or disables XDebug extension';
61
62
    /**
63
     * Class constructor.
64
     */
65
    public function __construct()
66
    {
67
        parent::__construct();
68
        $this->debug = false;
69
    }
70
71
    /**
72
     * initialization routines.
73
     */
74
    public function initializeCommand()
75
    {
76
        // Define custom format for bold text
77
        $style = new OutputFormatterStyle('default', 'default', ['bold']);
78
        $this->output->getFormatter()->setStyle('bold', $style);
79
80
        // Get the verbosity level to set debug mode flag
81
        $verbosityLevel = $this->getOutput()->getVerbosity();
82
        if ($verbosityLevel > OutputInterface::VERBOSITY_DEBUG) {
83
            $this->debug = true;
84
        }
85
    }
86
87
    /**
88
     * The method that handles the command.
89
     */
90
    public function handle()
91
    {
92
        $this->initializeCommand();
93
94
        // Get XDebug desired status from the command line arguments
95
        $desiredStatus = strval($this->argument('status'));
96
97
        // do the validation
98
        if ($this->validateDesiredStatus($desiredStatus) === false) {
99
            return false;
100
        }
101
102
        // Retrieve the INI path to the global variable
103
        if ($this->getIniPath() === false) {
104
            return false;
105
        }
106
107
        // Get the XDebug extension information from the INI file
108
        $this->getXDebugStatus();
109
110
        // do the validation
111
        if ($this->validateXDebugStatus($desiredStatus) === false) {
112
            return false;
113
        }
114
115
        // we need to alter the status to the new one. Do it!
116
        $this->setXDebugStatus($desiredStatus);
117
    }
118
119
    /**
120
     * Validates the desired status argument received from console.
121
     *
122
     * @param   string  $desiredStatus  Should be "on" or "off"
123
     *
124
     * @return  bool                 Whether it is a valid input
125
     */
126
    public function validateDesiredStatus(string $desiredStatus)
127
    {
128
        if ($this->debug) {
129
            echo 'Desired Status: '.($desiredStatus)."\n";
130
        }
131
132
        // validate desired XDebug status
133
        if (! in_array($desiredStatus, ['on', 'off'])) {
134
            $this->line('Status should be "on" or "off". Other values are not accepted.', 'fg=red;bold');
135
136
            return false;
137
        }
138
139
        return true;
140
    }
141
142
    /**
143
     * Gets the XDebug status and related configuration from the loaded php.ini file.
144
     */
145
    private function getXDebugStatus()
146
    {
147
        // get the extension status
148
        $this->getExtensionStatus();
149
150
        // get extemsion settings
151
        $this->getExtensionSettings();
152
    }
153
154
    /**
155
     * Retrieves the INI path from php.ini file.
156
     *
157
     * @return bool
158
     */
159
    private function getIniPath()
160
    {
161
        $this->iniPath = php_ini_loaded_file() ?? '';
162
163
        // If we can't retrieve the loaded INI path, bail out
164
        if ($this->iniPath === '') {
165
            $this->line("Can't get php.ini file path from phpinfo() output.
166
            Make sure that the function is allowed inside your php.ini configuration.", 'bold');
167
168
            return false;
169
        }
170
171
        return true;
172
    }
173
174
    /**
175
     * Validates the XDebug status received.
176
     *
177
     * @param   string  $desiredStatus  The desired status
178
     *
179
     * @return  bool                 Whether we should continue to modify the status or not
180
     */
181
    public function validateXDebugStatus(string $desiredStatus)
182
    {
183
        // prepare variables for comparison and output
184
        $currentStatus = $this->extensionStatus ? 'on' : 'off';
185
        $styledStatus = $this->extensionStatus ? '<fg=green;bold>on' : '<fg=red;bold>off';
186
187
        // print current status to the user
188
        $this->line("<fg=yellow>Current XDebug Status: $styledStatus</>");
189
190
        // if the desired status and current status are the same, we don't need to alter anything
191
        // inform the user and exit
192
        if ($currentStatus === $desiredStatus) {
193
            $this->line('<fg=green>Already at the desired state. No action has been taken.</>');
194
195
            return false;
196
        }
197
198
        return true;
199
    }
200
201
    /**
202
     * Sets the new XDebug extension status.
203
     *
204
     * @param   string  $status  Whether the extension should be active or not
205
     *
206
     * @return  void
207
     */
208
    private function setXDebugStatus($status)
209
    {
210
        // inform the user about the current operation
211
        $this->line("<bold>Setting status to \"$status\"</bold>");
212
213
        // read the ini file
214
        $contents = file_get_contents($this->iniPath);
215
216
        if ($this->debug) {
217
            echo "status: $status\n";
218
            echo 'line: '.$this->extensionLine."\n";
219
            echo 'new: '.trim($this->extensionLine, ';')."\n";
220
        }
221
222
        // replace the "zend_extension=*xdebug.*" line with the active/passive equivalent
223
        switch ($status) {
224
            case 'on':
225
                $contents = str_replace($this->extensionLine, trim($this->extensionLine, ';'), $contents);
226
                break;
227
228
            case 'off':
229
                $contents = str_replace($this->extensionLine, ';'.$this->extensionLine, $contents);
230
                break;
231
        }
232
233
        // rewrite the php.ini file
234
        file_put_contents($this->iniPath, $contents);
235
236
        // restart the service to put the changes in effect
237
        $this->restartServices();
238
    }
239
240
    /**
241
     * Reads the extension status from PHP ini file.
242
     *
243
     * @return void
244
     */
245
    private function getExtensionStatus()
246
    {
247
        // read the extension line from file,
248
        // can't use parse_ini_file here because the keyed array overwrites "extension" lines and keeps the last one
249
        $this->extensionLine = collect(file_get_contents($this->iniPath))
250
            ->explode("\n")
251
            ->filter(function ($line) {
252
                return Str::contains($line, 'extension=') && Str::contains($line, 'xdebug');
253
            })
254
            ->first();
255
256
        $this->extensionLine = trim($this->extensionLine ?? '');
257
258
        if (strlen($this->extensionLine) > 0) {
259
            $this->extensionStatus = $this->extensionLine[0] === ';';
260
        } else {
261
            $this->extensionStatus = false;
262
        }
263
264
        if ($this->debug) {
265
            echo 'line: '.$this->extensionLine."\n";
266
            echo 'ext.status: '.$this->extensionStatus."\n";
267
        }
268
    }
269
270
    /**
271
     * Reads the extension settings from PHP ini file.
272
     *
273
     * @return void
274
     */
275
    private function getExtensionSettings()
276
    {
277
        $settings = collect(parse_ini_file($this->iniPath))->filter(function ($setting, $key) {
278
            return Str::startsWith($key, 'xdebug.');
279
        });
280
        $this->extensionSettings = $settings->toArray();
281
    }
282
283
    /**
284
     * Restarts the services that takes the modification into effect.
285
     *
286
     * @return void
287
     */
288
    private function restartServices()
289
    {
290
        /**
291
         * Define a global outputter to display command output to user.
292
         *
293
         * @param   string  $type  The type of the output
294
         * @param   string  $data  The output
295
         *
296
         * @return  void
297
         */
298
        $output = function ($type, $data) {
299
            $this->info($data);
300
        };
301
        // run the command(s) needed to restart the service
302
        (new Process([env('XDEBUG_SERVICE_RESTART_COMMAND', 'valet restart nginx')]))->run($output);
303
        // display the new extension status
304
        (new Process(['php --ri xdebug']))->run($output);
305
    }
306
}
307