$query * Query parameters. * * @return array * The decoded XRPC response. */ public function get(string $method, array $query = [], ?XrpcOptions $options = NULL): array { return $this->request('GET', $method, $query, $options)->data; } /** * Sends a POST XRPC request and returns decoded data. * * @param array $payload * Request payload. * * @return array * The decoded XRPC response. */ public function post(string $method, array $payload = [], ?XrpcOptions $options = NULL): array { return $this->request('POST', $method, $payload, $options)->data; } /** * Sends a POST XRPC procedure that declares no input body. * * @return array */ public function postWithoutBody(string $method, ?XrpcOptions $options = NULL): array { return $this->requestWithoutBody('POST', $method, [], $options)->data; } /** * Executes the request without body operation. * * @param array $query */ public function requestWithoutBody( string $httpMethod, string $method, array $query = [], ?XrpcOptions $options = NULL, ): XrpcResponse { [$serviceUrl, $response, $options] = $this->sendWithoutBody($httpMethod, $method, $query, $options); return $this->decodeResponse($method, $serviceUrl, $response, $options); } /** * Executes the request raw without body operation. * * @param array $query */ public function requestRawWithoutBody( string $httpMethod, string $method, array $query = [], ?XrpcOptions $options = NULL, ): RawXrpcResponse { [$serviceUrl, $response, $options] = $this->sendWithoutBody($httpMethod, $method, $query, $options); return $this->decodeRawResponse($method, $serviceUrl, $response, $options); } /** * Sends a request whose Lexicon does not declare an output encoding. * * @param array $query */ public function requestUnknownWithoutBody( string $httpMethod, string $method, array $query = [], ?XrpcOptions $options = NULL, ): XrpcResponse|RawXrpcResponse { [$serviceUrl, $response, $options] = $this->sendWithoutBody($httpMethod, $method, $query, $options); return $this->decodeUnknownResponse($method, $serviceUrl, $response, $options); } /** * Sends a POST XRPC request with a caller-provided raw body. * * @return array */ public function postRaw( string $method, string|StreamInterface $body, string $contentType = 'application/octet-stream', ?XrpcOptions $options = NULL, ): array { return $this->requestWithBody('POST', $method, $body, $contentType, [], $options)->data; } /** * Sends an XRPC request and returns decoded data with response metadata. * * @param array $data */ public function request( string $httpMethod, string $method, array $data = [], ?XrpcOptions $options = NULL, ): XrpcResponse { $options ??= new XrpcOptions(); $serviceUrl = $this->resolveServiceUrl($options); $request = $this->createRequest($httpMethod, $method, $serviceUrl, $data, $options); try { $response = $this->sendRequest($request); } catch (ClientExceptionInterface $e) { throw new XrpcException( \sprintf('XRPC request %s failed: %s', $method, $e->getMessage()), $method, $serviceUrl, $e, ); } return $this->decodeResponse($method, $serviceUrl, $response, $options); } /** * Sends an XRPC request with a caller-provided raw body. * * @param array $query * Query parameters. */ public function requestWithBody( string $httpMethod, string $method, string|StreamInterface $body, string $contentType = 'application/octet-stream', array $query = [], ?XrpcOptions $options = NULL, ): XrpcResponse { $options ??= new XrpcOptions(); $serviceUrl = $this->resolveServiceUrl($options); $request = $this->createBodyRequest($httpMethod, $method, $serviceUrl, $query, $body, $contentType, $options); try { $response = $this->sendRequest($request); } catch (ClientExceptionInterface $e) { throw new XrpcException( \sprintf('XRPC request %s failed: %s', $method, $e->getMessage()), $method, $serviceUrl, $e, ); } return $this->decodeResponse($method, $serviceUrl, $response, $options); } /** * Sends an XRPC request and returns the raw response body. * * @param array $data */ public function requestRaw( string $httpMethod, string $method, array $data = [], ?XrpcOptions $options = NULL, ): RawXrpcResponse { $options ??= new XrpcOptions(); $serviceUrl = $this->resolveServiceUrl($options); $request = $this->createRequest($httpMethod, $method, $serviceUrl, $data, $options); try { $response = $this->sendRequest($request); } catch (ClientExceptionInterface $e) { throw new XrpcException( \sprintf('XRPC request %s failed: %s', $method, $e->getMessage()), $method, $serviceUrl, $e, ); } $body = $this->readBoundedBody($method, $serviceUrl, $response, $options->maxResponseBytes); if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) { throw $this->httpException($method, $serviceUrl, $response, $body); } return new RawXrpcResponse($body, $response->getStatusCode(), $this->responseHeaders($response)); } /** * Sends an XRPC request with a raw body and returns the raw response body. * * @param array $query * Query parameters. */ public function requestRawWithBody( string $httpMethod, string $method, string|StreamInterface $body, string $contentType = 'application/octet-stream', array $query = [], ?XrpcOptions $options = NULL, ): RawXrpcResponse { $options ??= new XrpcOptions(); $serviceUrl = $this->resolveServiceUrl($options); $request = $this->createBodyRequest($httpMethod, $method, $serviceUrl, $query, $body, $contentType, $options); try { $response = $this->sendRequest($request); } catch (ClientExceptionInterface $e) { throw new XrpcException( \sprintf('XRPC request %s failed: %s', $method, $e->getMessage()), $method, $serviceUrl, $e, ); } return $this->decodeRawResponse($method, $serviceUrl, $response, $options); } /** * Sends a body for a method whose Lexicon does not declare output. * * @param array $query */ public function requestUnknownWithBody( string $httpMethod, string $method, string|StreamInterface $body, string $contentType = 'application/octet-stream', array $query = [], ?XrpcOptions $options = NULL, ): XrpcResponse|RawXrpcResponse { $options ??= new XrpcOptions(); $serviceUrl = $this->resolveServiceUrl($options); $request = $this->createBodyRequest($httpMethod, $method, $serviceUrl, $query, $body, $contentType, $options); try { $response = $this->sendRequest($request); } catch (ClientExceptionInterface $e) { throw new XrpcException( \sprintf('XRPC request %s failed: %s', $method, $e->getMessage()), $method, $serviceUrl, $e, ); } return $this->decodeUnknownResponse($method, $serviceUrl, $response, $options); } private function decodeUnknownResponse( string $method, string $serviceUrl, ResponseInterface $response, XrpcOptions $options, ): XrpcResponse|RawXrpcResponse { $body = $this->readBoundedBody($method, $serviceUrl, $response, $options->maxResponseBytes); if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) { throw $this->httpException($method, $serviceUrl, $response, $body); } $headers = $this->responseHeaders($response); if ($body === '') { return new XrpcResponse([], $response->getStatusCode(), $headers, FALSE); } if (self::responseContentType($response) !== 'application/json') { return new RawXrpcResponse($body, $response->getStatusCode(), $headers); } try { $decoded = \json_decode( $body, FALSE, \max(1, \min(512, $options->maxJsonDepth)), JSON_THROW_ON_ERROR, ); } catch (\JsonException $e) { throw new XrpcDecodeException($method, $serviceUrl, $response->getStatusCode(), $body, $e); } if (!$decoded instanceof \stdClass) { return new RawXrpcResponse($body, $response->getStatusCode(), $headers); } return new XrpcResponse(self::normalizeDecodedObject($decoded), $response->getStatusCode(), $headers); } private function decodeRawResponse( string $method, string $serviceUrl, ResponseInterface $response, XrpcOptions $options, ): RawXrpcResponse { $body = $this->readBoundedBody($method, $serviceUrl, $response, $options->maxResponseBytes); if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) { throw $this->httpException($method, $serviceUrl, $response, $body); } return new RawXrpcResponse($body, $response->getStatusCode(), $this->responseHeaders($response)); } /** * @param array $query * @return array{string, \Psr\Http\Message\ResponseInterface, \Wotnak\Atproto\Client\XrpcOptions} */ private function sendWithoutBody( string $httpMethod, string $method, array $query, ?XrpcOptions $options, ): array { $options ??= new XrpcOptions(); $serviceUrl = $this->resolveServiceUrl($options); $request = $this->requestFactory ->createRequest(\strtoupper($httpMethod), $this->buildUrl($method, $serviceUrl, $query)) ->withHeader('Accept', 'application/json'); foreach ($options->headers as $name => $value) { $request = $request->withHeader($name, $value); } try { $response = $this->sendRequest($request); } catch (ClientExceptionInterface $e) { throw new XrpcException( \sprintf('XRPC request %s failed: %s', $method, $e->getMessage()), $method, $serviceUrl, $e, ); } return [$serviceUrl, $response, $options]; } /** * Returns the default service url. */ public function getDefaultServiceUrl(): ?string { return $this->defaultServiceUrl !== NULL ? \rtrim($this->defaultServiceUrl, '/') : NULL; } /** * @param array $data */ private function createRequest( string $httpMethod, string $method, string $serviceUrl, array $data, XrpcOptions $options, ): RequestInterface { $httpMethod = \strtoupper($httpMethod); $request = $this->requestFactory ->createRequest($httpMethod, $this->buildUrl($method, $serviceUrl, $httpMethod === 'GET' ? $data : [])) ->withHeader('Accept', 'application/json'); foreach ($options->headers as $name => $value) { $request = $request->withHeader($name, $value); } if ($httpMethod !== 'GET') { $request = $request ->withHeader('Content-Type', 'application/json') ->withBody($this->streamFactory->createStream(\json_encode((object) $data, JSON_THROW_ON_ERROR))); } return $request; } /** * @param array $query * Query parameters. */ private function createBodyRequest( string $httpMethod, string $method, string $serviceUrl, array $query, string|StreamInterface $body, string $contentType, XrpcOptions $options, ): RequestInterface { $httpMethod = \strtoupper($httpMethod); if ($httpMethod === 'GET') { throw new \InvalidArgumentException('GET XRPC requests cannot include a raw body.'); } $request = $this->requestFactory ->createRequest($httpMethod, $this->buildUrl($method, $serviceUrl, $query)) ->withHeader('Accept', 'application/json'); foreach ($options->headers as $name => $value) { $request = $request->withHeader($name, $value); } return $request ->withHeader('Content-Type', $contentType) ->withBody(\is_string($body) ? $this->streamFactory->createStream($body) : $body); } private function decodeResponse( string $method, string $serviceUrl, ResponseInterface $response, XrpcOptions $options, ): XrpcResponse { $body = $this->readBoundedBody($method, $serviceUrl, $response, $options->maxResponseBytes); if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) { throw $this->httpException($method, $serviceUrl, $response, $body); } if ($body === '') { return new XrpcResponse([], $response->getStatusCode(), $this->responseHeaders($response), FALSE); } $contentType = self::responseContentType($response); if ($contentType !== NULL && $contentType !== 'application/json') { throw new XrpcProtocolException( \sprintf('XRPC %s returned Content-Type "%s", expected "application/json".', $method, $contentType), $method, $serviceUrl, $response->getStatusCode(), $body, ); } try { $decoded = \json_decode( $body, FALSE, \max(1, \min(512, $options->maxJsonDepth)), JSON_THROW_ON_ERROR, ); } catch (\JsonException $e) { throw new XrpcDecodeException($method, $serviceUrl, $response->getStatusCode(), $body, $e); } if (!$decoded instanceof \stdClass) { throw new XrpcResponseException($method, $serviceUrl, $response->getStatusCode(), $decoded); } return new XrpcResponse( self::normalizeDecodedObject($decoded), $response->getStatusCode(), $this->responseHeaders($response), ); } /** * Keeps JSON arrays and empty objects distinct while retaining associative * arrays for ordinary object-shaped response data. * * @return array */ private static function normalizeDecodedObject(\stdClass $value): array { // JSON object member names are strings even though PHP exposes object vars // with the wider array-key type. // @mago-expect analysis:less-specific-return-statement return \array_map(self::normalizeDecodedValue(...), \get_object_vars($value)); } private static function normalizeDecodedValue(mixed $value): mixed { if ($value instanceof \stdClass) { $properties = self::normalizeDecodedObject($value); return $properties === [] ? (object) $properties : $properties; } if (\is_array($value)) { return \array_map(self::normalizeDecodedValue(...), $value); } return $value; } /** * Reads a response without allowing an unbounded body allocation. */ private static function readBoundedBody( string $method, string $serviceUrl, ResponseInterface $response, int $maxBytes, ): string { $maxBytes = \max(1, $maxBytes); try { return BoundedResponseBody::read($response, $maxBytes); } catch (\LengthException) { throw new XrpcException( \sprintf('XRPC response for %s exceeds the %d-byte limit.', $method, $maxBytes), $method, $serviceUrl, ); } } private function httpException( string $method, string $serviceUrl, ResponseInterface $response, string $body, ): XrpcHttpException { $decoded = self::decodeErrorBody($body); return new XrpcHttpException( $method, $serviceUrl, $response->getStatusCode(), $body, $decoded, \is_string($decoded['error'] ?? NULL) ? $decoded['error'] : NULL, \is_string($decoded['message'] ?? NULL) ? $decoded['message'] : NULL, $this->responseHeaders($response), ); } /** * @return array|null */ private static function decodeErrorBody(string $body): ?array { if ($body === '') { return NULL; } try { $decoded = \json_decode($body, TRUE, flags: JSON_THROW_ON_ERROR); } catch (\JsonException) { return NULL; } if (!\is_array($decoded)) { return NULL; } /** @var array $decoded */ return $decoded; } private static function responseContentType(ResponseInterface $response): ?string { $contentType = \trim($response->getHeaderLine('Content-Type')); return $contentType !== '' ? \strtolower(\trim(\explode(';', $contentType, 2)[0])) : NULL; } /** * @return array> */ private static function responseHeaders(ResponseInterface $response): array { // This assignment refines PSR-7's arrays to the lists guaranteed here. // @mago-expect lint:inline-variable-return /** @var array> $headers */ $headers = $response->getHeaders(); return $headers; } /** * @param array $query * Query parameters. */ private function buildUrl(string $method, string $serviceUrl, array $query = []): string { $method = $this->nsidParser->normalize($method); $url = $serviceUrl . '/xrpc/' . $method; if ($query !== []) { $queryString = $this->buildQueryString($query); if ($queryString !== '') { $url .= '?' . $queryString; } } return $url; } /** * @param array $query * Query parameters. */ private function buildQueryString(array $query): string { $pairs = []; foreach ($query as $name => $value) { if ($value === NULL) { continue; } if (\is_array($value)) { foreach ($value as $item) { if ($item === NULL) { continue; } $pairs[] = \rawurlencode($name) . '=' . \rawurlencode($this->encodeQueryValue($item)); } continue; } $pairs[] = \rawurlencode($name) . '=' . \rawurlencode($this->encodeQueryValue($value)); } return \implode('&', $pairs); } private static function encodeQueryValue(mixed $value): string { if (\is_bool($value)) { return $value ? 'true' : 'false'; } if (\is_scalar($value) || $value instanceof \Stringable) { return (string) $value; } throw new \InvalidArgumentException('XRPC query parameters must be scalar values or scalar arrays.'); } private function resolveServiceUrl(XrpcOptions $options): string { $serviceUrl = \rtrim((string) ($options->serviceUrl ?? $this->defaultServiceUrl), '/'); if ($serviceUrl === '') { throw new \InvalidArgumentException('An AT Protocol service URL is required.'); } $this->urlPolicy->assertAllowedServiceUrl($serviceUrl); $this->assertServiceOrigin($serviceUrl); return $serviceUrl; } private static function assertServiceOrigin(string $url): void { try { $parts = \parse_url($url); } // ValueError is an expected invalid-input result at this API boundary. // @mago-expect analysis:avoid-catching-error catch (\ValueError) { $parts = FALSE; } if ( !\is_array($parts) || isset($parts['user']) || isset($parts['pass']) || isset($parts['path']) || isset($parts['query']) || isset($parts['fragment']) ) { throw new \InvalidArgumentException( 'An AT Protocol service URL must be an origin without a path, query, or fragment.', ); } } private function sendRequest(RequestInterface $request): ResponseInterface { return $this->requestSender->send($request); } }