-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConsoleCommandRunner.php
78 lines (71 loc) · 2.53 KB
/
ConsoleCommandRunner.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
<?php
namespace panix\engine;
/**
* Class ConsoleCommandRunner
* @link https://github.com/tebazil/yii2-console-runner
*
* used
* $runner = new \panix\engine\ConsoleCommandRunner();
* $runner->run('migrate');
* $runner->run('migrate/create', ['insert_test_id','interactive'=>false]);
*
*
* $output = $runner->getOutput();
* $exitCode = $runner->getExitCode();
*
* @package panix\engine
*/
class ConsoleCommandRunner
{
private $outerApplication;
private $innerApplication;
private $output;
private $exitCode;
public function __construct($config = null)
{
if (is_null($config)) {
$config = '@app/config/console.php';
if (!is_file(\Yii::getAlias($config))) {
$config = '@console/config/console.php';
}
if (!is_file(\Yii::getAlias($config))) {
throw new \InvalidArgumentException('Config was not provided; and was not detected in common paths of basic and advanced templates');
}
}
if (is_string($config)) {
if (is_file($file = \Yii::getAlias($config))) {
$config = require($file);
} else {
throw new \InvalidArgumentException('if $config is a string, it should be a valid yii file path');
}
}
if (!is_array($config)) {
throw new \InvalidArgumentException('$config should either be a string (path) or array');
}
// fcgi doesn't have STDIN and STDOUT defined by default
defined('STDIN') or define('STDIN', fopen('php://stdin', 'r'));
defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w'));
$this->outerApplication = \Yii::$app;
$this->innerApplication = new \panix\engine\console\Application($config); //this changes \Yii::$app;
\Yii::$app = $this->outerApplication; //we set it back
}
public function run($route, array $params = [])
{
$this->output = null;
$this->exitCode = null;
\Yii::$app = $this->innerApplication; //Yii::$app references to console application, while you are running your command
ob_start();
$this->exitCode = $this->innerApplication->runAction($route, $params);
$this->output = ob_get_clean();
\Yii::$app = $this->outerApplication; //now Yii::$app is outer application again (typically web application)
return $this;
}
public function getOutput()
{
return $this->output;
}
public function getExitCode()
{
return $this->exitCode;
}
}