Completed
Push — master ( 44a125...86a7fc )
by Leo
01:54
created

Api::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace leocata\M1;
4
5
use leocata\M1\Abstracts\CallbackMethods;
6
use leocata\M1\Abstracts\RequestMethods;
7
use leocata\M1\Exceptions\MethodNotFound;
8
use leocata\M1\Exceptions\MissingMandatoryField;
9
use leocata\M1\InternalFunctionality\DummyLogger;
10
use Psr\Log\LoggerInterface;
11
12
/**
13
 * Class Api.
14
 */
15
class Api
16
{
17
    protected $logger;
18
    private $client;
19
20
    /**
21
     * @param LoggerInterface $logger
22
     */
23 2
    public function __construct(LoggerInterface $logger = null)
24
    {
25 2
        if ($logger === null) {
26 2
            $logger = new DummyLogger();
27
        }
28 2
        $this->logger = $logger;
29 2
    }
30
31
    /**
32
     * @param string $data
33
     *
34
     * @throws MethodNotFound | MissingMandatoryField
35
     *
36
     * @return bool|CallbackMethods
37
     */
38 1
    public function getCallbackMethod(string $data)
39
    {
40 1
        $data = \GuzzleHttp\json_decode($data);
41 1
        if (empty($data->method)) {
42
            return false;
43
        }
44
45 1
        $class = '\leocata\M1\Methods\Callback\\'.ucfirst($data->method);
46
47 1
        if (!class_exists($class)) {
48
            throw new MethodNotFound(sprintf(
49
                'The method "%s" not found, please correct',
50
                $class
51
            ));
52
        }
53
54
        /** @var \leocata\M1\Abstracts\CallbackMethods $method */
55 1
        $method = new $class();
56 1
        $method->import($data->params ?? new \stdClass());
57
58 1
        return $method;
59
    }
60
61
    /**
62
     * Performs the request to the Api servers.
63
     *
64
     * @param RequestMethods $method
65
     * @param Authorization $auth
66
     * @return RequestMethods
67
     */
68
    public function sendRequest(RequestMethods $method, Authorization $auth)
69
    {
70
        $this->client = new HttpClient($auth);
71
        $response = $this->client->getResponseContent($method->getRequestString());
72
        if (!empty($response)) {
73
            $method->setResult($response);
74
        }
75
76
        return $method;
77
    }
78
}
79