Completed
Push — master ( a20e35...2a3e96 )
by Greg
03:21
created

src/Task/Development/OpenBrowser.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
namespace Robo\Task\Development;
3
4
use Robo\Task\BaseTask;
5
use Robo\Common\ProcessUtils;
6
use Robo\Result;
7
8
/**
9
 * Opens the default's user browser
10
 * code inspired from openBrowser() function in https://github.com/composer/composer/blob/master/src/Composer/Command/HomeCommand.php
11
 *
12
 * ``` php
13
 * <?php
14
 * // open one browser window
15
 * $this->taskOpenBrowser('http://localhost')
16
 *  ->run();
17
 *
18
 * // open two browser windows
19
 * $this->taskOpenBrowser([
20
 *     'http://localhost/mysite',
21
 *     'http://localhost/mysite2'
22
 *   ])
23
 *   ->run();
24
 * ```
25
 */
26
class OpenBrowser extends BaseTask
27
{
28
    /**
29
     * @var string[]
30
     */
31
    protected $urls = [];
32
33
    /**
34
     * @param string|array $url
35
     */
36
    public function __construct($url)
37
    {
38
        $this->urls = (array) $url;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function run()
45
    {
46
        $openCommand = $this->getOpenCommand();
47
48
        if (empty($openCommand)) {
49
            return Result::error($this, 'no suitable browser opening command found');
50
        }
51
52
        foreach ($this->urls as $url) {
53
            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...
54
            $this->printTaskInfo('Opened {url}', ['url' => $url]);
55
        }
56
57
        return Result::success($this);
58
    }
59
60
    /**
61
     * @return null|string
62
     */
63
    private function getOpenCommand()
64
    {
65
        if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
66
            return 'start "web" explorer "%s"';
67
        }
68
69
        passthru('which xdg-open', $linux);
70
        passthru('which open', $osx);
71
72
        if (0 === $linux) {
73
            return 'xdg-open %s';
74
        }
75
76
        if (0 === $osx) {
77
            return 'open %s';
78
        }
79
    }
80
}
81