This repository has been archived by the owner on Apr 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClassAnalyser.php
107 lines (96 loc) · 3.08 KB
/
ClassAnalyser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
/**
* Copyright (C) GrizzIT, Inc. All rights reserved.
* See LICENSE for license details.
*/
namespace Ulrack\ObjectFactory\Component\Analyser;
use ReflectionClass;
use Ulrack\Storage\Common\StorageInterface;
use Ulrack\ObjectFactory\Common\ClassAnalyserInterface;
use Ulrack\ObjectFactory\Exception\NonInstantiableClassException;
class ClassAnalyser implements ClassAnalyserInterface
{
/**
* A translation array to equalize the expected types of the gettype method.
*
* @var array
*/
private $translations = [
'bool' => 'boolean',
'int' => 'integer',
'float' => 'double',
'callable' => 'array',
];
/**
* Contains the previously analysed classes.
*
* @var StorageInterface
*/
private $analysisStorage;
/**
* Constructor
*
* @param StorageInterface $analysisStorage
*/
public function __construct(StorageInterface $analysisStorage)
{
$this->analysisStorage = $analysisStorage;
}
/**
* Analyses the constructor of a class and returns a configuration array.
*
* @return array
*
* @throws NonInstantiableClassException When the analysed class is not instantiable.
*/
public function analyse(string $class): array
{
if (!$this->analysisStorage->has($class)) {
$this->analysisStorage->set(
$class,
$this->reflect($class)
);
}
return $this->analysisStorage->get($class);
}
/**
* Retrieves a class analysis.
*
* @param string $class
*
* @return array
*
* @throws NonInstantiableClassException When the analysed class is not instantiable.
*/
private function reflect(string $class): array
{
$reflection = new ReflectionClass($class);
if ($reflection->isInstantiable()) {
$constructor = $reflection->getConstructor();
$parameters = [];
if ($constructor !== null) {
foreach ($constructor->getParameters() as $parameter) {
$type = $parameter->getType();
$parameters[$parameter->getName()] = [
'type' => $type !== null ?
(array_key_exists($type->getName(), $this->translations)
? $this->translations[$type->getName()]
: $type->getName())
: 'mixed',
'builtin' => $type !== null ? $type->isBuiltin(): true,
'allowsNull' => $parameter->allowsNull(),
'isOptional' => $parameter->isOptional(),
'isVariadic' => $parameter->isVariadic(),
'default' => $parameter->isDefaultValueAvailable()
? $parameter->getDefaultValue()
: null,
];
}
}
return $parameters;
}
throw new NonInstantiableClassException(
$class
);
}
}