Completed
Push — master ( e64d63...07010a )
by Gabriel
10:26 queued 11s
created

StockbaseClient::downloadImage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 2
rs 10
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
     * Downloads a file using current client configuration and saves it at the specified destination.
85
     *
86
     * @param string|\GuzzleHttp\Url $uri File URI.
87
     * @param string|resource|\GuzzleHttp\Stream\StreamInterface $destination Destination where the file should be saved to.
88
     */
89
    public function downloadImage($uri, $destination)
90
    {
91
        return $this->divideIqClient->download($uri, $destination);
92
    }
93
94
    /**
95
     * Creates an order on Stockbase from reserved items for specified Magento order.
96
     *
97
     * @param OrderInterface     $order
98
     * @param StockItemReserve[] $reservedStockbaseItems
99
     * @return object
100
     * @throws \Exception
101
     */
102 2
    public function createOrder(OrderInterface $order, array $reservedStockbaseItems)
103
    {
104 2
        $orderPrefix = $this->stockbaseConfiguration->getOrderPrefix();
105 2
        $shippingAddress = $order->getShippingAddress();
106 2
        $now = new \DateTime('now', new \DateTimeZone('UTC'));
107 2
        $orderLines = [];
108
109 2
        $orderLineNumber = 0;
110 2
        foreach ($reservedStockbaseItems as $reserve) {
111 2
            $orderLineNumber++;
112 2
            $orderLines[] = [
113 2
                'Number' => $orderLineNumber, // Number starting from 1
114 2
                'EAN' => $reserve->getEan(),
115 2
                'Amount' => (int) $reserve->getAmount(),
116
            ];
117
        }
118
119
        $orderHeader = [
120 2
            'OrderNumber' => $orderPrefix.'#'.$order->getRealOrderId(),
121 2
            'TimeStamp' => $now->format('Y-m-d h:i:s'),
122 2
            'Attention' => $order->getCustomerNote() ? $order->getCustomerNote() : ' ',
123
        ];
124
        
125
        $orderDelivery = [
126
            'Person' => [
127 2
                'FirstName' => $shippingAddress->getFirstname(),
128 2
                'Surname' => $shippingAddress->getLastname(),
129 2
                'Company' => $shippingAddress->getCompany(),
130
            ],
131
            'Address' => [
132 2
                'Street' => $shippingAddress->getStreetLine(1),
133 2
                'StreetNumber' => $shippingAddress->getStreetLine(2) ?: '-',
134 2
                'ZipCode' => $shippingAddress->getPostcode(),
135 2
                'City' => $shippingAddress->getCity(),
136 2
                'CountryCode' => $shippingAddress->getCountryId(),
137
            ],
138
        ];
139
140
        $orderRequest = [
141 2
            'OrderHeader' => $orderHeader,
142 2
            'OrderLines' => $orderLines,
143 2
            'OrderDelivery' => $orderDelivery,
144
        ];
145
146 2
        $response = $this->divideIqClient->request(self::STOCKBASE_ORDER_REQUEST_ENDPOINT, $orderRequest, 'POST');
147 2
        if ($response->{'StatusCode'} != 1) {
148 1
            $message = '';
149 1
            if (isset($response->{'Items'}) && is_array($response->{'Items'})) {
150 1
                foreach ($response->{'Items'} as $item) {
151 1
                    if ($item->{'StatusCode'} != 1) {
152 1
                        $message .= ' '.trim($item->{'ExceptionMessage'});
153
                    }
154
                }
155
            }
156 1
            throw new StockbaseClientException('Failed sending order to stockbase.'.$message);
157
        }
158
        
159 1
        return $response;
160
    }
161
}
162