| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Metricool\Support\Helpers; |
| 6 |
|
| 7 |
/** |
| 8 |
* Event class to handle Metricool events. Useful for dispatching events and |
| 9 |
* catching them in different parts of the application based on the constants. |
| 10 |
* @see \Metricool\Features\TaskManagement\TaskManagementListener |
| 11 |
* @internal This could be an ENUM when supported. |
| 12 |
*/ |
| 13 |
class Event |
| 14 |
{ |
| 15 |
/** |
| 16 |
* Event names |
| 17 |
*/ |
| 18 |
/** @var string Event triggered when connections are loaded from Metricool API */ |
| 19 |
public const CONNECTED_SOCIAL_NETWORKS_DATA_LOADED = 'connected_social_networks_data_loaded'; |
| 20 |
/** @var string Event triggered when the user data is updated from Metricool API */ |
| 21 |
public const METRICOOL_USER_UPDATED = 'metricool_user_updated'; |
| 22 |
/** @var string Event triggered when the user scheduled a post through the plugin */ |
| 23 |
public const POST_SCHEDULED = 'post_scheduled'; |
| 24 |
|
| 25 |
/** |
| 26 |
* Execute a WordPress event based on our constants. |
| 27 |
*/ |
| 28 |
public static function dispatch(string $event, array $arguments = []): void |
| 29 |
{ |
| 30 |
self::validate($event); |
| 31 |
do_action('metricool_event_' . $event, $arguments); |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* Check if the given event matches the specified event. |
| 36 |
*/ |
| 37 |
public static function matches(string $event, string $eventToCheck): bool |
| 38 |
{ |
| 39 |
self::validate($event); |
| 40 |
self::validate($eventToCheck); |
| 41 |
|
| 42 |
return $event === $eventToCheck; |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* Validate a given event name based on our constants. |
| 47 |
* @throws \InvalidArgumentException |
| 48 |
*/ |
| 49 |
private static function validate(string $event): void |
| 50 |
{ |
| 51 |
if (!defined('self::' . strtoupper($event))) { |
| 52 |
throw new \InvalidArgumentException(sprintf('Invalid event name: %s', esc_html($event))); |
| 53 |
} |
| 54 |
} |
| 55 |
} |
| 56 |
|