1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Shlinkio\Shlink\TestUtils\ApiTest; |
6
|
|
|
|
7
|
|
|
use Closure; |
8
|
|
|
use Fig\Http\Message\RequestMethodInterface; |
9
|
|
|
use Fig\Http\Message\StatusCodeInterface; |
10
|
|
|
use GuzzleHttp\ClientInterface; |
11
|
|
|
use GuzzleHttp\RequestOptions; |
12
|
|
|
use PHPUnit\Framework\TestCase; |
13
|
|
|
use Psr\Http\Message\ResponseInterface; |
14
|
|
|
|
15
|
|
|
use function json_decode; |
16
|
|
|
use function sprintf; |
17
|
|
|
|
18
|
|
|
use const JSON_THROW_ON_ERROR; |
19
|
|
|
|
20
|
|
|
abstract class ApiTestCase extends TestCase implements StatusCodeInterface, RequestMethodInterface |
21
|
|
|
{ |
22
|
|
|
private const REST_PATH_PREFIX = '/rest/v2'; |
23
|
|
|
|
24
|
|
|
private static ClientInterface $client; |
25
|
|
|
private static ?Closure $seedFixtures = null; |
26
|
|
|
|
27
|
|
|
public static function setApiClient(ClientInterface $client): void |
28
|
|
|
{ |
29
|
|
|
self::$client = $client; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public static function setSeedFixturesCallback(callable $seedFixtures): void |
33
|
|
|
{ |
34
|
|
|
self::$seedFixtures = Closure::fromCallable($seedFixtures); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function setUp(): void |
38
|
|
|
{ |
39
|
|
|
if (self::$seedFixtures !== null) { |
40
|
|
|
(self::$seedFixtures)(); |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
protected function callApi(string $method, string $uri, array $options = []): ResponseInterface |
45
|
|
|
{ |
46
|
|
|
return self::$client->request($method, sprintf('%s%s', self::REST_PATH_PREFIX, $uri), $options); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
protected function callApiWithKey(string $method, string $uri, array $options = []): ResponseInterface |
50
|
|
|
{ |
51
|
|
|
$headers = $options[RequestOptions::HEADERS] ?? []; |
52
|
|
|
$headers['X-Api-Key'] = 'valid_api_key'; |
53
|
|
|
$options[RequestOptions::HEADERS] = $headers; |
54
|
|
|
|
55
|
|
|
return $this->callApi($method, $uri, $options); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
protected function getJsonResponsePayload(ResponseInterface $resp): array |
59
|
|
|
{ |
60
|
|
|
$body = (string) $resp->getBody(); |
61
|
|
|
return json_decode($body, true, 512, JSON_THROW_ON_ERROR); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
protected function callShortUrl(string $shortCode): ResponseInterface |
65
|
|
|
{ |
66
|
|
|
return self::$client->request(self::METHOD_GET, sprintf('/%s', $shortCode), [ |
67
|
|
|
RequestOptions::ALLOW_REDIRECTS => false, |
68
|
|
|
]); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|