'hello'])]); $response = self::client($sender, self::queryDefinition()) ->call( 'io.example.testQuery', ['limit' => 10], ); static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(200, $response->statusCode); static::assertSame(['value' => 'hello'], $response->data); static::assertTrue($response->hasBody); } public function testReturnsParsedJsonBodyForProcedure(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['id' => 'abc123'])]); $response = self::client($sender, self::procedureDefinition()) ->call( 'io.example.testProcedure', input: ['text' => 'hello world'], ); static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['id' => 'abc123'], $response->data); } public function testReturnsBinaryBodyForQuery(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/octet-stream'], "\x01\x02\x03\x04"), ]); $response = self::client($sender, self::binaryQueryDefinition())->call('io.example.testBinaryQuery'); static::assertInstanceOf(RawXrpcResponse::class, $response); static::assertSame("\x01\x02\x03\x04", $response->body); } public function testReturnsBinaryBodyForProcedure(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/octet-stream'], "\x0A\x14\x1E"), ]); $response = self::client($sender, self::binaryProcedureDefinition()) ->call( 'io.example.testBinaryProcedure', input: "\x63", ); static::assertInstanceOf(RawXrpcResponse::class, $response); static::assertSame("\x0A\x14\x1E", $response->body); static::assertSame('image/png', $sender->lastRequest?->getHeaderLine('Content-Type')); } public function testReturnsNoBodyForNoOutputQuery(): void { $sender = new TestXrpcRequestSender([new Response(200)]); $response = self::client($sender, self::noOutputQueryDefinition())->call('io.example.testNoOutputQuery'); static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(200, $response->statusCode); static::assertFalse($response->hasBody); } public function testPassesQueryParamsAsUrlSearchParams(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 'ok'])]); self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 25]); static::assertSame( 'https://service.example/xrpc/io.example.testQuery?limit=25', (string) $sender->lastRequest?->getUri(), ); } public function testSendsPostWithJsonBodyForProcedure(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['id' => 'new-id'])]); self::client($sender, self::procedureDefinition()) ->call( 'io.example.testProcedure', input: ['text' => 'test content'], ); static::assertSame('POST', $sender->lastRequest?->getMethod()); static::assertSame('application/json', $sender->lastRequest?->getHeaderLine('Content-Type')); static::assertSame('{"text":"test content"}', (string) $sender->lastRequest?->getBody()); } public function testForwardsCustomHeaders(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 'ok'])]); self::client($sender, self::queryDefinition()) ->call( 'io.example.testQuery', ['limit' => 1], options: new XrpcOptions(headers: ['Authorization' => 'Bearer token123']), ); static::assertSame('Bearer token123', $sender->lastRequest?->getHeaderLine('Authorization')); } public function testAcceptsOptionalParamsAsOmitted(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 'ok'])]); $response = self::client($sender, self::queryDefinition())->call('io.example.testQuery'); static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['value' => 'ok'], $response->data); static::assertSame('', $sender->lastRequest?->getUri()->getQuery()); } public function testIgnoresSchemaOutputForNoOutputQuery(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['unexpected' => 'data'])]); $response = self::client($sender, self::noOutputQueryDefinition())->call('io.example.testNoOutputQuery'); static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['unexpected' => 'data'], $response->data); } public function testAppliesAllCallerProvidedHeaders(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 'ok'])]); self::client($sender, self::queryDefinition()) ->call( 'io.example.testQuery', options: new XrpcOptions(headers: [ 'Atproto-Proxy' => 'did:plc:foo#bar', 'Atproto-Accept-Labelers' => 'did:plc:labeler1#a,did:plc:labeler2#b', 'X-Custom-Header' => 'custom-value', ]), ); static::assertSame('custom-value', $sender->lastRequest?->getHeaderLine('X-Custom-Header')); static::assertSame('did:plc:foo#bar', $sender->lastRequest?->getHeaderLine('Atproto-Proxy')); static::assertSame( 'did:plc:labeler1#a,did:plc:labeler2#b', $sender->lastRequest?->getHeaderLine('Atproto-Accept-Labelers'), ); } public function testWrapsFetchHandlerTypeError(): void { $sender = new FailingXrpcRequestSender(new ConnectException('fetch failed', new Request('GET', '/'))); try { self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); static::fail('Expected the transport exception.'); } catch (XrpcException $exception) { static::assertSame('fetch failed', $exception->getPrevious()?->getMessage()); static::assertStringContainsString('fetch failed', $exception->getMessage()); } } public function testWrapsRejectedFetchPromise(): void { $sender = new FailingXrpcRequestSender(new ConnectException('network timeout', new Request('GET', '/'))); try { self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); static::fail('Expected the transport exception.'); } catch (XrpcException $exception) { static::assertSame('network timeout', $exception->getPrevious()?->getMessage()); static::assertStringContainsString('network timeout', $exception->getMessage()); } } public function testThrowsFor400WithValidErrorPayload(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['error' => 'TestError', 'message' => 'bad request'], 400), ]); try { self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); static::fail('Expected an XRPC error.'); } catch (XrpcHttpException $exception) { static::assertSame(400, $exception->statusCode); static::assertSame('TestError', $exception->xrpcError); static::assertSame('bad request', $exception->xrpcMessage); } } public function testThrowsFor401AuthenticationError(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['error' => 'AuthenticationRequired', 'message' => 'Token expired'], 401), ]); try { self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); static::fail('Expected an authentication error.'); } catch (XrpcHttpException $exception) { static::assertSame(401, $exception->statusCode); static::assertSame('AuthenticationRequired', $exception->xrpcError); static::assertSame('Token expired', $exception->xrpcMessage); } } public function testThrowsForNonXrpcErrorResponse(): void { $sender = new TestXrpcRequestSender([ new Response(404, ['Content-Type' => 'text/plain'], 'Not Found'), ]); try { self::client($sender, self::queryDefinition())->call('io.example.testQuery'); static::fail('Expected an HTTP error.'); } catch (XrpcHttpException $exception) { static::assertSame(404, $exception->statusCode); static::assertNull($exception->xrpcError); static::assertSame('Not Found', $exception->responseBody); } } public function testThrowsFor500WithoutValidErrorPayload(): void { $sender = new TestXrpcRequestSender([ new Response(500, ['Content-Type' => 'text/html'], 'Internal Server Error'), ]); try { self::client($sender, self::queryDefinition())->call('io.example.testQuery'); static::fail('Expected an HTTP error.'); } catch (XrpcHttpException $exception) { static::assertSame(500, $exception->statusCode); static::assertNull($exception->decodedBody); static::assertSame('Internal Server Error', $exception->responseBody); } } public function testReflectsUpstream5xxWithValidXrpcPayload(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['error' => 'ServerError', 'message' => 'Something went wrong'], 502), ]); try { self::client($sender, self::queryDefinition())->call('io.example.testQuery'); static::fail('Expected an HTTP error.'); } catch (XrpcHttpException $exception) { static::assertSame(502, $exception->statusCode); static::assertSame('ServerError', $exception->xrpcError); static::assertSame('Something went wrong', $exception->xrpcMessage); } } public function testRejectsResponseBodyThatFailsSchemaValidation(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 123])]); try { self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); static::fail('Expected response validation to fail.'); } catch (LexiconValidationException $exception) { static::assertSame('output', $exception->phase); } } public function testRejectsWrongResponseContentTypeBeforeParsing(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'text/plain'], 'binary data'), ]); $this->expectException(XrpcProtocolException::class); $this->expectExceptionMessage('Content-Type'); self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); } public function testRejectsCallerProvidedContentTypeHeader(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 'ok'])]); $this->expectException(\InvalidArgumentException::class); self::client($sender, self::queryDefinition()) ->call( 'io.example.testQuery', ['limit' => 10], options: new XrpcOptions(headers: ['Content-Type' => 'application/json']), ); } public function testUnparseableJsonErrorResponseRemainsAnHttpException(): void { $sender = new TestXrpcRequestSender([ new Response(400, ['Content-Type' => 'application/json'], 'not valid json'), ]); $this->expectException(XrpcHttpException::class); self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); } public function testRejectsUnparseableJsonSuccessResponse(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/json'], 'not valid json'), ]); $this->expectException(XrpcDecodeException::class); self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); } public function testRejectsEmptyResponseWhenSchemaExpectsPayload(): void { $sender = new TestXrpcRequestSender([new Response(200)]); try { self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); static::fail('Expected empty output validation to fail.'); } catch (LexiconValidationException $exception) { static::assertSame('output', $exception->phase); } } public function testParsesContentTypeWithCharsetParameter(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/json; charset=utf-8'], '{"value":"hello"}'), ]); $response = self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['value' => 'hello'], $response->data); } public function testHandlesNoContentTypeAndEmptyBodyAsNoPayload(): void { $sender = new TestXrpcRequestSender([new Response(200, [], '')]); $response = self::client($sender, self::noOutputQueryDefinition())->call('io.example.testNoOutputQuery'); static::assertSame(200, $response->statusCode); } public function testTreatsNoContentTypeNonemptyBinaryResponseAsBinary(): void { $sender = new TestXrpcRequestSender([new Response(200, [], "\x01\x02\x03")]); $response = self::client($sender, self::binaryQueryDefinition())->call('io.example.testBinaryQuery'); static::assertInstanceOf(RawXrpcResponse::class, $response); static::assertSame("\x01\x02\x03", $response->body); } public function testRejects3xxStatusCode(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 'redirect'], 302)]); try { self::client($sender, self::queryDefinition())->call('io.example.testQuery'); static::fail('Expected a redirect response error.'); } catch (XrpcHttpException $exception) { static::assertSame(302, $exception->statusCode); } } public function testRejectsInvalidQueryParamsWhenValidationIsEnabled(): void { $sender = new TestXrpcRequestSender([]); try { self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 'not-a-number']); static::fail('Expected parameter validation to fail.'); } catch (LexiconValidationException $exception) { static::assertSame('parameters', $exception->phase); static::assertSame(0, $sender->requestCount); } } public function testRejectsInvalidProcedureBodyWhenValidationIsEnabled(): void { $sender = new TestXrpcRequestSender([]); try { self::client($sender, self::procedureDefinition()) ->call( 'io.example.testProcedure', input: ['text' => 123], options: new XrpcOptions(validateRequest: TRUE), ); static::fail('Expected input validation to fail.'); } catch (LexiconValidationException $exception) { static::assertSame('input', $exception->phase); static::assertSame(0, $sender->requestCount); } } public function testSkipsProcedureBodyValidationByDefault(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['id' => 'ok'])]); $response = self::client($sender, self::procedureDefinition()) ->call( 'io.example.testProcedure', input: ['text' => 123], ); static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['id' => 'ok'], $response->data); static::assertSame('{"text":123}', (string) $sender->lastRequest?->getBody()); } public function testSucceedsWithValidProcedureBodyWhenValidationIsEnabled(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['id' => 'valid'])]); $response = self::client($sender, self::procedureDefinition()) ->call( 'io.example.testProcedure', input: ['text' => 'hello'], options: new XrpcOptions(validateRequest: TRUE), ); static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['id' => 'valid'], $response->data); } public function testRejectsInvalidResponseBodyByDefault(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 123])]); $this->expectException(LexiconValidationException::class); self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); } public function testSucceedsWithValidResponseBodyWhenValidationIsEnabled(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['value' => 'hello'])]); $response = self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['value' => 'hello'], $response->data); } public function testRejectsInvalidLexDataByDefault(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['value' => 'hello', 'extra' => 1.5]), ]); $this->expectException(LexiconValidationException::class); self::client($sender, self::queryDefinition())->call('io.example.testQuery', ['limit' => 10]); } public function testRejectsErrorResponseWithInvalidLexDataByDefault(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse([ 'error' => 'TestError', 'message' => 'test-error-description', 'extra' => 1.5, ], 400), ]); try { self::client($sender, self::queryDefinition())->call('io.example.testQuery'); static::fail('Expected an XRPC error.'); } catch (XrpcHttpException $exception) { static::assertSame(400, $exception->statusCode); static::assertSame('test-error-description', $exception->xrpcMessage); } } public function testBinaryResponsesDoNotUseJsonValidation(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/octet-stream'], "\x01\x02\x03"), ]); $response = self::client($sender, self::binaryQueryDefinition())->call('io.example.testBinaryQuery'); static::assertInstanceOf(RawXrpcResponse::class, $response); static::assertSame("\x01\x02\x03", $response->body); } public function testAppliesRequestAndResponseDefaults(): void { $sender = new TestXrpcRequestSender([self::jsonResponse(['foo' => 'foo-value'])]); $response = self::client($sender, self::defaultsQueryDefinition())->call('io.example.testQueryWithDefaults'); static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame('foo=foo-default', $sender->lastRequest?->getUri()->getQuery()); static::assertSame(['foo' => 'foo-value', 'bar' => 'bar-default'], $response->data); } public function testRejectsInvalidBlobReference(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['blobRef' => ['$type' => 'blob']]), ]); $this->expectException(LexiconValidationException::class); self::client($sender, self::blobQueryDefinition())->call('io.example.testQueryGetBlobRef'); } public function testRejectsBlobReferenceWithCborCid(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['blobRef' => self::blob(self::CBOR_CID, 'image/png', 1)]), ]); $this->expectException(LexiconValidationException::class); self::client($sender, self::blobQueryDefinition())->call('io.example.testQueryGetBlobRef'); } public function testEnforcesBlobMimeTypeConstraintByDefault(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['blobRef' => self::blob(self::RAW_CID, 'invalid/mime', 10)]), ]); try { self::client($sender, self::blobQueryDefinition())->call('io.example.testQueryGetBlobRef'); static::fail('Expected blob MIME validation to fail.'); } catch (LexiconValidationException $exception) { static::assertStringContainsString('MIME type', $exception->getMessage()); } } public function testEnforcesBlobSizeConstraintByDefault(): void { $sender = new TestXrpcRequestSender([ self::jsonResponse(['blobRef' => self::blob(self::RAW_CID, 'image/png', 100)]), ]); try { self::client($sender, self::blobQueryDefinition())->call('io.example.testQueryGetBlobRef'); static::fail('Expected blob size validation to fail.'); } catch (LexiconValidationException $exception) { static::assertStringContainsString('10 bytes', $exception->getMessage()); } } /** * Derived from the official no-output payload rule and its explicit * unexpected-JSON-object case. */ public function testDerivedNoOutputQueryAcceptsBinaryBody(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/octet-stream'], "\x01\x02\x03"), ]); $response = self::client($sender, self::noOutputQueryDefinition())->call('io.example.testNoOutputQuery'); static::assertSame(200, $response->statusCode); } /** * Derived from the official no-output payload rule and its explicit * unexpected-JSON-object case. */ public function testDerivedNoOutputQueryAcceptsJsonScalar(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/json'], '"unexpected"'), ]); $response = self::client($sender, self::noOutputQueryDefinition())->call('io.example.testNoOutputQuery'); static::assertSame(200, $response->statusCode); } /** * Derived from the official no-output payload rule and its explicit * unexpected-JSON-object case. */ public function testDerivedNoOutputQueryAcceptsJsonList(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/json'], '[1,2,3]'), ]); $response = self::client($sender, self::noOutputQueryDefinition())->call('io.example.testNoOutputQuery'); static::assertSame(200, $response->statusCode); } /** * Derived from the official no-output payload rule and the official * content-type inference case for a non-empty response. */ public function testDerivedNoOutputQueryAcceptsBodyWithoutContentType(): void { $sender = new TestXrpcRequestSender([new Response(200, [], "\x01\x02\x03")]); $response = self::client($sender, self::noOutputQueryDefinition())->call('io.example.testNoOutputQuery'); static::assertSame(200, $response->statusCode); } /** * @param array $definition */ private static function client( XrpcRequestSenderInterface $sender, array $definition, ): LexiconXrpcClient { $factory = new HttpFactory(); $repository = new InMemoryLexiconRepository(); $repository->add(self::document($definition)); return new LexiconXrpcClient( new XrpcClient( $sender, $factory, $factory, 'https://service.example', new OutboundUrlPolicy(), ), new SchemaCompiler($repository), ); } /** * @param array $definition */ private static function document(array $definition): LexiconDocument { $result = new LexiconParser()->parse([ 'lexicon' => 1, 'id' => $definition['id'], 'defs' => ['main' => $definition['main']], ]); static::assertInstanceOf(LexiconDocument::class, $result->value, \implode('; ', $result->messages())); return $result->value; } /** @return array{id: string, main: array} */ private static function queryDefinition(): array { return [ 'id' => 'io.example.testQuery', 'main' => [ 'type' => 'query', 'parameters' => [ 'type' => 'params', 'properties' => ['limit' => ['type' => 'integer']], ], 'output' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['value'], 'properties' => ['value' => ['type' => 'string']], ], ], 'errors' => [['name' => 'TestError']], ], ]; } /** @return array{id: string, main: array} */ private static function procedureDefinition(): array { return [ 'id' => 'io.example.testProcedure', 'main' => [ 'type' => 'procedure', 'input' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['text'], 'properties' => ['text' => ['type' => 'string']], ], ], 'output' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['id'], 'properties' => ['id' => ['type' => 'string']], ], ], 'errors' => [['name' => 'ProcedureError']], ], ]; } /** @return array{id: string, main: array} */ private static function binaryQueryDefinition(): array { return [ 'id' => 'io.example.testBinaryQuery', 'main' => [ 'type' => 'query', 'output' => ['encoding' => 'application/octet-stream'], ], ]; } /** @return array{id: string, main: array} */ private static function binaryProcedureDefinition(): array { return [ 'id' => 'io.example.testBinaryProcedure', 'main' => [ 'type' => 'procedure', 'input' => ['encoding' => 'image/png'], 'output' => ['encoding' => 'application/octet-stream'], ], ]; } /** @return array{id: string, main: array} */ private static function noOutputQueryDefinition(): array { return [ 'id' => 'io.example.testNoOutputQuery', 'main' => ['type' => 'query'], ]; } /** @return array{id: string, main: array} */ private static function defaultsQueryDefinition(): array { return [ 'id' => 'io.example.testQueryWithDefaults', 'main' => [ 'type' => 'query', 'parameters' => [ 'type' => 'params', 'required' => ['foo'], 'properties' => [ 'foo' => ['type' => 'string', 'default' => 'foo-default'], ], ], 'output' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['foo'], 'properties' => [ 'foo' => ['type' => 'string'], 'bar' => ['type' => 'string', 'default' => 'bar-default'], ], ], ], ], ]; } /** @return array{id: string, main: array} */ private static function blobQueryDefinition(): array { return [ 'id' => 'io.example.testQueryGetBlobRef', 'main' => [ 'type' => 'query', 'output' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['blobRef'], 'properties' => [ 'blobRef' => [ 'type' => 'blob', 'accept' => ['image/png'], 'maxSize' => 10, ], ], ], ], ], ]; } /** @return array */ private static function blob(string $cid, string $mimeType, int $size): array { return [ '$type' => 'blob', 'ref' => ['$link' => $cid], 'mimeType' => $mimeType, 'size' => $size, ]; } /** @param array $data */ private static function jsonResponse(array $data, int $status = 200): Response { return new Response( $status, ['Content-Type' => 'application/json'], \json_encode($data, JSON_THROW_ON_ERROR), ); } public function testQueryAppliesDeclaredDefaultsAndValidatesOutput(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/json'], '{"name":"Alice","followers":1.0}'), ]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'query', 'parameters' => [ 'type' => 'params', 'properties' => [ 'limit' => ['type' => 'integer', 'default' => 50], 'reverse' => ['type' => 'boolean', 'default' => FALSE], ], ], 'output' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['name', 'followers'], 'properties' => [ 'name' => ['type' => 'string'], 'followers' => ['type' => 'integer'], ], ], ], 'errors' => [['name' => 'NotFound']], ])); $response = $client->call('com.example.getProfile'); static::assertInstanceOf(XrpcResponse::class, $response); static::assertSame(['name' => 'Alice', 'followers' => 1], $response->data); static::assertSame( 'https://service.example/xrpc/com.example.getProfile?limit=50&reverse=false', (string) $sender->lastRequest?->getUri(), ); } public function testQueryRejectsInvalidUndeclaredParametersBeforeSending(): void { $sender = new TestXrpcRequestSender([]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'query', 'parameters' => [ 'type' => 'params', 'properties' => [], ], ])); try { $client->call('com.example.getProfile', ['filter' => ['nested' => 'value']]); static::fail('Expected parameter validation to fail.'); } catch (LexiconValidationException $exception) { static::assertSame('parameters', $exception->phase); static::assertSame(0, $sender->requestCount); } } public function testProcedureValidatesJsonInputBeforeSending(): void { $sender = new TestXrpcRequestSender([]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'procedure', 'input' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['text'], 'properties' => ['text' => ['type' => 'string']], ], ], 'output' => ['encoding' => 'application/json'], ])); try { $client->call( 'com.example.getProfile', input: ['text' => 1], options: new \Wotnak\Atproto\Client\XrpcOptions(validateRequest: TRUE), ); static::fail('Expected input validation to fail.'); } catch (LexiconValidationException $exception) { static::assertSame('input', $exception->phase); static::assertSame(0, $sender->requestCount); } } public function testRejectsJsonOutputThatViolatesLexicon(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'application/json'], '{"count":"many"}'), ]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'query', 'output' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['count'], 'properties' => ['count' => ['type' => 'integer']], ], ], ])); try { $client->call('com.example.getProfile'); static::fail('Expected output validation to fail.'); } catch (LexiconValidationException $exception) { static::assertSame('output', $exception->phase); static::assertSame(1, $sender->requestCount); } } public function testRejectsResponseBodyWithoutDeclaredContentType(): void { $sender = new TestXrpcRequestSender([ new Response(200, [], '{"name":"Alice"}'), ]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'query', 'output' => [ 'encoding' => 'application/json', 'schema' => [ 'type' => 'object', 'required' => ['name'], 'properties' => ['name' => ['type' => 'string']], ], ], ])); $this->expectException(XrpcProtocolException::class); $this->expectExceptionMessage('without Content-Type'); $client->call('com.example.getProfile'); } public function testAllowsEmptyResponseWithoutContentType(): void { $sender = new TestXrpcRequestSender([new Response(200)]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'query', 'output' => ['encoding' => 'application/json'], ])); $response = $client->call('com.example.getProfile'); static::assertInstanceOf(XrpcResponse::class, $response); static::assertFalse($response->hasBody); } public function testExecutesRawProcedureUsingDeclaredContentTypes(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'image/png'], 'png-bytes'), ]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'procedure', 'input' => ['encoding' => 'application/octet-stream'], 'output' => ['encoding' => 'image/*'], ])); $response = $client->call('com.example.getProfile', input: 'source-bytes'); static::assertInstanceOf(RawXrpcResponse::class, $response); static::assertSame('png-bytes', $response->body); static::assertNotNull($sender->lastRequest); static::assertSame('application/octet-stream', $sender->lastRequest->getHeaderLine('Content-Type')); static::assertSame('image/*', $sender->lastRequest->getHeaderLine('Accept')); } public function testExecutesRawProcedureWithCallerProvidedStream(): void { $sender = new TestXrpcRequestSender([ new Response(200, ['Content-Type' => 'image/png'], 'png-bytes'), ]); $client = self::existingClient($sender, self::existingDocument([ 'type' => 'procedure', 'input' => ['encoding' => 'application/octet-stream'], 'output' => ['encoding' => 'image/*'], ])); $stream = new NoSeekStream(Utils::streamFor('source-bytes')); $response = $client->call('com.example.getProfile', input: $stream); static::assertInstanceOf(RawXrpcResponse::class, $response); static::assertSame($stream, $sender->lastRequest?->getBody()); } private static function existingClient(TestXrpcRequestSender $sender, LexiconDocument $document): LexiconXrpcClient { $factory = new HttpFactory(); $repository = new InMemoryLexiconRepository(); $repository->add($document); return new LexiconXrpcClient( new XrpcClient( $sender, $factory, $factory, 'https://service.example', new OutboundUrlPolicy(), ), new SchemaCompiler($repository), ); } /** * @param array $definition */ private static function existingDocument(array $definition): LexiconDocument { $result = new LexiconParser()->parse([ 'lexicon' => 1, 'id' => 'com.example.getProfile', 'defs' => ['main' => $definition], ]); static::assertInstanceOf(LexiconDocument::class, $result->value, \implode('; ', $result->messages())); return $result->value; } }