phpvms/app/Contracts/Command.php

118 lines
2.9 KiB
PHP
Raw Normal View History

2017-12-30 00:23:42 +08:00
<?php
namespace App\Contracts;
2017-12-30 00:23:42 +08:00
use Illuminate\Support\Facades\Log;
2020-05-24 00:51:12 +08:00
use function is_array;
use Symfony\Component\Process\Process;
2017-12-30 00:23:42 +08:00
/**
* Class BaseCommand
*/
abstract class Command extends \Illuminate\Console\Command
2017-12-30 00:23:42 +08:00
{
/**
* @return mixed
*/
abstract public function handle();
/**
* Adjust the logging depending on where we're running from
*/
public function __construct()
{
parent::__construct();
// Running in the console but not in the tests
if (app()->runningInConsole() && env('APP_ENV') !== 'testing') {
$this->redirectLoggingToFile('stdout');
}
}
/**
* Splice the logger and replace the active handlers with the handlers from the
* a stack in config/logging.php
*
* @param string $channel_name Channel name from config/logging.php
*/
public function redirectLoggingToFile($channel_name): void
{
$logger = app(\Illuminate\Log\Logger::class);
// Close the existing loggers
try {
$handlers = $logger->getHandlers();
foreach ($handlers as $handler) {
$handler->close();
}
} catch (\Exception $e) {
$this->error('Error closing handlers: '.$e->getMessage());
}
// Open the handlers for the channel name,
// and then set them to the main logger
try {
$logger->setHandlers(
Log::channel($channel_name)->getHandlers()
);
} catch (\Exception $e) {
$this->error('Couldn\'t splice the logger: '.$e->getMessage());
}
}
2017-12-30 00:23:42 +08:00
/**
* Streaming file reader
2018-08-27 00:40:04 +08:00
*
2017-12-30 00:23:42 +08:00
* @param $filename
2018-08-27 00:40:04 +08:00
*
2017-12-30 00:23:42 +08:00
* @return \Generator
*/
public function readFile($filename): ?\Generator
2017-12-30 00:23:42 +08:00
{
$fp = fopen($filename, 'rb');
while (($line = fgets($fp)) !== false) {
$line = rtrim($line, "\r\n");
if ($line[0] === ';') {
continue;
}
yield $line;
}
fclose($fp);
}
/**
2020-05-24 00:51:12 +08:00
* @param array|string $cmd
* @param bool $return
* @param mixed $verbose
2018-08-27 00:40:04 +08:00
*
* @throws \Symfony\Component\Process\Exception\RuntimeException
* @throws \Symfony\Component\Process\Exception\LogicException
2018-08-27 00:40:04 +08:00
*
* @return string
2017-12-30 00:23:42 +08:00
*/
public function runCommand($cmd, $return = false, $verbose = true): string
2017-12-30 00:23:42 +08:00
{
2020-05-24 00:51:12 +08:00
if (is_array($cmd)) {
$cmd = implode(' ', $cmd);
}
2017-12-30 00:23:42 +08:00
if ($verbose) {
2020-05-24 00:51:12 +08:00
$this->info('Running '.$cmd);
}
2017-12-30 00:23:42 +08:00
$val = '';
2020-05-24 00:51:12 +08:00
$process = Process::fromShellCommandline($cmd);
$process->run(function ($type, $buffer) use ($return, &$val) {
if ($return) {
$val .= $buffer;
2017-12-30 00:23:42 +08:00
} else {
echo $buffer;
}
});
return $val;
2017-12-30 00:23:42 +08:00
}
}