Completed
Push — master ( 014efc...9ead79 )
by Leo
02:34
created

Methods::validate()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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