/
v.bolshakov
/
AIEcosystem-Testing
Обзор
Документация
Войти
/
v.bolshakov
/
AIEcosystem-Testing
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
dev
common/helpers/ConsoleHelper.php
185 строк
5 KB
Developer
Initial commit
03 авг 2026, 17:43
03 авг 2026, 17:43
7433917
Код
Авторство
О чём код?
<?php namespace common\helpers; use RuntimeException; use Yii; use yii\helpers\BaseConsole; /** * Расширение функций для работы с консолью * * @author Dmitry E. Semenov <sde.tomsk@gmail.com> * @copyright Self (c) 2020 */ class ConsoleHelper extends BaseConsole { /** * Выполнить команду на сервере * @param $command * @return string|null */ public static function exec($command) { Yii::debug('exec: ' . $command); $result = shell_exec($command); Yii::debug('result: ' . $result); return $result; } /** * Получение информации приложеия по текущему Git */ public static function info() { $cmd = 'git log -1 --pretty=format:"%H-%h-%cd"'; $data = explode('-', self::exec($cmd)); if (count($data) == 3) { $url = Yii::t('app', Yii::$app->params['git']['url'], [ 'commit' => $data[0], ]); return [ 'commit' => $data[0], 'hash' => $data[1], 'url' => $url, 'data' => DateHelper::userdate($data[2], true) ]; } else { return []; } } /** * Получить PID процесса * * @param $service_name * @return bool|int */ public static function pid($service_name) { $command = strtr('ps axu | pgrep {sname} | grep -v grep', [ '{sname}' => escapeshellarg($service_name), ]); $pid = self::exec($command); if (!$pid) { return false; } return (int)$pid; } /** * Время работы сервиса * @param $pid * @return string|null */ public static function uptime($pid) { $command = strtr('ps -p {pid} -o etime', [ '{pid}' => escapeshellarg($pid), ]); $data = self::exec($command); return $data; } /** * Prompts the user for input and hides what they type * * @param bool $allowFallback If prompting fails for any reason and this is set to true the prompt * will be done using the regular prompt() function, otherwise a * \RuntimeException is thrown. * @return string * @throws RuntimeException on failure to prompt, unless $allowFallback is true */ public static function hiddenPrompt($text, $allowFallback = false) { parent::stdout($text); // handle windows if (defined('PHP_WINDOWS_VERSION_BUILD')) { // fallback to hiddeninput executable $exe = __DIR__ . '\\..\\res\\hiddeninput.exe'; // handle code running from a phar if ('phar:' === substr(__FILE__, 0, 5)) { $tmpExe = sys_get_temp_dir() . '/hiddeninput.exe'; // use stream_copy_to_stream instead of copy // to work around https://bugs.php.net/bug.php?id=64634 $source = fopen($exe, 'r'); $target = fopen($tmpExe, 'w+'); stream_copy_to_stream($source, $target); fclose($source); fclose($target); unset($source, $target); $exe = $tmpExe; } $output = shell_exec($exe); // clean up if (isset($tmpExe)) { unlink($tmpExe); } if ($output !== null) { // output a newline to be on par with the regular prompt() echo PHP_EOL; return self::trimAnswer($output); } } if (file_exists('/usr/bin/env')) { // handle other OSs with bash/zsh/ksh/csh if available to hide the answer $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null"; foreach (array('bash', 'zsh', 'ksh', 'csh', 'sh') as $sh) { if ('OK' === rtrim(self::exec(sprintf($test, $sh)))) { $shell = $sh; break; } } if (isset($shell)) { $readCmd = ($shell === 'csh') ? 'set mypassword = $<' : 'read -r mypassword'; $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd); $output = self::exec($command); if ($output !== null) { // output a newline to be on par with the regular prompt() echo PHP_EOL; return self::trimAnswer($output); } } } // not able to hide the answer if (!$allowFallback) { throw new RuntimeException('Could not prompt for input in a secure fashion, aborting'); } return self::prompt($text); } /** * Нормализация строки * @param $str * @return string|string[]|null */ private static function trimAnswer($str) { return preg_replace('{\r?\n$}D', '', $str); } }