-
-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathActivityMiddleware.php
More file actions
83 lines (69 loc) · 2.48 KB
/
ActivityMiddleware.php
File metadata and controls
83 lines (69 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
declare(strict_types=1);
namespace Workflow\Middleware;
use Illuminate\Support\Str;
use LimitIterator;
use SplFileObject;
use Workflow\Events\ActivityCompleted;
use Workflow\Events\ActivityFailed;
use Workflow\Events\ActivityStarted;
use Workflow\Exceptions\TransitionNotFound;
final class ActivityMiddleware
{
private $job;
private $result;
private string $uuid;
public function handle($job, $next): void
{
$this->job = $job;
$this->uuid = (string) Str::uuid();
ActivityStarted::dispatch(
$job->storedWorkflow->id,
$this->uuid,
$job::class,
$job->index,
json_encode($job->arguments),
now()
->format('Y-m-d\TH:i:s.u\Z')
);
try {
$this->result = $next($job);
$job->onUnlock = fn (bool $shouldSignal) => $this->onUnlock($shouldSignal);
} catch (\Throwable $throwable) {
$file = new SplFileObject($throwable->getFile());
$iterator = new LimitIterator($file, max(0, $throwable->getLine() - 4), 7);
ActivityFailed::dispatch($job->storedWorkflow->id, $this->uuid, json_encode([
'class' => get_class($throwable),
'message' => $throwable->getMessage(),
'code' => $throwable->getCode(),
'line' => $throwable->getLine(),
'file' => $throwable->getFile(),
'trace' => $throwable->getTrace(),
'snippet' => array_slice(iterator_to_array($iterator), 0, 7),
]), now()
->format('Y-m-d\TH:i:s.u\Z'));
throw $throwable;
}
}
public function onUnlock(bool $shouldSignal): void
{
try {
$this->job->storedWorkflow->toWorkflow()
->next($this->job->index, $this->job->now, $this->job::class, $this->result, $shouldSignal);
ActivityCompleted::dispatch(
$this->job->storedWorkflow->id,
$this->uuid,
json_encode($this->result),
now()
->format('Y-m-d\TH:i:s.u\Z')
);
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $throwable) {
$this->job->storedWorkflow->toWorkflow()
->fail($throwable);
} catch (TransitionNotFound) {
if ($this->job->storedWorkflow->toWorkflow()->running()) {
$this->job->release();
}
}
}
}