shlink/module/Common/test-db/ApiTest/ApiTestCase.php

68 lines
2 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace ShlinkioTest\Shlink\Common\ApiTest;
2019-01-26 12:19:20 +03:00
use Fig\Http\Message\RequestMethodInterface;
use Fig\Http\Message\StatusCodeInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\RequestOptions;
use PHPUnit\Framework\TestCase;
2019-01-26 12:19:20 +03:00
use Psr\Http\Message\ResponseInterface;
2019-01-27 14:35:00 +03:00
use Shlinkio\Shlink\Rest\Authentication\Plugin\ApiKeyHeaderPlugin;
use function Shlinkio\Shlink\Common\json_decode;
2019-01-27 12:30:38 +03:00
use function sprintf;
2019-01-26 12:19:20 +03:00
abstract class ApiTestCase extends TestCase implements StatusCodeInterface, RequestMethodInterface
{
private const REST_PATH_PREFX = '/rest/v1';
2019-01-27 12:30:38 +03:00
2019-01-26 12:19:20 +03:00
/** @var ClientInterface */
private static $client;
/** @var callable */
private static $seedFixtures;
2019-01-26 12:19:20 +03:00
public static function setApiClient(ClientInterface $client): void
{
self::$client = $client;
}
public static function setSeedFixturesCallback(callable $seedFixtures): void
{
self::$seedFixtures = $seedFixtures;
}
public function setUp(): void
{
if (self::$seedFixtures) {
(self::$seedFixtures)();
}
}
2019-01-26 12:19:20 +03:00
protected function callApi(string $method, string $uri, array $options = []): ResponseInterface
{
return self::$client->request($method, sprintf('%s%s', self::REST_PATH_PREFX, $uri), $options);
2019-01-26 12:19:20 +03:00
}
2019-01-27 14:35:00 +03:00
protected function callApiWithKey(string $method, string $uri, array $options = []): ResponseInterface
{
$headers = $options[RequestOptions::HEADERS] ?? [];
2019-01-27 14:35:00 +03:00
$headers[ApiKeyHeaderPlugin::HEADER_NAME] = 'valid_api_key';
$options[RequestOptions::HEADERS] = $headers;
2019-01-27 14:35:00 +03:00
return $this->callApi($method, $uri, $options);
}
protected function getJsonResponsePayload(ResponseInterface $resp): array
{
return json_decode((string) $resp->getBody());
}
protected function callShortUrl(string $shortCode): ResponseInterface
{
return self::$client->request(self::METHOD_GET, sprintf('/%s', $shortCode), [
RequestOptions::ALLOW_REDIRECTS => false,
]);
}
}