13 private readonly Closure $backgroundPart;
14 private bool $isBackgroundPartStarted =
false;
15 private bool $immediateIfBackground;
17 public function __construct(callable $job, ?callable $backgroundPart =
null,
bool $immediateIfBackground =
true)
23 $this->backgroundPart = $this->wrapBackgroundPart($backgroundPart);
25 $decoratedJob = $this->wrapForQueue($job);
26 parent::__construct($decoratedJob);
29 public function wait(): mixed
31 if ($this->
getState() !== State::Pending)
36 return $this->queue->wait($this);
41 if ($this->
getState() !== State::Pending)
46 if (isset($this->backgroundPart) && !$this->isBackgroundPartStarted)
48 $this->isBackgroundPartStarted =
true;
49 ($this->backgroundPart)();
55 public static function deferJob(callable $deferredJob,
bool $runImmediatelyIfInBackground =
true): static
57 return new static(
static function () {}, $deferredJob, $runImmediatelyIfInBackground);
62 return $this->immediateIfBackground;
65 private function wrapForQueue(callable $job): callable
67 return function (callable $fulfill, callable $reject) use ($job):
void {
68 if (isset($this->backgroundPart))
70 $this->queue->add($this);
72 $job($fulfill, $reject);
76 private function wrapBackgroundPart(callable $backgroundPart): callable
78 return function () use ($backgroundPart):
void {
96 parent::complete($newState,
$result);
100 $this->queue->onAfterPromiseComplete($this);