1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 
<?php

/* --------------------------------------------------------------
   OrderStatusesApiV2Controller.inc.php 2017-03-28
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2017 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

class OrderStatusesApiV2Controller extends HttpApiV2Controller
{
    /**
     * @var OrderStatusServiceInterface
     */
    protected $orderStatusService;
    
    
    /**
     * Initialize Controller
     */
    public function __initialize()
    {
        $this->orderStatusService = StaticGXCoreLoader::getService('OrderStatus');
    }
    
    
    /**
     * @api        {get} /order_statuses/:id Get order statuses
     * @apiVersion 2.4.0
     * @apiName    GetOrderStatus
     * @apiGroup   OrderStatus
     *
     * @apiDescription
     * Get a single order status entry. This method is currently limited to
     * only fetching a single order status resource so make sure that you provide the order status ID in
     * the request URI.
     *
     * @apiExample {curl} Get all order statuses
     *             curl --user admin@shop.de:12345 http://shop.de/api.php/v2/order_statuses
     *
     * @apiExample {curl} Get order status with ID = 2
     *             curl --user admin@shop.de:12345 http://shop.de/api.php/v2/order_statuses/2
     *
     * @apiSuccess Response-Body If successful, this method will return the order status resource in JSON format.
     *
     * @apiError (Error 5xx) 500-InternalError If the record is not found or something else goes wrong the API will
     * return a 500 error status. Read the message for more info.
     *
     * @apiError (Error 4xx) 400-Bad Request If the ID is not numeric in the request URI then the API will return
     * a 400 error status because it cannot return the order status resource.
     */
    public function get()
    {
        // Get order status is not supported.
        if(isset($this->uri[1]) && !is_numeric($this->uri[1]))
        {
            throw new HttpApiV2Exception('Order status id is invalid or was not provided.', 400);
        }
        elseif(!isset($this->uri[1]))
        {
            $this->_writeResponse($this->_serializeOrderStatusCollection($this->orderStatusService->findAll()));
        }
        else
        {
            $this->_writeResponse($this->_serializeOrderStatus($this->orderStatusService->find(new IntType($this->uri[1]))));
        }
    }
    
    
    /**
     * @api        {post} /order_statuses Create Order Status
     * @apiVersion 2.4.0
     * @apiName    CreateOrderStatus
     * @apiGroup   OrderStatus
     *
     * @apiDescription
     * This method creates a new order status in the database.
     *
     * @apiExample {curl} Creates New Order Status
     *             curl -X POST --user admin@shop.de:12345 http://shop.de/api.php/v2/order_statuses
     *
     * @apiParamExample {json} Create new order status
     * {
     *   "names": {
     *     "EN": "new order status name",
     *     "DE": "neuer order status name"
     *   },
     *   "color": "adad1313"
     * }
     *
     * @apiParam {object} names Language related order status names. Provide the language id as object key.
     * @apiParam {string} color Label color of order status.
     *
     * @apiSuccess (Success 201) Response-Body If successful, this method returns the created order status resource in
     * the response body.
     *
     * @apiError   400-Bad Request The API will return this status code if the order status data was not provided.
     */
    public function post()
    {
        $orderStatusJson = $this->api->request->getBody();
        
        if(empty($orderStatusJson))
        {
            throw new HttpApiV2Exception('Order status data were not provided.', 400);
        }
        
        $orderStatusData = json_decode($orderStatusJson, true);
        $orderStatus     = $this->_deserializeOrderStatus($orderStatusData);
        $orderStatusId   = $this->orderStatusService->create($orderStatus);
        $newOrderStatus  = $this->orderStatusService->get(new IntType($orderStatusId));
        
        $this->_writeResponse($this->_serializeOrderStatus($newOrderStatus), 201);
    }
    
    
    /**
     * @api        {put} /order_statuses/:id Update Order Status
     * @apiVersion 2.4.0
     * @apiName    UpdateOrderStatus
     * @apiGroup   OrderStatus
     *
     * @apiDescription
     * This method updates a order status in the database.
     *
     * @apiExample {curl} Update Order Status with ID = 2
     *             curl -X PUT --user admin@shop.de:12345 http://shop.de/api.php/v2/order_statuses/2
     *
     * @apiParamExample {json} Create new order status
     * {
     *   "names": {
     *     "EN": "updated order status name",
     *     "DE": "aktualisierter order status name"
     *   },
     *   "color": "adad1313"
     * }
     *
     * @apiParam {object} names Language related order status names. Provide the language id as object key.
     * @apiParam {string} color Label color of order status.
     *
     * @apiSuccess (Success 201) Response-Body If successful, this method returns the updated order status resource in
     * the response body.
     *
     * @apiError   400-Bad Request The API will return this status code if the order status data or order status id was
     * not provided.
     */
    public function put()
    {
        if(!isset($this->uri[1]) || !is_numeric($this->uri[1]))
        {
            throw new HttpApiV2Exception('Order status id is invalid or was not provided.', 400);
        }
        $orderStatusJson = $this->api->request->getBody();
        if(empty($orderStatusJson))
        {
            throw new HttpApiV2Exception('Order status data were not provided.', 400);
        }
        $orderStatusData = json_decode($orderStatusJson, true);
        $orderStatus     = $this->orderStatusService->get(new IntType($this->uri[1]));
        
        foreach($orderStatusData['names'] as $languageCode => $name)
        {
            $orderStatus->setName(MainFactory::create('LanguageCode', new StringType($languageCode)),
                                  new StringType($name));
        }
        $orderStatus->setColor(new StringType($orderStatusData['color']));
        $this->orderStatusService->update($orderStatus);
        
        $this->_writeResponse($this->_serializeOrderStatus($orderStatus));
    }
    
    
    /**
     * @api        {delete} /order_statuses/:id Delete Order Status
     * @apiVersion 2.4.0
     * @apiName    DeleteOrderStatus
     * @apiGroup   OrderStatus
     *
     * @apiDescription
     * Removes a order status record from the system. This method will always return success.
     *
     * @apiExample {curl} Delete Order Status with ID = 2
     *             curl -X DELETE --user admin@shop.de:12345 http://shop.de/api.php/v2/order_statuses/2
     *
     * @apiSuccessExample {json} Success-Response
     * {
     *   "code": 200,
     *   "status": "success",
     *   "action": "delete",
     *   "orderStatusId": 2
     * }
     */
    public function delete()
    {
        if(!isset($this->uri[1]) || !is_numeric($this->uri[1]))
        {
            throw new HttpApiV2Exception('Order status id is invalid or was not provided.', 400);
        }
        $this->orderStatusService->remove(new IntType($this->uri[1]));
        
        // Return response JSON.
        $response = [
            'code'          => 200,
            'status'        => 'success',
            'action'        => 'delete',
            'orderStatusId' => (int)$this->uri[1]
        ];
        $this->_writeResponse($response);
    }
    
    
    /**
     * Serializes an order status collection.
     *
     * @param \OrderStatusCollection $collection Collection of order statuses to be serialized.
     *
     * @return array Serialized order status collection data.
     */
    private function _serializeOrderStatusCollection(OrderStatusCollection $collection)
    {
        $data = [];
        
        foreach($collection->getArray() as $item)
        {
            $data[] = $this->_serializeOrderStatus($item);
        }
        
        return $data;
    }
    
    
    /**
     * Serializes an order status object.
     *
     * @param \OrderStatus $orderStatus Order status object to be serialized.
     *
     * @return array Serialized order status data.
     */
    private function _serializeOrderStatus(OrderStatus $orderStatus)
    {
        return [
            'id'    => $orderStatus->getId(),
            'names' => $orderStatus->getNames(),
            'color' => $orderStatus->getColor()
        ];
    }
    
    
    /**
     * Deserializes an order status object.
     *
     * @param array $data Order status object to be deserialized.
     *
     * @return OrderStatus Deserialized order status data.
     */
    private function _deserializeOrderStatus(array $data)
    {
        $id          = array_key_exists('id', $data) ? $data['id'] : null;
        $orderStatus = new OrderStatus($id);
        
        foreach($data['names'] as $languageCode => $name)
        {
            $orderStatus->setName(MainFactory::create('LanguageCode', new StringType($languageCode)),
                                  new StringType($name));
        }
        
        return $orderStatus->setColor(new StringType($data['color']));
    }
}