Detects the file type and processes it accordingly.
Parameters
$filestringrequired- The file string to process.
$providedMimeTypestring|nullrequired- The explicitly provided MIME type.
Source
private function detectAndProcessFile(string $file, ?string $providedMimeType): void
{
// Check if it's a URL
if ($this->isUrl($file)) {
$this->fileType = FileTypeEnum::remote();
$this->url = $file;
$this->mimeType = $this->determineMimeType($providedMimeType, null, $file);
return;
}
// Data URI pattern.
$dataUriPattern = '/^data:(?:([a-zA-Z0-9][a-zA-Z0-9!#$&\-\^_+.]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-\^_+.]*' . '(?:;[a-zA-Z0-9\-]+=[a-zA-Z0-9\-]+)*)?;)?base64,([A-Za-z0-9+\/]*={0,2})$/';
// Check if it's a data URI.
if (preg_match($dataUriPattern, $file, $matches)) {
$this->fileType = FileTypeEnum::inline();
$this->base64Data = $matches[2];
// Extract just the base64 data
$extractedMimeType = empty($matches[1]) ? null : $matches[1];
$this->mimeType = $this->determineMimeType($providedMimeType, $extractedMimeType, null);
return;
}
// Check if it's a local file path (before base64 check)
if (file_exists($file) && is_file($file)) {
$this->fileType = FileTypeEnum::inline();
$this->base64Data = $this->convertFileToBase64($file);
$this->mimeType = $this->determineMimeType($providedMimeType, null, $file);
return;
}
// Check if it's plain base64
if (preg_match('/^[A-Za-z0-9+\/]*={0,2}$/', $file)) {
if ($providedMimeType === null) {
throw new InvalidArgumentException('MIME type is required when providing plain base64 data without data URI format.');
}
$this->fileType = FileTypeEnum::inline();
$this->base64Data = $file;
$this->mimeType = new MimeType($providedMimeType);
return;
}
throw new InvalidArgumentException('Invalid file provided. Expected URL, base64 data, or valid local file path.');
}
Changelog
| Version | Description |
|---|---|
| 0.1.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.