Completed
Pull Request — master (#23)
by Marco
37:36 queued 35:24
created

Instantiator::isInstantiableViaReflection()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 2
eloc 2
nc 2
nop 1
crap 2
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\Instantiator;
21
22
use Closure;
23
use Doctrine\Instantiator\Exception\InvalidArgumentException;
24
use Doctrine\Instantiator\Exception\UnexpectedValueException;
25
use Exception;
26
use ReflectionClass;
27
28
/**
29
 * {@inheritDoc}
30
 *
31
 * @author Marco Pivetta <[email protected]>
32
 */
33
final class Instantiator implements InstantiatorInterface
34
{
35
    /**
36
     * Markers used internally by PHP to define whether {@see \unserialize} should invoke
37
     * the method {@see \Serializable::unserialize()} when dealing with classes implementing
38
     * the {@see \Serializable} interface.
39
     */
40
    const SERIALIZATION_FORMAT_USE_UNSERIALIZER   = 'C';
41
    const SERIALIZATION_FORMAT_AVOID_UNSERIALIZER = 'O';
42
43
    /**
44
     * @var \callable[] used to instantiate specific classes, indexed by class name
45
     */
46
    private static $cachedInstantiators = [];
47
48
    /**
49
     * @var object[] of objects that can directly be cloned, indexed by class name
50
     */
51
    private static $cachedCloneables = [];
52
53
    /**
54
     * {@inheritDoc}
55
     */
56 40
    public function instantiate($className)
57
    {
58 40
        if (isset(self::$cachedCloneables[$className])) {
59 10
            return clone self::$cachedCloneables[$className];
60
        }
61
62 31
        if (isset(self::$cachedInstantiators[$className])) {
63 9
            $factory = self::$cachedInstantiators[$className];
64
65 9
            return $factory();
66
        }
67
68 22
        return $this->buildAndCacheFromFactory($className);
69
    }
70
71
    /**
72
     * Builds the requested object and caches it in static properties for performance
73
     *
74
     * @param string $className
75
     *
76
     * @return object
77
     */
78 22
    private function buildAndCacheFromFactory($className)
79
    {
80 22
        $factory  = self::$cachedInstantiators[$className] = $this->buildFactory($className);
81 17
        $instance = $factory();
82
83 17
        if ($this->isSafeToClone(new ReflectionClass($instance))) {
84 10
            self::$cachedCloneables[$className] = clone $instance;
85 10
        }
86
87 17
        return $instance;
88
    }
89
90
    /**
91
     * Builds a callable capable of instantiating the given $className without
92
     * invoking its constructor.
93
     *
94
     * @param string $className
95
     *
96
     * @return callable
97
     */
98 22
    private function buildFactory($className)
99
    {
100 22
        $reflectionClass = $this->getReflectionClass($className);
101
102 18
        if ($this->isInstantiableViaReflection($reflectionClass)) {
103 16
            return [$reflectionClass, 'newInstanceWithoutConstructor'];
104
        }
105
106 2
        $serializedString = sprintf(
107 2
            '%s:%d:"%s":0:{}',
108 2
            self::SERIALIZATION_FORMAT_AVOID_UNSERIALIZER,
109 2
            strlen($className),
110
            $className
111 2
        );
112
113 2
        $this->checkIfUnSerializationIsSupported($reflectionClass, $serializedString);
114
115
        return function () use ($serializedString) {
116 2
            return unserialize($serializedString);
117 1
        };
118
    }
119
120
    /**
121
     * @param string $className
122
     *
123
     * @return ReflectionClass
124
     *
125
     * @throws InvalidArgumentException
126
     */
127 22
    private function getReflectionClass($className)
128
    {
129 22
        if (! class_exists($className)) {
130 3
            throw InvalidArgumentException::fromNonExistingClass($className);
131
        }
132
133 19
        $reflection = new ReflectionClass($className);
134
135 19
        if ($reflection->isAbstract()) {
136 1
            throw InvalidArgumentException::fromAbstractClass($reflection);
137
        }
138
139 18
        return $reflection;
140
    }
141
142
    /**
143
     * @param ReflectionClass $reflectionClass
144
     * @param string          $serializedString
145
     *
146
     * @throws UnexpectedValueException
147
     *
148
     * @return void
149
     */
150
    private function checkIfUnSerializationIsSupported(ReflectionClass $reflectionClass, $serializedString)
151
    {
152 2
        set_error_handler(function ($code, $message, $file, $line) use ($reflectionClass, & $error) {
153 1
            $error = UnexpectedValueException::fromUncleanUnSerialization(
154 1
                $reflectionClass,
155 1
                $message,
156 1
                $code,
157 1
                $file,
158
                $line
159 1
            );
160 2
        });
161
162 2
        $this->attemptInstantiationViaUnSerialization($reflectionClass, $serializedString);
163
164 2
        restore_error_handler();
165
166 2
        if ($error) {
167 1
            throw $error;
168
        }
169 1
    }
170
171
    /**
172
     * @param ReflectionClass $reflectionClass
173
     * @param string          $serializedString
174
     *
175
     * @throws UnexpectedValueException
176
     *
177
     * @return void
178
     */
179 2
    private function attemptInstantiationViaUnSerialization(ReflectionClass $reflectionClass, $serializedString)
180
    {
181
        try {
182 2
            unserialize($serializedString);
183 2
        } catch (Exception $exception) {
184
            restore_error_handler();
185
186
            throw UnexpectedValueException::fromSerializationTriggeredException($reflectionClass, $exception);
187
        }
188 2
    }
189
190
    /**
191
     * @param ReflectionClass $reflectionClass
192
     *
193
     * @return bool
194
     */
195 18
    private function isInstantiableViaReflection(ReflectionClass $reflectionClass)
196
    {
197 18
        return ! ($this->hasInternalAncestors($reflectionClass) && $reflectionClass->isFinal());
198
    }
199
200
    /**
201
     * Verifies whether the given class is to be considered internal
202
     *
203
     * @param ReflectionClass $reflectionClass
204
     *
205
     * @return bool
206
     */
207 18
    private function hasInternalAncestors(ReflectionClass $reflectionClass)
208
    {
209
        do {
210 18
            if ($reflectionClass->isInternal()) {
211 13
                return true;
212
            }
213 13
        } while ($reflectionClass = $reflectionClass->getParentClass());
214
215 5
        return false;
216
    }
217
218
    /**
219
     * Checks if a class is cloneable
220
     *
221
     * Classes implementing `__clone` cannot be safely cloned, as that may cause side-effects.
222
     *
223
     * @param ReflectionClass $reflection
224
     *
225
     * @return bool
226
     */
227 17
    private function isSafeToClone(ReflectionClass $reflection)
228
    {
229 17
        return $reflection->isCloneable() && ! $reflection->hasMethod('__clone');
230
    }
231
}
232