isPhpVersionWithBrokenSerializationFormat()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 2
eloc 2
nc 2
nop 0
crap 6
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 Mockery;
21
22
use Closure;
23
use ReflectionClass;
24
use UnexpectedValueException;
25
use InvalidArgumentException;
26
27
/**
28
 * This is a trimmed down version of https://github.com/doctrine/instantiator,
29
 * basically without the caching
30
 *
31
 * @author Marco Pivetta <[email protected]>
32
 */
33
final class Instantiator
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
     * {@inheritDoc}
45
     */
46 402
    public function instantiate($className)
47
    {
48 402
        $factory    = $this->buildFactory($className);
49 402
        $instance   = $factory();
50 402
        $reflection = new ReflectionClass($instance);
51
52 402
        return $instance;
53
    }
54
55
    /**
56
     * @internal
57
     * @private
58
     *
59
     * Builds a {@see \Closure} capable of instantiating the given $className without
60
     * invoking its constructor.
61
     * This method is only exposed as public because of PHP 5.3 compatibility. Do not
62
     * use this method in your own code
63
     *
64
     * @param string $className
65
     *
66
     * @return Closure
67
     */
68 402
    public function buildFactory($className)
69
    {
70 402
        $reflectionClass = $this->getReflectionClass($className);
71
72 402
        if ($this->isInstantiableViaReflection($reflectionClass)) {
73
            return function () use ($reflectionClass) {
74 402
                return $reflectionClass->newInstanceWithoutConstructor();
75 402
            };
76
        }
77
78
        $serializedString = sprintf(
79
            '%s:%d:"%s":0:{}',
80
            $this->getSerializationFormat($reflectionClass),
81
            strlen($className),
82
            $className
83
        );
84
85
        $this->attemptInstantiationViaUnSerialization($reflectionClass, $serializedString);
86
87
        return function () use ($serializedString) {
88
            return unserialize($serializedString);
89
        };
90
    }
91
92
    /**
93
     * @param string $className
94
     *
95
     * @return ReflectionClass
96
     *
97
     * @throws InvalidArgumentException
98
     */
99 402
    private function getReflectionClass($className)
100
    {
101 402
        if (! class_exists($className)) {
102
            throw new InvalidArgumentException("Class:$className does not exist");
103
        }
104
105 402
        $reflection = new ReflectionClass($className);
106
107 402
        if ($reflection->isAbstract()) {
108
            throw new InvalidArgumentException("Class:$className is an abstract class");
109
        }
110
111 402
        return $reflection;
112
    }
113
114
    /**
115
     * @param ReflectionClass $reflectionClass
116
     * @param string          $serializedString
117
     *
118
     * @throws UnexpectedValueException
119
     *
120
     * @return void
121
     */
122
    private function attemptInstantiationViaUnSerialization(ReflectionClass $reflectionClass, $serializedString)
123
    {
124
        set_error_handler(function ($code, $message, $file, $line) use ($reflectionClass, & $error) {
125
            $msg = sprintf(
126
                'Could not produce an instance of "%s" via un-serialization, since an error was triggered in file "%s" at line "%d"',
127
                $reflectionClass->getName(),
0 ignored issues
show
Bug introduced by
Consider using $reflectionClass->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
128
                $file,
129
                $line
130
            );
131
132
            $error = new UnexpectedValueException($msg, 0, new \Exception($message, $code));
133
        });
134
135
        try {
136
            unserialize($serializedString);
137
        } catch (\Exception $exception) {
138
            restore_error_handler();
139
140
            throw new UnexpectedValueException("An exception was raised while trying to instantiate an instance of \"{$reflectionClass->getName()}\" via un-serialization", 0, $exception);
0 ignored issues
show
Bug introduced by
Consider using $reflectionClass->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
141
        }
142
143
        restore_error_handler();
144
145
        if ($error) {
146
            throw $error;
147
        }
148
    }
149
150
    /**
151
     * @param ReflectionClass $reflectionClass
152
     *
153
     * @return bool
154
     */
155 402
    private function isInstantiableViaReflection(ReflectionClass $reflectionClass)
156
    {
157 402
        return ! ($reflectionClass->isInternal() && $reflectionClass->isFinal());
158
    }
159
160
    /**
161
     * Verifies whether the given class is to be considered internal
162
     *
163
     * @param ReflectionClass $reflectionClass
164
     *
165
     * @return bool
166
     */
167
    private function hasInternalAncestors(ReflectionClass $reflectionClass)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
168
    {
169
        do {
170
            if ($reflectionClass->isInternal()) {
171
                return true;
172
            }
173
        } while ($reflectionClass = $reflectionClass->getParentClass());
174
175
        return false;
176
    }
177
178
    /**
179
     * Verifies if the given PHP version implements the `Serializable` interface serialization
180
     * with an incompatible serialization format. If that's the case, use serialization marker
181
     * "C" instead of "O".
182
     *
183
     * @link http://news.php.net/php.internals/74654
184
     *
185
     * @param ReflectionClass $reflectionClass
186
     *
187
     * @return string the serialization format marker, either self::SERIALIZATION_FORMAT_USE_UNSERIALIZER
188
     *                or self::SERIALIZATION_FORMAT_AVOID_UNSERIALIZER
189
     */
190
    private function getSerializationFormat(ReflectionClass $reflectionClass)
191
    {
192
        if ($this->isPhpVersionWithBrokenSerializationFormat()
193
            && $reflectionClass->implementsInterface('Serializable')
194
        ) {
195
            return self::SERIALIZATION_FORMAT_USE_UNSERIALIZER;
196
        }
197
198
        return self::SERIALIZATION_FORMAT_AVOID_UNSERIALIZER;
199
    }
200
201
    /**
202
     * Checks whether the current PHP runtime uses an incompatible serialization format
203
     *
204
     * @return bool
205
     */
206
    private function isPhpVersionWithBrokenSerializationFormat()
207
    {
208
        return PHP_VERSION_ID === 50429 || PHP_VERSION_ID === 50513;
209
    }
210
}
211