|
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\Context\ReaderContext; |
|
12
|
|
|
use Tebru\Gson\Context\WriterContext; |
|
13
|
|
|
use Tebru\Gson\Internal\TypeAdapterProvider; |
|
14
|
|
|
use Tebru\Gson\TypeAdapter; |
|
15
|
|
|
use Tebru\Gson\TypeAdapterFactory; |
|
16
|
|
|
use Tebru\PhpType\TypeToken; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Class IntegerTypeAdapter |
|
20
|
|
|
* |
|
21
|
|
|
* @author Nate Brunette <[email protected]> |
|
22
|
|
|
*/ |
|
23
|
|
|
class IntegerTypeAdapter extends TypeAdapter implements TypeAdapterFactory |
|
24
|
|
|
{ |
|
25
|
|
|
/** |
|
26
|
|
|
* Accepts the current type and a [@see TypeAdapterProvider] in case another type adapter needs |
|
27
|
|
|
* to be fetched during creation. Should return a new instance of the TypeAdapter. Will return |
|
28
|
|
|
* null if the type adapter is not supported for the provided type. |
|
29
|
|
|
* |
|
30
|
|
|
* @param TypeToken $type |
|
31
|
|
|
* @param TypeAdapterProvider $typeAdapterProvider |
|
32
|
|
|
* @return TypeAdapter|null |
|
33
|
|
|
*/ |
|
34
|
5 |
|
public function create(TypeToken $type, TypeAdapterProvider $typeAdapterProvider): ?TypeAdapter |
|
35
|
|
|
{ |
|
36
|
5 |
|
return $type->phpType === TypeToken::INTEGER ? $this : null; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Read the next value, convert it to its type and return it |
|
41
|
|
|
* |
|
42
|
|
|
* @param int|null $value |
|
43
|
|
|
* @param ReaderContext $context |
|
44
|
|
|
* @return int|null |
|
45
|
|
|
*/ |
|
46
|
2 |
|
public function read($value, ReaderContext $context): ?int |
|
47
|
|
|
{ |
|
48
|
2 |
|
return $value === null ? null : (int)$value; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* Write the value to the writer for the type |
|
53
|
|
|
* |
|
54
|
|
|
* @param int|null $value |
|
55
|
|
|
* @param WriterContext $context |
|
56
|
|
|
* @return int|null |
|
57
|
|
|
*/ |
|
58
|
2 |
|
public function write($value, WriterContext $context): ?int |
|
59
|
|
|
{ |
|
60
|
2 |
|
return $value === null ? null : (int)$value; |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|