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

Api::performApiRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 8
nc 1
nop 1
1
<?php
2
3
namespace leocata\M1;
4
5
use leocata\M1\Abstracts\Methods;
6
use leocata\M1\Exceptions\JsonParserException;
7
8
/**
9
 * Class Api
10
 * @package leocata\M1
11
 */
12
class Api
13
{
14
15
    const RESPONSE_METHOD_ALIAS = 'Response';
16
    const REQUEST_METHOD_ALIAS = 'Request';
17
    private $method;
18
    private $methodType;
19
20
    /**
21
     * @param $data
22
     * @return string
23
     */
24
    public function getApiResponse(string $data)
25
    {
26
        $this->methodType = self::RESPONSE_METHOD_ALIAS;
27
        $data = $this->parseData($data);
28
        $this->method = $this->setMethod($data->method);
29
        $this->method->import($data->params);
30
31
        return $this->method;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->method returns the type leocata\M1\Abstracts\Methods which is incompatible with the documented return type string.
Loading history...
32
    }
33
34
    private function parseData($data)
35
    {
36
        $data = $this->methodType === self::REQUEST_METHOD_ALIAS ? json_encode($data) : json_decode($data);
37
38
        if ($data === null) {
39
            throw new JsonParserException(sprintf(
40
                'JSON decode error: "%s"',
41
                json_last_error_msg()
42
            ));
43
        }
44
45
        return $data;
46
    }
47
48
    /**
49
     * @param $data Methods
50
     * @return string
51
     */
52
    public function sendApiRequest(Methods $data): string
53
    {
54
        $this->methodType = self::REQUEST_METHOD_ALIAS;
55
        $this->method = $data;
56
        $this->method->export();
57
58
        return $this->parseData(['method' => $this->method->getMethodName(), 'params' => $this->method]);
59
    }
60
61
    /**
62
     * @return Methods
63
     */
64
    public function getMethod(): Methods
65
    {
66
        return $this->method;
67
    }
68
69
    /**
70
     * @param $method
71
     * @return Methods
72
     * @internal param string $alias
73
     */
74
    public function setMethod($method): Methods
75
    {
76
        class_alias('\leocata\M1\Methods\\' . $this->methodType . '\\' . $method, $method);
77
78
        return new $method();
0 ignored issues
show
Bug Best Practice introduced by
The expression return new $method() returns the type object which includes types incompatible with the type-hinted return leocata\M1\Abstracts\Methods.
Loading history...
79
    }
80
}
81