WordPress\AiClient\Files\DTO

File::detectAndProcessFileprivateWP 0.1.0

Detects the file type and processes it accordingly.

Method of the class: File{}

No Hooks.

Returns

null. Nothing (null).

Usage

// private - for code of main (parent) class only
$result = $this->detectAndProcessFile( $file, ?string $providedMimeType ): void;
$file(string) (required)
The file string to process.
?string $providedMimeType(required)
.

Changelog

Since 0.1.0 Introduced.

File::detectAndProcessFile() code WP 7.0

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.');
}