Cli
1 year ago
Exporters
1 year ago
Importers
11 months ago
ResourceStorages
1 year ago
ResultFormatters
1 year ago
Schemas
1 year ago
Steps
1 year ago
docs
1 year ago
BuiltInExporters.php
1 year ago
BuiltInStepProcessors.php
1 year ago
ClassExtractor.php
1 year ago
Cli.php
1 year ago
ExportSchema.php
1 year ago
ImportSchema.php
1 year ago
ImportStep.php
1 year ago
Logger.php
1 year ago
ResourceStorages.php
1 year ago
StepProcessor.php
1 year ago
StepProcessorResult.php
1 year ago
UsePluginHelpers.php
1 year ago
UsePubSub.php
1 year ago
UseWPFunctions.php
1 year ago
Util.php
1 year ago
UsePubSub.php
68 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Automattic\WooCommerce\Blueprint; |
| 4 | |
| 5 | trait UsePubSub { |
| 6 | |
| 7 | /** |
| 8 | * Subscribers. |
| 9 | * |
| 10 | * @var array |
| 11 | */ |
| 12 | private array $subscribers = array(); |
| 13 | |
| 14 | /** |
| 15 | * Subscribe to an event with a callback. |
| 16 | * |
| 17 | * @param string $event The event name. |
| 18 | * @param callable $callback The callback to execute when the event is published. |
| 19 | * @return void |
| 20 | */ |
| 21 | public function subscribe( string $event, callable $callback ): void { |
| 22 | if ( ! isset( $this->subscribers[ $event ] ) ) { |
| 23 | $this->subscribers[ $event ] = array(); |
| 24 | } |
| 25 | |
| 26 | $this->subscribers[ $event ][] = $callback; |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * Publish an event to all subscribers. |
| 31 | * |
| 32 | * @param string $event The event name. |
| 33 | * @param mixed ...$args Arguments to pass to the callbacks. |
| 34 | * @return void |
| 35 | */ |
| 36 | public function publish( string $event, ...$args ): void { |
| 37 | if ( ! isset( $this->subscribers[ $event ] ) ) { |
| 38 | return; |
| 39 | } |
| 40 | |
| 41 | foreach ( $this->subscribers[ $event ] as $callback ) { |
| 42 | call_user_func( $callback, ...$args ); |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | /** |
| 47 | * Unsubscribe a specific callback from an event. |
| 48 | * |
| 49 | * @param string $event The event name. |
| 50 | * @param callable $callback The callback to remove. |
| 51 | * @return void |
| 52 | */ |
| 53 | public function unsubscribe( string $event, callable $callback ): void { |
| 54 | if ( ! isset( $this->subscribers[ $event ] ) ) { |
| 55 | return; |
| 56 | } |
| 57 | |
| 58 | $this->subscribers[ $event ] = array_filter( |
| 59 | $this->subscribers[ $event ], |
| 60 | fn( $subscriber ) => $subscriber !== $callback |
| 61 | ); |
| 62 | |
| 63 | if ( empty( $this->subscribers[ $event ] ) ) { |
| 64 | unset( $this->subscribers[ $event ] ); |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 |