forked from vova07/yii2-console-runner-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConsoleRunner.php
126 lines (104 loc) · 2.62 KB
/
ConsoleRunner.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
<?php
/**
* @changelog 18 Jan 2018 Added compatibility with Windows
* @changelog 18 Jan 2018 Returned compatibility with PHP-FPM
*/
namespace cbackup\console;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
use yii\base\NotSupportedException;
/**
* ConsoleRunner - a component for running console commands on background.
*
* Usage:
* ```
* ...
* $cr = new ConsoleRunner(['file' => 'my/path/to/yii']);
* $cr->run('controller/action param1 param2 ...');
* ...
* ```
* or use it like an application component:
* ```
* // config.php
* ...
* components [
* 'consoleRunner' => [
* 'class' => 'vova07\console\ConsoleRunner',
* 'file' => 'my/path/to/yii' // or an absolute path to console file
* ]
* ]
* ...
*
* // some-file.php
* Yii::$app->consoleRunner->run('controller/action param1 param2 ...');
* ```
*/
class ConsoleRunner extends Component
{
/**
* Console application file that will be executed.
* Usually it can be `yii` file.
*
* @var string
*/
public $file;
/**
* Absolute path to PHP executable
* @var string
*/
private $php;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->file === null) {
throw new InvalidConfigException('The "file" property must be set.');
}
if($this->isWindows()) {
$this->php = exec('where php.exe');
if( is_dir(PHP_BINDIR) && file_exists(PHP_BINDIR.DIRECTORY_SEPARATOR.'php.exe') ) {
$this->php = PHP_BINDIR.DIRECTORY_SEPARATOR.'php.exe';
}
if( empty($this->php) ) {
throw new NotSupportedException('Could not find php.exe');
}
}
else {
$this->php = PHP_BINDIR . '/php';
}
}
/**
* Running console command on background
*
* @param string $cmd Argument that will be passed to console application
* @return boolean
*/
public function run($cmd)
{
$cmd = $this->php . ' ' . Yii::getAlias($this->file) . ' ' . $cmd;
if ($this->isWindows() === true) {
pclose(popen('start /b ' . $cmd, 'r'));
}
else {
pclose(popen($cmd . ' > /dev/null 2>&1 &', 'r'));
}
return true;
}
/**
* Check if operating system is Windows
*
* @return boolean true if it's Windows OS
*/
protected function isWindows()
{
if( mb_stripos(PHP_OS, 'WIN') !== false ) {
return true;
}
else {
return false;
}
}
}