| 1 |
<?php declare(strict_types=1); |
| 2 |
/** |
| 3 |
* If you want to add improvements, please create a fork in our GitHub: |
| 4 |
* https://github.com/myparcelnl |
| 5 |
* |
| 6 |
* @author Reindert Vetter <[email protected]> |
| 7 |
* @copyright 2010-2020 MyParcel |
| 8 |
* @license http://creativecommons.org/licenses/by-nc-nd/3.0/nl/deed.en_US CC BY-NC-ND 3.0 NL |
| 9 |
* @link https://github.com/myparcelnl/sdk |
| 10 |
* @since File available since Release v1.1.7 |
| 11 |
*/ |
| 12 |
|
| 13 |
namespace MyParcelNL\Sdk\src\Services; |
| 14 |
|
| 15 |
use MyParcelNL\Sdk\src\Helper\MyParcelCollection; |
| 16 |
use MyParcelNL\Sdk\src\Model\Consignment\AbstractConsignment; |
| 17 |
|
| 18 |
class CollectionEncode |
| 19 |
{ |
| 20 |
private $consignments; |
| 21 |
|
| 22 |
/** |
| 23 |
* CollectionEncode constructor. |
| 24 |
* @param $consignments MyParcelCollection |
| 25 |
*/ |
| 26 |
public function __construct($consignments) |
| 27 |
{ |
| 28 |
$this->consignments = $consignments; |
| 29 |
} |
| 30 |
|
| 31 |
/** |
| 32 |
* Encode multiple shipments so that the data can be sent to MyParcel. |
| 33 |
* |
| 34 |
* @return string |
| 35 |
* @throws \MyParcelNL\Sdk\src\Exception\MissingFieldException |
| 36 |
*/ |
| 37 |
public function encode() |
| 38 |
{ |
| 39 |
$data = []; |
| 40 |
|
| 41 |
$groupedConsignments = $this->groupMultiColloConsignments(); |
| 42 |
|
| 43 |
foreach ($groupedConsignments as $consignments) { |
| 44 |
$data['data']['shipments'][] = (new ConsignmentEncode($consignments))->apiEncode(); |
| 45 |
} |
| 46 |
|
| 47 |
// Remove \\n because json_encode encode \\n for \s |
| 48 |
return str_replace('\\n', " ", json_encode($data)); |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* @return array |
| 53 |
*/ |
| 54 |
private function groupMultiColloConsignments() |
| 55 |
{ |
| 56 |
return $this->consignments->groupBy(function (AbstractConsignment $consignment) { |
| 57 |
if ($consignment->isPartOfMultiCollo()) { |
| 58 |
return $consignment->getReferenceId(); |
| 59 |
} |
| 60 |
|
| 61 |
return 'random_to_prevent_multi_collo_' . uniqid(); |
| 62 |
})->toArray(); |
| 63 |
} |
| 64 |
} |
| 65 |
|