Passed
Push — master ( 9b86f1...395fc6 )
by Baptiste
03:46
created

src/Json/Context.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
    protected function getJson()
31
    {
32
        return json_decode((string) $this->getResponse()->getBody());
33
    }
34
35
    protected function getContentTypes(): array
36
    {
37
        return ['application/json'];
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->getResponse()->getHeaderLine('Content-Type'), 2);
0 ignored issues
show
The variable $contentType does not exist. Did you forget to declare it?

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.

Loading history...
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->getContentTypes(), 'The response should have a valid content-type (expected one of %2$s, got %1$s)');
57
    }
58
}
59