Completed
Push — master ( 2851a0...d0aa61 )
by Taosikai
10:36
created

SeventeenTracker::createRequest()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 19
rs 9.4285
cc 1
eloc 11
nc 1
nop 1
1
<?php
2
/**
3
 * Slince shipment tracker library
4
 * @author Tao <[email protected]>
5
 */
6
namespace Slince\ShipmentTracking\SeventeenTrack;
7
8
use GuzzleHttp\Psr7\Request;
9
use Psr\Http\Message\RequestInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use Slince\ShipmentTracking\Foundation\Exception\TrackException;
12
use Slince\ShipmentTracking\Foundation\HttpAwareTracker;
13
use Slince\ShipmentTracking\Foundation\ShipmentEvent;
14
15
class SeventeenTracker extends HttpAwareTracker
16
{
17
    const TRACK_ENDPOINT = 'http://www.17track.net/restapi/handlertrack.ashx';
18
19
    const REFERER = 'http://www.17track.net/zh-cn/track?nums={trackingNumber}';
20
21
    /**
22
     * {@inheritdoc}
23
     */
24
    public function track($trackingNumber)
25
    {
26
        $request = static::createRequest($trackingNumber);
27
        $response = $this->sendRequest($request);
28
        $json = \GuzzleHttp\json_decode($response->getBody(), true);
29
        if ($json['ret'] != 1) {
30
            throw new TrackException($json['msg']);
31
        }
32
        return static::buildShipment($json);
33
    }
34
35
    /**
36
     * @param string $trackingNumber
37
     * @return Request
38
     */
39
    protected static function createRequest($trackingNumber)
40
    {
41
        $parameterKey = [
42
            'guid' => '',
43
            'data' => [
44
                [
45
                    'num' => $trackingNumber
46
                ]
47
            ]
48
        ];
49
        return new Request('POST', static::TRACK_ENDPOINT, [
50
                'Referer' => str_replace('{trackingNumber}', $trackingNumber, static::REFERER),
51
                'X-Requested-With' => 'XMLHttpRequest',
52
                'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
53
                'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'
54
            ],
55
            \GuzzleHttp\json_encode($parameterKey)
56
        );
57
    }
58
59
    /**
60
     * @param RequestInterface $request
61
     * @param array $options
62
     * @return ResponseInterface
63
     * @codeCoverageIgnore
64
     */
65
    protected function sendRequest(RequestInterface $request, $options = [])
66
    {
67
        return $this->getHttpClient()->send($request, $options);
68
    }
69
70
    /**
71
     * @param array $json
72
     * @return Shipment
73
     */
74
    protected static function buildShipment($json)
75
    {
76
        if (empty($json['dat'][0]['track'])) {
77
            throw new TrackException('Bad response');
78
        }
79
        $track = $json['dat'][0]['track'];
80
        $shipment = new Shipment();
81
        //源国家的跟踪轨迹
82
        $originEvents = array_map(function($item){
83
            return ShipmentEvent::fromArray([
84
                'description' => $item['z'],
85
                'location' => $item['d'],
86
                'date' => $item['a']
87
            ]);
88
        }, array_reverse($track['z1']));
89
        $shipment->setOriginEvents($originEvents);
90
        //目标国家跟踪轨迹
91
        $destinationEvents = array_map(function($item){
92
            return ShipmentEvent::fromArray([
93
                'description' => $item['z'],
94
                'location' => $item['d'],
95
                'date' => $item['a']
96
            ]);
97
        }, array_reverse($track['z2']));
98
        $shipment->setDestinationEvents($destinationEvents);
99
        $shipment->setEvents(array_merge($shipment->getOriginEvents(), $shipment->getDestinationEvents()));
100
        //状态
101
        $shipment->setStatus($track['e'])
102
            ->setIsDelivered($shipment->getStatus() === Shipment::STATUS_DELIVERED);
103
        //发货国家与目的国家暂时不得而知
104
        return $shipment;
105
    }
106
}