|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PhpLlm\LlmChain\Model\Message\Content; |
| 6 | + |
| 7 | +use PhpLlm\LlmChain\Exception\InvalidArgumentException; |
| 8 | + |
| 9 | +use function Symfony\Component\String\u; |
| 10 | + |
| 11 | +readonly class File |
| 12 | +{ |
| 13 | + final public function __construct( |
| 14 | + private string|\Closure $data, |
| 15 | + private string $format, |
| 16 | + private ?string $path = null, |
| 17 | + ) { |
| 18 | + } |
| 19 | + |
| 20 | + public static function fromDataUrl(string $dataUrl): static |
| 21 | + { |
| 22 | + if (!str_starts_with($dataUrl, 'data:')) { |
| 23 | + throw new InvalidArgumentException('Invalid audio data URL format.'); |
| 24 | + } |
| 25 | + |
| 26 | + return new static( |
| 27 | + base64_decode(u($dataUrl)->after('base64,')->toString()), |
| 28 | + u($dataUrl)->after('data:')->before(';base64,')->toString(), |
| 29 | + ); |
| 30 | + } |
| 31 | + |
| 32 | + public static function fromFile(string $path): static |
| 33 | + { |
| 34 | + if (!is_readable($path)) { |
| 35 | + throw new \InvalidArgumentException(sprintf('The file "%s" does not exist or is not readable.', $path)); |
| 36 | + } |
| 37 | + |
| 38 | + return new static( |
| 39 | + fn () => file_get_contents($path), |
| 40 | + mime_content_type($path), |
| 41 | + $path, |
| 42 | + ); |
| 43 | + } |
| 44 | + |
| 45 | + public function getFormat(): string |
| 46 | + { |
| 47 | + return $this->format; |
| 48 | + } |
| 49 | + |
| 50 | + public function asBinary(): string |
| 51 | + { |
| 52 | + return $this->data instanceof \Closure ? ($this->data)() : $this->data; |
| 53 | + } |
| 54 | + |
| 55 | + public function asBase64(): string |
| 56 | + { |
| 57 | + return base64_encode($this->asBinary()); |
| 58 | + } |
| 59 | + |
| 60 | + public function asDataUrl(): string |
| 61 | + { |
| 62 | + return sprintf('data:%s;base64,%s', $this->format, $this->asBase64()); |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * @return resource|false |
| 67 | + */ |
| 68 | + public function asResource() |
| 69 | + { |
| 70 | + if (null === $this->path) { |
| 71 | + throw new \RuntimeException('You can only get a resource after creating fromFile.'); |
| 72 | + } |
| 73 | + |
| 74 | + return fopen($this->path, 'r'); |
| 75 | + } |
| 76 | +} |
0 commit comments