Completed
Pull Request — master (#457)
by Alejandro
06:50
created

ApiTestCase   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 8
eloc 15
dl 0
loc 49
rs 10
c 0
b 0
f 0
ccs 0
cts 19
cp 0

7 Methods

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