forked from vova07/yii2-console-runner-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConsoleRunner.php
85 lines (78 loc) · 1.85 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
<?php
namespace vova07\console;
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
/**
* 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
{
/**
* @var string Console application file that will be executed.
* Usually it can be `yii` file.
*/
public $file;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->file === null) {
throw new InvalidConfigException('The "file" property must be set.');
}
}
/**
* Running console command on background
*
* @param string $cmd Argument that will be passed to console application
* @return boolean
*/
public function run($cmd)
{
$cmd = PHP_BINDIR . '/php ' . Yii::getAlias($this->file) . ' ' . $cmd;
if ($this->isWindows() === true) {
pclose(popen('start /b ' . $cmd, 'r'));
} else {
pclose(popen($cmd . ' > /dev/null &', 'r'));
}
return true;
}
/**
* Check operating system
*
* @return boolean true if it's Windows OS
*/
protected function isWindows()
{
if (PHP_OS == 'WINNT' || PHP_OS == 'WIN32') {
return true;
} else {
return false;
}
}
}