1
|
|
|
<?php |
2
|
|
|
namespace LinusShops\CanadaPost; |
3
|
|
|
|
4
|
|
|
use GuzzleHttp\Client; |
5
|
|
|
use GuzzleHttp\Psr7\Request; |
6
|
|
|
use GuzzleHttp\Psr7\Response; |
7
|
|
|
|
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* |
11
|
|
|
* |
12
|
|
|
* @author Sam Schmidt <[email protected]> |
13
|
|
|
* @since 2015-12-09 |
14
|
|
|
* @company Linus Shops |
15
|
|
|
*/ |
16
|
|
|
abstract class Service |
17
|
|
|
{ |
18
|
|
|
const HTTP_GET = 'GET'; |
19
|
|
|
const HTTP_POST = 'POST'; |
20
|
|
|
const HTTP_PUT = 'PUT'; |
21
|
|
|
const HTTP_DELETE = 'DELETE'; |
22
|
|
|
const HTTP_PATCH = 'PATCH'; |
23
|
|
|
|
24
|
|
|
protected $baseUrl; |
25
|
|
|
protected $userid; |
26
|
|
|
protected $password; |
27
|
|
|
protected $parameters = array(); |
28
|
|
|
protected $headers = array( |
29
|
|
|
'Accept-language'=> 'en-CA' |
30
|
|
|
); |
31
|
|
|
|
32
|
4 |
|
public function __construct($baseUrl, $userid, $password) |
33
|
|
|
{ |
34
|
4 |
|
$this->baseUrl = $baseUrl; |
35
|
4 |
|
$this->userid = $userid; |
36
|
4 |
|
$this->password = $password; |
37
|
4 |
|
} |
38
|
|
|
|
39
|
|
|
public function setLanguage($value) |
40
|
|
|
{ |
41
|
|
|
$this->setHeader('Accept-language', $value); |
42
|
|
|
} |
43
|
|
|
|
44
|
3 |
|
public function setHeader($name, $value) |
45
|
|
|
{ |
46
|
3 |
|
$this->headers[$name] = $value; |
47
|
3 |
|
return $this; |
48
|
1 |
|
} |
49
|
|
|
|
50
|
3 |
|
public function hasParameter($name) |
51
|
|
|
{ |
52
|
3 |
|
return isset($this->parameters[$name]); |
53
|
|
|
} |
54
|
|
|
|
55
|
3 |
|
public function setParameter($name, $value) |
56
|
|
|
{ |
57
|
3 |
|
$this->parameters[$name] = $value; |
58
|
3 |
|
return $this; |
59
|
|
|
} |
60
|
|
|
|
61
|
3 |
|
public function getParameter($name, $default=null) |
62
|
|
|
{ |
63
|
3 |
|
return $this->hasParameter($name) ? |
64
|
3 |
|
$this->parameters[$name] : $default; |
65
|
1 |
|
} |
66
|
|
|
|
67
|
3 |
|
public function getBaseUrl() |
68
|
|
|
{ |
69
|
3 |
|
return $this->baseUrl; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @return Request |
74
|
|
|
*/ |
75
|
|
|
abstract protected function buildRequest(); |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @return Response |
79
|
|
|
*/ |
80
|
3 |
|
public function send() |
81
|
|
|
{ |
82
|
3 |
|
$request = $this->buildRequest(); |
83
|
|
|
|
84
|
|
|
//Apply standard headers |
85
|
3 |
|
$this->setHeader('Authorization', 'Basic '.base64_encode( |
86
|
3 |
|
$this->userid.':'.$this->password |
87
|
3 |
|
)); |
88
|
|
|
|
89
|
3 |
|
$client = new Client(array( |
90
|
3 |
|
'base_uri' => $this->getBaseUrl() |
91
|
3 |
|
)); |
92
|
|
|
|
93
|
3 |
|
return $client->send($request, array( |
94
|
3 |
|
'headers' => $this->headers |
95
|
3 |
|
)); |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|