2019-11-16 10:21:14 +03:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Traits;
|
|
|
|
|
2020-06-26 13:40:19 +03:00
|
|
|
use Exception;
|
|
|
|
use Throwable;
|
|
|
|
|
2019-11-16 10:21:14 +03:00
|
|
|
trait Jobs
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* Dispatch a job to its appropriate handler.
|
|
|
|
*
|
|
|
|
* @param mixed $job
|
|
|
|
* @return mixed
|
|
|
|
*/
|
|
|
|
public function dispatch($job)
|
|
|
|
{
|
2019-12-22 15:58:48 +03:00
|
|
|
$function = $this->getDispatchFunction();
|
2019-11-16 10:21:14 +03:00
|
|
|
|
|
|
|
return $function($job);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Dispatch a command to its appropriate handler in the current process.
|
|
|
|
*
|
|
|
|
* @param mixed $job
|
|
|
|
* @param mixed $handler
|
|
|
|
* @return mixed
|
|
|
|
*/
|
|
|
|
public function dispatchNow($job, $handler = null)
|
|
|
|
{
|
|
|
|
$result = dispatch_now($job, $handler);
|
|
|
|
|
|
|
|
return $result;
|
|
|
|
}
|
|
|
|
|
2020-03-09 10:26:02 +03:00
|
|
|
/**
|
|
|
|
* Dispatch a job to its appropriate handler and return a response array for ajax calls.
|
|
|
|
*
|
|
|
|
* @param mixed $job
|
|
|
|
* @return mixed
|
|
|
|
*/
|
|
|
|
public function ajaxDispatch($job)
|
|
|
|
{
|
|
|
|
try {
|
|
|
|
$data = $this->dispatch($job);
|
|
|
|
|
|
|
|
$response = [
|
|
|
|
'success' => true,
|
|
|
|
'error' => false,
|
|
|
|
'data' => $data,
|
|
|
|
'message' => '',
|
|
|
|
];
|
2020-06-26 13:40:19 +03:00
|
|
|
} catch (Exception | Throwable $e) {
|
2020-03-09 10:26:02 +03:00
|
|
|
$response = [
|
|
|
|
'success' => false,
|
|
|
|
'error' => true,
|
|
|
|
'data' => null,
|
|
|
|
'message' => $e->getMessage(),
|
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
return $response;
|
|
|
|
}
|
|
|
|
|
2019-12-22 15:58:48 +03:00
|
|
|
public function getDispatchFunction()
|
2019-11-16 10:21:14 +03:00
|
|
|
{
|
|
|
|
$config = config('queue.default');
|
|
|
|
|
|
|
|
return ($config == 'sync') ? 'dispatch_now' : 'dispatch';
|
|
|
|
}
|
|
|
|
}
|