Passed
Pull Request — master (#44)
by Nate
06:25 queued 02:42
created

WildcardTypeAdapter   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 9
eloc 11
c 0
b 0
f 0
dl 0
loc 49
ccs 13
cts 13
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A read() 0 8 4
A __construct() 0 3 1
A write() 0 8 4
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\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 19
    public function __construct(TypeAdapterProvider $typeAdapterProvider)
35
    {
36 19
        $this->typeAdapterProvider = $typeAdapterProvider;
37 19
    }
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 10
    public function read($value, ReaderContext $context)
47
    {
48 10
        $type = TypeToken::createFromVariable($value);
49 10
        if ($type->genericTypes === [] && !$context->enableScalarAdapters() && $type->isScalar()) {
50 1
            return $value;
51
        }
52
53 9
        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 9
    public function write($value, WriterContext $context)
64
    {
65 9
        $type = TypeToken::createFromVariable($value);
66 9
        if ($type->genericTypes === [] && !$context->enableScalarAdapters() && $type->isScalar()) {
67 1
            return $value;
68
        }
69
70 8
        return $this->typeAdapterProvider->getAdapter($type)->write($value, $context);
71
    }
72
}
73