1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
BackgroundJobPromise.php
См. документацию.
1<?php
2
4
7use Closure;
8use Throwable;
9
11{
12 private Queue $queue;
13 private readonly Closure $backgroundPart;
14 private bool $isBackgroundPartStarted = false;
15 private bool $immediateIfBackground;
16
17 public function __construct(callable $job, ?callable $backgroundPart = null, bool $immediateIfBackground = true)
18 {
19 $this->immediateIfBackground = $immediateIfBackground;
20 $this->queue = Queue::getInstance();
21 if ($backgroundPart)
22 {
23 $this->backgroundPart = $this->wrapBackgroundPart($backgroundPart);
24 }
25 $decoratedJob = $this->wrapForQueue($job);
26 parent::__construct($decoratedJob);
27 }
28
29 public function wait(): mixed
30 {
31 if ($this->getState() !== State::Pending)
32 {
33 return $this->getResult();
34 }
35
36 return $this->queue->wait($this);
37 }
38
39 public function onWait(): mixed
40 {
41 if ($this->getState() !== State::Pending)
42 {
43 return $this->getResult();
44 }
45
46 if (isset($this->backgroundPart) && !$this->isBackgroundPartStarted)
47 {
48 $this->isBackgroundPartStarted = true;
49 ($this->backgroundPart)();
50 }
51
52 return $this->getResult();
53 }
54
55 public static function deferJob(callable $deferredJob, bool $runImmediatelyIfInBackground = true): static
56 {
57 return new static(static function () {}, $deferredJob, $runImmediatelyIfInBackground);
58 }
59
60 public function immediateIfBackground(): bool
61 {
62 return $this->immediateIfBackground;
63 }
64
65 private function wrapForQueue(callable $job): callable
66 {
67 return function (callable $fulfill, callable $reject) use ($job): void {
68 if (isset($this->backgroundPart))
69 {
70 $this->queue->add($this);
71 }
72 $job($fulfill, $reject);
73 };
74 }
75
76 private function wrapBackgroundPart(callable $backgroundPart): callable
77 {
78 return function () use ($backgroundPart): void {
79 $result = null;
80 try
81 {
82 $result = $backgroundPart();
83 }
84 catch (Throwable $e)
85 {
86 $this->reject($e);
87 }
88 $this->fulfill($result);
89 };
90 }
91
92 protected function complete(State $newState, mixed $result): void
93 {
94 try
95 {
96 parent::complete($newState, $result);
97 }
98 finally
99 {
100 $this->queue->onAfterPromiseComplete($this);
101 }
102 }
103
104}
static deferJob(callable $deferredJob, bool $runImmediatelyIfInBackground=true)
Определения BackgroundJobPromise.php:55
complete(State $newState, mixed $result)
Определения BackgroundJobPromise.php:92
__construct(callable $job, ?callable $backgroundPart=null, bool $immediateIfBackground=true)
Определения BackgroundJobPromise.php:17
reject(mixed $result)
Определения Promise.php:77
mixed $result
Определения Promise.php:16
fulfill(mixed $result)
Определения Promise.php:72
getResult()
Определения Promise.php:40
getState()
Определения Promise.php:35
static getInstance()
Определения Queue.php:29
$result
Определения get_property_values.php:14