get( 'shared/dropdown/shipment-services' ); } catch ( AbsError $e ) { return self::from_error( $e ); } try { $client->get( 'webhooks/me', array( 'page' => 1, 'limit' => 1, ) ); } catch ( AbsError $e ) { if ( in_array( $e->type(), array( AbsError::FORBIDDEN, AbsError::VALIDATION, AbsError::NOT_FOUND ), true ) ) { return self::state( self::UNBOUND, __( 'ABS accepted the key, but it is not linked to a sub-account or is missing permissions. In your ABS portal, create an API key bound to your sub-account with the permissions listed below.', 'abs-courier' ) ); } return self::from_error( $e ); } return self::state( self::CONNECTED, __( 'Connected to ABS Courier.', 'abs-courier' ) ); } /** * Last recorded state. * * @return array{status:string, message:string, checked_at:int} */ public static function state_saved() { $saved = get_option( self::OPTION, array() ); return array_merge( self::state( self::NOT_CONNECTED, '', 0 ), is_array( $saved ) ? $saved : array() ); } /** * Records a state. * * @param array $state Output of check(). * @return void */ public static function record( array $state ) { update_option( self::OPTION, $state, false ); } /** * Clears the recorded state. * * @return void */ public static function forget() { delete_option( self::OPTION ); } /** * Builds a state array. * * @param string $status Status constant. * @param string $message Message for the merchant. * @param int|null $checked_at Unix time, default now. * @return array{status:string, message:string, checked_at:int} */ private static function state( $status, $message, $checked_at = null ) { return array( 'status' => $status, 'message' => $message, 'checked_at' => null === $checked_at ? time() : (int) $checked_at, ); } /** * Maps a failed check to a state with a plain-language message. * * @param AbsError $e Error. * @return array{status:string, message:string, checked_at:int} */ private static function from_error( AbsError $e ) { Logger::error( 'Connection check failed', array( 'type' => $e->type(), 'status' => $e->status(), ) ); switch ( $e->type() ) { case AbsError::AUTH: return self::state( self::INVALID, __( 'ABS Courier rejected this API key. Check that you copied the whole key and that it has not been revoked or expired.', 'abs-courier' ) ); case AbsError::CONFIG: return self::state( self::ERROR, $e->getMessage() ); case AbsError::RETRYABLE: case AbsError::UNKNOWN_OUTCOME: return self::state( self::ERROR, __( 'ABS Courier could not be reached right now. Try again in a few minutes.', 'abs-courier' ) ); default: /* translators: %s: error message from ABS Courier. */ return self::state( self::ERROR, sprintf( __( 'ABS Courier returned an error: %s', 'abs-courier' ), $e->getMessage() ) ); } } }