1<?php
2/*
3 * This file is part of PHPUnit.
4 *
5 * (c) Sebastian Bergmann <sebastian@phpunit.de>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10
11/**
12 * Constraint that asserts that a string is valid JSON.
13 */
14class PHPUnit_Framework_Constraint_IsJson extends PHPUnit_Framework_Constraint
15{
16    /**
17     * Evaluates the constraint for parameter $other. Returns true if the
18     * constraint is met, false otherwise.
19     *
20     * @param mixed $other Value or object to evaluate.
21     *
22     * @return bool
23     */
24    protected function matches($other)
25    {
26        if ($other === '') {
27            return false;
28        }
29
30        json_decode($other);
31        if (json_last_error()) {
32            return false;
33        }
34
35        return true;
36    }
37
38    /**
39     * Returns the description of the failure
40     *
41     * The beginning of failure messages is "Failed asserting that" in most
42     * cases. This method should return the second part of that sentence.
43     *
44     * @param mixed $other Evaluated value or object.
45     *
46     * @return string
47     */
48    protected function failureDescription($other)
49    {
50        if ($other === '') {
51            return 'an empty string is valid JSON';
52        }
53
54        json_decode($other);
55        $error = PHPUnit_Framework_Constraint_JsonMatches_ErrorMessageProvider::determineJsonError(
56            json_last_error()
57        );
58
59        return sprintf(
60            '%s is valid JSON (%s)',
61            $this->exporter->shortenedExport($other),
62            $error
63        );
64    }
65
66    /**
67     * Returns a string representation of the constraint.
68     *
69     * @return string
70     */
71    public function toString()
72    {
73        return 'is valid JSON';
74    }
75}
76