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 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 
<?php
/* --------------------------------------------------------------
 TrackingCodeApiV2Controller.inc.php 2018-01-15
 Gambio GmbH
 http://www.gambio.de
 Copyright (c) 2018 Gambio GmbH
 Released under the GNU General Public License (Version 2)
 [http://www.gnu.org/licenses/gpl-2.0.html]
 --------------------------------------------------------------
 */

class TrackingCodeApiV2Controller extends HttpApiV2Controller
{
    /**
     * @var \ParcelTrackingCodeFactory
     */
    private $factory;
    
    
    /**
     * Initializes API Controller
     */
    protected function init()
    {
        $this->factory = new ParcelTrackingCodeFactory();
    }
    
    
    /**
     * @api        {get} /tracking_code Get parcel tracking codes
     * @apiVersion 2.6.0
     * @apiName    GetParcelTrackingCodes
     * @apiGroup   TrackingCode
     *
     * @apiDescription
     * Returns a list with all parcel tracking code entities. You can fetch a single resource by providing the tracking
     * code id in the request URI.
     *
     * @apiExample {curl} Get all parcel tracking codes
     *             curl --user admin@shop.de:12345 http://shop.de/api.php/v2/tracking_code
     *
     * @apiExample {curl} Get parcel tracking code with ID = 2
     *             curl --user admin@shop.de:12345 http://shop.de/api.php/v2/tracking_code/2
     *
     * @apiSuccess Response-Body If successful, this method will return the parcel tracking code resource in JSON
     *             format.
     *
     * @apiSuccessExample {json} Response-Body
     * [
     *  {
     *      "id": "1",
     *      "orderId": "400210",
     *      "trackingCode": "",
     *      "parcelServiceId": "0",
     *      "parcelServiceName": "Parcel Service",
     *      "languageId": "0",
     *      "url": "http://custom-url.com",
     *      "comment": "hello world",
     *      "creationDate": "2018-01-15 18:09:34"
     *  },
     *  {
     *      "id": "2",
     *      "orderId": "400211",
     *      "trackingCode": "",
     *      "parcelServiceId": "0",
     *      "parcelServiceName": "A Parcel Service",
     *      "languageId": "0",
     *      "url": "http://best-url.com",
     *      "comment": "Custom comment",
     *      "creationDate": "2018-01-15 18:09:52"
     *  }
     * ]
     *
     * @apiSuccessExample {json} Response-Body
     * {
     *      "id": "1",
     *      "orderId": "400210",
     *      "trackingCode": "",
     *      "parcelServiceId": "0",
     *      "parcelServiceName": "Parcel Service",
     *      "languageId": "0",
     *      "url": "http://custom-url.com",
     *      "comment": "hello world",
     *      "creationDate": "2018-01-15 18:09:34"
     *  }
     *
     * @apiError (Error 4xx) 404-NotFound If no resource could be found by the provided id.
     */
    public function get()
    {
        $finder = $this->factory->finder();
        
        if(!array_key_exists(1, $this->uri))
        {
            return $this->_writeResponse($this->_convertTrackingCodes($finder->getAll()));
        }
        
        if($this->uri[0] === 'tracking_code')
        {
            $trackingCodeId = ParcelTrackingCodeId::create($this->uri[1]);
            
            return $this->_writeResponse($this->_convertTrackingCode($finder->find($trackingCodeId)));
        }
        
        $orderId = ParcelTrackingCodeOrderId::create($this->uri[1]);
        
        return $this->_writeResponse($this->_convertTrackingCodes($finder->findByOrderId($orderId)));
    }
    
    
    /**
     * @api             {post} /orders/:order_id/tracking_code Add Tracking Code
     * @apiVersion      2.6.0
     * @apiName         AddTrackingCode
     * @apiGroup        Orders
     *
     * @apiDescription
     * Adds a new parcel tracking code to the order resource.
     *
     * @apiParamExample {json} Request-Body
     * {
     *      "parcelServiceId": 3,
     *      "trackingCode": "some-tracking-code"
     * }
     *
     * @apiParamExample {json} Request-Body
     * {
     *      "parcelServiceName": "My Custom Parcel Service",
     *      "url": "http://parcel-service-tracking-url.de?code=my-code"
     * }
     *
     * @apiParamExample {json} Request-Body
     * {
     *      "parcelServiceName": "My Custom Parcel Service",
     *      "url": "http://parcel-service-tracking-url.de?code=my-code",
     *      "comment": "This is a custom comment"
     * }
     *
     * @apiParam {int} parcelServiceId Id of parcel service, must be an existing parcel service ID.
     * @apiParam {String} trackingCode Parcel tracking code of order.
     * @apiParam {String} parcelServiceName Custom name of parcel service, used for lightweight entity.
     * @apiParam {String} url Parcel tracking url of order.
     * @apiParam {String} comment Optional comment for orders tracking code.
     *
     * @apiSuccess (Success 201) Response-Body If successful, this method returns a complete TrackingCode resource in
     *             the response body.
     *
     * @apiError        400-BadRequest The body of the request was empty or invalid.
     *
     * @apiErrorExample Error-Response
     * HTTP/1.1 400 Bad Request
     * {
     *   "code": 400,
     *   "status": "error",
     *   "message": "Tracking code data were not provided."
     * }
     */
    public function post()
    {
        $trackingCode   = $this->_deserialize(json_decode($this->api->request->getBody(), true));
        $trackingCodeId = $trackingCode->save();
        
        $this->_writeResponse($this->_convertTrackingCode($this->factory->finder()->find($trackingCodeId)), 201);
    }
    
    
    /**
     * @api             {delete} /tracking_code/:id Delete tracking code
     * @apiVersion      2.6.0
     * @apiName         DeleteTrackingCode
     * @apiGroup        TrackingCode
     *
     * @apiDescription
     * Removes an order parcel tracking code entry from the database.
     *
     * @apiExample {curl} Delete Parcel Tracking Code
     *                    curl -X DELETE --user admin@shop.de:12345 http://shop.de/api.php/v2/tracking_code/4
     *
     * @apiSuccessExample {json} Success-Response
     * {
     *      "code": 200,
     *      "status": "success",
     *      "action": "delete",
     *      "resource": "TrackingCode",
     *      "trackingCodeId": 4
     * }
     *
     * @apiError        400-BadRequest The provided tracking code id was invalid or not found.
     *
     * @apiErrorExample Error-Response
     * HTTP/1.1 400 Bad Request
     * {
     *      "code" 400,
     *      "status": "error",
     *      "message": Invalid tracking code id provided
     * }
     *
     */
    public function delete()
    {
        if(!array_key_exists(1, $this->uri))
        {
            throw new HttpApiV2Exception('Invalid resource provided, tracking code id is missing in URI.', 400);
        }
        
        $this->factory->deleteService()->delete(ParcelTrackingCodeId::create($this->uri[1]));
        
        $this->_writeResponse([
                                  'code'           => 200,
                                  'status'         => 'success',
                                  'action'         => 'delete',
                                  'resource'       => 'TrackingCode',
                                  'trackingCodeId' => $this->uri[1],
                              ]);
    }
    
    
    protected function _convertTrackingCodes(array $orderParcelTrackingCodes)
    {
        $data = [];
        
        foreach($orderParcelTrackingCodes as $orderParcelTrackingCode)
        {
            $data[] = $this->_convertTrackingCode($orderParcelTrackingCode);
        }
        
        return $data;
    }
    
    
    protected function _convertTrackingCode(array $orderParcelTrackingCode)
    {
        return [
            'id'                => $orderParcelTrackingCode['orders_parcel_tracking_code_id'],
            'orderId'           => $orderParcelTrackingCode['order_id'],
            'trackingCode'      => $orderParcelTrackingCode['tracking_code'],
            'parcelServiceId'   => $orderParcelTrackingCode['parcel_service_id'],
            'parcelServiceName' => $orderParcelTrackingCode['parcel_service_name'],
            'languageId'        => $orderParcelTrackingCode['language_id'],
            'url'               => $orderParcelTrackingCode['url'],
            'comment'           => $orderParcelTrackingCode['comment'],
            'creationDate'      => $orderParcelTrackingCode['creation_date'],
        ];
    }
    
    
    protected function _deserialize(array $json)
    {
        $this->ensureJsonIsValid($json);
        
        if(array_key_exists('parcelServiceId', $json))
        {
            return $this->_deserializeEntity($json);
        }
        
        return $this->_deserializeLightweightEntity($json);
    }
    
    
    protected function ensureJsonIsValid(array $json)
    {
        $error         = 'Invalid Request-Body for REST-Operation provided! ';
        $specificDummy = 'The key "%s" is set, so the other required key in the request body is "%s" and optionally "%s".';
        $generalDummy  = 'If the key "%s" exists in the request body, the other required key is "%s" and optionally "%s".';
        
        if(array_key_exists('parcelServiceId', $json))
        {
            if(!array_key_exists('trackingCode', $json))
            {
                $error .= sprintf($specificDummy, 'parcelServiceId', 'trackingCode', 'languageId');
                throw new \InvalidArgumentException($error);
            }
            
            return;
        }
        
        if(array_key_exists('parcelServiceName', $json))
        {
            if(!array_key_exists('url', $json))
            {
                $error .= sprintf($specificDummy, 'parcelServiceName', 'url', 'comment');
                throw new \InvalidArgumentException($error);
            }
            
            return;
        }
        
        $error .= sprintf($generalDummy, 'parcelServiceId', 'trackingCode', 'languageId') . ' ';
        $error .= sprintf($generalDummy, 'parcelServiceName', 'url', 'comment');
        
        throw new \Exception($error);
    }
    
    
    protected function _deserializeEntity(array $json)
    {
        $parcelServiceId = ParcelTrackingCodeServiceId::create($json['parcelServiceId']);
        $orderId         = ParcelTrackingCodeOrderId::create($this->uri[1]);
        $trackingCode    = OrderParcelTrackingCode::create($json['trackingCode']);
        $languageId      = $this->determineLanguageId($json);
        
        return $this->factory->create($parcelServiceId, $orderId, $trackingCode, $languageId);
    }
    
    
    protected function _deserializeLightweightEntity(array $json)
    {
        $orderId           = ParcelTrackingCodeOrderId::create($this->uri[1]);
        $parcelServiceName = ParcelTrackingCodeServiceName::name($json['parcelServiceName']);
        $url               = ParcelTrackingCodeUrl::create($json['url']);
        $comment           = array_key_exists('comment',
                                              $json) ? ParcelTrackingCodeComment::write($json['comment']) : null;
        
        return $this->factory->createLightweight($orderId, $parcelServiceName, $url, $comment);
    }
    
    
    protected function determineLanguageId(array $json)
    {
        if(array_key_exists('languageId', $json))
        {
            return ParcelTrackingCodeLanguageId::create($json['languageId']);
        }
        
        $languageProvider = MainFactory::create('LanguageProvider', StaticGXCoreLoader::getDatabaseQueryBuilder());
        
        return ParcelTrackingCodeLanguageId::create($languageProvider->getDefaultLanguageId());
    }
}