cache_key() ); if ( is_string( $cached ) && '' !== $cached ) { return $this->ok( $cached ); } return $this->mint(); } /** * Throws the cached token away. * * Called when the platform refuses one: a token the workspace no longer * accepts is worse than no token, because every retry reuses it. */ public function forget(): void { delete_transient( $this->cache_key() ); delete_transient( self::TRANSIENT ); } /** * Mints a fresh bearer, replacing anything cached. * * @return array{ok:bool, token:string, code:string, message:string} */ public function mint(): array { $result = ( new Client( $this->connection ) )->mint_bearer(); if ( ! $result['ok'] ) { return array( 'ok' => false, 'token' => '', 'code' => (string) $result['code'], 'message' => (string) $result['message'], ); } $token = is_array( $result['data'] ) ? (string) ( $result['data']['token'] ?? '' ) : ''; if ( '' === $token ) { return array( 'ok' => false, 'token' => '', 'code' => 'NO_TOKEN', 'message' => __( 'Sharely returned no token.', 'sharelyai' ), ); } set_transient( $this->cache_key(), $token, self::TTL ); return $this->ok( $token ); } /** * A successful result. * * @param string $token The bearer. * * @return array{ok:bool, token:string, code:string, message:string} */ private function ok( string $token ): array { return array( 'ok' => true, 'token' => $token, 'code' => '', 'message' => '', ); } /** * The cache key for the workspace this connection points at. */ private function cache_key(): string { return self::TRANSIENT . '_' . md5( $this->connection->workspace_id() ); } }