Passed
Push — master ( 61f9d7...77b152 )
by Baptiste
29s
created

Http::setTheParameters()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
1
<?php
2
namespace Behapi\Context;
3
4
use RuntimeException;
5
6
use Psr\Http\Message\RequestInterface;
7
8
use Behat\Behat\Context\Context;
9
use Behat\Gherkin\Node\TableNode;
10
11
use Http\Client\HttpClient;
12
use Http\Message\StreamFactory;
13
use Http\Message\MessageFactory;
14
15
use Twig_Environment;
16
17
use Behapi\Extension\Context\ApiTrait;
18
use Behapi\Extension\Context\TwigTrait;
19
20
use Behapi\Extension\Tools\Assert;
21
use Behapi\Extension\Tools\HttpHistory;
22
23
class Http implements Context
24
{
25
    use ApiTrait;
26
    use TwigTrait;
27
28
    /** @var RequestInterface */
29
    private $request;
30
31
    /** @var mixed[] Query args to add */
32
    private $query;
33
34
    public function __construct(HttpClient $client, StreamFactory $streamFactory, MessageFactory $messageFactory, HttpHistory $history, Twig_Environment $twig = null)
35
    {
36
        $this->client = $client;
37
        $this->history = $history;
38
        $this->streamFactory = $streamFactory;
39
        $this->messageFactory = $messageFactory;
40
41
        $this->twig = $twig;
42
    }
43
44
    /** @When /^I create a "(?P<method>GET|POST|PATCH|PUT|DELETE|OPTIONS|HEAD)" request to "(?P<url>.+?)"$/ */
45
    public function createARequest(string $method, string $url)
46
    {
47
        $url = trim($url);
48
49
        $this->query = [];
50
        $this->request = $this->messageFactory->createRequest(strtoupper($method), $url);
51
52
        // let's set a default content-type
53
        $this->setContentType($this->getDefaultContentType());
54
    }
55
56
    /** @When I add/set the value :value to the parameter :parameter */
57
    public function addAParameter(string $parameter, string $value)
58
    {
59
        if (!isset($this->query[$parameter])) {
60
            $this->query[$parameter] = $value;
61
            return;
62
        }
63
64
        $current = &$this->query[$parameter];
65
66
        if (is_array($current)) {
67
            $current[] = $value;
68
            return;
69
        }
70
71
        $current = [$current, $value];
72
    }
73
74
    /** @When I set the following query arguments: */
75
    public function setTheParameters(TableNode $parameters)
76
    {
77
        $this->query = [];
78
79
        foreach ($parameters->getRowsHash() as $parameter => $value) {
80
            if (is_string($value)) {
81
                $value = $this->renderString($value);
82
            }
83
84
            $this->addAParameter($parameter, $value);
85
        }
86
    }
87
88
    /** @When I set the content-type to :type */
89
    public function setContentType(string $type)
90
    {
91
        $request = $this->getRequest();
92
        $this->request = $request->withHeader('Content-Type', $type);
93
    }
94
95
    /** @When I set the following body: */
96
    public function setTheBody(string $body)
97
    {
98
        $body = $this->renderString($body);
99
        $stream = $this->streamFactory->createStream($body);
100
101
        $request = $this->getRequest();
102
        $this->request = $request->withBody($stream);
103
    }
104
105
    /** @When I add/set the value :value to the header :header */
106
    public function addHeader(string $header, string $value)
107
    {
108
        $request = $this->getRequest();
109
        $this->request = $request->withAddedHeader($header, $value);
110
    }
111
112
    /** @When I set the headers: */
113
    public function setHeaders(TableNode $headers)
114
    {
115
        $request = $this->getRequest();
116
117
        foreach ($headers->getRowsHash() as $header => $value) {
118
            $request = $request->withHeader($header, $value);
119
        }
120
121
        $this->request = $request;
122
    }
123
124
    /** @When I send the request */
125
    public function sendRequest()
126
    {
127
        $request = $this->getRequest();
128
129
        if (!empty($this->query)) {
130
            $uri = $request->getUri();
131
            $current = $uri->getQuery();
132
            $query = http_build_query($this->query);
133
134
            if (!empty($current)) {
135
                $query = "{$current}&{$query}";
136
            }
137
138
            $uri = $uri->withQuery($query);
139
            $request = $request->withUri($uri);
140
        }
141
142
        $this->client->sendRequest($request);
143
    }
144
145
    /** @Then the status code should be :expected */
146
    public function statusCodeShouldBe(int $expected)
147
    {
148
        $response = $this->getResponse();
149
        Assert::same((int) $response->getStatusCode(), $expected);
150
    }
151
152
    /** @Then the status code should not be :expected */
153
    public function statusCodeShouldNotBe(int $expected)
154
    {
155
        $response = $this->getResponse();
156
        Assert::notSame((int) $response->getStatusCode(), $expected);
157
    }
158
159
    /** @Then the content-type should be equal to :expected */
160
    public function contentTypeShouldBe(string $expected)
161
    {
162
        $response = $this->getResponse();
163
        Assert::same($response->getHeaderLine('Content-type'), $expected);
164
    }
165
166
    /** @Then the response header :header should be equal to :expected */
167
    public function headerShouldBe(string $header, string $expected)
168
    {
169
        $response = $this->getResponse();
170
        Assert::same($response->getHeaderLine($header), $expected);
171
    }
172
173
    /** @Then the response header :header should contain :expected */
174
    public function headerShouldContain(string $header, string $expected)
175
    {
176
        $response = $this->getResponse();
177
        Assert::contains((string) $response->getHeaderLine($header), $expected);
178
    }
179
180
    /** @Then the response should have a header :header */
181
    public function responseShouldHaveHeader(string $header)
182
    {
183
        $response = $this->getResponse();
184
        Assert::true($response->hasHeader($header));
185
    }
186
187
    /** @Then the response should have sent some data */
188
    public function responseShouldHaveSentSomeData()
189
    {
190
        $body = $this->getResponse()->getBody();
191
192
        Assert::notNull($body->getSize());
193
        Assert::greaterThan($body->getSize(), 0);
194
    }
195
196
    /** @Then the response should not have sent any data */
197
    public function responseShouldNotHaveAnyData()
198
    {
199
        $body = $this->getResponse()->getBody();
200
        Assert::nullOrSame($body->getSize(), 0);
201
    }
202
203
    /** @Then the response should contain :data */
204
    public function responseShouldContain(string $data)
205
    {
206
        $response = $this->getResponse();
207
        Assert::contains((string) $response->getBody(), $data);
208
    }
209
210
    /** @Then the response should not contain :data */
211
    public function responseShouldNotContain(string $data)
212
    {
213
        $response = $this->getResponse();
214
        Assert::notContains((string) $response->getBody(), $data);
215
    }
216
217
    /** @Then the response should be :data */
218
    public function responseShouldBe(string $data)
219
    {
220
        $response = $this->getResponse();
221
        Assert::eq((string) $response->getBody(), $data);
222
    }
223
224
    /** @Then the response should not be :data */
225
    public function responseShouldNotBe(string $data)
226
    {
227
        $response = $this->getResponse();
228
        Assert::NotEq((string) $response->getBody(), $data);
229
    }
230
231
    /**
232
     * @AfterScenario @api
233
     * @AfterScenario @rest
234
     */
235
    public function clearCache()
236
    {
237
        $this->query = [];
238
        $this->request = null;
239
        // the history is resetted in its own event listener
240
    }
241
242
    /**
243
     * @return RequestInterface
244
     * @throws RuntimeException
245
     */
246
    public function getRequest(): RequestInterface
247
    {
248
        if (null === $this->request) {
249
            throw new RuntimeException('No request initiated');
250
        }
251
252
        return $this->request;
253
    }
254
255
    /**
256
     * Get the default content type, used when makeRequest is called
257
     *
258
     * @return string
259
     */
260
    protected function getDefaultContentType(): string
261
    {
262
        return 'application/json';
263
    }
264
}
265