akaunting/app/Utilities/Console.php

57 lines
1.3 KiB
PHP
Raw Normal View History

2019-12-03 15:41:56 +03:00
<?php
namespace App\Utilities;
2020-06-28 09:39:20 +03:00
use Illuminate\Console\Application;
2020-08-12 02:33:40 +03:00
use Illuminate\Support\Str;
2019-12-03 15:41:56 +03:00
use Symfony\Component\Process\Process;
2020-08-24 17:45:29 +03:00
use Throwable;
2019-12-03 15:41:56 +03:00
class Console
{
2020-08-12 02:33:40 +03:00
public static function run($string, $timeout = 0)
2019-12-03 15:41:56 +03:00
{
2020-06-28 09:39:20 +03:00
$command = Application::formatCommandString($string);
2020-03-19 17:18:19 +03:00
2020-05-20 02:20:48 +03:00
logger('Console command:: ' . $command);
2020-08-12 02:33:40 +03:00
try {
$process = Process::fromShellCommandline($command, base_path());
$process->setTimeout($timeout);
2019-12-03 15:41:56 +03:00
2020-08-12 02:33:40 +03:00
$process->mustRun();
2019-12-03 15:41:56 +03:00
2020-08-12 02:33:40 +03:00
$output = $process->getOutput();
2019-12-03 15:41:56 +03:00
2020-08-12 02:33:40 +03:00
if (static::isValidOutput($output)) {
return true;
}
2022-06-01 10:15:55 +03:00
} catch (Throwable $e) {
2020-08-12 02:33:40 +03:00
$output = $e->getMessage();
}
2020-03-19 17:34:24 +03:00
2020-05-20 02:20:48 +03:00
logger('Console output:: ' . $output);
2020-03-19 17:34:24 +03:00
2020-08-24 17:45:29 +03:00
return static::formatOutput($output);
}
public static function formatOutput($output)
{
$output = nl2br($output);
$output = str_replace(['"', "'"], '', $output);
$output = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $output);
2020-03-19 17:34:24 +03:00
return $output;
2019-12-03 15:41:56 +03:00
}
2020-08-12 02:33:40 +03:00
public static function isValidOutput($output)
{
$errors = [
'Content-Type: application/json',
'CSRF token mismatch',
];
return !Str::contains($output, $errors);
}
2019-12-03 15:41:56 +03:00
}