phpvms/app/Console/BaseCommand.php

79 lines
1.8 KiB
PHP
Raw Normal View History

2017-12-30 00:23:42 +08:00
<?php
namespace App\Console;
use Illuminate\Console\Command;
use Monolog\Handler\StreamHandler;
2017-12-30 00:23:42 +08:00
use Symfony\Component\Process\Process;
class BaseCommand extends Command
{
/**
* Splice the logger and replace the handler to direct
* everything to stdout as well as the log
*/
public function redirectLoggingToStdout()
{
$logger = app(\Illuminate\Log\Logger::class);
$handlers = $logger->getHandlers();
try {
$handlers[] = new StreamHandler('php://stdout');
$logger->setHandlers($handlers);
} catch (\Exception $e) {
$this->error('Couldn\'t splice the logger');
}
}
2017-12-30 00:23:42 +08:00
/**
* Streaming file reader
2017-12-30 00:23:42 +08:00
* @param $filename
* @return \Generator
*/
public function readFile($filename)
{
$fp = fopen($filename, 'rb');
while (($line = fgets($fp)) !== false) {
$line = rtrim($line, "\r\n");
if ($line[0] === ';') {
continue;
}
yield $line;
}
fclose($fp);
}
/**
* @param $cmd
* @param bool $return
* @return string
* @throws \Symfony\Component\Process\Exception\RuntimeException
* @throws \Symfony\Component\Process\Exception\LogicException
2017-12-30 00:23:42 +08:00
*/
public function runCommand($cmd, $return=false, $verbose=true)
2017-12-30 00:23:42 +08:00
{
if (\is_array($cmd)) {
2017-12-30 00:23:42 +08:00
$cmd = join(' ', $cmd);
}
2017-12-30 00:23:42 +08:00
if($verbose) {
$this->info('Running "' . $cmd . '"');
}
2017-12-30 00:23:42 +08:00
$val = '';
2017-12-30 00:23:42 +08:00
$process = new Process($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
}
}