Skip to content

Commit ac3c9e7

Browse files
committed
feat: parses mime type from base64 data
1 parent cb20ce1 commit ac3c9e7

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

src/Files/DTO/InlineFile.php

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,36 @@ class InlineFile implements FileInterface, WithJsonSchemaInterface
3131
* @since n.e.x.t
3232
*
3333
* @param string $base64Data The base64-encoded file data.
34-
* @param string $mimeType The MIME type of the file.
34+
* @param string|null $mimeType The MIME type of the file.
3535
*/
36-
public function __construct(string $base64Data, string $mimeType)
36+
public function __construct(string $base64Data, string $mimeType = null)
3737
{
38+
// RFC 2397: dataurl := "data:" [ mediatype ] ";base64," data
39+
// mediatype is optional; if omitted, defaults to text/plain;charset=US-ASCII
40+
// We'll be more permissive and accept data URLs with or without MIME type
41+
$pattern = '/^data:(?:([a-zA-Z0-9][a-zA-Z0-9!#$&\-\^_+.]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-\^_+.]*'
42+
. '(?:;[a-zA-Z0-9\-]+=[a-zA-Z0-9\-]+)*)?;)?base64,([A-Za-z0-9+\/]*={0,2})$/';
43+
44+
if (!preg_match($pattern, $base64Data, $matches)) {
45+
throw new \InvalidArgumentException(
46+
'Invalid base64 data provided. Expected format: data:[mimeType];base64,[data]'
47+
);
48+
}
49+
3850
$this->base64Data = $base64Data;
39-
$this->mimeType = $mimeType;
51+
52+
if ($mimeType === null) {
53+
// Extract MIME type from data URL if present
54+
if (!empty($matches[1])) {
55+
// MIME type was provided in the data URL
56+
$this->mimeType = $matches[1];
57+
} else {
58+
// No MIME type provided; default to text/plain per RFC 2397
59+
$this->mimeType = 'text/plain';
60+
}
61+
} else {
62+
$this->mimeType = $mimeType;
63+
}
4064
}
4165

4266
/**

0 commit comments

Comments
 (0)