Repository URL to install this package:
|
Version:
2.2.0 ▾
|
<?php
namespace CrazyFactory\Jobs\Processors;
use CrazyFactory\Jobs\IJobResultProcessor;
use CrazyFactory\Jobs\JobConfig;
use CrazyFactory\Jobs\JobResult;
use CrazyFactory\Jobs\Utils\Format;
class LogToDiskResultProcessor implements IJobResultProcessor
{
protected $directory;
/**
* LogToDiskResultProcessor constructor.
*
* @param string|null $dir
*/
public function __construct($dir)
{
$this->directory = $dir;
}
/**
* @param string|null $dir
* @param int $mode
*
* @return $this
* @throws \Exception
*/
public function withEnsuredDirectory($dir = null, $mode = 0777)
{
$dir = isset($dir)
? $dir
: $this->directory;
// there is no directory name given
if (empty($dir)) {
throw new \Exception('No directory configured');
}
// if directory doesn`t exist yet, create it and then validate it`s existence
if(!is_dir($dir) && !@mkdir($dir, $mode, true) && !is_dir($dir)){
throw new \Exception('Couldn`t create directory');
}
$this->directory = $dir;
return $this;
}
/**
* @param JobResult $jobResult
* @param JobConfig $jobConfig
*
* @return bool
*/
public function process(JobResult $jobResult, JobConfig $jobConfig)
{
$code = $jobResult->getCode();
if (!$this->shouldLog($code, $jobConfig)) {
return false;
}
$timestamp = date('Ymd-his');
$filename = "{$this->directory}/{$timestamp}_{$jobConfig->name}.log";
$lines = array_merge(
$this->getPrefix($jobResult, $jobConfig),
$jobResult->getOutput(),
$this->getSuffix($jobResult, $jobConfig));
file_put_contents($filename, implode('', $lines));
return true;
}
/**
* @param $code
* @param JobConfig $jobConfig
*
* @return bool
*/
protected function shouldLog($code, JobConfig $jobConfig)
{
return ($code == 0 && $jobConfig->logSuccess) || ($code != 0 && $jobConfig->logError);
}
/**
* @param JobResult $jobResult
* @param JobConfig $jobConfig
*
* @return array
*/
protected function getPrefix(
/** @noinspection PhpUnusedParameterInspection */
JobResult $jobResult,
JobConfig $jobConfig)
{
return [
'' . PHP_EOL,
'job: ' . $jobConfig->name . PHP_EOL,
'cmd: ' . $jobConfig->cmd . PHP_EOL,
'--------------------------------' . PHP_EOL,
];
}
/**
* @param JobResult $jobResult
* @param JobConfig $jobConfig
*
* @return array
*/
protected function getSuffix(
JobResult $jobResult,
/** @noinspection PhpUnusedParameterInspection */
JobConfig $jobConfig)
{
$code = $jobResult->getCode();
return [
!$jobResult->hasOutput()
? '[MANAGER] job did not emit output' . PHP_EOL
: PHP_EOL,
'--------------------------------' . PHP_EOL,
'status: ' . $code . PHP_EOL,
'runtime: ' . $jobResult->getDurationFormatted() . PHP_EOL,
];
}
}