1
|
|
|
<?php |
2
|
|
|
namespace Loevgaard\Consignor\ShipmentServer\Response; |
3
|
|
|
|
4
|
|
|
use Loevgaard\Consignor\ShipmentServer\Exception\InvalidBase64Exception; |
5
|
|
|
use Loevgaard\Consignor\ShipmentServer\Exception\InvalidLabelsOptionException; |
6
|
|
|
use Loevgaard\Consignor\ShipmentServer\Request\SubmitShipmentRequest; |
7
|
|
|
|
8
|
|
|
class SubmitShippingResponse extends Response |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var SubmitShipmentRequest |
12
|
|
|
*/ |
13
|
|
|
protected $request; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @param string $prefix |
17
|
|
|
* @param string|null $dir |
18
|
|
|
* @return \SplFileObject[]|null |
19
|
|
|
* @throws InvalidBase64Exception |
20
|
|
|
* @throws InvalidLabelsOptionException |
21
|
|
|
*/ |
22
|
|
|
public function saveLabels(string $prefix = 'label-', string $dir = null) : ?array |
23
|
|
|
{ |
24
|
|
|
$labelsOption = $this->request->getOption('Labels'); |
25
|
|
|
if (!$labelsOption) { |
26
|
|
|
throw new InvalidLabelsOptionException('The labels option is not set. This is unexpected.'); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
if ($labelsOption === 'none') { |
30
|
|
|
return null; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
$extensionMapping = [ |
34
|
|
|
'PNG' => 'png', |
35
|
|
|
'PDF' => 'pdf', |
36
|
|
|
'EPL' => 'epl', |
37
|
|
|
'ZPL' => 'zpl', |
38
|
|
|
'ZPLGK' => 'zplgk', |
39
|
|
|
'DATAMAXLP2' => 'datamaxlp2' |
40
|
|
|
]; |
41
|
|
|
|
42
|
|
|
if (!isset($extensionMapping[$labelsOption])) { |
43
|
|
|
throw new InvalidLabelsOptionException('The labels option `'.$labelsOption.'` was not found in: '.join(', ', array_keys($extensionMapping))); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$extension = $extensionMapping[$labelsOption]; |
47
|
|
|
|
48
|
|
|
if (!$dir) { |
|
|
|
|
49
|
|
|
$dir = sys_get_temp_dir(); |
50
|
|
|
} |
51
|
|
|
$dir = rtrim($dir, '/'); |
52
|
|
|
|
53
|
|
|
$files = []; |
54
|
|
|
|
55
|
|
|
foreach ($this->data['Labels'] as $label) { |
56
|
|
|
$decoded = base64_decode($label['Content']); |
57
|
|
|
|
58
|
|
|
if ($decoded === false) { |
59
|
|
|
throw new InvalidBase64Exception('An error occurred during the base64_decode'); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$file = $this->getFile($extension, $prefix, $dir); |
63
|
|
|
$file->fwrite($decoded); |
64
|
|
|
|
65
|
|
|
$files[] = $file; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
return $files; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
protected function getFile(string $extension, string $prefix, string $dir) : \SplFileObject |
72
|
|
|
{ |
73
|
|
|
do { |
74
|
|
|
$filename = $dir.'/'.uniqid($prefix, true).'.'.$extension; |
75
|
|
|
} while (file_exists($filename)); |
76
|
|
|
|
77
|
|
|
return new \SplFileObject($filename, 'w+'); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
In PHP, under loose comparison (like
==
, or!=
, orswitch
conditions), values of different types might be equal.For
string
values, the empty string''
is a special case, in particular the following results might be unexpected: