Completed
Pull Request — master (#105)
by
unknown
04:19
created

Request::setClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace Ups;
4
5
use DateTime;
6
use Exception;
7
use GuzzleHttp\Client as Guzzle;
8
use Psr\Log\LoggerAwareInterface;
9
use Psr\Log\LoggerInterface;
10
use Psr\Log\NullLogger;
11
use SimpleXMLElement;
12
use Ups\Exception\InvalidResponseException;
13
use Ups\Exception\RequestException;
14
15
class Request implements RequestInterface, LoggerAwareInterface
16
{
17
    /**
18
     * @var string
19
     */
20
    protected $access;
21
22
    /**
23
     * @var string
24
     */
25
    protected $request;
26
27
    /**
28
     * @var string
29
     */
30
    protected $endpointUrl;
31
32
    /**
33
     * @var LoggerInterface
34
     */
35
    protected $logger;
36
37
    /**
38
     * @var Guzzle
39
     */
40
    protected $client;
41
42
    /**
43
     * @param LoggerInterface $logger
44
     */
45 View Code Duplication
    public function __construct(LoggerInterface $logger = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
46
    {
47
        if ($logger !== null) {
48
            $this->setLogger($logger);
49
        } else {
50
            $this->setLogger(new NullLogger);
51
        }
52
53
        $this->setClient();
54
    }
55
56
    /**
57
     * Sets a logger instance on the object.
58
     *
59
     * @param LoggerInterface $logger
60
     *
61
     * @return null
62
     */
63
    public function setLogger(LoggerInterface $logger)
64
    {
65
        $this->logger = $logger;
66
    }
67
68
    /**
69
     * Creates a single instance of the Guzzle client
70
     *
71
     * @return null
72
     */
73
    public function setClient()
74
    {
75
        $this->client = new Guzzle();
76
    }
77
78
    /**
79
     * Send request to UPS.
80
     *
81
     * @param string $access The access request xml
82
     * @param string $request The request xml
83
     * @param string $endpointurl The UPS API Endpoint URL
84
     *
85
     * @throws Exception
86
     *                   todo: make access, request and endpointurl nullable to make the testable
87
     *
88
     * @return ResponseInterface
89
     */
90
    public function request($access, $request, $endpointurl)
91
    {
92
        $this->setAccess($access);
93
        $this->setRequest($request);
94
        $this->setEndpointUrl($endpointurl);
95
96
        // Log request
97
        $date = new DateTime();
98
        $id = $date->format('YmdHisu');
99
        $this->logger->info('Request To UPS API', [
100
            'id' => $id,
101
            'endpointurl' => $this->getEndpointUrl(),
102
        ]);
103
104
        $this->logger->debug('Request: ' . $this->getRequest(), [
105
            'id' => $id,
106
            'endpointurl' => $this->getEndpointUrl(),
107
        ]);
108
109
        try {
110
            $response = $this->client->post(
111
                $this->getEndpointUrl(),
112
                [
113
                    'body' => $this->getAccess() . $this->getRequest(),
114
                    'headers' => [
115
                        'Content-type' => 'application/x-www-form-urlencoded; charset=utf-8',
116
                        'Accept-Charset' => 'UTF-8',
117
                    ],
118
                    'http_errors' => true,
119
                ]
120
            );
121
122
            $body = (string)$response->getBody();
123
124
            $this->logger->info('Response from UPS API', [
125
                'id' => $id,
126
                'endpointurl' => $this->getEndpointUrl(),
127
            ]);
128
129
            $this->logger->debug('Response: ' . $body, [
130
                'id' => $id,
131
                'endpointurl' => $this->getEndpointUrl(),
132
            ]);
133
134
            if ($response->getStatusCode() === 200) {
135
                if (function_exists('mb_convert_encoding')) {
136
                    $body = mb_convert_encoding($body, 'UTF-8', mb_detect_encoding($body));
137
                }
138
139
                $xml = new SimpleXMLElement($body);
140
                if (isset($xml->Response) && isset($xml->Response->ResponseStatusCode)) {
141
                    if ($xml->Response->ResponseStatusCode == 1) {
142
                        $responseInstance = new Response();
143
144
                        return $responseInstance->setText($body)->setResponse($xml);
145
                    } elseif ($xml->Response->ResponseStatusCode == 0) {
146
                        throw new InvalidResponseException('Failure: ' . $xml->Response->Error->ErrorDescription . ' (' . $xml->Response->Error->ErrorCode . ')');
147
                    }
148
                } else {
149
                    throw new InvalidResponseException('Failure: response is in an unexpected format.');
150
                }
151
            }
152
        } catch (\GuzzleHttp\Exception\TransferException $e) { // Guzzle: All of the exceptions extend from GuzzleHttp\Exception\TransferException
153
            $this->logger->alert($e->getMessage(), [
154
                'id' => $id,
155
                'endpointurl' => $this->getEndpointUrl(),
156
            ]);
157
158
            throw new RequestException('Failure: ' . $e->getMessage());
159
        }
160
    }
161
162
    /**
163
     * @param $access
164
     *
165
     * @return $this
166
     */
167
    public function setAccess($access)
168
    {
169
        $this->access = $access;
170
171
        return $this;
172
    }
173
174
    /**
175
     * @return string
176
     */
177
    public function getAccess()
178
    {
179
        return $this->access;
180
    }
181
182
    /**
183
     * @param $request
184
     *
185
     * @return $this
186
     */
187
    public function setRequest($request)
188
    {
189
        $this->request = $request;
190
191
        return $this;
192
    }
193
194
    /**
195
     * @return string
196
     */
197
    public function getRequest()
198
    {
199
        return $this->request;
200
    }
201
202
    /**
203
     * @param $endpointUrl
204
     *
205
     * @return $this
206
     */
207
    public function setEndpointUrl($endpointUrl)
208
    {
209
        $this->endpointUrl = $endpointUrl;
210
211
        return $this;
212
    }
213
214
    /**
215
     * @return string
216
     */
217
    public function getEndpointUrl()
218
    {
219
        return $this->endpointUrl;
220
    }
221
}
222