2023-08-16 00:43:28 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Lib\JobMiddleware;
|
|
|
|
|
2023-08-16 01:07:48 +02:00
|
|
|
use App\Lib\Events\JobFailed;
|
2023-08-16 00:43:28 +02:00
|
|
|
use App\Lib\Events\JobFinished;
|
|
|
|
use App\Lib\Events\JobStarted;
|
|
|
|
use Closure;
|
|
|
|
use Lorisleiva\Actions\Decorators\JobDecorator;
|
2023-08-16 01:07:48 +02:00
|
|
|
use Throwable;
|
2023-08-16 00:43:28 +02:00
|
|
|
|
|
|
|
class WithJobState
|
|
|
|
{
|
|
|
|
|
|
|
|
public JobStarted $beforeMessage;
|
|
|
|
public JobFinished $afterMessage;
|
2023-08-16 01:07:48 +02:00
|
|
|
public JobFailed $failedMessage;
|
2023-08-16 00:43:28 +02:00
|
|
|
|
|
|
|
private function __construct(public string $channel)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
|
|
|
public static function make(string $channel): self
|
|
|
|
{
|
|
|
|
return new self($channel);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function before(string $message): self
|
|
|
|
{
|
|
|
|
$this->beforeMessage = JobStarted::on($this->channel)->withMessage($message);
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function after(string $message): self
|
|
|
|
{
|
|
|
|
$this->afterMessage = JobFinished::on($this->channel)->withMessage($message);
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2023-08-16 01:07:48 +02:00
|
|
|
public function failed(string $message): self
|
|
|
|
{
|
|
|
|
$this->failedMessage = JobFailed::on($this->channel)->withMessage($message);
|
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2023-08-16 00:43:28 +02:00
|
|
|
public function shouldReload(): self
|
|
|
|
{
|
|
|
|
$this->afterMessage->shouldReload();
|
2023-08-16 01:07:48 +02:00
|
|
|
$this->failedMessage->shouldReload();
|
2023-08-16 00:43:28 +02:00
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function handle(JobDecorator $job, Closure $next): void
|
|
|
|
{
|
|
|
|
event($this->beforeMessage);
|
2023-08-16 01:07:48 +02:00
|
|
|
|
|
|
|
try {
|
|
|
|
$next($job);
|
|
|
|
} catch (Throwable $e) {
|
|
|
|
event($this->failedMessage);
|
|
|
|
throw $e;
|
|
|
|
}
|
|
|
|
|
2023-08-16 00:43:28 +02:00
|
|
|
event($this->afterMessage);
|
|
|
|
}
|
|
|
|
}
|