Completed
Push — master ( 18ad07...f11cd8 )
by Byron
02:09
created

Resource::jsonSerialize()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
ccs 9
cts 9
cp 1
rs 9.4285
cc 3
eloc 7
nc 3
nop 0
crap 3
1
<?php
2
/**
3
 * This file is part of the badams\GoogleUrl library
4
 *
5
 * @license http://opensource.org/licenses/MIT
6
 * @link https://github.com/badams/google-url
7
 * @package badams/google-url
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
namespace badams\GoogleUrl;
14
15
/**
16
 * Class Resource
17
 * @package badams\GoogleUrl\Resource
18
 */
19
abstract class Resource implements \JsonSerializable
20
{
21
    /**
22
     * @param \stdClass $json
23
     * @return static
24
     */
25 6
    public static function createFromJson(\stdClass $json)
26
    {
27 6
        $resource = new static;
28 6
        $class = new \ReflectionClass($resource);
29
30 6
        foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
31 6
            if (isset($json->{$property->getName()})) {
32 6
                $resource->{$property->getName()} = $json->{$property->getName()};
33 4
            }
34 4
        }
35
36 6
        return $resource;
37
    }
38
39
    /**
40
     * Serialize this resource into an array for json
41
     *
42
     * @return array
43
     */
44 12
    public function jsonSerialize()
45
    {
46 12
        $class = new \ReflectionClass($this);
47 12
        $json = [];
48
49 12
        foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
50 12
            if (null !== ($value = $property->getValue($this))) {
51 12
                $json[$property->getName()] = $value;
52 8
            }
53 8
        }
54
55 12
        return $json;
56
    }
57
}