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\HttpHistory\History as HttpHistory; |
10
|
|
|
|
11
|
|
|
use function sprintf; |
12
|
|
|
|
13
|
|
|
use function json_decode; |
14
|
|
|
use function json_last_error; |
15
|
|
|
use function json_last_error_msg; |
16
|
|
|
|
17
|
|
|
use const JSON_ERROR_NONE; |
18
|
|
|
|
19
|
|
|
class Context extends AbstractContext |
20
|
|
|
{ |
21
|
|
|
/** @var HttpHistory */ |
22
|
|
|
private $history; |
23
|
|
|
|
24
|
|
|
/** @var string[] */ |
25
|
|
|
private $contentTypes; |
26
|
|
|
|
27
|
|
|
public function __construct(HttpHistory $history, array $contentTypes = ['application/json']) |
28
|
|
|
{ |
29
|
|
|
parent::__construct(); |
30
|
|
|
|
31
|
|
|
$this->history = $history; |
32
|
|
|
$this->contentTypes = $contentTypes; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
protected function getJson() |
36
|
|
|
{ |
37
|
|
|
return json_decode((string) $this->history->getLastResponse()->getBody()); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @Then the response should be a valid json response |
42
|
|
|
* |
43
|
|
|
* --- |
44
|
|
|
* |
45
|
|
|
* This method is built-on the default php's json extension. You should |
46
|
|
|
* overwrite it if you want to add supplementary checks or use something |
47
|
|
|
* else instead (such as Seldaek's JsonLint package). |
48
|
|
|
*/ |
49
|
|
|
public function response_should_be_a_valid_json_response() |
50
|
|
|
{ |
51
|
|
|
$this->getJson(); |
52
|
|
|
|
53
|
|
|
[$contentType,] = explode(';', $this->history->getLastResponse()->getHeaderLine('Content-Type'), 2); |
54
|
|
|
|
55
|
|
|
Assert::same(JSON_ERROR_NONE, json_last_error(), sprintf('The response is not a valid json (%s)', json_last_error_msg())); |
56
|
|
|
Assert::oneOf($contentType, $this->contentTypes, 'The response should have a valid content-type (expected one of %2$s, got %1$s)'); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|