adrema/app/Lib/JobMiddleware/WithJobState.php

79 lines
1.7 KiB
PHP
Raw Normal View History

<?php
namespace App\Lib\JobMiddleware;
2023-08-16 01:07:48 +02:00
use App\Lib\Events\JobFailed;
use App\Lib\Events\JobFinished;
use App\Lib\Events\JobStarted;
2023-10-16 15:41:37 +02:00
use App\Lib\Events\ReloadTriggered;
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;
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-10-16 15:41:37 +02:00
private function __construct(public UuidInterface $jobId)
{
}
2023-10-16 15:41:37 +02:00
public static function make(UuidInterface $jobId): self
{
2023-10-16 15:41:37 +02:00
return new self($jobId);
}
public function before(string $message): self
{
2023-10-16 15:41:37 +02:00
$this->beforeMessage = JobStarted::on($this->jobId)->withMessage($message);
return $this;
}
public function after(string $message): self
{
2023-10-16 15:41:37 +02:00
$this->afterMessage = JobFinished::on($this->jobId)->withMessage($message);
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-10-16 15:41:37 +02:00
$this->reloadAfter = ReloadTriggered::on($channels);
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);
}
}
}