Passed
Push — master ( c91c8c...4b8a92 )
by Owen
21:17
created

Drawing::setPath()   C

Complexity

Conditions 15
Paths 22

Size

Total Lines 52
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 15.3085

Importance

Changes 0
Metric Value
eloc 34
c 0
b 0
f 0
dl 0
loc 52
ccs 24
cts 27
cp 0.8889
rs 5.9166
cc 15
nc 22
nop 3
crap 15.3085

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Worksheet;
4
5
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
6
use ZipArchive;
7
8
class Drawing extends BaseDrawing
9
{
10
    const IMAGE_TYPES_CONVERTION_MAP = [
11
        IMAGETYPE_GIF => IMAGETYPE_PNG,
12
        IMAGETYPE_JPEG => IMAGETYPE_JPEG,
13
        IMAGETYPE_PNG => IMAGETYPE_PNG,
14
        IMAGETYPE_BMP => IMAGETYPE_PNG,
15
    ];
16
17
    /**
18
     * Path.
19
     */
20
    private string $path;
21
22
    /**
23
     * Whether or not we are dealing with a URL.
24
     */
25
    private bool $isUrl;
26
27
    /**
28
     * Create a new Drawing.
29
     */
30 178
    public function __construct()
31
    {
32
        // Initialise values
33 178
        $this->path = '';
34 178
        $this->isUrl = false;
35
36
        // Initialize parent
37 178
        parent::__construct();
38
    }
39
40
    /**
41
     * Get Filename.
42
     */
43 1
    public function getFilename(): string
44
    {
45 1
        return basename($this->path);
46
    }
47
48
    /**
49
     * Get indexed filename (using image index).
50
     */
51 39
    public function getIndexedFilename(): string
52
    {
53 39
        return md5($this->path) . '.' . $this->getExtension();
54
    }
55
56
    /**
57
     * Get Extension.
58
     */
59 39
    public function getExtension(): string
60
    {
61 39
        $exploded = explode('.', basename($this->path));
62
63 39
        return $exploded[count($exploded) - 1];
64
    }
65
66
    /**
67
     * Get full filepath to store drawing in zip archive.
68
     */
69 3
    public function getMediaFilename(): string
70
    {
71 3
        if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) {
72 1
            throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
73
        }
74
75 3
        return sprintf('image%d%s', $this->getImageIndex(), $this->getImageFileExtensionForSave());
76
    }
77
78
    /**
79
     * Get Path.
80
     */
81 83
    public function getPath(): string
82
    {
83 83
        return $this->path;
84
    }
85
86
    /**
87
     * Set Path.
88
     *
89
     * @param string $path File path
90
     * @param bool $verifyFile Verify file
91
     * @param ?ZipArchive $zip Zip archive instance
92
     *
93
     * @return $this
94
     */
95 90
    public function setPath(string $path, bool $verifyFile = true, ?ZipArchive $zip = null): static
96
    {
97 90
        $this->isUrl = false;
98
        if (preg_match('~^data:image/[a-z]+;base64,~', $path) === 1) {
99 43
            $this->path = $path;
100 1
101
            return $this;
102 1
        }
103 1
104 1
        $this->path = '';
105 1
        // Check if a URL has been passed. https://stackoverflow.com/a/2058596/1252979
106 1
        if (filter_var($path, FILTER_VALIDATE_URL)) {
107 1
            if (!preg_match('/^(http|https|file|ftp|s3):/', $path)) {
108 1
                throw new PhpSpreadsheetException('Invalid protocol for linked drawing');
109 1
            }
110
            // Implicit that it is a URL, rather store info than running check above on value in other places.
111
            $this->isUrl = true;
112 42
            $imageContents = @file_get_contents($path);
113 39
            if ($imageContents !== false) {
114 39
                $filePath = tempnam(sys_get_temp_dir(), 'Drawing');
115 5
                if ($filePath) {
116 5
                    $put = @file_put_contents($filePath, $imageContents);
117 5
                    if ($put !== false) {
118 5
                        if ($this->isImage($filePath)) {
119 5
                            $this->path = $path;
120
                            $this->setSizesAndType($filePath);
121
                        }
122
                        unlink($filePath);
123
                    }
124
                }
125 57
            }
126
        } elseif ($zip instanceof ZipArchive) {
127
            $zipPath = explode('#', $path)[1];
128 90
            $locate = @$zip->locateName($zipPath);
129
            if ($locate !== false) {
130
                if ($this->isImage($path)) {
131
                    $this->path = $path;
132
                    $this->setSizesAndType($path);
133
                }
134 2
            }
135
        } else {
136 2
            $exists = @file_exists($path);
137
            if ($exists !== false && $this->isImage($path)) {
138
                $this->path = $path;
139
                $this->setSizesAndType($path);
140
            }
141
        }
142
        if ($this->path === '' && $verifyFile) {
143
            throw new PhpSpreadsheetException("File $path not found!");
144
        }
145
146
        return $this;
147
    }
148
149
    private function isImage(string $path): bool
150
    {
151
        $mime = (string) @mime_content_type($path);
152
        $retVal = false;
153
        if (str_starts_with($mime, 'image/')) {
154
            $retVal = true;
155
        } elseif ($mime === 'application/octet-stream') {
156 37
            $extension = pathinfo($path, PATHINFO_EXTENSION);
157
            $retVal = in_array($extension, ['bin', 'emf'], true);
158 37
        }
159 37
160 37
        return $retVal;
161 37
    }
162 37
163
    /**
164
     * Get isURL.
165
     */
166
    public function getIsURL(): bool
167
    {
168 1
        return $this->isUrl;
169
    }
170 1
171 1
    /**
172
     * Set isURL.
173
     *
174 1
     * @return $this
175
     */
176
    public function setIsURL(bool $isUrl): self
177
    {
178
        $this->isUrl = $isUrl;
179
180 3
        return $this;
181
    }
182 3
183 1
    /**
184
     * Get hash code.
185
     *
186 3
     * @return string Hash code
187
     */
188 3
    public function getHashCode(): string
189
    {
190
        return md5(
191
            $this->path
192
            . parent::getHashCode()
193
            . __CLASS__
194 3
        );
195
    }
196 3
197 1
    /**
198
     * Get Image Type for Save.
199
     */
200 3
    public function getImageTypeForSave(): int
201
    {
202
        if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) {
203
            throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
204
        }
205
206
        return self::IMAGE_TYPES_CONVERTION_MAP[$this->type];
207
    }
208
209
    /**
210
     * Get Image file extention for Save.
211
     */
212
    public function getImageFileExtensionForSave(bool $includeDot = true): string
213
    {
214
        if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) {
215
            throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
216
        }
217
218
        $result = image_type_to_extension(self::IMAGE_TYPES_CONVERTION_MAP[$this->type], $includeDot);
219
220
        return "$result";
221
    }
222
223
    /**
224
     * Get Image mime type.
225
     */
226
    public function getImageMimeType(): string
227
    {
228
        if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) {
229
            throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
230
        }
231
232
        return image_type_to_mime_type(self::IMAGE_TYPES_CONVERTION_MAP[$this->type]);
233
    }
234
}
235