LabelFileFactory   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 63
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B read() 0 24 4
A create() 0 6 1
1
<?php
2
3
namespace Loevgaard\PakkelabelsBundle\File;
4
5
use Loevgaard\Pakkelabels\Client;
6
use Loevgaard\PakkelabelsBundle\Entity\Label;
7
8
class LabelFileFactory
9
{
10
    /**
11
     * @var string
12
     */
13
    protected $labelDir;
14
15
    /**
16
     * @var Client
17
     */
18
    protected $pakkelabelsClient;
19
20
    public function __construct(Client $client, string $labelDir)
21
    {
22
        $this->pakkelabelsClient = $client;
23
        $this->labelDir = $labelDir;
24
    }
25
26
    /**
27
     * @param Label $label
28
     *
29
     * @return LabelFile
30
     */
31
    public function create(Label $label): LabelFile
32
    {
33
        $file = new LabelFile($this->labelDir.'/'.$label->getId().'.png', 'w+');
34
35
        return $file;
36
    }
37
38
    /**
39
     * @todo This is a bit wrong. This should probably be a service of some sort instead of being called a 'factory'
40
     *
41
     * @param Label $label
42
     * @param bool  $verifyExistence
43
     *
44
     * @return LabelFile
45
     */
46
    public function read(Label $label, bool $verifyExistence = false): LabelFile
47
    {
48
        $labelFilePath = $this->labelDir.'/'.$label->getId().'.png';
49
50
        if ($verifyExistence && !file_exists($labelFilePath)) {
51
            $file = new LabelFile($labelFilePath, 'w+');
52
53
            $labelRes = $this->pakkelabelsClient->doRequest('get', '/shipments/'.$label->getExternalId().'/labels', [
54
                'query' => [
55
                    'label_format' => 'png',
56
                ],
57
            ]);
58
59
            if (isset($labelRes['error'])) {
60
                throw new \RuntimeException('The labels for label id '.$label->getId().' could not be downloaded from Pakkelabels. Error was: '.$labelRes['error']);
61
            }
62
63
            $file->fwrite(base64_decode($labelRes['base64']));
64
        } else {
65
            $file = new LabelFile($labelFilePath, 'r');
66
        }
67
68
        return $file;
69
    }
70
}
71