Completed
Pull Request — master (#80)
by
unknown
11:04 queued 05:59
created

AddressValidation::validateReturnAVObject()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Ups;
4
5
use DOMDocument;
6
use Exception;
7
use Psr\Log\LoggerInterface;
8
use SimpleXMLElement;
9
use stdClass;
10
use Ups\Entity\Address;
11
use Ups\Entity\AddressValidationResponse;
12
13
/**
14
 * Address Validation API Wrapper.
15
 */
16
class AddressValidation extends Ups
17
{
18
    const ENDPOINT = '/XAV';
19
20
    /**
21
     * @var RequestInterface
22
     */
23
    private $request;
24
25
    /**
26
     * @var ResponseInterface
27
     *
28
     * @todo make private
29
     */
30
    public $response;
31
32
    /**
33
     * @var int
34
     */
35
    private $requestOption;
36
37
    /**
38
     * @var Address
39
     */
40
    private $address;
41
42
    /**
43
     * @var int
44
     */
45
    private $maxSuggestion;
46
    /**
47
     * @var bool
48
     */
49
    private $useAVResponseObject = false;
50
51
    /**
52
     * Request Options.
53
     */
54
    const REQUEST_OPTION_ADDRESS_VALIDATION = 1;
55
    const REQUEST_OPTION_ADDRESS_CLASSIFICATION = 2;
56
    const REQUEST_OPTION_ADDRESS_VALIDATION_AND_CLASSIFICATION = 3;
57
58
    /**
59
     * @param string|null $accessKey UPS License Access Key
60
     * @param string|null $userId UPS User ID
61
     * @param string|null $password UPS User Password
62
     * @param bool $useIntegration Determine if we should use production or CIE URLs.
63
     * @param RequestInterface $request
64
     * @param LoggerInterface PSR3 compatible logger (optional)
65
     */
66 15 View Code Duplication
    public function __construct(
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...
67
        $accessKey = null,
68
        $userId = null,
69
        $password = null,
70
        $useIntegration = false,
71
        RequestInterface $request = null,
72
        LoggerInterface $logger = null
73
    ) {
74 15
        if (null !== $request) {
75
            $this->setRequest($request);
76
        }
77 15
        parent::__construct($accessKey, $userId, $password, $useIntegration, $logger);
78 15
    }
79
80
    /**
81
     * This message set the addressValidationResponseObject
82
     * @param bool $value
83
     */
84 14
    public function validateReturnAVObject($value = true)
85
    {
86 14
        $this->useAVResponseObject = $value;
87 14
    }
88
    /**
89
     * Get address suggestions from UPS.
90
     *
91
     * @param $address
92
     * @param int $requestOption
93
     * @param int $maxSuggestion
94
     *
95
     * @throws Exception
96
     *
97
     * @return stdClass|AddressValidationResponse
98
     */
99 15
    public function validate($address, $requestOption = self::REQUEST_OPTION_ADDRESS_VALIDATION, $maxSuggestion = 15)
100
    {
101 15
        if ($maxSuggestion > 50) {
102
            throw new \Exception('Maximum of 50 suggestions allowed');
103
        }
104
105 15
        if (!in_array($requestOption, range(1, 3))) {
106
            throw new \Exception('Invalid request option supplied');
107
        }
108
109 15
        $this->address = $address;
110 15
        $this->requestOption = $requestOption;
111 15
        $this->maxSuggestion = $maxSuggestion;
112
113 15
        $access = $this->createAccess();
114 15
        $request = $this->createRequest();
115
116 15
        $this->response = $this->getRequest()->request($access, $request, $this->compileEndpointUrl(self::ENDPOINT));
117 15
        $response = $this->response->getResponse();
118
119 15
        if (null === $response) {
120 1
            throw new Exception('Failure (0): Unknown error', 0);
121
        }
122
123 14
        if ($response instanceof SimpleXMLElement && $response->Response->ResponseStatusCode == 0) {
124
            throw new Exception(
125
                "Failure ({$response->Response->Error->ErrorSeverity}): {$response->Response->Error->ErrorDescription}",
126
                (int)$response->Response->Error->ErrorCode
127
            );
128
        }
129 14
        if ($this->useAVResponseObject) {
130 14
            unset($response->Response);
131 14
            $avResponse = new AddressValidationResponse($response,$requestOption);
132 14
            return $avResponse;
133
        }
134
        return $this->formatResponse($response);
135
    }
136
137
    /**
138
     * Create the XAV request.
139
     *
140
     * @return string
141
     */
142 15
    private function createRequest()
143
    {
144 15
        $xml = new DOMDocument();
145 15
        $xml->formatOutput = true;
146
147 15
        $avRequest = $xml->appendChild($xml->createElement('AddressValidationRequest'));
148 15
        $avRequest->setAttribute('xml:lang', 'en-US');
149
150 15
        $request = $avRequest->appendChild($xml->createElement('Request'));
151
152 15
        $node = $xml->importNode($this->createTransactionNode(), true);
153 15
        $request->appendChild($node);
154
155 15
        $request->appendChild($xml->createElement('RequestAction', 'XAV'));
156
157 15
        if (null !== $this->requestOption) {
158 15
            $request->appendChild($xml->createElement('RequestOption', $this->requestOption));
159 15
        }
160
161 15
        if (null !== $this->maxSuggestion) {
162 15
            $avRequest->appendChild($xml->createElement('MaximumListSize', $this->maxSuggestion));
163 15
        }
164
165 15
        if (null !== $this->address) {
166 15
            $addressNode = $avRequest->appendChild($xml->createElement('AddressKeyFormat'));
167
168 15
            if ($this->address->getAttentionName()) {
169 15
                $addressNode->appendChild($xml->createElement('ConsigneeName', $this->address->getAttentionName()));
170 15
            }
171 15
            if ($this->address->getBuildingName()) {
172 15
                $addressNode->appendChild($xml->createElement('BuildingName', $this->address->getBuildingName()));
173 15
            }
174 15
            if ($this->address->getAddressLine1()) {
175 15
                $addressNode->appendChild($xml->createElement('AddressLine', $this->address->getAddressLine1()));
176 15
            }
177 15
            if ($this->address->getAddressLine2()) {
178 15
                $addressNode->appendChild($xml->createElement('AddressLine', $this->address->getAddressLine2()));
179 15
            }
180 15
            if ($this->address->getAddressLine3()) {
181 15
                $addressNode->appendChild($xml->createElement('AddressLine', $this->address->getAddressLine3()));
182 15
            }
183 15
            if ($this->address->getStateProvinceCode()) {
184 15
                $addressNode->appendChild($xml->createElement('PoliticalDivision2',
185 15
                    $this->address->getStateProvinceCode()));
186 15
            }
187 15
            if ($this->address->getCity()) {
188 15
                $addressNode->appendChild($xml->createElement('PoliticalDivision1', $this->address->getCity()));
189 15
            }
190 15
            if ($this->address->getCountryCode()) {
191 15
                $addressNode->appendChild($xml->createElement('CountryCode', $this->address->getCountryCode()));
192 15
            }
193 15
            if ($this->address->getPostalCode()) {
194 15
                $addressNode->appendChild($xml->createElement('PostcodePrimaryLow', $this->address->getPostalCode()));
195 15
            }
196 15
        }
197
198 15
        return $xml->saveXML();
199
    }
200
201
    /**
202
     * Format the response.
203
     *
204
     * @param SimpleXMLElement $response
205
     *
206
     * @return stdClass
207
     */
208
    private function formatResponse(SimpleXMLElement $response)
209
    {
210
        return $this->convertXmlObject($response->AddressKeyFormat);
211
    }
212
213
    /**
214
     * @return RequestInterface
215
     */
216 15
    public function getRequest()
217
    {
218 15
        if (null === $this->request) {
219
            $this->request = new Request();
220
        }
221
222 15
        return $this->request;
223
    }
224
225
    /**
226
     * @param RequestInterface $request
227
     *
228
     * @return $this
229
     */
230 15
    public function setRequest(RequestInterface $request)
231
    {
232 15
        $this->request = $request;
233
234 15
        return $this;
235
    }
236
237
    /**
238
     * @return ResponseInterface
239
     */
240
    public function getResponse()
241
    {
242
        return $this->response;
243
    }
244
245
    /**
246
     * @param ResponseInterface $response
247
     *
248
     * @return $this
249
     */
250
    public function setResponse(ResponseInterface $response)
251
    {
252
        $this->response = $response;
253
254
        return $this;
255
    }
256
}
257