Repository URL to install this package:
|
Version:
2.2.0 ▾
|
<?php
namespace CrazyFactory\Jobs;
class Job
{
/**
* @param callable $function
* @param int $time_limit
* @param int $error_reporting
*
* @throws \Throwable
*/
public static function run(callable $function, $time_limit = 0, $error_reporting = E_ALL)
{
set_time_limit($time_limit);
error_reporting($error_reporting);
$exitCode = 1;
try {
if (static::shouldRun()) {
$exitCode = static::determineExitCode(call_user_func($function));
}
} catch (\Throwable $exception) {
echo 'Message: ' . $exception->getMessage() . PHP_EOL;
echo 'Origin: ' . $exception->getFile() . ':' . $exception->getLine() . PHP_EOL;
echo 'Trace: ' . $exception->getTraceAsString();
throw $exception;
} finally {
exit($exitCode);
}
}
/**
* @return bool
*/
protected static function shouldRun()
{
return php_sapi_name() == 'cli';
}
/**
* @param null|bool|int $returnValue
*
* @return int
*/
protected static function determineExitCode($returnValue = null)
{
// numbers from 0-255 get returned directly.
if (is_numeric($returnValue) && $returnValue >= 0 && $returnValue <= 255) {
return intval($returnValue);
}
// an explicit false will trigger and error. everything else will be treated as success
return ($returnValue === false)
? 1
: 0;
}
}