Completed
Push — master ( 2b3b62...a74c29 )
by Taosikai
14:49
created

EMSTracker::parseXml()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
/**
3
 * Slince shipment tracker library
4
 * @author Tao <[email protected]>
5
 */
6
namespace Slince\ShipmentTracking\EMS;
7
8
use GuzzleHttp\Client as HttpClient;
9
use GuzzleHttp\Psr7\Request;
10
use GuzzleHttp\Exception\GuzzleException;
11
use Psr\Http\Message\RequestInterface;
12
use Slince\ShipmentTracking\Foundation\Exception\InvalidArgumentException;
13
use Slince\ShipmentTracking\Foundation\Exception\TrackException;
14
use Slince\ShipmentTracking\Foundation\HttpAwareTracker;
15
use Slince\ShipmentTracking\Foundation\Shipment;
16
use Slince\ShipmentTracking\Foundation\ShipmentEvent;
17
18
class EMSTracker extends HttpAwareTracker
19
{
20
    /**
21
     * @var string
22
     */
23
    const TRACKING_ENDPOINT = 'http://shipping.ems.com.cn/partner/api/public/p/track/query/{language}/{trackingNumber}';
24
25
    /**
26
     * @var string
27
     */
28
    protected $language;
29
30
    /**
31
     * @var string
32
     */
33
    protected static $version = 'international_eub_us_1.1';
34
35
    /**
36
     * @var string
37
     */
38
    protected $authenticate;
39
40
    public function __construct($authenticate, $language, HttpClient $httpClient = null)
41
    {
42
        $this->authenticate = $authenticate;
43
        $this->setLanguage($language);
44
        $httpClient && $this->setHttpClient($httpClient);
45
    }
46
47
    /**
48
     * @return string
49
     */
50
    public function getLanguage()
51
    {
52
        return $this->language;
53
    }
54
55
    /**
56
     * @param string $language
57
     * @return EMSTracker
58
     */
59
    public function setLanguage($language)
60
    {
61
        if ($language != 'en' && $language != 'cn') {
62
            throw new InvalidArgumentException(sprintf('Invalid language, expect "cn" or "en", giving "%s"', $language));
63
        }
64
        $this->language = $language;
65
        return $this;
66
    }
67
68
    /**
69
     * @return string
70
     */
71
    public function getAuthenticate()
72
    {
73
        return $this->authenticate;
74
    }
75
76
    /**
77
     * @param string $authenticate
78
     * @return EMSTracker
79
     */
80
    public function setAuthenticate($authenticate)
81
    {
82
        $this->authenticate = $authenticate;
83
        return $this;
84
    }
85
86
    /**
87
     * @param string $version
88
     */
89
    public static function setVersion($version)
90
    {
91
        static::$version = $version;
92
    }
93
94
    /**
95
     * @return string
96
     */
97
    public static function getVersion()
98
    {
99
        return static::$version;
100
    }
101
102
    /**
103
     * {@inheritdoc}
104
     */
105
    public function track($trackingNumber)
106
    {
107
        $request = new Request('GET', static::formatEndpoint($this->language, $trackingNumber));
108
        $array = static::parseXml($this->sendRequest($request));
109
        if (!isset($array['trace'])) {
110
            throw new TrackException(sprintf('Bad response,code: "%s", message:"%s"', $array['code'], $array['description']));
111
        }
112
        return static::buildShipment($array);
113
    }
114
115
    /**
116
     * @param RequestInterface $request
117
     * @param array $options
118
     * @return string
119
     * @codeCoverageIgnore
120
     */
121
    protected function sendRequest(RequestInterface $request, array $options = [])
122
    {
123
        try {
124
            $request = $request->withHeader('version', static::$version)
125
                ->withHeader('authenticate', $this->authenticate);
126
            $response = $this->getHttpClient()->send($request, $options);
127
            return (string)$response->getBody();
128
        } catch (GuzzleException $exception) {
129
            throw new TrackException($exception->getMessage());
130
        }
131
    }
132
133
    /**
134
     * @param string $language
135
     * @param string $trackingNumber
136
     * @return string
137
     */
138
    protected static function formatEndpoint($language, $trackingNumber)
139
    {
140
        return str_replace(['{language}', '{trackingNumber}'], [$language, $trackingNumber], static::TRACKING_ENDPOINT);
141
    }
142
143
    /**
144
     * @param string $xml
145
     * @return array
146
     */
147
    protected static function parseXml($xml)
148
    {
149
        libxml_use_internal_errors(true);
150
        $data = simplexml_load_string($xml, null, LIBXML_NOERROR);
151
        if ($data === false) {
152
            throw new TrackException(sprintf('Invalid xml response "%s"', $xml));
153
        }
154
        return json_decode(json_encode($data), true);
155
    }
156
157
    /**
158
     * @param array $json
159
     * @return Shipment
160
     */
161
    protected static function buildShipment($json)
162
    {
163
        $events = array_map(function($item) {
164
            return ShipmentEvent::fromArray([
165
                'location' => $item['acceptAddress'],
166
                'description' => $item['remark'],
167
                'date' => $item['acceptTime'],
168
            ]);
169
        }, $json['trace']);
170
        $shipment = new Shipment($events);
171
        if ($firstEvent = reset($events)) {
172
            $shipment->setDeliveredAt($firstEvent->getDate());
173
        }
174
        return $shipment;
175
    }
176
}