1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace MelhorEnvio\Resources; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use GuzzleHttp\Client; |
7
|
|
|
use GuzzleHttp\ClientInterface; |
8
|
|
|
use MelhorEnvio\Enums\Endpoint; |
9
|
|
|
use MelhorEnvio\Enums\Environment; |
10
|
|
|
use MelhorEnvio\Exceptions\InvalidEnvironmentException; |
11
|
|
|
|
12
|
|
|
abstract class Base implements Resource |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var string |
16
|
|
|
*/ |
17
|
|
|
protected $token; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var string |
21
|
|
|
*/ |
22
|
|
|
protected $environment; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var ClientInterface |
26
|
|
|
*/ |
27
|
|
|
protected $http; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param $token |
31
|
|
|
* @param $environment |
32
|
|
|
*/ |
33
|
|
|
public function __construct($token, $environment = null) |
34
|
|
|
{ |
35
|
|
|
$this->token = $token; |
36
|
|
|
|
37
|
|
|
$this->setEnvironment($environment ? $environment : Environment::SANDBOX); |
38
|
|
|
|
39
|
|
|
$this->http = new Client([ |
40
|
|
|
'base_uri' => Endpoint::ENDPOINTS[$this->environment] . '/api/' . Endpoint::VERSIONS[$this->environment] . '/', |
41
|
|
|
'headers' => [ |
42
|
|
|
'Authorization' => 'Bearer ' . $this->token, |
43
|
|
|
'Accept' => 'application/json', |
44
|
|
|
] |
45
|
|
|
]); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @return string |
50
|
|
|
*/ |
51
|
|
|
public function getEnvironment() |
52
|
|
|
{ |
53
|
|
|
return $this->environment; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param string $environment |
58
|
|
|
* @return void |
59
|
|
|
*/ |
60
|
|
|
public function setEnvironment($environment) |
61
|
|
|
{ |
62
|
|
|
if (! in_array($environment, Environment::ENVIRONMENTS)) { |
63
|
|
|
throw new InvalidEnvironmentException; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
$this->environment = $environment; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Get Http Client |
71
|
|
|
* @return ClientInterface |
72
|
|
|
*/ |
73
|
|
|
public function getHttp() |
74
|
|
|
{ |
75
|
|
|
return $this->http; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* Set Http Client |
80
|
|
|
* |
81
|
|
|
* @param ClientInterface $http |
82
|
|
|
* @throws Exception |
83
|
|
|
*/ |
84
|
|
|
public function setHttp($http) |
85
|
|
|
{ |
86
|
|
|
if (! $http instanceof ClientInterface) { |
|
|
|
|
87
|
|
|
throw new Exception('The parameter passed is not an instance of ' . ClientInterface::class); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
$this->http = $http; |
91
|
|
|
} |
92
|
|
|
} |
93
|
|
|
|