Completed
Pull Request — master (#1)
by
unknown
12:52
created

StockbaseClient::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 2
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
4
namespace Stockbase\Integration\StockbaseApi\Client;
5
6
use Assert\Assertion;
7
use DivideBV\PHPDivideIQ\DivideIQ;
8
use Magento\Sales\Api\Data\OrderInterface;
9
use Stockbase\Integration\Model\Config\StockbaseConfiguration;
10
use Stockbase\Integration\Model\StockItemReserve;
11
12
/**
13
 * Stockbase API client.
14
 */
15
class StockbaseClient
16
{
17
    const STOCKBASE_STOCK_ENDPOINT = 'stockbase_stock';
18
    const STOCKBASE_IMAGES_ENDPOINT = 'stockbase_images';
19
    const STOCKBASE_ORDER_REQUEST_ENDPOINT = 'stockbase_orderrequest';
20
    
21
    /**
22
     * @var DivideIQ
23
     */
24
    private $divideIqClient;
25
    
26
    /**
27
     * @var StockbaseConfiguration
28
     */
29
    private $stockbaseConfiguration;
30
31
    /**
32
     * StockbaseClient constructor.
33
     * @param DivideIQ               $divideIqClient
34
     * @param StockbaseConfiguration $stockbaseConfiguration
35
     */
36 4
    public function __construct(
37
        DivideIQ $divideIqClient,
38
        StockbaseConfiguration $stockbaseConfiguration
39
    ) {
40 4
        $this->divideIqClient = $divideIqClient;
41 4
        $this->stockbaseConfiguration = $stockbaseConfiguration;
42 4
    }
43
44
    /**
45
     * Gets current Stockbase stock state.
46
     *
47
     * @param \DateTime|null $since
48
     * @param \DateTime|null $until
49
     * @return object
50
     * @throws \Exception
51
     */
52 1
    public function getStock(\DateTime $since = null, \DateTime $until = null)
53
    {
54 1
        $data = [];
55 1
        if ($since !== null) {
56 1
            $data['Since'] = $since->getTimestamp();
57
        }
58 1
        if ($until !== null) {
59 1
            $data['Until'] = $until->getTimestamp();
60
        }
61
        
62 1
        return $this->divideIqClient->request(self::STOCKBASE_STOCK_ENDPOINT, $data);
63
    }
64
65
    /**
66
     * Gets images for specified EANs.
67
     *
68
     * @param string[] $eans
69
     * @return object
70
     * @throws \Exception
71
     */
72 1
    public function getImages(array $eans)
73
    {
74 1
        Assertion::allNumeric($eans);
75
        
76
        $data = [
77 1
            'ean' => implode(',', $eans),
78
        ];
79
        
80 1
        return $this->divideIqClient->request(self::STOCKBASE_IMAGES_ENDPOINT, $data);
81
    }
82
83
    /**
84
     * Creates an order on Stockbase from reserved items for specified Magento order.
85
     *
86
     * @param OrderInterface     $order
87
     * @param StockItemReserve[] $reservedStockbaseItems
88
     * @return object
89
     * @throws \Exception
90
     */
91 2
    public function createOrder(OrderInterface $order, array $reservedStockbaseItems)
92
    {
93 2
        $orderPrefix = $this->stockbaseConfiguration->getOrderPrefix();
94 2
        $shippingAddress = $order->getShippingAddress();
95 2
        $now = new \DateTime('now', new \DateTimeZone('UTC'));
96 2
        $orderLines = [];
97
98 2
        $orderLineNumber = 0;
99 2
        foreach ($reservedStockbaseItems as $reserve) {
100 2
            $orderLineNumber++;
101 2
            $orderLines[] = [
102 2
                'Number' => $orderLineNumber, // Number starting from 1
103 2
                'EAN' => $reserve->getEan(),
104 2
                'Amount' => (int) $reserve->getAmount(),
105
            ];
106
        }
107
108
        $orderHeader = [
109 2
            'OrderNumber' => $orderPrefix.'#'.$order->getRealOrderId(),
110 2
            'TimeStamp' => $now->format('Y-m-d h:i:s'),
111 2
            'Attention' => $order->getCustomerNote() ? $order->getCustomerNote() : ' ',
112
        ];
113
        
114
        $orderDelivery = [
115
            'Person' => [
116 2
                'FirstName' => $shippingAddress->getFirstname(),
117 2
                'Surname' => $shippingAddress->getLastname(),
118 2
                'Company' => $shippingAddress->getCompany(),
119
            ],
120
            'Address' => [
121 2
                'Street' => $shippingAddress->getStreetLine(1),
122 2
                'StreetNumber' => $shippingAddress->getStreetLine(2) ?: '-',
123 2
                'ZipCode' => $shippingAddress->getPostcode(),
124 2
                'City' => $shippingAddress->getCity(),
125 2
                'CountryCode' => $shippingAddress->getCountryId(),
126
            ],
127
        ];
128
129
        $orderRequest = [
130 2
            'OrderHeader' => $orderHeader,
131 2
            'OrderLines' => $orderLines,
132 2
            'OrderDelivery' => $orderDelivery,
133
        ];
134
135 2
        $response = $this->divideIqClient->request(self::STOCKBASE_ORDER_REQUEST_ENDPOINT, $orderRequest, 'POST');
136 2
        if ($response->{'StatusCode'} != 1) {
137 1
            $message = '';
138 1
            if (isset($response->{'Items'}) && is_array($response->{'Items'})) {
139 1
                foreach ($response->{'Items'} as $item) {
140 1
                    if ($item->{'StatusCode'} != 1) {
141 1
                        $message .= ' '.trim($item->{'ExceptionMessage'});
142
                    }
143
                }
144
            }
145 1
            throw new StockbaseClientException('Failed sending order to stockbase.'.$message);
146
        }
147
        
148 1
        return $response;
149
    }
150
151
    /**
152
     * @param $imageUrl
153
     * @return mixed
154
     */
155
    public function getImageFile($imageUrl)
156
    {
157
        return $this->divideIqClient->request($imageUrl)->getBody();
158
    }
159
160
}
161