Passed
Push — master ( f881c5...014efc )
by Leo
02:57
created

Methods::import()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
namespace leocata\M1\Abstracts;
4
5
use leocata\M1\Exceptions\MissingMandatoryField;
6
use leocata\M1\Interfaces\MethodDefinitions;
7
8
/**
9
 * Class Methods
10
 * @package leocata\M1\Abstracts
11
 */
12
abstract class Methods implements MethodDefinitions
13
{
14
15
    /**
16
     * Import data from json string
17
     *
18
     * @param $data \stdClass
19
     * @return bool
20
     */
21
    final public function import(\stdClass $data)
22
    {
23
        foreach ($data as $key => $value) {
24
            $this->$key = $value;
25
        }
26
27
        return $this->isValid();
28
    }
29
30
    /**
31
     * Validate properties
32
     * @return bool
33
     */
34
    final protected function isValid(): bool
35
    {
36
        $fields = $this->getMandatoryFields();
37
        foreach ($this as $key => $value) {
38
            if ($this->$key === null && in_array($key, $fields, true)) {
39
                throw new MissingMandatoryField(sprintf(
40
                    'The field "%s" is mandatory and empty, please correct',
41
                    $key
42
                ));
43
            }
44
        }
45
46
        return true;
47
    }
48
49
    /**
50
     * Export data
51
     * @return bool|Methods
52
     * @internal param Methods $data
53
     * @internal param Methods $method
54
     */
55
    final public function export()
56
    {
57
58
        foreach ($this as $key => $value) {
59
            $this->$key = $value;
60
        }
61
62
        return $this->isValid() ? $this : false;
63
    }
64
65
    /**
66
     * Convert method name to api
67
     * @return string
68
     */
69
    final public function getMethodName(): string
70
    {
71
        return lcfirst((new \ReflectionClass($this))->getShortName());
72
    }
73
}
74