Passed
Push — master ( 8bd912...d93388 )
by Alan
06:58 queued 02:20
created

src/Bridge/Symfony/Bundle/Test/Client.php (1 issue)

1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Bridge\Symfony\Bundle\Test;
15
16
use Symfony\Bundle\FrameworkBundle\KernelBrowser;
17
use Symfony\Component\DependencyInjection\ContainerInterface;
18
use Symfony\Component\HttpClient\HttpClientTrait;
19
use Symfony\Component\HttpKernel\KernelInterface;
20
use Symfony\Component\HttpKernel\Profiler\Profile;
21
use Symfony\Contracts\HttpClient\HttpClientInterface;
22
use Symfony\Contracts\HttpClient\ResponseInterface;
23
use Symfony\Contracts\HttpClient\ResponseStreamInterface;
24
25
/**
26
 * Convenient test client that makes requests to a Kernel object.
27
 *
28
 * @experimental
29
 *
30
 * @author Kévin Dunglas <[email protected]>
31
 */
32
final class Client implements HttpClientInterface
33
{
34
    use HttpClientTrait;
35
36
    /**
37
     * @see HttpClientInterface::OPTIONS_DEFAULTS
38
     */
39
    public const API_OPTIONS_DEFAULTS = [
40
        'auth_basic' => null,
41
        'auth_bearer' => null,
42
        'query' => [],
43
        'headers' => ['accept' => ['application/ld+json']],
44
        'body' => '',
45
        'json' => null,
46
        'base_uri' => 'http://example.com',
47
    ];
48
49
    private $kernelBrowser;
50
51
    private $defaultOptions = self::API_OPTIONS_DEFAULTS;
52
53
    /**
54
     * @var Response
55
     */
56
    private $response;
57
58
    /**
59
     * @param array $defaultOptions Default options for the requests
60
     *
61
     * @see HttpClientInterface::OPTIONS_DEFAULTS for available options
62
     */
63
    public function __construct(KernelBrowser $kernelBrowser, array $defaultOptions = [])
64
    {
65
        $this->kernelBrowser = $kernelBrowser;
66
        $kernelBrowser->followRedirects(false);
67
        if ($defaultOptions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $defaultOptions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
68
            $this->setDefaultOptions($defaultOptions);
69
        }
70
    }
71
72
    /**
73
     * Sets the default options for the requests.
74
     *
75
     * @see HttpClientInterface::OPTIONS_DEFAULTS for available options
76
     */
77
    public function setDefaultOptions(array $defaultOptions): void
78
    {
79
        [, $this->defaultOptions] = self::prepareRequest(null, null, $defaultOptions, self::API_OPTIONS_DEFAULTS);
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     *
85
     * @return Response
86
     */
87
    public function request(string $method, string $url, array $options = []): ResponseInterface
88
    {
89
        $basic = $options['auth_basic'] ?? null;
90
        [$url, $options] = self::prepareRequest($method, $url, $options, $this->defaultOptions);
91
        $resolvedUrl = implode('', $url);
92
        $server = [];
93
94
        // Convert headers to a $_SERVER-like array
95
        foreach (self::extractHeaders($options) as $key => $value) {
96
            if ('content-type' === $key) {
97
                $server['CONTENT_TYPE'] = $value[0] ?? '';
98
99
                continue;
100
            }
101
102
            // BrowserKit doesn't support setting several headers with the same name
103
            $server['HTTP_'.strtoupper(strtr($key, '-', '_'))] = $value[0] ?? '';
104
        }
105
106
        if ($basic) {
107
            $credentials = \is_array($basic) ? $basic : explode(':', $basic, 2);
108
            $server['PHP_AUTH_USER'] = $credentials[0];
109
            $server['PHP_AUTH_PW'] = $credentials[1] ?? '';
110
        }
111
112
        $info = [
113
            'response_headers' => [],
114
            'redirect_count' => 0,
115
            'redirect_url' => null,
116
            'start_time' => 0.0,
117
            'http_method' => $method,
118
            'http_code' => 0,
119
            'error' => null,
120
            'user_data' => $options['user_data'] ?? null,
121
            'url' => $resolvedUrl,
122
            'primary_port' => 'http:' === $url['scheme'] ? 80 : 443,
123
        ];
124
        $this->kernelBrowser->request($method, $resolvedUrl, [], [], $server, $options['body'] ?? null);
125
126
        return $this->response = new Response($this->kernelBrowser->getResponse(), $this->kernelBrowser->getInternalResponse(), $info);
127
    }
128
129
    /**
130
     * {@inheritdoc}
131
     */
132
    public function stream($responses, float $timeout = null): ResponseStreamInterface
133
    {
134
        throw new \LogicException('Not implemented yet');
135
    }
136
137
    /**
138
     * Gets the latest response.
139
     *
140
     * @internal
141
     */
142
    public function getResponse(): ?Response
143
    {
144
        return $this->response;
145
    }
146
147
    /**
148
     * Gets the underlying test client.
149
     *
150
     * @internal
151
     */
152
    public function getKernelBrowser(): KernelBrowser
153
    {
154
        return $this->kernelBrowser;
155
    }
156
157
    // The following methods are proxy methods for KernelBrowser's ones
158
159
    /**
160
     * Returns the container.
161
     *
162
     * @return ContainerInterface|null Returns null when the Kernel has been shutdown or not started yet
163
     */
164
    public function getContainer(): ?ContainerInterface
165
    {
166
        return $this->kernelBrowser->getContainer();
167
    }
168
169
    /**
170
     * Returns the kernel.
171
     */
172
    public function getKernel(): KernelInterface
173
    {
174
        return $this->kernelBrowser->getKernel();
175
    }
176
177
    /**
178
     * Gets the profile associated with the current Response.
179
     *
180
     * @return Profile|false A Profile instance
181
     */
182
    public function getProfile()
183
    {
184
        return $this->kernelBrowser->getProfile();
185
    }
186
187
    /**
188
     * Enables the profiler for the very next request.
189
     *
190
     * If the profiler is not enabled, the call to this method does nothing.
191
     */
192
    public function enableProfiler(): void
193
    {
194
        $this->kernelBrowser->enableProfiler();
195
    }
196
197
    /**
198
     * Disables kernel reboot between requests.
199
     *
200
     * By default, the Client reboots the Kernel for each request. This method
201
     * allows to keep the same kernel across requests.
202
     */
203
    public function disableReboot(): void
204
    {
205
        $this->kernelBrowser->disableReboot();
206
    }
207
208
    /**
209
     * Enables kernel reboot between requests.
210
     */
211
    public function enableReboot(): void
212
    {
213
        $this->kernelBrowser->enableReboot();
214
    }
215
216
    /**
217
     * Extracts headers depending on the symfony/http-client version being used.
218
     *
219
     * @return array<string, string[]>
220
     */
221
    private static function extractHeaders(array $options): array
222
    {
223
        if (!isset($options['normalized_headers'])) {
224
            return $options['headers'];
225
        }
226
227
        $headers = [];
228
229
        /** @var string $key */
230
        foreach ($options['normalized_headers'] as $key => $values) {
231
            foreach ($values as $value) {
232
                [, $value] = explode(': ', $value, 2);
233
                $headers[$key][] = $value;
234
            }
235
        }
236
237
        return $headers;
238
    }
239
}
240