1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* Copyright (c) Nate Brunette. |
4
|
|
|
* Distributed under the MIT License (http://opensource.org/licenses/MIT) |
5
|
|
|
*/ |
6
|
|
|
|
7
|
|
|
declare(strict_types=1); |
8
|
|
|
|
9
|
|
|
namespace Tebru\Gson\TypeAdapter; |
10
|
|
|
|
11
|
|
|
use Tebru\Gson\Internal\TypeAdapterProvider; |
12
|
|
|
use Tebru\Gson\Context\ReaderContext; |
13
|
|
|
use Tebru\Gson\TypeAdapter; |
14
|
|
|
use Tebru\Gson\Context\WriterContext; |
15
|
|
|
use Tebru\PhpType\TypeToken; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Class WildcardTypeAdapter |
19
|
|
|
* |
20
|
|
|
* @author Nate Brunette <[email protected]> |
21
|
|
|
*/ |
22
|
|
|
class WildcardTypeAdapter extends TypeAdapter |
23
|
|
|
{ |
24
|
|
|
/** |
25
|
|
|
* @var TypeAdapterProvider |
26
|
|
|
*/ |
27
|
|
|
protected $typeAdapterProvider; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Constructor |
31
|
|
|
* |
32
|
|
|
* @param TypeAdapterProvider $typeAdapterProvider |
33
|
|
|
*/ |
34
|
17 |
|
public function __construct(TypeAdapterProvider $typeAdapterProvider) |
35
|
|
|
{ |
36
|
17 |
|
$this->typeAdapterProvider = $typeAdapterProvider; |
37
|
17 |
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Read the next value, convert it to its type and return it |
41
|
|
|
* |
42
|
|
|
* @param $value |
43
|
|
|
* @param ReaderContext $context |
44
|
|
|
* @return mixed |
45
|
|
|
*/ |
46
|
9 |
|
public function read($value, ReaderContext $context) |
47
|
|
|
{ |
48
|
9 |
|
$type = TypeToken::createFromVariable($value); |
49
|
9 |
|
if ($type->genericTypes === [] && !$context->enableScalarAdapters() && $type->isScalar()) { |
50
|
7 |
|
return $value; |
51
|
|
|
} |
52
|
|
|
|
53
|
2 |
|
return $this->typeAdapterProvider->getAdapter($type)->read($value, $context); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Write the value to the writer for the type |
58
|
|
|
* |
59
|
|
|
* @param mixed $value |
60
|
|
|
* @param WriterContext $context |
61
|
|
|
* @return mixed |
62
|
|
|
*/ |
63
|
8 |
|
public function write($value, WriterContext $context) |
64
|
|
|
{ |
65
|
8 |
|
$type = TypeToken::createFromVariable($value); |
66
|
8 |
|
if ($type->genericTypes === [] && !$context->enableScalarAdapters() && $type->isScalar()) { |
67
|
5 |
|
return $value; |
68
|
|
|
} |
69
|
|
|
|
70
|
3 |
|
return $this->typeAdapterProvider->getAdapter($type)->write($value, $context); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|