-
Notifications
You must be signed in to change notification settings - Fork 0
/
SymfonySerializerResponseBodyConverter.php
52 lines (45 loc) · 1.61 KB
/
SymfonySerializerResponseBodyConverter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
declare(strict_types=1);
namespace Retrofit\Converter\SymfonySerializer;
use Psr\Http\Message\StreamInterface;
use Retrofit\Core\Converter\ResponseBodyConverter;
use Retrofit\Core\Type;
use Symfony\Component\Serializer\Exception\NotEncodableValueException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Component\Serializer\Serializer;
/**
* {@link ResponseBodyConverter} implementation.
*
* @internal
*/
readonly class SymfonySerializerResponseBodyConverter implements ResponseBodyConverter
{
public function __construct(
private Serializer $serializer,
private SymfonySerializerFormat $symfonySerializerFormat,
private Type $type,
)
{
}
public function convert(StreamInterface $value): mixed
{
if ($this->type->isA(StreamInterface::class)) {
return $value;
}
$contents = $value->getContents();
$typeIsArray = $this->type->isA('array');
try {
$type = $this->type->getRawType();
if ($typeIsArray) {
$type = "{$this->type->getParametrizedType()}[]";
}
return $this->serializer->deserialize($contents, $type, $this->symfonySerializerFormat->value);
} catch (NotNormalizableValueException|NotEncodableValueException) {
// If type is a scalar or scalar list (e.g.: string or string[]), whe must try to decode value.
if ($typeIsArray) {
return $this->serializer->decode($contents, $this->symfonySerializerFormat->value);
}
return $contents;
}
}
}