Passed
Push — master ( 9b5861...5bdc47 )
by Joao
06:11 queued 16s
created

SwaggerRequester::assertHeaderContains()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace ByJG\Swagger;
4
5
use ByJG\Swagger\Exception\NotMatchedException;
6
use ByJG\Swagger\Exception\StatusCodeNotMatchedException;
7
use GuzzleHttp\Client;
8
use GuzzleHttp\ClientInterface;
9
use GuzzleHttp\Exception\BadResponseException;
10
use GuzzleHttp\Exception\GuzzleException;
11
use GuzzleHttp\Psr7\Request;
12
13
class SwaggerRequester
14
{
15
    protected $method = 'get';
16
    protected $path = '/';
17
    protected $requestHeader = [];
18
    protected $query = [];
19
    protected $requestBody = null;
20
    /**
21
     * @var SwaggerSchema
22
     */
23
    protected $swaggerSchema = null;
24
25
    protected $statusExpected = 200;
26
    protected $assertHeader = [];
27
28
    /**
29
     * @var ClientInterface
30
     */
31
    protected $guzzleHttpClient;
32
33
    public function __construct()
34
    {
35
        $this->guzzleHttpClient = new Client(['headers' => ['User-Agent' => 'Swagger Test']]);
36
    }
37
38
    /**
39
     * @param SwaggerSchema $schema
40
     * @return $this
41
     */
42
    public function withSwaggerSchema($schema)
43
    {
44
        $this->swaggerSchema = $schema;
45
46
        return $this;
47
    }
48
49
    /**
50
     * @return bool
51
     */
52
    public function hasSwaggerSchema()
53
    {
54
        return !empty($this->swaggerSchema);
55
    }
56
57
    /**
58
     * @param string $method
59
     * @return SwaggerRequester
60
     */
61
    public function withMethod($method)
62
    {
63
        $this->method = $method;
64
65
        return $this;
66
    }
67
68
    /**
69
     * @param string $path
70
     * @return SwaggerRequester
71
     */
72
    public function withPath($path)
73
    {
74
        $this->path = $path;
75
76
        return $this;
77
    }
78
79
    /**
80
     * @param array $requestHeader
81
     * @return SwaggerRequester
82
     */
83
    public function withRequestHeader($requestHeader)
84
    {
85
        if (is_null($requestHeader)) {
86
            $this->requestHeader = [];
87
            return $this;
88
        }
89
90
        $this->requestHeader = array_merge($this->requestHeader, $requestHeader);
91
92
        return $this;
93
    }
94
95
    /**
96
     * @param array $query
97
     * @return SwaggerRequester
98
     */
99
    public function withQuery($query)
100
    {
101
        if (is_null($query)) {
102
            $this->query = [];
103
            return $this;
104
        }
105
106
        $this->query = array_merge($this->query, $query);
107
108
        return $this;
109
    }
110
111
    /**
112
     * @param null $requestBody
113
     * @return SwaggerRequester
114
     */
115
    public function withRequestBody($requestBody)
116
    {
117
        $this->requestBody = $requestBody;
118
119
        return $this;
120
    }
121
122
    public function assertResponseCode($code)
123
    {
124
        $this->statusExpected = $code;
125
126
        return $this;
127
    }
128
129
    public function assertHeaderContains($header, $contains)
130
    {
131
        $this->assertHeader[$header] = $contains;
132
133
        return $this;
134
    }
135
136
    /**
137
     * @return mixed
138
     * @throws Exception\DefinitionNotFoundException
139
     * @throws Exception\GenericSwaggerException
140
     * @throws Exception\HttpMethodNotFoundException
141
     * @throws Exception\InvalidDefinitionException
142
     * @throws Exception\InvalidRequestException
143
     * @throws Exception\PathNotFoundException
144
     * @throws Exception\RequiredArgumentNotFound
145
     * @throws NotMatchedException
146
     * @throws StatusCodeNotMatchedException
147
     * @throws GuzzleException
148
     */
149
    public function send()
150
    {
151
        // Preparing Parameters
152
        $paramInQuery = null;
153
        if (!empty($this->query)) {
154
            $paramInQuery = '?' . http_build_query($this->query);
155
        }
156
157
        // Preparing Header
158
        if (empty($this->requestHeader)) {
159
            $this->requestHeader = [];
160
        }
161
        $header = array_merge(
162
            [
163
                'Accept' => 'application/json'
164
            ],
165
            $this->requestHeader
166
        );
167
168
        // Defining Variables
169
        $serverUrl = null;
0 ignored issues
show
Unused Code introduced by
$serverUrl is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
170
        $basePath = "";
171
        $pathName = "";
172
        if ($this->swaggerSchema->getSpecificationVersion() === '3') {
173
            $serverUrl = $this->swaggerSchema->getServerUrl();
174
        } else {
175
            $httpSchema = $this->swaggerSchema->getHttpSchema();
176
            $host = $this->swaggerSchema->getHost();
177
            $basePath = $this->swaggerSchema->getBasePath();
178
            $pathName = $this->path;
179
            $serverUrl = "$httpSchema://$host$basePath$pathName$paramInQuery";
180
        }
181
182
        // Check if the body is the expected before request
183
        $bodyRequestDef = $this->swaggerSchema->getRequestParameters("$basePath$pathName", $this->method);
184
        $bodyRequestDef->match($this->requestBody);
185
186
        // Make the request
187
        $request = new Request(
188
            $this->method,
189
            $serverUrl,
190
            $header,
191
            json_encode($this->requestBody)
192
        );
193
194
        $statusReturned = null;
195
        try {
196
            $response = $this->guzzleHttpClient->send($request, ['allow_redirects' => false]);
197
            $responseHeader = $response->getHeaders();
198
            $responseBody = json_decode((string) $response->getBody(), true);
199
            $statusReturned = $response->getStatusCode();
200
        } catch (BadResponseException $ex) {
201
            $responseHeader = $ex->getResponse()->getHeaders();
202
            $responseBody = json_decode((string) $ex->getResponse()->getBody(), true);
203
            $statusReturned = $ex->getResponse()->getStatusCode();
204
        }
205
206
        // Assert results
207
        if ($this->statusExpected != $statusReturned) {
208
            throw new StatusCodeNotMatchedException(
209
                "Status code not matched $statusReturned",
210
                $responseBody
211
            );
212
        }
213
214
        $bodyResponseDef = $this->swaggerSchema->getResponseParameters(
215
            "$basePath$pathName",
216
            $this->method,
217
            $this->statusExpected
218
        );
219
        $bodyResponseDef->match($responseBody);
220
221
        if (count($this->assertHeader) > 0) {
222
            foreach ($this->assertHeader as $key => $value) {
223
                if (!isset($responseHeader[$key]) || strpos($responseHeader[$key][0], $value) === false) {
224
                    throw new NotMatchedException(
225
                        "Does not exists header '$key' with value '$value'",
226
                        $responseHeader
227
                    );
228
                }
229
            }
230
        }
231
232
        return $responseBody;
233
    }
234
}
235