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;
|
2023-10-16 15:41:37 +02:00
|
|
|
use App\Lib\Events\ReloadTriggered;
|
2023-08-16 00:43:28 +02:00
|
|
|
use Closure;
|
|
|
|
use Lorisleiva\Actions\Decorators\JobDecorator;
|
2023-08-17 12:46:48 +02:00
|
|
|
use Ramsey\Uuid\UuidInterface;
|
2023-08-16 01:07:48 +02:00
|
|
|
use Throwable;
|
2023-08-16 00:43:28 +02:00
|
|
|
|
|
|
|
class WithJobState
|
|
|
|
{
|
|
|
|
|
2023-08-17 12:46:48 +02:00
|
|
|
public ?JobStarted $beforeMessage = null;
|
|
|
|
public ?JobFinished $afterMessage = null;
|
|
|
|
public ?JobFailed $failedMessage = null;
|
2023-10-16 15:41:37 +02:00
|
|
|
public ?ReloadTriggered $reloadAfter = null;
|
2023-08-16 00:43:28 +02:00
|
|
|
|
2023-10-16 15:41:37 +02:00
|
|
|
private function __construct(public UuidInterface $jobId)
|
2023-08-16 00:43:28 +02:00
|
|
|
{
|
|
|
|
}
|
|
|
|
|
2023-10-16 15:41:37 +02:00
|
|
|
public static function make(UuidInterface $jobId): self
|
2023-08-16 00:43:28 +02:00
|
|
|
{
|
2023-10-16 15:41:37 +02:00
|
|
|
return new self($jobId);
|
2023-08-16 00:43:28 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public function before(string $message): self
|
|
|
|
{
|
2023-10-16 15:41:37 +02:00
|
|
|
$this->beforeMessage = JobStarted::on($this->jobId)->withMessage($message);
|
2023-08-16 00:43:28 +02:00
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function after(string $message): self
|
|
|
|
{
|
2023-10-16 15:41:37 +02:00
|
|
|
$this->afterMessage = JobFinished::on($this->jobId)->withMessage($message);
|
2023-08-16 00:43:28 +02:00
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2023-08-16 01:07:48 +02:00
|
|
|
public function failed(string $message): self
|
|
|
|
{
|
2023-10-16 15:41:37 +02:00
|
|
|
$this->failedMessage = JobFailed::on($this->jobId)->withMessage($message);
|
2023-08-16 01:07:48 +02:00
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
2023-10-16 15:41:37 +02:00
|
|
|
public function shouldReload(JobChannels $channels): self
|
2023-08-16 00:43:28 +02:00
|
|
|
{
|
2023-10-16 15:41:37 +02:00
|
|
|
$this->reloadAfter = ReloadTriggered::on($channels);
|
2023-08-16 00:43:28 +02:00
|
|
|
|
|
|
|
return $this;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function handle(JobDecorator $job, Closure $next): void
|
|
|
|
{
|
2023-08-16 01:07:48 +02:00
|
|
|
try {
|
|
|
|
$next($job);
|
|
|
|
} catch (Throwable $e) {
|
2023-08-17 12:46:48 +02:00
|
|
|
if ($this->failedMessage) {
|
|
|
|
event($this->failedMessage);
|
|
|
|
}
|
2023-08-16 01:07:48 +02:00
|
|
|
throw $e;
|
|
|
|
}
|
|
|
|
|
2023-08-17 12:46:48 +02:00
|
|
|
if ($this->afterMessage) {
|
|
|
|
event($this->afterMessage);
|
|
|
|
}
|
2023-10-16 15:41:37 +02:00
|
|
|
|
|
|
|
if ($this->reloadAfter) {
|
|
|
|
event($this->reloadAfter);
|
|
|
|
}
|
2023-08-16 00:43:28 +02:00
|
|
|
}
|
|
|
|
}
|