Passed
Pull Request — master (#2608)
by Kévin
05:16
created

Client::enableReboot()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
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\Client as FrameworkBundleClient;
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 as HttpProfile;
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
    public const OPTIONS_DEFAULT = [
35
        'auth_basic' => null,                               // array|string - an array containing the username as first value, and optionally the
36
        //   password as the second one; or string like username:password - enabling HTTP Basic
37
        //   authentication (RFC 7617)
38
        'auth_bearer' => null,                              // string - a token enabling HTTP Bearer authorization (RFC 6750)
39
        'query' => [],                                      // string[] - associative array of query string values to merge with the request's URL
40
        'headers' => ['accept' => ['application/ld+json']], // iterable|string[]|string[][] - headers names provided as keys or as part of values
41
        'body' => '',                                       // array|string|resource|\Traversable|\Closure - the callback SHOULD yield a string
42
        'json' => null,                                     // array|\JsonSerializable - when set, implementations MUST set the "body" option to
43
        //   the JSON-encoded value and set the "content-type" headers to a JSON-compatible
44
        'base_uri' => 'http://example.com',                 // string - the URI to resolve relative URLs, following rules in RFC 3986, section 2
45
    ];
46
47
    use HttpClientTrait;
48
49
    private $fwbClient;
50
51
    public function __construct(FrameworkBundleClient $fwbClient)
52
    {
53
        $this->fwbClient = $fwbClient;
54
        $fwbClient->followRedirects(false);
55
    }
56
57
    /**
58
     * @see Client::OPTIONS_DEFAULTS for available options
59
     *
60
     * {@inheritdoc}
61
     */
62
    public function request(string $method, string $url, array $options = []): ResponseInterface
63
    {
64
        $basic = $options['auth_basic'] ?? null;
65
        [$url, $options] = self::prepareRequest($method, $url, $options, self::OPTIONS_DEFAULT);
66
        $resolvedUrl = implode('', $url);
67
68
        $server = [];
69
        // Convert headers to a $_SERVER-like array
70
        foreach ($options['headers'] as $key => $value) {
71
            if ('content-type' === $key) {
72
                $server['CONTENT_TYPE'] = $value[0] ?? '';
73
74
                continue;
75
            }
76
77
            // BrowserKit doesn't support setting several headers with the same name
78
            $server['HTTP_'.strtoupper(str_replace('-', '_', $key))] = $value[0] ?? '';
79
        }
80
81
        if ($basic) {
82
            $credentials = \is_array($basic) ? $basic : explode(':', $basic, 2);
83
            $server['PHP_AUTH_USER'] = $credentials[0];
84
            $server['PHP_AUTH_PW'] = $credentials[1] ?? '';
85
        }
86
87
        $info = [
88
            'response_headers' => [],
89
            'redirect_count' => 0,
90
            'redirect_url' => null,
91
            'start_time' => 0.0,
92
            'http_method' => $method,
93
            'http_code' => 0,
94
            'error' => null,
95
            'user_data' => $options['user_data'] ?? null,
96
            'url' => $resolvedUrl,
97
            'primary_port' => 'http:' === $url['scheme'] ? 80 : 443,
98
        ];
99
        $this->fwbClient->request($method, $resolvedUrl, [], [], $server, $options['body'] ?? null);
100
101
        return new Response($this->fwbClient->getResponse(), $this->fwbClient->getInternalResponse(), $info);
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107
    public function stream($responses, float $timeout = null): ResponseStreamInterface
108
    {
109
        throw new \LogicException('Not implemented yet');
110
    }
111
112
    /**
113
     * Gets the underlying test client.
114
     */
115
    public function getFrameworkBundleClient(): FrameworkBundleClient
116
    {
117
        return $this->fwbClient;
118
    }
119
120
    // The following methods are proxy methods for FrameworkBundleClient's ones
121
122
    /**
123
     * Returns the container.
124
     *
125
     * @return ContainerInterface|null Returns null when the Kernel has been shutdown or not started yet
126
     */
127
    public function getContainer()
128
    {
129
        return $this->fwbClient->getContainer();
130
    }
131
132
    /**
133
     * Returns the kernel.
134
     *
135
     * @return KernelInterface
136
     */
137
    public function getKernel()
138
    {
139
        return $this->fwbClient->getKernel();
140
    }
141
142
    /**
143
     * Gets the profile associated with the current Response.
144
     *
145
     * @return HttpProfile|false A Profile instance
146
     */
147
    public function getProfile()
148
    {
149
        return $this->fwbClient->getProfile();
150
    }
151
152
    /**
153
     * Enables the profiler for the very next request.
154
     *
155
     * If the profiler is not enabled, the call to this method does nothing.
156
     */
157
    public function enableProfiler()
158
    {
159
        $this->fwbClient->enableProfiler();
160
    }
161
162
    /**
163
     * Disables kernel reboot between requests.
164
     *
165
     * By default, the Client reboots the Kernel for each request. This method
166
     * allows to keep the same kernel across requests.
167
     */
168
    public function disableReboot()
169
    {
170
        $this->fwbClient->disableReboot();
171
    }
172
173
    /**
174
     * Enables kernel reboot between requests.
175
     */
176
    public function enableReboot()
177
    {
178
        $this->fwbClient->enableReboot();
179
    }
180
}
181