Completed
Pull Request — master (#40)
by Ulrich
01:53
created

AbstractRequester::withPath()   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 1
1
<?php
2
3
namespace ByJG\Swagger;
4
5
use ByJG\Swagger\Exception\NotMatchedException;
6
use ByJG\Swagger\Exception\StatusCodeNotMatchedException;
7
use GuzzleHttp\Exception\BadResponseException;
8
use GuzzleHttp\Exception\GuzzleException;
9
use GuzzleHttp\Psr7\Request;
10
use Psr\Http\Message\RequestInterface;
11
use Psr\Http\Message\ResponseInterface;
12
13
/**
14
 * Abstract baseclass for request handlers.
15
 *
16
 * The baseclass provides processing and verification of request and response.
17
 * It only delegates the actual message exchange to the derived class. For the
18
 * messages, it uses the PSR-7 implementation from Guzzle.
19
 *
20
 * This is an implementation of the Template Method Patttern
21
 * (https://en.wikipedia.org/wiki/Template_method_pattern).
22
 */
23
abstract class AbstractRequester
24
{
25
    protected $method = 'get';
26
    protected $path = '/';
27
    protected $requestHeader = [];
28
    protected $query = [];
29
    protected $requestBody = null;
30
    /**
31
     * @var SwaggerSchema
32
     */
33
    protected $swaggerSchema = null;
34
35
    protected $statusExpected = 200;
36
    protected $assertHeader = [];
37
38
    public function __construct()
39
    {
40
    }
41
42
    /**
43
     * abstract function to be implemented by derived classes
44
     *
45
     * This function must be implemented by derived classes. It should process
46
     * the given request and return an according response.
47
     *
48
     * @param RequestInterface $request
49
     * @return ResponseInterface
50
     */
51
    abstract protected function handleRequest(RequestInterface $request);
52
53
    /**
54
     * @param SwaggerSchema $schema
55
     * @return $this
56
     */
57
    public function withSwaggerSchema($schema)
58
    {
59
        $this->swaggerSchema = $schema;
60
61
        return $this;
62
    }
63
64
    /**
65
     * @return bool
66
     */
67
    public function hasSwaggerSchema()
68
    {
69
        return !empty($this->swaggerSchema);
70
    }
71
72
    /**
73
     * @param string $method
74
     * @return $this
75
     */
76
    public function withMethod($method)
77
    {
78
        $this->method = $method;
79
80
        return $this;
81
    }
82
83
    /**
84
     * @param string $path
85
     * @return $this
86
     */
87
    public function withPath($path)
88
    {
89
        $this->path = $path;
90
91
        return $this;
92
    }
93
94
    /**
95
     * @param array $requestHeader
96
     * @return $this
97
     */
98
    public function withRequestHeader($requestHeader)
99
    {
100
        if (is_null($requestHeader)) {
101
            $this->requestHeader = [];
102
            return $this;
103
        }
104
105
        $this->requestHeader = array_merge($this->requestHeader, $requestHeader);
106
107
        return $this;
108
    }
109
110
    /**
111
     * @param array $query
112
     * @return $this
113
     */
114
    public function withQuery($query)
115
    {
116
        if (is_null($query)) {
117
            $this->query = [];
118
            return $this;
119
        }
120
121
        $this->query = array_merge($this->query, $query);
122
123
        return $this;
124
    }
125
126
    /**
127
     * @param null $requestBody
128
     * @return $this
129
     */
130
    public function withRequestBody($requestBody)
131
    {
132
        $this->requestBody = $requestBody;
133
134
        return $this;
135
    }
136
137
    public function assertResponseCode($code)
138
    {
139
        $this->statusExpected = $code;
140
141
        return $this;
142
    }
143
144
    public function assertHeaderContains($header, $contains)
145
    {
146
        $this->assertHeader[$header] = $contains;
147
148
        return $this;
149
    }
150
151
    /**
152
     * @return mixed
153
     * @throws Exception\DefinitionNotFoundException
154
     * @throws Exception\GenericSwaggerException
155
     * @throws Exception\HttpMethodNotFoundException
156
     * @throws Exception\InvalidDefinitionException
157
     * @throws Exception\InvalidRequestException
158
     * @throws Exception\PathNotFoundException
159
     * @throws Exception\RequiredArgumentNotFound
160
     * @throws NotMatchedException
161
     * @throws StatusCodeNotMatchedException
162
     * @throws GuzzleException
163
     */
164
    public function send()
165
    {
166
        // Preparing Parameters
167
        $paramInQuery = null;
168
        if (!empty($this->query)) {
169
            $paramInQuery = '?' . http_build_query($this->query);
170
        }
171
172
        // Preparing Header
173
        if (empty($this->requestHeader)) {
174
            $this->requestHeader = [];
175
        }
176
        $header = array_merge(
177
            [
178
                'Accept' => 'application/json'
179
            ],
180
            $this->requestHeader
181
        );
182
183
        // Defining Variables
184
        $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...
185
        $basePath = "";
186
        $pathName = "";
187
        if ($this->swaggerSchema->getSpecificationVersion() === '3') {
188
            $serverUrl = $this->swaggerSchema->getServerUrl();
189
        } else {
190
            $httpSchema = $this->swaggerSchema->getHttpSchema();
191
            $host = $this->swaggerSchema->getHost();
192
            $basePath = $this->swaggerSchema->getBasePath();
193
            $pathName = $this->path;
194
            $serverUrl = "$httpSchema://$host$basePath$pathName$paramInQuery";
195
        }
196
197
        // Check if the body is the expected before request
198
        $bodyRequestDef = $this->swaggerSchema->getRequestParameters("$basePath$pathName", $this->method);
199
        $bodyRequestDef->match($this->requestBody);
200
201
        // Make the request
202
        $request = new Request(
203
            $this->method,
204
            $serverUrl,
205
            $header,
206
            json_encode($this->requestBody)
207
        );
208
209
        $statusReturned = null;
210
        try {
211
            $response = $this->handleRequest($request);
212
            $responseHeader = $response->getHeaders();
213
            $responseBody = json_decode((string) $response->getBody(), true);
214
            $statusReturned = $response->getStatusCode();
215
        } catch (BadResponseException $ex) {
216
            $responseHeader = $ex->getResponse()->getHeaders();
217
            $responseBody = json_decode((string) $ex->getResponse()->getBody(), true);
218
            $statusReturned = $ex->getResponse()->getStatusCode();
219
        }
220
221
        // Assert results
222
        if ($this->statusExpected != $statusReturned) {
223
            throw new StatusCodeNotMatchedException(
224
                "Status code not matched $statusReturned",
225
                $responseBody
226
            );
227
        }
228
229
        $bodyResponseDef = $this->swaggerSchema->getResponseParameters(
230
            "$basePath$pathName",
231
            $this->method,
232
            $this->statusExpected
233
        );
234
        $bodyResponseDef->match($responseBody);
235
236
        if (count($this->assertHeader) > 0) {
237
            foreach ($this->assertHeader as $key => $value) {
238
                if (!isset($responseHeader[$key]) || strpos($responseHeader[$key][0], $value) === false) {
239
                    throw new NotMatchedException(
240
                        "Does not exists header '$key' with value '$value'",
241
                        $responseHeader
242
                    );
243
                }
244
            }
245
        }
246
247
        return $responseBody;
248
    }
249
}
250