| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 3 declare (strict_types=1); 4 namespace WordPress\AiClient\Files\Util; 5 6 use WordPress\AiClient\Common\Exception\InvalidArgumentException; 7 use WordPress\AiClient\Common\Exception\RuntimeException; 8 use WordPress\AiClient\Files\DTO\File; 9 /** 10 * Resolves developer-supplied file strings into File objects. 11 * 12 * This utility backs the convenience of passing a plain string to builder methods such as 13 * PromptBuilder::withFile(). Because it may read from the local filesystem, it must only be used with 14 * strings the developer controls. Never pass untrusted input (user input, API response data); construct 15 * a File explicitly via File::fromUrl(), File::fromDataUri() or File::fromBase64() instead. 16 * 17 * @since 1.5.1 18 */ 19 final class FileInputUtil 20 { 21 /** 22 * Resolves a file string into a File object. 23 * 24 * The string is interpreted, in this order, as an http(s) URL, a data URI, a local file path, or plain 25 * base64 data (which requires a MIME type). Any other URL scheme is rejected before the filesystem is 26 * consulted. 27 * 28 * @since 1.5.1 29 * 30 * @param string $input The file string. 31 * @param string|null $mimeType The MIME type (optional, required for plain base64 data). 32 * @return File The resolved file. 33 * @throws InvalidArgumentException If the string is not a supported file representation. 34 * @throws RuntimeException If a local file cannot be read. 35 */ 36 public static function fromString(string $input, ?string $mimeType = null): File 37 { 38 if (preg_match('/^https?:\/\//i', $input) === 1) { 39 return File::fromUrl($input, $mimeType); 40 } 41 if (str_contains($input, '://')) { 42 throw new InvalidArgumentException('Unsupported URL scheme. Only http:// and https:// URLs are supported.'); 43 } 44 if (str_starts_with($input, 'data:')) { 45 return File::fromDataUri($input, $mimeType); 46 } 47 // Local paths take precedence over plain base64: an extension-less path can look like base64. 48 if (is_file($input)) { 49 return File::fromLocalPath($input, $mimeType); 50 } 51 // Plain base64 (an empty payload is allowed, matching an empty local file). 52 if (preg_match('/^[A-Za-z0-9+\/]*={0,2}\z/', $input) === 1) { 53 if ($mimeType === null) { 54 throw new InvalidArgumentException('MIME type is required when providing plain base64 data without data URI format.'); 55 } 56 return File::fromBase64($input, $mimeType); 57 } 58 throw new InvalidArgumentException('Invalid file provided. Expected URL, data URI, base64 data, or valid local file path.'); 59 } 60 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Fri Oct 30 08:20:34 2026 | Cross-referenced by PHPXref |