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

ApiTestCase::callShortUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 0
cts 3
cp 0
cc 1
nc 1
nop 1
crap 2
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