| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\HttpClient\Response; |
| 13 |
|
| 14 |
use Symfony\Component\HttpClient\Exception\InvalidArgumentException; |
| 15 |
|
| 16 |
class JsonMockResponse extends MockResponse |
| 17 |
{ |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
public function __construct(mixed $body = [], array $info = []) |
| 22 |
{ |
| 23 |
try { |
| 24 |
$json = json_encode($body, \JSON_THROW_ON_ERROR | \JSON_PRESERVE_ZERO_FRACTION); |
| 25 |
} catch (\JsonException $e) { |
| 26 |
throw new InvalidArgumentException('JSON encoding failed: '.$e->getMessage(), $e->getCode(), $e); |
| 27 |
} |
| 28 |
|
| 29 |
$info['response_headers']['content-type'] ??= 'application/json'; |
| 30 |
|
| 31 |
parent::__construct($json, $info); |
| 32 |
} |
| 33 |
|
| 34 |
public static function fromFile(string $path, array $info = []): static |
| 35 |
{ |
| 36 |
if (!is_file($path)) { |
| 37 |
throw new InvalidArgumentException(\sprintf('File not found: "%s".', $path)); |
| 38 |
} |
| 39 |
|
| 40 |
$json = file_get_contents($path); |
| 41 |
if (!json_validate($json)) { |
| 42 |
throw new \InvalidArgumentException(\sprintf('File "%s" does not contain valid JSON.', $path)); |
| 43 |
} |
| 44 |
|
| 45 |
return new static(json_decode($json, true, flags: \JSON_THROW_ON_ERROR), $info); |
| 46 |
} |
| 47 |
} |