|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace OpenAI\Responses\Audio; |
| 4 | + |
| 5 | +use Generator; |
| 6 | +use Http\Discovery\Psr17Factory; |
| 7 | +use OpenAI\Contracts\ResponseHasMetaInformationContract; |
| 8 | +use OpenAI\Contracts\ResponseStreamContract; |
| 9 | +use OpenAI\Responses\Meta\MetaInformation; |
| 10 | +use Psr\Http\Message\ResponseInterface; |
| 11 | + |
| 12 | +/** |
| 13 | + * @implements ResponseStreamContract<string> |
| 14 | + */ |
| 15 | +final class SpeechStreamResponse implements ResponseHasMetaInformationContract, ResponseStreamContract |
| 16 | +{ |
| 17 | + public function __construct( |
| 18 | + private readonly ResponseInterface $response, |
| 19 | + ) { |
| 20 | + // |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * {@inheritDoc} |
| 25 | + */ |
| 26 | + public function getIterator(): Generator |
| 27 | + { |
| 28 | + while (! $this->response->getBody()->eof()) { |
| 29 | + yield $this->response->getBody()->read(1024); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + public function meta(): MetaInformation |
| 34 | + { |
| 35 | + // @phpstan-ignore-next-line |
| 36 | + return MetaInformation::from($this->response->getHeaders()); |
| 37 | + } |
| 38 | + |
| 39 | + public static function fake(string $content = null, MetaInformation $meta = null): static |
| 40 | + { |
| 41 | + $psr17Factory = new Psr17Factory(); |
| 42 | + $response = $psr17Factory->createResponse() |
| 43 | + ->withBody($psr17Factory->createStream($content ?? (string) file_get_contents(__DIR__.'/../../Testing/Responses/Fixtures/Audio/speech-streamed.mp3'))); |
| 44 | + |
| 45 | + if ($meta instanceof \OpenAI\Responses\Meta\MetaInformation) { |
| 46 | + foreach ($meta->toArray() as $key => $value) { |
| 47 | + $response = $response->withHeader($key, (string) $value); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + return new self($response); |
| 52 | + } |
| 53 | +} |
0 commit comments