-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathWorkflow.php
More file actions
973 lines (933 loc) · 31.1 KB
/
Workflow.php
File metadata and controls
973 lines (933 loc) · 31.1 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
<?php
/**
* This file is part of Temporal package.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Temporal;
use DateTimeInterface;
use Ramsey\Uuid\UuidInterface;
use React\Promise\PromiseInterface;
use Temporal\Activity\ActivityOptions;
use Temporal\Activity\ActivityOptionsInterface;
use Temporal\Client\WorkflowStubInterface;
use Temporal\DataConverter\Type;
use Temporal\DataConverter\ValuesInterface;
use Temporal\Exception\OutOfContextException;
use Temporal\Internal\Support\Facade;
use Temporal\Internal\Workflow\ScopeContext;
use Temporal\Workflow\ActivityStubInterface;
use Temporal\Workflow\CancellationScopeInterface;
use Temporal\Workflow\ChildWorkflowOptions;
use Temporal\Workflow\ChildWorkflowStubInterface;
use Temporal\Workflow\ContinueAsNewOptions;
use Temporal\Workflow\ExternalWorkflowStubInterface;
use Temporal\Workflow\ScopedContextInterface;
use Temporal\Workflow\UpdateContext;
use Temporal\Workflow\WorkflowExecution;
use Temporal\Workflow\WorkflowInfo;
use Temporal\Internal\Support\DateInterval;
/**
* This class provides coroutine specific access to active WorkflowContext. It is safe to use this Facade inside
* your helper classes.
*
* This is main class you can use in your workflow code.
*
* @method static ScopeContext getCurrentContext() Get current workflow context.
*
* @psalm-import-type TypeEnum from Type
* @psalm-import-type DateIntervalValue from DateInterval
* @see DateInterval
*
* @template-extends Facade<ScopedContextInterface>
*/
final class Workflow extends Facade
{
public const DEFAULT_VERSION = -1;
/**
* Returns current datetime.
*
* Unlike "real" system time, this method returns the time at which the
* given workflow task started at a certain point in time.
*
* Thus, in the case of an execution error and when the workflow has been
* restarted ({@see Workflow::isReplaying()}), the result of this method
* will return exactly the date and time at which this workflow task was
* first started, which eliminates the problems of side effects.
*
* Please, use this method {@see Workflow::now()} instead of:
*
* - {@see time()} function.
* - {@see \DateTime} constructor.
* - {@see \DateTimeImmutable} constructor.
*
* And each other like this.
*
* @return \DateTimeInterface
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function now(): \DateTimeInterface
{
return self::getCurrentContext()->now();
}
/**
* Checks if the code is under a workflow.
*
* Returns **false** if not under workflow code.
*
* In the case that the workflow is started for the first time, the **true** value will be returned.
*
* @return bool
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function isReplaying(): bool
{
return self::getCurrentContext()->isReplaying();
}
/**
* Returns information about current workflow execution.
*
* @return WorkflowInfo
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function getInfo(): WorkflowInfo
{
return self::getCurrentContext()->getInfo();
}
/**
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function getUpdateContext(): ?UpdateContext
{
return self::getCurrentContext()->getUpdateContext();
}
/**
* Returns workflow execution input arguments.
*
* The data is equivalent to what is passed to the workflow handler.
*
* For example:
* ```php
* #[WorkflowInterface]
* interface ExampleWorkflowInterface
* {
* #[WorkflowMethod]
* public function handle(int $first, string $second);
* }
* ```
*
* And
*
* ```php
* // ...
* $arguments = Workflow::getInput();
*
* // Contains the value passed as the first argument to the workflow
* $first = $arguments->getValue(0, Type::TYPE_INT);
*
* // Contains the value passed as the second argument to the workflow
* $second = $arguments->getValue(1, Type::TYPE_STRING);
* ```
*
* @return ValuesInterface
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function getInput(): ValuesInterface
{
return self::getCurrentContext()->getInput();
}
/**
* The method calls an asynchronous task and returns a promise with
* additional properties/methods.
*
* You can use this method to call and manipulate a group of methods.
*
* For example:
*
* ```php
* #[WorkflowMethod]
* public function handler()
* {
* // Create the new "group" of executions
* $promise = Workflow::async(function() {
* $first = yield Workflow::executeActivity('first');
* $second = yield Workflow::executeActivity('second');
*
* return yield Promise::all([$first, $second]);
* });
*
* // Waiting for the execution result
* yield $promise;
*
* // Or cancel all group requests (activity executions)
* $promise->cancel();
*
* // Or get information about the execution of the group
* $promise->isCancelled();
* }
* ```
*
* You can see more information about the capabilities of the child
* asynchronous task in {@see CancellationScopeInterface} interface.
*
* @param callable $task
* @return CancellationScopeInterface
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function async(callable $task): CancellationScopeInterface
{
return self::getCurrentContext()->async($task);
}
/**
* Creates a child task that is not affected by parent task interruption, cancellation, or completion.
*
* The method is similar to the {@see Workflow::async()}, however, unlike
* it, it creates a child task, the execution of which is not affected by
* interruption, cancellation or completion of the parent task.
*
* Default behaviour through {@see Workflow::async()}:
*
* ```php
* $parent = Workflow::async(fn() =>
* $child = Workflow::async(fn() =>
* // ...
* )
* );
*
* $parent->cancel();
*
* // In this case, the "$child" promise will also be canceled:
* $child->isCancelled(); // true
* ```
*
* When creating a detaching task using {@see Workflow::asyncDetached()}
* inside the parent, it will not be stopped when the parent context
* finishes working:
*
* ```php
* $parent = Workflow::async(fn() =>
* $child = Workflow::asyncDetached(fn() =>
* // ...
* )
* );
*
* $parent->cancel();
*
* // In this case, the "$child" promise will NOT be canceled:
* $child->isCancelled(); // false
* ```
*
* Use asyncDetached to handle cleanup and compensation logic.
*
* @param callable $task
* @return CancellationScopeInterface
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function asyncDetached(callable $task): CancellationScopeInterface
{
return self::getCurrentContext()->asyncDetached($task);
}
/**
* Moves to the next step if the expression evaluates to `true`.
*
* Please note that a state change should ONLY occur if the internal
* workflow conditions are met.
*
* ```php
* #[WorkflowMethod]
* public function handler()
* {
* yield Workflow::await(
* Workflow::executeActivity('shouldByContinued')
* );
*
* // ...do something
* }
* ```
*
* Or in the case of an explicit signal method execution of the specified
* workflow.
*
* ```php
* private bool $continued = false;
*
* #[WorkflowMethod]
* public function handler()
* {
* yield Workflow::await(fn() => $this->continued);
*
* // ...continue execution
* }
*
* #[SignalMethod]
* public function continue()
* {
* $this->continued = true;
* }
* ```
*
* @param callable|PromiseInterface ...$conditions
* @return PromiseInterface
*/
public static function await(...$conditions): PromiseInterface
{
return self::getCurrentContext()->await(...$conditions);
}
/**
* Checks if any conditions were met or the timeout was reached.
*
* Returns **true** if any of conditions were fired and **false** if
* timeout was reached.
*
* This method is similar to {@see Workflow::await()}, but in any case it
* will proceed to the next step either if the internal workflow conditions
* are met, or after the specified timer interval expires.
*
* ```php
* #[WorkflowMethod]
* public function handler()
* {
* // Continue after 42 seconds or when bool "continued" will be true.
* yield Workflow::awaitWithTimeout(42, fn() => $this->continued);
*
* // ...continue execution
* }
* ```
*
* @param DateIntervalValue $interval
* @param callable|PromiseInterface ...$conditions
* @return PromiseInterface<bool>
*/
public static function awaitWithTimeout($interval, ...$conditions): PromiseInterface
{
return self::getCurrentContext()->awaitWithTimeout($interval, ...$conditions);
}
/**
* Returns value of last completion result, if any.
*
* @param Type|TypeEnum|mixed $type
* @return mixed
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function getLastCompletionResult($type = null)
{
return self::getCurrentContext()->getLastCompletionResult($type);
}
/**
* A method that allows you to dynamically register additional query
* handler in a workflow during the execution of a workflow.
*
* ```php
* #[WorkflowMethod]
* public function handler()
* {
* Workflow::registerQuery('query', function(string $argument) {
* echo sprintf('Executed query "query" with argument "%s"', $argument);
* });
* }
* ```
*
* The same method ({@see WorkflowStubInterface::query()}) should be used
* to call such query handlers as in the case of ordinary query methods.
*
* @param string|class-string $queryType
* @param callable $handler
* @return ScopedContextInterface
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function registerQuery(string $queryType, callable $handler): ScopedContextInterface
{
return self::getCurrentContext()->registerQuery($queryType, $handler);
}
/**
* Registers a query with an additional signal handler.
*
* The method is similar to the {@see Workflow::registerQuery()}, but it
* registers an additional signal handler.
*
* ```php
* #[WorkflowMethod]
* public function handler()
* {
* Workflow::registerSignal('signal', function(string $argument) {
* echo sprintf('Executed signal "signal" with argument "%s"', $argument);
* });
* }
* ```
*
* The same method ({@see WorkflowStubInterface::signal()}) should be used
* to call such signal handlers as in the case of ordinary signal methods.
*
* @param non-empty-string $queryType
* @param callable $handler
* @return ScopedContextInterface
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function registerSignal(string $queryType, callable $handler): ScopedContextInterface
{
return self::getCurrentContext()->registerSignal($queryType, $handler);
}
/**
* Updates the behavior of an existing workflow to resolve inconsistency errors during replay.
*
* The method is used to update the behavior (code) of an existing workflow
* which was already implemented earlier in order to get rid of errors of
* inconsistency of workflow replay and existing new code.
*
* ```php
* #[WorkflowMethod]
* public function handler()
* {
* $version = yield Workflow::getVersion('new-activity-added', 1, 2);
*
* $result = yield match($version) {
* 1 => Workflow::executeActivity('before'), // Old behaviour
* 2 => Workflow::executeActivity('after'), // New behaviour
* }
* }
* ```
*
* @param string $changeId
* @param int $minSupported
* @param int $maxSupported
* @return PromiseInterface<int>
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function getVersion(string $changeId, int $minSupported, int $maxSupported): PromiseInterface
{
return self::getCurrentContext()->getVersion($changeId, $minSupported, $maxSupported);
}
/**
* Isolates non-pure data to ensure consistent results during workflow replays.
*
* This method serves to isolate any non-pure data. When the workflow is
* replayed (for example, in case of an error), such isolated data will
* return the result of the previous replay.
*
* ```php
* #[WorkflowMethod]
* public function handler()
* {
* // ❌ Bad: Each call to workflow, the data will change.
* $time = hrtime(true);
*
* // ✅ Good: The calculation of the data with the side-effect
* // will be performed once.
* $time = yield Workflow::sideEffect(fn() => hrtime(true));
* }
* ```
*
* @template TReturn
* @param callable(): TReturn $value
* @return PromiseInterface<TReturn>
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function sideEffect(callable $value): PromiseInterface
{
return self::getCurrentContext()->sideEffect($value);
}
/**
* Stops workflow execution work for a specified period.
*
* The first argument can take implementation of the {@see \DateInterval},
* string Carbon format ({@link https://carbon.nesbot.com/docs/#api-interval})
* or a positive number, which is equivalent to the seconds for which the
* workflow should be suspended.
*
* ```php
* #[WorkflowMethod]
* public function handler()
* {
* // Wait 10 seconds
* yield Workflow::timer(10);
*
* // Wait 42 hours
* yield Workflow::timer(new \DateInterval('PT42H'));
*
* // Wait 23 months
* yield Workflow::timer('23 months');
* }
* ```
*
* @param DateIntervalValue $interval
* @return PromiseInterface<null>
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function timer($interval): PromiseInterface
{
return self::getCurrentContext()->timer($interval);
}
/**
* Completes the current workflow execution atomically and starts a new execution with the same Workflow Id.
*
* Method atomically completes the current workflow execution and starts a
* new execution of the Workflow with the same Workflow Id. The new
* execution will not carry over any history from the old execution.
*
* ```php
* #[WorkflowMethod]
* public function handler()
* {
* return yield Workflow::continueAsNew('AnyAnotherWorkflow');
* }
* ```
*
* @param string $type
* @param array $args
* @param ContinueAsNewOptions|null $options
* @return PromiseInterface
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function continueAsNew(
string $type,
array $args = [],
ContinueAsNewOptions $options = null
): PromiseInterface {
return self::getCurrentContext()->continueAsNew($type, $args, $options);
}
/**
* Creates a proxy for a workflow class to continue as new.
*
* This method is equivalent to {@see Workflow::continueAsNew()}, but it takes
* the workflow class as the first argument, and the further api is built on
* the basis of calls to the methods of the passed workflow.
*
* ```php
* // Any workflow interface example:
*
* #[WorkflowInterface]
* interface ExampleWorkflow
* {
* #[WorkflowMethod]
* public function handle(int $value);
* }
*
* // Workflow::newContinueAsNewStub usage example:
*
* #[WorkflowMethod]
* public function handler()
* {
* // ExampleWorkflow proxy
* $proxy = Workflow::newContinueAsNewStub(ExampleWorkflow::class);
*
* // Executes ExampleWorkflow::handle(int $value)
* return yield $proxy->handle(42);
* }
* ```
*
* @psalm-template T of object
*
* @param class-string<T> $class
* @param ContinueAsNewOptions|null $options
* @return T
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function newContinueAsNewStub(string $class, ContinueAsNewOptions $options = null): object
{
return self::getCurrentContext()->newContinueAsNewStub($class, $options);
}
/**
* Calls an external workflow without stopping the current one.
*
* Method for calling an external workflow without stopping the current one.
* It is similar to {@see Workflow::continueAsNew()}, but does not terminate
* the current workflow execution.
*
* ```php
* #[WorkflowMethod]
* public function handler()
* {
* $result = yield Workflow::executeChildWorkflow('AnyAnotherWorkflow');
*
* // Do something else
* }
* ```
*
* Please note that due to the fact that PHP does not allow defining the
* type on {@see \Generator}, you sometimes need to specify the type of
* the child workflow result explicitly.
*
* ```php
* // External child workflow handler method with Generator return type-hint
* public function handle(): \Generator
* {
* yield Workflow::executeActivity('example');
*
* return 42; // Generator which returns int type (Type::TYPE_INT)
* }
*
* // Child workflow execution
* #[WorkflowMethod]
* public function handler()
* {
* $result = yield Workflow::executeChildWorkflow(
* type: 'ChildWorkflow',
* returnType: Type::TYPE_INT,
* );
*
* // Do something else
* }
* ```
*
* @param string $type
* @param array $args
* @param ChildWorkflowOptions|null $options
* @param Type|string|\ReflectionType|\ReflectionClass|null $returnType
*
* @return PromiseInterface
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function executeChildWorkflow(
string $type,
array $args = [],
ChildWorkflowOptions $options = null,
mixed $returnType = null,
): PromiseInterface {
return self::getCurrentContext()->executeChildWorkflow($type, $args, $options, $returnType);
}
/**
* Creates a proxy for a workflow class to execute as a child workflow.
*
* This method is equivalent to {@see Workflow::executeChildWorkflow()}, but
* it takes the workflow class as the first argument, and the further api
* is built on the basis of calls to the methods of the passed workflow.
* For starting abandon child workflow {@see Workflow::newUntypedChildWorkflowStub()}.
*
* ```php
* // Any workflow interface example:
*
* #[WorkflowInterface]
* interface ChildWorkflowExample
* {
* #[WorkflowMethod]
* public function handle(int $value);
* }
*
* // Workflow::newChildWorkflowStub usage example:
*
* #[WorkflowMethod]
* public function handler()
* {
* // ExampleWorkflow proxy
* $proxy = Workflow::newChildWorkflowStub(ChildWorkflowExample::class);
*
* // Executes ChildWorkflowExample::handle(int $value)
* $result = yield $proxy->handle(42);
*
* // etc ...
* }
* ```
*
* @psalm-template T of object
*
* @param class-string<T> $class
* @param ChildWorkflowOptions|null $options
*
* @return T
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function newChildWorkflowStub(
string $class,
ChildWorkflowOptions $options = null,
): object {
return self::getCurrentContext()->newChildWorkflowStub($class, $options);
}
/**
* Creates a proxy for a workflow by name to execute as a child workflow.
*
* This method is equivalent to {@see Workflow::newChildWorkflowStub()}, but
* it takes the workflow name (instead of class name) as the first argument.
*
* ```php
* #[WorkflowMethod]
* public function handler()
* {
* // ExampleWorkflow proxy
* $workflow = Workflow::newUntypedChildWorkflowStub('WorkflowName');
*
* // Executes workflow
* $workflow->execute(42);
*
* // Executes workflow signal named "name"
* $workflow->signal('name');
*
* // etc ...
* }
* ```
*
* To start abandoned child workflow use `yield` and method `start()`:
*
* ```php
* #[WorkflowMethod]
* public function handler()
* {
* // ExampleWorkflow proxy
* $workflow = Workflow::newUntypedChildWorkflowStub(
* 'WorkflowName',
* ChildWorkflowOptions::new()->withParentClosePolicy(ParentClosePolicy::Abandon)
* );
*
* // Start child workflow
* yield $workflow->start(42);
* }
* ```
*
* @param string $name
* @param ChildWorkflowOptions|null $options
*
* @return ChildWorkflowStubInterface
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function newUntypedChildWorkflowStub(
string $name,
ChildWorkflowOptions $options = null,
): ChildWorkflowStubInterface {
return self::getCurrentContext()->newUntypedChildWorkflowStub($name, $options);
}
/**
* This method allows you to create a "proxy" for an existing and
* running workflow by fqn class name of the existing workflow.
*
* ```php
* #[WorkflowMethod]
* public function handler(string $existingWorkflowId)
* {
* $externalWorkflow = Workflow::newExternalWorkflowStub(ClassName::class,
* new WorkflowExecution($existingWorkflowId)
* );
*
* // The method "signalMethod" from the class "ClassName" will be called:
* yield $externalWorkflow->signalMethod();
* }
* ```
*
* @psalm-template T of object
*
* @param class-string<T> $class
* @param WorkflowExecution $execution
* @return T
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function newExternalWorkflowStub(string $class, WorkflowExecution $execution): object
{
return self::getCurrentContext()->newExternalWorkflowStub($class, $execution);
}
/**
* Allows to create a "proxy" for an existing and running workflow by
* name (type) of the existing workflow.
*
* ```php
* #[WorkflowMethod]
* public function handler(string $existingWorkflowId)
* {
* $externalWorkflow = Workflow::newUntypedExternalWorkflowStub(
* new WorkflowExecution($existingWorkflowId)
* );
*
* // Executes signal named "name"
* $externalWorkflow->signal('name');
*
* // Stops the external workflow
* $externalWorkflow->cancel();
* }
* ```
*
* @param WorkflowExecution $execution
* @return ExternalWorkflowStubInterface
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function newUntypedExternalWorkflowStub(WorkflowExecution $execution): ExternalWorkflowStubInterface
{
return self::getCurrentContext()->newUntypedExternalWorkflowStub($execution);
}
/**
* Calls an activity by its name and gets the result of its execution.
*
* ```php
* #[WorkflowMethod]
* public function handler(string $existingWorkflowId)
* {
* $result1 = yield Workflow::executeActivity('activityName');
* $result2 = yield Workflow::executeActivity('anotherActivityName');
* }
* ```
*
* In addition to this method of calling, you can use alternative methods
* of working with the result using Promise API ({@see PromiseInterface}).
*
* ```php
* #[WorkflowMethod]
* public function handler(string $existingWorkflowId)
* {
* Workflow::executeActivity('activityName')
* ->then(function ($result) {
* // Execution result
* })
* ->otherwise(function (\Throwable $error) {
* // Execution error
* })
* ;
* }
* ```
*
* @param string $type
* @param array $args
* @param ActivityOptions|null $options
* @param Type|string|null|\ReflectionClass|\ReflectionType $returnType
* @return PromiseInterface<mixed>
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function executeActivity(
string $type,
array $args = [],
ActivityOptionsInterface $options = null,
Type|string|\ReflectionClass|\ReflectionType $returnType = null,
): PromiseInterface {
return self::getCurrentContext()->executeActivity($type, $args, $options, $returnType);
}
/**
* The method returns a proxy over the class containing the activity, which
* allows you to conveniently and beautifully call all methods within the
* passed class.
*
* ```php
* #[ActivityInterface]
* class ExampleActivityClass
* {
* public function firstActivity() { ... }
* public function secondActivity() { ... }
* public function thirdActivity() { ... }
* }
*
* // Execution
* #[WorkflowMethod]
* public function handler(string $existingWorkflowId)
* {
* $activities = Workflow::newActivityStub(ExampleActivityClass::class);
*
* // Activity methods execution
* yield $activities->firstActivity();
* yield $activities->secondActivity();
* }
* ```
*
* @psalm-template T of object
*
* @param class-string<T> $class
* @param ActivityOptionsInterface|null $options
*
* @return T
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function newActivityStub(
string $class,
ActivityOptionsInterface $options = null,
): object {
return self::getCurrentContext()->newActivityStub($class, $options);
}
/**
* The method creates and returns a proxy class with the specified settings
* that allows to call an activities with the passed options.
*
* ```php
* #[WorkflowMethod]
* public function handler(string $existingWorkflowId)
* {
* $options = ActivityOptions::new()
* ->withTaskQueue('custom-task-queue')
* ;
*
* $activities = Workflow::newUntypedActivityStub($options);
*
* // Executes an activity named "activity"
* $result = yield $activities->execute('activity');
* }
* ```
*
* @param ActivityOptionsInterface|null $options
*
* @return ActivityStubInterface
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function newUntypedActivityStub(
ActivityOptionsInterface $options = null,
): ActivityStubInterface {
return self::getCurrentContext()->newUntypedActivityStub($options);
}
/**
* Returns a complete trace of the last calls (for debugging).
*
* @return string
* @throws OutOfContextException in the absence of the workflow execution context.
*/
public static function getStackTrace(): string
{
return self::getCurrentContext()->getStackTrace();
}
/**
* Whether update and signal handlers have finished executing.
*
* Consider waiting on this condition before workflow return or continue-as-new, to prevent
* interruption of in-progress handlers by workflow exit:
*
* ```php
* yield Workflow.await(static fn() => Workflow::allHandlersFinished());
* ```
*
* @return bool True if all handlers have finished executing.
*/
public static function allHandlersFinished(): bool
{
/** @var ScopedContextInterface $context */
$context = self::getCurrentContext();
return $context->allHandlersFinished();
}
/**
* Upsert search attributes
*
* @param array<string, mixed> $searchAttributes
*/
public static function upsertSearchAttributes(array $searchAttributes): void
{
self::getCurrentContext()->upsertSearchAttributes($searchAttributes);
}
/**
* Generate a UUID.
*
* @return PromiseInterface<UuidInterface>
*/
public static function uuid(): PromiseInterface
{
/** @var ScopedContextInterface $context */
$context = self::getCurrentContext();
return $context->uuid();
}
/**
* Generate a UUID version 4 (random).
*
* @return PromiseInterface<UuidInterface>
*/
public static function uuid4(): PromiseInterface
{
/** @var ScopedContextInterface $context */
$context = self::getCurrentContext();
return $context->uuid4();
}
/**
* Generate a UUID version 7 (Unix Epoch time).
*
* @param DateTimeInterface|null $dateTime An optional date/time from which
* to create the version 7 UUID. If not provided, the UUID is generated
* using the current date/time.
*
* @return PromiseInterface<UuidInterface>
*/
public static function uuid7(?DateTimeInterface $dateTime = null): PromiseInterface
{
/** @var ScopedContextInterface $context */
$context = self::getCurrentContext();
return $context->uuid7($dateTime);
}
}