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
|
5 |
|
public function __construct($baseUrl, $userid, $password) |
33
|
|
|
{ |
34
|
5 |
|
$this->baseUrl = $baseUrl; |
35
|
5 |
|
$this->userid = $userid; |
36
|
5 |
|
$this->password = $password; |
37
|
5 |
|
} |
38
|
|
|
|
39
|
1 |
|
public function setLanguage($value) |
40
|
|
|
{ |
41
|
1 |
|
$this->setHeader('Accept-language', $value); |
42
|
1 |
|
return $this; |
43
|
|
|
} |
44
|
|
|
|
45
|
4 |
|
public function setHeader($name, $value) |
46
|
|
|
{ |
47
|
4 |
|
$this->headers[$name] = $value; |
48
|
4 |
|
return $this; |
49
|
|
|
} |
50
|
|
|
|
51
|
4 |
|
public function hasParameter($name) |
52
|
|
|
{ |
53
|
4 |
|
return isset($this->parameters[$name]); |
54
|
|
|
} |
55
|
|
|
|
56
|
4 |
|
public function setParameter($name, $value) |
57
|
|
|
{ |
58
|
4 |
|
$this->parameters[$name] = $value; |
59
|
4 |
|
return $this; |
60
|
|
|
} |
61
|
|
|
|
62
|
4 |
|
public function getParameter($name, $default=null) |
63
|
|
|
{ |
64
|
4 |
|
return $this->hasParameter($name) ? |
65
|
4 |
|
$this->parameters[$name] : $default; |
66
|
|
|
} |
67
|
|
|
|
68
|
4 |
|
public function getBaseUrl() |
69
|
|
|
{ |
70
|
4 |
|
return $this->baseUrl; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* @return Request |
75
|
|
|
*/ |
76
|
|
|
abstract protected function buildRequest(); |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @return Response |
80
|
|
|
*/ |
81
|
4 |
|
public function send() |
82
|
|
|
{ |
83
|
4 |
|
$request = $this->buildRequest(); |
84
|
|
|
|
85
|
|
|
//Apply standard headers |
86
|
4 |
|
$this->setHeader('Authorization', 'Basic '.base64_encode( |
87
|
4 |
|
$this->userid.':'.$this->password |
88
|
4 |
|
)); |
89
|
|
|
|
90
|
4 |
|
$client = new Client(array( |
91
|
4 |
|
'base_uri' => $this->getBaseUrl() |
92
|
4 |
|
)); |
93
|
|
|
|
94
|
4 |
|
return $client->send($request, array( |
95
|
4 |
|
'headers' => $this->headers |
96
|
4 |
|
)); |
97
|
|
|
} |
98
|
|
|
} |
99
|
|
|
|