File: JsonTestCase.php

package info (click to toggle)
php-ml-json-ld 1.2.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 628 kB
  • sloc: php: 4,521; makefile: 21
file content (64 lines) | stat: -rw-r--r-- 1,714 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php

/*
 * (c) Markus Lanthaler <mail@markus-lanthaler.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ML\JsonLD\Test;

/**
 * A JSON Test Case
 *
 * This class extends {@link \PHPUnit_Framework_TestCase} with an assertion
 * to compare JSON.
 *
 * @author Markus Lanthaler <mail@markus-lanthaler.com>
 */
abstract class JsonTestCase extends \PHPUnit\Framework\TestCase
{
    /**
     * Asserts that two JSON structures are equal.
     *
     * @param  object|array $expected
     * @param  object|array $actual
     * @param  string $message
     */
    public static function assertJsonEquals($expected, $actual, $message = '')
    {
        $expected = self::normalizeJson($expected);
        $actual = self::normalizeJson($actual);

        self::assertEquals($expected, $actual, $message);
    }

    /**
     * Brings the keys of objects to a deterministic order to enable
     * comparison of JSON structures
     *
     * @param mixed $element The element to normalize.
     *
     * @return mixed The same data with all object keys ordered in a
     *               deterministic way.
     */
    private static function normalizeJson($element)
    {
        if (is_array($element)) {
            foreach ($element as &$item) {
                $item = self::normalizeJson($item);
            }
        } elseif (is_object($element)) {
            $element = (array) $element;
            ksort($element);
            $element = (object) $element;

            foreach ($element as &$item) {
                $item = self::normalizeJson($item);
            }
        }

        return $element;
    }
}