|
| 1 | +<?php |
| 2 | + |
| 3 | +use Sentry\State\Scope; |
| 4 | +use Sentry\State\HubInterface; |
| 5 | + |
| 6 | +/** |
| 7 | + * Sentry for WordPress Action Scheduler Integration |
| 8 | + * |
| 9 | + * @see https://wordpress.org/plugins/action-scheduler/ |
| 10 | + * |
| 11 | + * @internal This class is not part of the public API and may be removed or changed at any time. |
| 12 | + */ |
| 13 | +final class WP_Sentry_Action_Scheduler_Integration { |
| 14 | + /** |
| 15 | + * Holds the class instance. |
| 16 | + * |
| 17 | + * @var WP_Sentry_Action_Scheduler_Integration |
| 18 | + */ |
| 19 | + private static $instance; |
| 20 | + |
| 21 | + /** |
| 22 | + * Get the Sentry Action Scheduler Integration instance. |
| 23 | + * |
| 24 | + * @return WP_Sentry_Action_Scheduler_Integration |
| 25 | + */ |
| 26 | + public static function get_instance(): WP_Sentry_Action_Scheduler_Integration { |
| 27 | + return self::$instance ?: self::$instance = new self; |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * Class constructor. |
| 32 | + */ |
| 33 | + protected function __construct() { |
| 34 | + add_action( 'action_scheduler_failed_execution', [ $this, 'handle_action_scheduler_failure' ], 10, 3 ); |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Capture and send Action Scheduler failures to Sentry. |
| 39 | + * |
| 40 | + * @param int $action_id The action ID that failed. |
| 41 | + * @param \Throwable $e The exception that was thrown. |
| 42 | + * @param string $context The context in which the exception was thrown. |
| 43 | + * |
| 44 | + * @return void |
| 45 | + */ |
| 46 | + public function handle_action_scheduler_failure( $action_id, $e, $context ): void { |
| 47 | + // This should never happen, but let's be safe. |
| 48 | + if ( ! $e instanceof Throwable ) { |
| 49 | + return; |
| 50 | + } |
| 51 | + |
| 52 | + wp_sentry_safe( |
| 53 | + function ( HubInterface $client ) use ( $action_id, $e, $context ) { |
| 54 | + $client->withScope( function ( Scope $scope ) use ( $client, $action_id, $e, $context ) { |
| 55 | + $scope->setContext( |
| 56 | + 'action_scheduler', |
| 57 | + [ |
| 58 | + 'action_id' => (string) $action_id, |
| 59 | + 'context' => (string) $context, |
| 60 | + ] |
| 61 | + ); |
| 62 | + |
| 63 | + $client->captureException( $e ); |
| 64 | + } ); |
| 65 | + } |
| 66 | + ); |
| 67 | + } |
| 68 | +} |
0 commit comments