Failed Conditions
Pull Request — master (#4244)
by Owen
12:13
created

Drawing::getImageFileExtensionForSave()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 9
rs 10
c 0
b 0
f 0
ccs 3
cts 3
cp 1
cc 2
nc 2
nop 1
crap 2
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 194
    public function __construct()
31
    {
32
        // Initialise values
33 194
        $this->path = '';
34 194
        $this->isUrl = false;
35
36
        // Initialize parent
37 194
        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 44
    public function getIndexedFilename(): string
52
    {
53 44
        return md5($this->path) . '.' . $this->getExtension();
54
    }
55
56
    /**
57
     * Get Extension.
58
     */
59 44
    public function getExtension(): string
60
    {
61 44
        $exploded = explode('.', basename($this->path));
62
63 44
        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 117
    public function getPath(): string
82
    {
83 117
        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 104
    public function setPath(string $path, bool $verifyFile = true, ?ZipArchive $zip = null): static
96
    {
97 104
        $this->isUrl = false;
98 104
        if (preg_match('~^data:image/[a-z]+;base64,~', $path) === 1) {
99 4
            $this->path = $path;
100
101 4
            return $this;
102
        }
103
104 102
        $this->path = '';
105
        // Check if a URL has been passed. https://stackoverflow.com/a/2058596/1252979
106 102
        if (filter_var($path, FILTER_VALIDATE_URL)) {
107 6
            if (!preg_match('/^(http|https|file|ftp|s3):/', $path)) {
108 2
                throw new PhpSpreadsheetException('Invalid protocol for linked drawing');
109
            }
110
            // Implicit that it is a URL, rather store info than running check above on value in other places.
111 4
            $this->isUrl = true;
112 4
            $ctx = null;
113
            // https://github.com/php/php-src/issues/16023
114 4
            if (str_starts_with($path, 'https:')) {
115 4
                $ctx = stream_context_create(['ssl' => ['crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT]]);
116
            }
117 4
            $imageContents = @file_get_contents($path, false, $ctx);
118 4
            if ($imageContents !== false) {
119 2
                $filePath = tempnam(sys_get_temp_dir(), 'Drawing');
120 2
                if ($filePath) {
121 2
                    $put = @file_put_contents($filePath, $imageContents);
122 2
                    if ($put !== false) {
123 2
                        if ($this->isImage($filePath)) {
124 2
                            $this->path = $path;
125 2
                            $this->setSizesAndType($filePath);
126
                        }
127 2
                        unlink($filePath);
128
                    }
129
                }
130
            }
131 96
        } elseif ($zip instanceof ZipArchive) {
132 60
            $zipPath = explode('#', $path)[1];
133 60
            $locate = @$zip->locateName($zipPath);
134 60
            if ($locate !== false) {
135 60
                if ($this->isImage($path)) {
136 60
                    $this->path = $path;
137 60
                    $this->setSizesAndType($path);
138
                }
139
            }
140
        } else {
141 50
            $exists = @file_exists($path);
142 50
            if ($exists !== false && $this->isImage($path)) {
143 48
                $this->path = $path;
144 48
                $this->setSizesAndType($path);
145
            }
146
        }
147 100
        if ($this->path === '' && $verifyFile) {
148 1
            throw new PhpSpreadsheetException("File $path not found!");
149
        }
150
151 99
        if ($this->worksheet !== null) {
152
            if ($this->path !== '') {
153
                $this->worksheet->getCell($this->coordinates);
154 96
            }
155
        }
156 96
157 96
        return $this;
158 96
    }
159 95
160 3
    private function isImage(string $path): bool
161 2
    {
162 2
        $mime = (string) @mime_content_type($path);
163
        $retVal = false;
164
        if (str_starts_with($mime, 'image/')) {
165 96
            $retVal = true;
166
        } elseif ($mime === 'application/octet-stream') {
167
            $extension = pathinfo($path, PATHINFO_EXTENSION);
168
            $retVal = in_array($extension, ['bin', 'emf'], true);
169
        }
170
171 43
        return $retVal;
172
    }
173 43
174
    /**
175
     * Get isURL.
176
     */
177
    public function getIsURL(): bool
178
    {
179
        return $this->isUrl;
180
    }
181
182
    /**
183
     * Set isURL.
184
     *
185
     * @return $this
186
     */
187
    public function setIsURL(bool $isUrl): self
188
    {
189
        $this->isUrl = $isUrl;
190
191
        return $this;
192
    }
193 42
194
    /**
195 42
     * Get hash code.
196 42
     *
197 42
     * @return string Hash code
198 42
     */
199 42
    public function getHashCode(): string
200
    {
201
        return md5(
202
            $this->path
203
            . parent::getHashCode()
204
            . __CLASS__
205 1
        );
206
    }
207 1
208 1
    /**
209
     * Get Image Type for Save.
210
     */
211 1
    public function getImageTypeForSave(): int
212
    {
213
        if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) {
214
            throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
215
        }
216
217 3
        return self::IMAGE_TYPES_CONVERTION_MAP[$this->type];
218
    }
219 3
220 1
    /**
221
     * Get Image file extention for Save.
222
     */
223 3
    public function getImageFileExtensionForSave(bool $includeDot = true): string
224
    {
225 3
        if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) {
226
            throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
227
        }
228
229
        $result = image_type_to_extension(self::IMAGE_TYPES_CONVERTION_MAP[$this->type], $includeDot);
230
231 3
        return "$result";
232
    }
233 3
234 1
    /**
235
     * Get Image mime type.
236
     */
237 3
    public function getImageMimeType(): string
238
    {
239
        if (!array_key_exists($this->type, self::IMAGE_TYPES_CONVERTION_MAP)) {
240
            throw new PhpSpreadsheetException('Unsupported image type in comment background. Supported types: PNG, JPEG, BMP, GIF.');
241
        }
242
243
        return image_type_to_mime_type(self::IMAGE_TYPES_CONVERTION_MAP[$this->type]);
244
    }
245
}
246