YanWenTracker   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 143
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 9
dl 0
loc 143
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A getKey() 0 4 1
A setKey() 0 5 1
A getCulture() 0 4 1
A setCulture() 0 5 1
A track() 0 16 2
A sendRequest() 0 9 2
B buildShipment() 0 42 3
1
<?php
2
/**
3
 * Slince shipment tracker library
4
 * @author Tao <[email protected]>
5
 */
6
namespace Slince\ShipmentTracking\YanWenExpress;
7
8
use Carbon\Carbon;
9
use GuzzleHttp\Client as HttpClient;
10
use GuzzleHttp\Psr7\Request;
11
use GuzzleHttp\Exception\GuzzleException;
12
use Psr\Http\Message\RequestInterface;
13
use Slince\ShipmentTracking\Foundation\Exception\TrackException;
14
use Slince\ShipmentTracking\Foundation\HttpAwareTracker;
15
use Slince\ShipmentTracking\Foundation\ShipmentEvent;
16
17
class YanWenTracker extends HttpAwareTracker
18
{
19
    /**
20
     * @var string
21
     */
22
    const TRACKING_ENDPOINT = 'http://api.track.yw56.com.cn/v2/api/Tracking';
23
24
    /**
25
     * @var string
26
     */
27
    protected $key;
28
29
    /**
30
     * @var string
31
     */
32
    protected $culture;
33
34
    public function __construct($key = 'none', $culture =  'en', HttpClient $httpClient = null)
35
    {
36
        $this->key = $key;
37
        $this->culture = $culture;
38
        $httpClient && $this->setHttpClient($httpClient);
39
    }
40
41
    /**
42
     * @return string
43
     */
44
    public function getKey()
45
    {
46
        return $this->key;
47
    }
48
49
    /**
50
     * @param string $key
51
     * @return YanWenTracker
52
     */
53
    public function setKey($key)
54
    {
55
        $this->key = $key;
56
        return $this;
57
    }
58
59
    /**
60
     * @return string
61
     */
62
    public function getCulture()
63
    {
64
        return $this->culture;
65
    }
66
67
    /**
68
     * @param string $culture
69
     * @return YanWenTracker
70
     */
71
    public function setCulture($culture)
72
    {
73
        $this->culture = $culture;
74
        return $this;
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80
    public function track($trackingNumber)
81
    {
82
        $parameters  = [
83
            'key' => $this->key,
84
            'culture' => $this->culture,
85
            'tracking_number' => $trackingNumber
86
        ];
87
        $request = new Request('GET', static::TRACKING_ENDPOINT);
88
        $json = $this->sendRequest($request, [
89
            'query' => $parameters
90
        ]);
91
        if ($json['code'] != 0) {
92
            throw new TrackException(sprintf('Bad response with code "%d"', $json['code']));
93
        }
94
        return static::buildShipment($json);
95
    }
96
97
    /**
98
     * @param RequestInterface $request
99
     * @param array $options
100
     * @return array
101
     * @codeCoverageIgnore
102
     */
103
    protected function sendRequest(RequestInterface $request, array $options = [])
104
    {
105
        try {
106
            $response = $this->getHttpClient()->send($request, $options);
107
            return \GuzzleHttp\json_decode((string)$response->getBody(), true);
108
        } catch (GuzzleException $exception) {
109
            throw new TrackException($exception->getMessage());
110
        }
111
    }
112
113
    /**
114
     * @param array $json
115
     * @return Shipment
116
     */
117
    protected static function buildShipment($json)
118
    {
119
        if (is_null($json['origin_items']) && is_null($json['destin_items'])) {
120
            throw new TrackException(sprintf('Bad response'));
121
        }
122
        $shippingItems = array_merge($json['origin_items'], $json['destin_items']);
123
        $events = array_map(function($item) {
124
            return ShipmentEvent::fromArray([
125
                'location' => $item['location'],
126
                'description' => $item['message'],
127
                'date' => Carbon::parse($item['timestamp']),
128
                'status' => null
129
            ]);
130
        }, $shippingItems);
131
        $shipment = new Shipment($events);
132
133
        //build origin events
134
        $shipment->setOriginEvents(array_map(function($item) {
135
            return ShipmentEvent::fromArray([
136
                'location' => $item['location'],
137
                'description' => $item['message'],
138
                'date' => Carbon::parse($item['timestamp']),
139
                'status' => null
140
            ]);
141
        }, (array)$json['origin_items']));
142
143
        //build destination events
144
        $shipment->setDestinationEvents(array_map(function($item) {
145
            return ShipmentEvent::fromArray([
146
                'location' => $item['location'],
147
                'description' => $item['message'],
148
                'date' => Carbon::parse($item['timestamp']),
149
                'status' => null
150
            ]);
151
        }, (array)$json['destin_items']));
152
153
        $shipment->setIsDelivered($json['state'] == 40)
154
            ->setOrigin($json['origin_country'])
155
            ->setDestination($json['destin_country'])
156
            ->setDeliveredAt($json['receive_date']);
157
        return $shipment;
158
    }
159
}