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

RequestMethods   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Test Coverage

Coverage 37.04%

Importance

Changes 0
Metric Value
wmc 12
dl 0
loc 67
rs 10
c 0
b 0
f 0
ccs 10
cts 27
cp 0.3704

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getRequestString() 0 9 2
A getResult() 0 3 1
A getMethodName() 0 3 1
A setResult() 0 8 3
B export() 0 20 5
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