Phred/tests/ContentNegotiationTest.php
Funky Waddle cf30f3e41a
Some checks failed
CI / PHP ${{ matrix.php }} (8.1) (push) Has been cancelled
CI / PHP ${{ matrix.php }} (8.2) (push) Has been cancelled
CI / PHP ${{ matrix.php }} (8.3) (push) Has been cancelled
M12: Serialization/validation utilities and pagination
2025-12-23 17:40:02 -06:00

76 lines
2.6 KiB
PHP

<?php
declare(strict_types=1);
namespace Phred\Tests;
use Nyholm\Psr7Server\ServerRequestCreator;
use Nyholm\Psr7\Factory\Psr17Factory;
use Phred\Http\Kernel;
use PHPUnit\Framework\TestCase;
final class ContentNegotiationTest extends TestCase
{
protected function tearDown(): void
{
putenv('API_FORMAT');
\Phred\Support\Config::clear();
}
private function kernel(): Kernel
{
return new Kernel();
}
private function request(string $method, string $uri, array $headers = []): \Psr\Http\Message\ServerRequestInterface
{
$psr17 = new Psr17Factory();
$creator = new ServerRequestCreator($psr17, $psr17, $psr17, $psr17);
$server = [
'REQUEST_METHOD' => strtoupper($method),
'REQUEST_URI' => $uri,
];
return $creator->fromArrays($server, $headers, [], [], []);
}
public function testDefaultRestWhenNoAccept(): void
{
putenv('API_FORMAT'); // unset to use default
$kernel = $this->kernel();
$req = $this->request('GET', '/_phred/format');
$res = $kernel->handle($req);
$this->assertSame(200, $res->getStatusCode());
$this->assertStringStartsWith('application/json', $res->getHeaderLine('Content-Type'));
$data = json_decode((string) $res->getBody(), true);
$this->assertIsArray($data);
$this->assertSame('rest', $data['format'] ?? null);
}
public function testJsonApiWhenAcceptHeaderPresent(): void
{
putenv('API_FORMAT'); // unset
$kernel = $this->kernel();
$req = $this->request('GET', '/_phred/format', ['Accept' => 'application/vnd.api+json']);
$res = $kernel->handle($req);
$this->assertSame(200, $res->getStatusCode());
$this->assertSame('application/vnd.api+json', $res->getHeaderLine('Content-Type'));
$doc = json_decode((string) $res->getBody(), true);
$this->assertIsArray($doc);
$this->assertArrayHasKey('data', $doc);
$this->assertSame('jsonapi', $doc['data']['format'] ?? null);
}
public function testEnvDefaultJsonApiWithoutAccept(): void
{
putenv('API_FORMAT=jsonapi');
$kernel = $this->kernel();
$req = $this->request('GET', '/_phred/format');
$res = $kernel->handle($req);
$this->assertSame(200, $res->getStatusCode());
$this->assertSame('application/vnd.api+json', $res->getHeaderLine('Content-Type'));
$doc = json_decode((string) $res->getBody(), true);
$this->assertIsArray($doc);
$this->assertArrayHasKey('data', $doc);
$this->assertSame('jsonapi', $doc['data']['format'] ?? null);
}
}