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
|
|
|
private static $callbacks = []; |
18
|
|
|
protected $logger; |
19
|
|
|
private $client; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param LoggerInterface $logger |
23
|
|
|
*/ |
24
|
2 |
|
public function __construct(LoggerInterface $logger = null) |
25
|
|
|
{ |
26
|
2 |
|
if ($logger === null) { |
27
|
2 |
|
$logger = new DummyLogger(); |
28
|
|
|
} |
29
|
2 |
|
$this->logger = $logger; |
30
|
2 |
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param $name |
34
|
|
|
* @param \Closure $func |
35
|
|
|
* |
36
|
|
|
* @throws \BadFunctionCallException |
37
|
|
|
*/ |
38
|
|
|
public static function doCallback($name, \Closure $func) |
39
|
|
|
{ |
40
|
|
|
if (array_key_exists($name, self::$callbacks)) { |
41
|
|
|
if (!is_callable($func)) { |
42
|
|
|
throw new \BadFunctionCallException(); |
43
|
|
|
} |
44
|
|
|
call_user_func($func); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param string $data |
50
|
|
|
* |
51
|
|
|
* @throws MethodNotFound | MissingMandatoryField |
52
|
|
|
* |
53
|
|
|
* @return bool|CallbackMethods |
54
|
|
|
*/ |
55
|
1 |
|
public function getCallbackMethod(string $data) |
56
|
|
|
{ |
57
|
1 |
|
$data = \GuzzleHttp\json_decode($data); |
58
|
1 |
|
if (empty($data->method)) { |
59
|
|
|
return false; |
60
|
|
|
} |
61
|
|
|
|
62
|
1 |
|
$class = '\leocata\M1\Methods\Callback\\'.ucfirst($data->method); |
63
|
|
|
|
64
|
1 |
|
if (!class_exists($class)) { |
65
|
|
|
throw new MethodNotFound(sprintf( |
66
|
|
|
'The method "%s" not found, please correct', |
67
|
|
|
$class |
68
|
|
|
)); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** @var \leocata\M1\Abstracts\CallbackMethods $method */ |
72
|
1 |
|
$method = new $class(); |
73
|
1 |
|
$method->import($data->params ?? new \stdClass()); |
74
|
1 |
|
self::$callbacks += ['after'.$method->getMethodName() => $method]; |
75
|
|
|
|
76
|
1 |
|
return $method; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* Performs the request to the Api servers. |
81
|
|
|
* |
82
|
|
|
* @param RequestMethods $method |
83
|
|
|
* @param Authorization $auth |
84
|
|
|
* @return RequestMethods |
85
|
|
|
*/ |
86
|
|
|
public function sendRequest(RequestMethods $method, Authorization $auth) |
87
|
|
|
{ |
88
|
|
|
$this->client = new HttpClient($auth); |
89
|
|
|
$response = $this->client->getResponseContent($method->getRequestString()); |
90
|
|
|
if (!empty($response)) { |
91
|
|
|
$method->setResult($response); |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
return $method; |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|