CaiWuXiTong/app/Utilities/Console.php

60 lines
1.6 KiB
PHP

<?php
namespace App\Utilities;
use Illuminate\Console\Application;
use Illuminate\Support\Str;
use Symfony\Component\Process\Process;
use Throwable;
class Console
{
public static function run($string, $timeout = 0)
{
// PHP_BINARY is empty under some web SAPIs (including Apache mod_php).
// PHP_BINDIR still points to the directory containing the active PHP binary.
$phpBinary = PHP_BINARY ?: PHP_BINDIR . DIRECTORY_SEPARATOR . 'php';
$command = sprintf('%s %s %s', escapeshellarg($phpBinary), Application::artisanBinary(), $string);
logger('Console command:: ' . $command);
try {
$process = Process::fromShellCommandline($command, base_path());
$process->setTimeout($timeout);
$process->mustRun();
$output = $process->getOutput();
if (static::isValidOutput($output)) {
return true;
}
} catch (Throwable $e) {
$output = $e->getMessage();
}
logger('Console output:: ' . $output);
return static::formatOutput($output);
}
public static function formatOutput($output)
{
$output = nl2br($output);
$output = str_replace(['"', "'"], '', $output);
$output = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $output);
return $output;
}
public static function isValidOutput($output)
{
$errors = [
'Content-Type: application/json',
'CSRF token mismatch',
];
return !Str::contains($output, $errors);
}
}