adrema/app/Lib/JobMiddleware/WithJobState.php

79 lines
1.8 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;
use Closure;
use Lorisleiva\Actions\Decorators\JobDecorator;
2023-08-17 12:46:48 +02:00
use Ramsey\Uuid\Lazy\LazyUuidFromString;
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-08-17 12:46:48 +02:00
private function __construct(public string $channel, public UuidInterface $jobId)
{
}
2023-08-17 12:46:48 +02:00
public static function make(string $channel, UuidInterface $jobId): self
{
2023-08-17 12:46:48 +02:00
return new self($channel, $jobId);
}
public function before(string $message): self
{
2023-08-17 12:46:48 +02:00
$this->beforeMessage = JobStarted::on($this->channel, $this->jobId)->withMessage($message);
return $this;
}
public function after(string $message): self
{
2023-08-17 12:46:48 +02:00
$this->afterMessage = JobFinished::on($this->channel, $this->jobId)->withMessage($message);
return $this;
}
2023-08-16 01:07:48 +02:00
public function failed(string $message): self
{
2023-08-17 12:46:48 +02:00
$this->failedMessage = JobFailed::on($this->channel, $this->jobId)->withMessage($message);
2023-08-16 01:07:48 +02:00
return $this;
}
public function shouldReload(): self
{
2023-08-17 12:46:48 +02:00
$this->afterMessage?->shouldReload();
$this->failedMessage?->shouldReload();
return $this;
}
public function handle(JobDecorator $job, Closure $next): void
{
2023-08-17 12:46:48 +02:00
if ($this->beforeMessage) {
event($this->beforeMessage);
}
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);
}
}
}