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 BooleanTypeAdapter |
20
|
|
|
* |
21
|
|
|
* @author Nate Brunette <[email protected]> |
22
|
|
|
*/ |
23
|
|
|
class BooleanTypeAdapter 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::BOOLEAN ? $this : null; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Read the next value, convert it to its type and return it |
41
|
|
|
* |
42
|
|
|
* @param bool|null $value |
43
|
|
|
* @param ReaderContext $context |
44
|
|
|
* @return bool|null |
45
|
|
|
*/ |
46
|
3 |
|
public function read($value, ReaderContext $context): ?bool |
47
|
|
|
{ |
48
|
3 |
|
return $value === null ? null : (bool)$value; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Write the value to the writer for the type |
53
|
|
|
* |
54
|
|
|
* @param boolean|null $value |
55
|
|
|
* @param WriterContext $context |
56
|
|
|
* @return bool|null |
57
|
|
|
*/ |
58
|
3 |
|
public function write($value, WriterContext $context): ?bool |
59
|
|
|
{ |
60
|
3 |
|
return $value === null ? null : (bool)$value; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|