Completed
Pull Request — master (#48)
by John
02:30
created

ApiTestCase::getJsonForLastRequest()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 37
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 37
rs 8.439
cc 6
eloc 25
nc 9
nop 2
1
<?php
2
/*
3
 * This file is part of the KleijnWeb\SwaggerBundle package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace KleijnWeb\SwaggerBundle\Test;
10
11
use FR3D\SwaggerAssertions\PhpUnit\AssertsTrait;
12
use FR3D\SwaggerAssertions\SchemaManager;
13
use JsonSchema\Validator;
14
use KleijnWeb\SwaggerBundle\Document\SwaggerDocument;
15
use org\bovigo\vfs\vfsStream;
16
use org\bovigo\vfs\vfsStreamDirectory;
17
use org\bovigo\vfs\vfsStreamWrapper;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\HttpFoundation\Response;
20
use Symfony\Component\Yaml\Yaml;
21
22
/**
23
 * @author John Kleijn <[email protected]>
24
 */
25
trait ApiTestCase
26
{
27
    use AssertsTrait;
28
29
    /**
30
     * @var SchemaManager
31
     */
32
    protected static $schemaManager;
33
34
    /**
35
     * @var SwaggerDocument
36
     */
37
    protected static $document;
38
39
    /**
40
     * @var ApiTestClient
41
     */
42
    protected $client;
43
44
    /**
45
     * PHPUnit cannot add this to code coverage
46
     *
47
     * @codeCoverageIgnore
48
     *
49
     * @param $swaggerPath
50
     *
51
     * @throws \InvalidArgumentException
52
     * @throws \org\bovigo\vfs\vfsStreamException
53
     */
54
    public static function initSchemaManager($swaggerPath)
55
    {
56
        $validator = new Validator();
57
        $validator->check(
58
            json_decode(json_encode(Yaml::parse(file_get_contents($swaggerPath)))),
59
            json_decode(file_get_contents(__DIR__ . '/../../assets/swagger-schema.json'))
60
        );
61
62
        if (!$validator->isValid()) {
63
            throw new \InvalidArgumentException(
64
                "Swagger '$swaggerPath' not valid"
65
            );
66
        }
67
68
        vfsStreamWrapper::register();
69
        vfsStreamWrapper::setRoot(new vfsStreamDirectory('root'));
70
71
        file_put_contents(
72
            vfsStream::url('root') . '/swagger.json',
73
            json_encode(Yaml::parse(file_get_contents($swaggerPath)))
74
        );
75
76
        self::$schemaManager = new SchemaManager(vfsStream::url('root') . '/swagger.json');
77
        self::$document = new SwaggerDocument($swaggerPath);
78
    }
79
80
    /**
81
     * Create a client, booting the kernel using SYMFONY_ENV = $this->env
82
     */
83
    protected function setUp()
84
    {
85
        $this->client = static::createClient(['environment' => $this->env ?: 'test', 'debug' => true]);
0 ignored issues
show
Bug introduced by
The property env does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
86
87
        parent::setUp();
88
    }
89
90
91
    /**
92
     * @param string $path
93
     * @param array  $params
94
     *
95
     * @return object
96
     * @throws ApiResponseErrorException
97
     */
98
    protected function get($path, array $params = [])
99
    {
100
        return $this->sendRequest($path, 'GET', $params);
0 ignored issues
show
Documentation introduced by
'GET' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
101
    }
102
103
    /**
104
     * @param string $path
105
     * @param array  $params
106
     *
107
     * @return object
108
     * @throws ApiResponseErrorException
109
     */
110
    protected function delete($path, array $params = [])
111
    {
112
        return $this->sendRequest($path, 'DELETE', $params);
0 ignored issues
show
Documentation introduced by
'DELETE' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
113
    }
114
115
    /**
116
     * @param string $path
117
     * @param array  $content
118
     * @param array  $params
119
     *
120
     * @return object
121
     * @throws ApiResponseErrorException
122
     */
123
    protected function patch($path, array $content, array $params = [])
124
    {
125
        return $this->sendRequest($path, 'PATCH', $params, $content);
0 ignored issues
show
Documentation introduced by
'PATCH' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
126
    }
127
128
    /**
129
     * @param string $path
130
     * @param array  $content
131
     * @param array  $params
132
     *
133
     * @return object
134
     * @throws ApiResponseErrorException
135
     */
136
    protected function post($path, array $content, array $params = [])
137
    {
138
        return $this->sendRequest($path, 'POST', $params, $content);
0 ignored issues
show
Documentation introduced by
'POST' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
139
    }
140
141
    /**
142
     * @param string $path
143
     * @param array  $content
144
     * @param array  $params
145
     *
146
     * @return object
147
     * @throws ApiResponseErrorException
148
     */
149
    protected function put($path, array $content, array $params = [])
150
    {
151
        return $this->sendRequest($path, 'PUT', $params, $content);
0 ignored issues
show
Documentation introduced by
'PUT' is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
152
    }
153
154
    /**
155
     * @param string     $path
156
     * @param array      $method
157
     * @param array      $params
158
     * @param array|null $content
159
     *
160
     * @return object
161
     * @throws ApiResponseErrorException
162
     */
163
    protected function sendRequest($path, $method, array $params = [], array $content = null)
164
    {
165
        $request = new ApiRequest($this->assembleUri($path, $params), $method);
0 ignored issues
show
Documentation introduced by
$method is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
166
        $defaults = isset($this->defaultServerVars) ? $this->defaultServerVars : [];
0 ignored issues
show
Bug introduced by
The property defaultServerVars does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
167
        $request->setServer(array_merge($defaults ?: [], ['CONTENT_TYPE' => 'application/json']));
168
        if ($content !== null) {
169
            $request->setContent(json_encode($content));
170
        }
171
        $this->client->requestFromRequest($request);
172
173
        return $this->getJsonForLastRequest($path, $method);
0 ignored issues
show
Documentation introduced by
$method is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
174
    }
175
176
177
    /**
178
     * @param string $path
179
     * @param array  $params
180
     *
181
     * @return string
182
     */
183
    private function assembleUri($path, array $params = [])
184
    {
185
        $uri = $path;
186
        if ($params) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $params 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...
187
            $uri = $path . '?' . http_build_query($params);
188
        }
189
190
        return $uri;
191
    }
192
193
    /**
194
     * @param string $fullPath
195
     * @param string $method
196
     *
197
     * @return object|null
198
     * @throws ApiResponseErrorException
199
     */
200
    private function getJsonForLastRequest($fullPath, $method)
201
    {
202
        $method = strtolower($method);
203
        $response = $this->client->getResponse();
204
        $responseContent = $response->getContent();
205
        $data = json_decode($responseContent);
206
207
        if ($response->getStatusCode() !== 204) {
208
            static $errors = [
209
                JSON_ERROR_NONE           => 'No error',
210
                JSON_ERROR_DEPTH          => 'Maximum stack depth exceeded',
211
                JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)',
212
                JSON_ERROR_CTRL_CHAR      => 'Control character error, possibly incorrectly encoded',
213
                JSON_ERROR_SYNTAX         => 'Syntax error',
214
                JSON_ERROR_UTF8           => 'Malformed UTF-8 characters, possibly incorrectly encoded'
215
            ];
216
            $error = json_last_error();
217
            $jsonErrorMessage = isset($errors[$error]) ? $errors[$error] : 'Unknown error';
218
            $this->assertSame(
0 ignored issues
show
Bug introduced by
It seems like assertSame() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
219
                JSON_ERROR_NONE,
220
                json_last_error(),
221
                "Not valid JSON: " . $jsonErrorMessage . "(" . var_export($responseContent, true) . ")"
222
            );
223
        }
224
225
        if (substr($response->getStatusCode(), 0, 1) != '2') {
226
            if (!isset($this->validateErrorResponse) || $this->validateErrorResponse) {
0 ignored issues
show
Bug introduced by
The property validateErrorResponse does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
227
                $this->validateResponse($response->getStatusCode(), $response, $method, $fullPath, $data);
228
            }
229
            // This throws an exception so that tests can catch it when it is expected
230
            throw new ApiResponseErrorException($data, $response->getStatusCode());
231
        }
232
233
        $this->validateResponse($response->getStatusCode(), $response, $method, $fullPath, $data);
234
235
        return $data;
236
    }
237
238
    /**
239
     * @param          $code
240
     * @param Response $response
241
     * @param string   $method
242
     * @param string   $fullPath
243
     * @param mixed    $data
244
     */
245
    private function validateResponse($code, $response, $method, $fullPath, $data)
246
    {
247
        $request = $this->client->getRequest();
248
        if (!self::$schemaManager->hasPath(['paths', $request->get('_swagger_path'), $method, 'responses', $code])) {
249
            if ($code === 404) {
250
                return;
251
            }
252
            throw new \UnexpectedValueException(
253
                "There is no $code response definition for {$request->get('_swagger_path')}:$method. "
254
            );
255
        }
256
        $headers = [];
257
258
        foreach ($response->headers->all() as $key => $values) {
259
            $headers[str_replace(' ', '-', ucwords(str_replace('-', ' ', $key)))] = $values[0];
260
        }
261
        $this->assertResponseHeadersMatch($headers, self::$schemaManager, $fullPath, $method, $code);
262
        $this->assertResponseBodyMatch($data, self::$schemaManager, $fullPath, $method, $code);
263
    }
264
}
265