Completed
Push — master ( a904dc...40c607 )
by Joachim
01:50
created

SubmitShippingResponse::saveLabels()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 13
nc 6
nop 3
dl 0
loc 24
ccs 0
cts 18
cp 0
crap 20
rs 8.6845
c 0
b 0
f 0
1
<?php
2
namespace Loevgaard\Consignor\ShipmentServer\Response;
3
4
use Loevgaard\Consignor\ShipmentServer\Exception\InvalidBase64Exception;
5
6
class SubmitShippingResponse extends Response
7
{
8
    /**
9
     * @param string $extension
10
     * @param string $prefix
11
     * @param string|null $dir
12
     * @return \SplFileObject[]
13
     * @throws InvalidBase64Exception
14
     */
15
    public function saveLabels(string $extension, string $prefix = 'label-', string $dir = null) : array
16
    {
17
        if (!$dir) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $dir of type null|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch 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:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
18
            $dir = sys_get_temp_dir();
19
        }
20
        $dir = rtrim($dir, '/');
21
22
        $files = [];
23
24
        foreach ($this->data['Labels'] as $label) {
25
            $decoded = base64_decode($label['Content']);
26
27
            if ($decoded === false) {
28
                throw new InvalidBase64Exception('An error occurred during the base64_decode');
29
            }
30
31
            $file = $this->getFile($extension, $prefix, $dir);
32
            $file->fwrite($decoded);
33
34
            $files[] = $file;
35
        }
36
37
        return $files;
38
    }
39
40
    protected function getFile(string $extension, string $prefix, string $dir) : \SplFileObject
41
    {
42
        do {
43
            $filename = $dir.'/'.uniqid($prefix, true).'.'.$extension;
44
        } while (file_exists($filename));
45
46
        return new \SplFileObject($filename, 'w+');
47
    }
48
}
49