-
Notifications
You must be signed in to change notification settings - Fork 316
Expand file tree
/
Copy pathDataUriParser.php
More file actions
60 lines (48 loc) · 1.16 KB
/
DataUriParser.php
File metadata and controls
60 lines (48 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2022 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\Mail\Service\DataUri;
use OCA\Mail\Exception\InvalidDataUriException;
use function str_contains;
class DataUriParser {
private const PATTERN = '#^data:(?<media_type>[^,.]*),(?<data>.*)$#';
/**
* @throws InvalidDataUriException
*/
public function parse(string $dataUri): DataUri {
$matches = [];
if (preg_match(self::PATTERN, $dataUri, $matches) !== 1) {
throw new InvalidDataUriException();
}
if ($matches['media_type'] === '') {
$items = [];
} else {
$items = explode(';', $matches['media_type']);
}
$mediaType = 'text/plain';
$parameters = ['charset' => 'US-ASCII'];
$base64 = false;
if ($items !== []) {
$mediaType = array_shift($items);
foreach ($items as $item) {
if ($item === 'base64') {
$base64 = true;
continue;
}
if (str_contains($item, '=')) {
[$key, $value] = explode('=', $item);
$parameters[$key] = $value;
}
}
}
return new DataUri(
$mediaType,
$parameters,
$base64,
$matches['data']
);
}
}