| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- <?php
- namespace common\components;
- use Yii;
- class AsyncConsole
- {
- /**
- * Start a detached Yii console command.
- *
- * @param array $arguments Command route followed by positional arguments.
- * @param string $logName
- * @return bool
- */
- public static function run(array $arguments, $logName = 'async-console.log')
- {
- if (empty($arguments)) {
- Yii::warning('Unable to start async console command: command arguments are empty');
- return false;
- }
- if (!self::canExec()) {
- Yii::warning('Unable to start async console command: exec is disabled');
- return false;
- }
- $phpBinary = getenv('PHP_CLI_BINARY') ?: '/usr/local/bin/php';
- $yii = dirname(Yii::getAlias('@console')) . '/yii';
- if (!is_file($phpBinary) || !is_executable($phpBinary)) {
- Yii::warning('Unable to start async console command: invalid PHP_CLI_BINARY ' . $phpBinary);
- return false;
- }
- if (!is_file($yii) || !is_executable($yii)) {
- Yii::warning('Unable to start async console command: yii entrypoint is not executable ' . $yii);
- return false;
- }
- $logName = basename($logName);
- $logFile = Yii::getAlias('@console/runtime/logs') . '/' . $logName;
- $escapedArguments = array_map(function ($argument) {
- return escapeshellarg((string)$argument);
- }, $arguments);
- $command = 'nohup '
- . escapeshellarg($phpBinary) . ' '
- . escapeshellarg($yii) . ' '
- . implode(' ', $escapedArguments)
- . ' >> ' . escapeshellarg($logFile)
- . ' 2>&1 < /dev/null &';
- $output = [];
- $exitCode = 0;
- exec($command, $output, $exitCode);
- if ($exitCode !== 0) {
- Yii::warning('Unable to start async console command, exit code: ' . $exitCode);
- return false;
- }
- return true;
- }
- private static function canExec()
- {
- if (!is_callable('exec')) {
- return false;
- }
- $disabled = array_filter(array_map('trim', explode(',', (string)ini_get('disable_functions'))));
- return !in_array('exec', $disabled, true);
- }
- }
|