wordpress-seo
/
src
/
myyoast-client
/
application
/
exceptions
/
token-request-failed-exception.php
token-request-failed-exception.php in Yoast SEO – Advanced SEO with real-time guidance and built-in AI 28.2, at src/myyoast-client/application/exceptions/token-request-failed-exception.php
| 1 | <?php |
| 2 | // phpcs:disable Yoast.NamingConventions.NamespaceName.TooLong -- Needed in the folder structure. |
| 3 | |
| 4 | namespace Yoast\WP\SEO\MyYoast_Client\Application\Exceptions; |
| 5 | |
| 6 | use RuntimeException; |
| 7 | use Throwable; |
| 8 | |
| 9 | /** |
| 10 | * Exception thrown when a token endpoint request fails. |
| 11 | * |
| 12 | * Wraps OAuth error codes like `invalid_grant`, `invalid_client`, |
| 13 | * `invalid_dpop_proof`, etc. |
| 14 | */ |
| 15 | class Token_Request_Failed_Exception extends RuntimeException { |
| 16 | |
| 17 | /** |
| 18 | * The OAuth error code from the token endpoint response. |
| 19 | * |
| 20 | * @var string |
| 21 | */ |
| 22 | private $error_code; |
| 23 | |
| 24 | /** |
| 25 | * Token_Request_Failed_Exception constructor. |
| 26 | * |
| 27 | * @param string $error_code The OAuth error code. |
| 28 | * @param string $error_description A human-readable description. |
| 29 | * @param int $code The HTTP status code. |
| 30 | * @param Throwable|null $previous The previous exception. |
| 31 | */ |
| 32 | public function __construct( string $error_code, string $error_description = '', int $code = 0, ?Throwable $previous = null ) { |
| 33 | $this->error_code = $error_code; |
| 34 | |
| 35 | $message = $error_code; |
| 36 | if ( $error_description !== '' ) { |
| 37 | $message .= ': ' . $error_description; |
| 38 | } |
| 39 | |
| 40 | parent::__construct( $message, $code, $previous ); |
| 41 | } |
| 42 | |
| 43 | /** |
| 44 | * Returns the OAuth error code. |
| 45 | * |
| 46 | * @return string |
| 47 | */ |
| 48 | public function get_error_code(): string { |
| 49 | return $this->error_code; |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Creates an exception from a token endpoint response body. |
| 54 | * |
| 55 | * @param array<string, string> $response_body The parsed JSON response. |
| 56 | * @param int $status_code The HTTP status code. |
| 57 | * |
| 58 | * @return self |
| 59 | */ |
| 60 | public static function from_response( array $response_body, int $status_code = 0 ): self { |
| 61 | return new self( |
| 62 | ( $response_body['error'] ?? 'unknown_error' ), |
| 63 | ( $response_body['error_description'] ?? '' ), |
| 64 | $status_code, |
| 65 | ); |
| 66 | } |
| 67 | } |
| 68 |