Completed
Push — master ( 048bf8...346c21 )
by Leo
03:28
created

RequestMethods::export()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.1158

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 8.8571
c 0
b 0
f 0
ccs 10
cts 12
cp 0.8333
cc 5
eloc 12
nc 6
nop 0
crap 5.1158
1
<?php
2
3
namespace leocata\M1\Abstracts;
4
5
use leocata\M1\Exceptions\MissingMandatoryField;
6
use leocata\M1\Interfaces\MethodDefinitions;
7
8
abstract class RequestMethods implements MethodDefinitions
9
{
10
11
    private $result;
12
13
    /**
14
     * @return mixed
15
     */
16
    final public function getResult()
17
    {
18
        return $this->result;
19
    }
20
21
    final public function setResult($data)
22
    {
23
        if (is_array($data->result)) {
24
            foreach ($data->result as $key => $value) {
25
                $this->result[$key] = $value;
26
            }
27
        } else {
28
            $this->result = $data;
29
        }
30
    }
31
32
    /**
33
     * @return string
34
     */
35
    final public function getRequestString()
36
    {
37
        $request = ['method' => $this->getMethodName()];
38
39
        if (!empty($params = $this->export())) {
40
            $request += ['params' => $params];
41
        }
42
43
        return \GuzzleHttp\json_encode($request);
44
    }
45
46
    /**
47
     * @return array
48
     * @throws MissingMandatoryField
49
     */
50 2
    final public function export()
51
    {
52 2
        $finalArray = [];
53 2
        $mandatoryFields = $this->getMandatoryFields();
54
55 2
        $cleanObject = new $this();
56 2
        foreach ($cleanObject as $fieldId => $value) {
57 2
            if ($this->$fieldId === $cleanObject->$fieldId) {
58 2
                if (in_array($fieldId, $mandatoryFields, true)) {
59 2
                    throw new MissingMandatoryField(sprintf(
60 2
                        'The field "%s" is mandatory and empty, please correct',
61 2
                        $fieldId
62
                    ));
63
                }
64
            } else {
65
                $finalArray[$fieldId] = $this->$fieldId;
66
            }
67
        }
68
69
        return empty($finalArray) ? null : $finalArray;
70
    }
71
72
    final public function getMethodName(): string
73
    {
74
        return lcfirst((new \ReflectionClass($this))->getShortName());
75
    }
76
}
77