|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace Symfony\AI\Platform; |
| 13 | + |
| 14 | +use Symfony\AI\Platform\Result\InMemoryRawResult; |
| 15 | +use Symfony\AI\Platform\Result\ResultPromise; |
| 16 | +use Symfony\AI\Platform\Result\TextResult; |
| 17 | + |
| 18 | +/** |
| 19 | + * A fake implementation of PlatformInterface that returns fixed or callable responses. |
| 20 | + * |
| 21 | + * Useful for unit or integration testing without real API calls. |
| 22 | + * |
| 23 | + * @author Ramy Hakam <[email protected]> |
| 24 | + */ |
| 25 | +class InMemoryPlatform implements PlatformInterface |
| 26 | +{ |
| 27 | + /** |
| 28 | + * The mock result can be a string or a callable that returns a string. |
| 29 | + * If it's a closure, it receives the model, input, and optionally options as parameters like a real platform call. |
| 30 | + */ |
| 31 | + public function __construct(private readonly \Closure|string $mockResult) |
| 32 | + { |
| 33 | + } |
| 34 | + |
| 35 | + public function invoke(Model $model, array|string|object $input, array $options = []): ResultPromise |
| 36 | + { |
| 37 | + $resultText = $this->mockResult instanceof \Closure |
| 38 | + ? ($this->mockResult)($model, $input, $options) |
| 39 | + : $this->mockResult; |
| 40 | + |
| 41 | + $textResult = new TextResult($resultText); |
| 42 | + |
| 43 | + return new ResultPromise( |
| 44 | + static fn () => $textResult, |
| 45 | + rawResult: new InMemoryRawResult( |
| 46 | + ['text' => $resultText], |
| 47 | + (object) ['text' => $resultText], |
| 48 | + ), |
| 49 | + options: $options |
| 50 | + ); |
| 51 | + } |
| 52 | +} |
0 commit comments