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\Internal; |
10
|
|
|
|
11
|
|
|
use Tebru\Gson\InstanceCreator; |
12
|
|
|
use Tebru\Gson\Internal\ObjectConstructor\CreateFromInstanceCreator; |
13
|
|
|
use Tebru\Gson\Internal\ObjectConstructor\CreateFromReflectionClass; |
14
|
|
|
use Tebru\Gson\Internal\ObjectConstructor\CreateWithoutArguments; |
15
|
|
|
use Tebru\PhpType\TypeToken; |
16
|
|
|
use Throwable; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Class ConstructorConstructor |
20
|
|
|
* |
21
|
|
|
* This class acts as an ObjectConstructor factory. It takes in a map of instance creators and |
22
|
|
|
* wraps object creation in an [@see ObjectConstructor]. This does expensive operations |
23
|
|
|
* (like reflection) once and allows it to be cached for subsequent calls. |
24
|
|
|
* |
25
|
|
|
* @author Nate Brunette <[email protected]> |
26
|
|
|
*/ |
27
|
|
|
final class ConstructorConstructor |
28
|
|
|
{ |
29
|
|
|
/** |
30
|
|
|
* An array of [@see InstanceCreator] objects that can be used |
31
|
|
|
* for custom instantiation of a class |
32
|
|
|
* |
33
|
|
|
* @var InstanceCreator[] |
34
|
|
|
*/ |
35
|
|
|
private $instanceCreators; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Constructor |
39
|
|
|
* |
40
|
|
|
* @param InstanceCreator[] $instanceCreators |
41
|
|
|
*/ |
42
|
12 |
|
public function __construct(array $instanceCreators = []) |
43
|
|
|
{ |
44
|
12 |
|
$this->instanceCreators = $instanceCreators; |
45
|
12 |
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Get the correct [@see ObjectConstructor] to use |
49
|
|
|
* |
50
|
|
|
* @param TypeToken $type |
51
|
|
|
* @return ObjectConstructor |
52
|
|
|
*/ |
53
|
7 |
|
public function get(TypeToken $type): ObjectConstructor |
54
|
|
|
{ |
55
|
7 |
|
$class = $type->rawType; |
56
|
7 |
|
foreach ($this->instanceCreators as $instanceCreatorClass => $creator) { |
57
|
2 |
|
if ($type->isA($instanceCreatorClass)) { |
58
|
2 |
|
return new CreateFromInstanceCreator($creator, $type); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
try { |
63
|
|
|
// attempt to instantiate a new class without any arguments |
64
|
5 |
|
new $class(); |
65
|
|
|
|
66
|
4 |
|
return new CreateWithoutArguments($class); |
67
|
1 |
|
} /** @noinspection BadExceptionsProcessingInspection */ catch (Throwable $throwable) { |
68
|
1 |
|
return new CreateFromReflectionClass($class); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|