OpenBrowser::getOpenCommand()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
cc 4
nc 4
nop 0
1
<?php
2
3
namespace Robo\Task\Development;
4
5
use Robo\Task\BaseTask;
6
use Robo\Common\ProcessUtils;
7
use Robo\Result;
8
9
/**
10
 * Opens the default's user browser
11
 * code inspired from openBrowser() function in https://github.com/composer/composer/blob/master/src/Composer/Command/HomeCommand.php
12
 *
13
 * ``` php
14
 * <?php
15
 * // open one browser window
16
 * $this->taskOpenBrowser('http://localhost')
17
 *  ->run();
18
 *
19
 * // open two browser windows
20
 * $this->taskOpenBrowser([
21
 *     'http://localhost/mysite',
22
 *     'http://localhost/mysite2'
23
 *   ])
24
 *   ->run();
25
 * ```
26
 */
27
class OpenBrowser extends BaseTask
28
{
29
    /**
30
     * @var string[]
31
     */
32
    protected $urls = [];
33
34
    /**
35
     * @param string|string[] $url
36
     */
37
    public function __construct($url)
38
    {
39
        $this->urls = (array) $url;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function run()
46
    {
47
        $openCommand = $this->getOpenCommand();
48
49
        if (empty($openCommand)) {
50
            return Result::error($this, 'no suitable browser opening command found');
51
        }
52
53
        foreach ($this->urls as $url) {
54
            passthru(sprintf($openCommand, ProcessUtils::escapeArgument($url)));
0 ignored issues
show
Deprecated Code introduced by
The method Robo\Common\ProcessUtils::escapeArgument() has been deprecated with message: since version 3.3, to be removed in 4.0. Use a command line array or give env vars to the `Process::start/run()` method instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
55
            $this->printTaskInfo('Opened {url}', ['url' => $url]);
56
        }
57
58
        return Result::success($this);
59
    }
60
61
    /**
62
     * @return null|string
63
     */
64
    private function getOpenCommand()
65
    {
66
        if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
67
            return 'start "web" explorer "%s"';
68
        }
69
70
        passthru('which xdg-open', $linux);
71
        passthru('which open', $osx);
72
73
        if (0 === $linux) {
74
            return 'xdg-open %s';
75
        }
76
77
        if (0 === $osx) {
78
            return 'open %s';
79
        }
80
    }
81
}
82