1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
namespace Behapi\Json; |
3
|
|
|
|
4
|
|
|
use stdClass; |
5
|
|
|
use InvalidArgumentException; |
6
|
|
|
|
7
|
|
|
use Webmozart\Assert\Assert; |
8
|
|
|
|
9
|
|
|
use Behapi\Http\Response; |
10
|
|
|
use Behapi\HttpHistory\History as HttpHistory; |
11
|
|
|
|
12
|
|
|
use function sprintf; |
13
|
|
|
|
14
|
|
|
use function json_decode; |
15
|
|
|
use function json_last_error; |
16
|
|
|
use function json_last_error_msg; |
17
|
|
|
|
18
|
|
|
use const JSON_ERROR_NONE; |
19
|
|
|
|
20
|
|
|
class Context extends AbstractContext |
21
|
|
|
{ |
22
|
|
|
use Response; |
23
|
|
|
|
24
|
|
|
public function __construct(HttpHistory $history) |
25
|
|
|
{ |
26
|
|
|
parent::__construct(); |
27
|
|
|
$this->history = $history; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** {@inheritDoc} */ |
31
|
|
|
protected function getJson() |
32
|
|
|
{ |
33
|
|
|
return json_decode((string) $this->getResponse()->getBody()); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
protected function getContentTypes(): array |
37
|
|
|
{ |
38
|
|
|
return ['application/json']; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @Then the response should be a valid json response |
43
|
|
|
* |
44
|
|
|
* --- |
45
|
|
|
* |
46
|
|
|
* This method is built-on the default php's json extension. You should |
47
|
|
|
* overwrite it if you want to add supplementary checks or use something |
48
|
|
|
* else instead (such as Seldaek's JsonLint package). |
49
|
|
|
*/ |
50
|
|
|
public function responseIsValidjson() |
51
|
|
|
{ |
52
|
|
|
$this->getJson(); |
53
|
|
|
|
54
|
|
|
[$contentType,] = explode(';', $this->getResponse()->getHeaderLine('Content-Type'), 2); |
|
|
|
|
55
|
|
|
|
56
|
|
|
Assert::same(JSON_ERROR_NONE, json_last_error(), sprintf('The response is not a valid json (%s)', json_last_error_msg())); |
57
|
|
|
Assert::oneOf($contentType, $this->getContentTypes(), 'The response should have a valid content-type (expected one of %2$s, got %1$s)'); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.