Completed
Push — master ( 362581...591230 )
by Алексей
08:11
created

BaseType::createFromJson()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: akeinhell
5
 * Date: 27.06.16
6
 * Time: 11:58
7
 */
8
9
namespace Telegram\Base;
10
11
12
use Telegram\Helpers\AnnotationHelper;
13
14
/**
15
 * https://core.telegram.org/bots/api#available-types
16
 * Class BaseType
17
 * @package Telegram\Base
18
 */
19
class BaseType
20 1
{
21
    /**
22 1
     * BaseType constructor.
23
     * @param array $data
24
     */
25 1
    public function __construct($data)
26 1
    {
27 1
        if (!is_array($data)) {
28
            return $data;
29
        }
30
        foreach ($data as $key => $value) {
31
            $key          = $this->toCamelCase($key);
32 1
            $annotatinons = AnnotationHelper::getAnnotations($this, $key);
33 1
34 1
            if ($annotatinons && array_key_exists('var', $annotatinons)) {
35
                $class = '\\Telegram\\Types\\' . $annotatinons['var'];
36 1
                if (class_exists($class)) {
37 1
                    /** @var BaseType $class */
38 1
                    $this->$key = $class::create($value);
39 1
                    continue;
40 1
                }
41
            }
42
43
            if (!property_exists($this, $key)) {
44
                $this->$key = $value;
45
                continue;
46 1
            }
47
        }
48 1
    }
49
50
    /**
51
     * @param $data
52
     * @return static
53
     */
54
    public static function create($data)
55
    {
56
        return new static($data);
57
    }
58
59
    /**
60
     * @param $json
61
     * @return static
62
     */
63
    public static function createFromJson($json)
64
    {
65
        return new static(json_decode($json, true));
66
    }
67
68
    /**
69
     * @param $key
70
     * @return string
71
     */
72
    private function toCamelCase($key)
73
    {
74
        return lcfirst(implode(array_map(function ($part) {
75
            return ucfirst($part);
76
        }, explode('_', $key))));
77
78
    }
79
}