summaryrefslogtreecommitdiffstats
path: root/vendor/gipfl/json/src/SerializationHelper.php
blob: 0714e3011e305f89b4106b40b34f25c38f1abfff (plain)
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
<?php

namespace gipfl\Json;

use InvalidArgumentException;
use JsonSerializable;
use stdClass;

class SerializationHelper
{
    /**
     * TODO: Check whether json_encode() is faster
     *
     * @param mixed $value
     * @return bool
     */
    public static function assertSerializableValue($value)
    {
        if ($value === null || is_scalar($value)) {
            return true;
        }
        if (is_object($value)) {
            if ($value instanceof JsonSerializable) {
                return true;
            }

            if ($value instanceof stdClass) {
                foreach ((array) $value as $val) {
                    static::assertSerializableValue($val);
                }

                return true;
            }
        }

        if (is_array($value)) {
            foreach ($value as $val) {
                static::assertSerializableValue($val);
            }

            return true;
        }

        throw new InvalidArgumentException('Serializable value expected, got ' . static::getPhpType($value));
    }

    public static function getPhpType($var)
    {
        if (is_object($var)) {
            return get_class($var);
        }

        return gettype($var);
    }
}