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.
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>.
20 namespace Doctrine\Common\Proxy;
22 use Doctrine\Common\Persistence\Mapping\ClassMetadata;
23 use Doctrine\Common\Proxy\Exception\InvalidArgumentException;
24 use Doctrine\Common\Proxy\Exception\UnexpectedValueException;
25 use Doctrine\Common\Util\ClassUtils;
28 * This factory is used to generate proxy classes.
29 * It builds proxies from given parameters, a template and class metadata.
31 * @author Marco Pivetta <ocramius@gmail.com>
37 * Used to match very simple id methods that don't need
38 * to be decorated since the identifier is known.
40 const PATTERN_MATCH_ID_METHOD = '((public\s+)?(function\s+%s\s*\(\)\s*)\s*(?::\s*\??\s*\\\\?[a-z_\x7f-\xff][\w\x7f-\xff]*(?:\\\\[a-z_\x7f-\xff][\w\x7f-\xff]*)*\s*)?{\s*return\s*\$this->%s;\s*})i';
43 * The namespace that contains all proxy classes.
47 private $proxyNamespace;
50 * The directory that contains all proxy classes.
54 private $proxyDirectory;
57 * Map of callables used to fill in placeholders set in the template.
59 * @var string[]|callable[]
61 protected $placeholders = [
62 'baseProxyInterface' => Proxy::class,
63 'additionalProperties' => '',
67 * Template used as a blueprint to generate proxies.
71 protected $proxyClassTemplate = '<?php
73 namespace <namespace>;
76 * DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE\'S PROXY GENERATOR
78 class <proxyShortClassName> extends \<className> implements \<baseProxyInterface>
81 * @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with
82 * three parameters, being respectively the proxy object to be initialized, the method that triggered the
83 * initialization process and an array of ordered parameters that were passed to that method.
85 * @see \Doctrine\Common\Persistence\Proxy::__setInitializer
87 public $__initializer__;
90 * @var \Closure the callback responsible of loading properties that need to be copied in the cloned object
92 * @see \Doctrine\Common\Persistence\Proxy::__setCloner
97 * @var boolean flag indicating if this object was already initialized
99 * @see \Doctrine\Common\Persistence\Proxy::__isInitialized
101 public $__isInitialized__ = false;
104 * @var array properties to be lazy loaded, with keys being the property
105 * names and values being their default values
107 * @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties
109 public static $lazyPropertiesDefaults = [<lazyPropertiesDefaults>];
111 <additionalProperties>
128 * Forces initialization of the proxy
130 public function __load()
132 $this->__initializer__ && $this->__initializer__->__invoke($this, \'__load\', []);
137 * @internal generated method: use only when explicitly handling proxy specific loading logic
139 public function __isInitialized()
141 return $this->__isInitialized__;
146 * @internal generated method: use only when explicitly handling proxy specific loading logic
148 public function __setInitialized($initialized)
150 $this->__isInitialized__ = $initialized;
155 * @internal generated method: use only when explicitly handling proxy specific loading logic
157 public function __setInitializer(\Closure $initializer = null)
159 $this->__initializer__ = $initializer;
164 * @internal generated method: use only when explicitly handling proxy specific loading logic
166 public function __getInitializer()
168 return $this->__initializer__;
173 * @internal generated method: use only when explicitly handling proxy specific loading logic
175 public function __setCloner(\Closure $cloner = null)
177 $this->__cloner__ = $cloner;
182 * @internal generated method: use only when explicitly handling proxy specific cloning logic
184 public function __getCloner()
186 return $this->__cloner__;
191 * @internal generated method: use only when explicitly handling proxy specific loading logic
194 public function __getLazyProperties()
196 return self::$lazyPropertiesDefaults;
204 * Initializes a new instance of the <tt>ProxyFactory</tt> class that is
205 * connected to the given <tt>EntityManager</tt>.
207 * @param string $proxyDirectory The directory to use for the proxy classes. It must exist.
208 * @param string $proxyNamespace The namespace to use for the proxy classes.
210 * @throws InvalidArgumentException
212 public function __construct($proxyDirectory, $proxyNamespace)
214 if ( ! $proxyDirectory) {
215 throw InvalidArgumentException::proxyDirectoryRequired();
218 if ( ! $proxyNamespace) {
219 throw InvalidArgumentException::proxyNamespaceRequired();
222 $this->proxyDirectory = $proxyDirectory;
223 $this->proxyNamespace = $proxyNamespace;
227 * Sets a placeholder to be replaced in the template.
229 * @param string $name
230 * @param string|callable $placeholder
232 * @throws InvalidArgumentException
234 public function setPlaceholder($name, $placeholder)
236 if ( ! is_string($placeholder) && ! is_callable($placeholder)) {
237 throw InvalidArgumentException::invalidPlaceholder($name);
240 $this->placeholders[$name] = $placeholder;
244 * Sets the base template used to create proxy classes.
246 * @param string $proxyClassTemplate
248 public function setProxyClassTemplate($proxyClassTemplate)
250 $this->proxyClassTemplate = (string) $proxyClassTemplate;
254 * Generates a proxy class file.
256 * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class Metadata for the original class.
257 * @param string|bool $fileName Filename (full path) for the generated class. If none is given, eval() is used.
259 * @throws InvalidArgumentException
260 * @throws UnexpectedValueException
262 public function generateProxyClass(ClassMetadata $class, $fileName = false)
264 $this->verifyClassCanBeProxied($class);
266 preg_match_all('(<([a-zA-Z]+)>)', $this->proxyClassTemplate, $placeholderMatches);
268 $placeholderMatches = array_combine($placeholderMatches[0], $placeholderMatches[1]);
271 foreach ($placeholderMatches as $placeholder => $name) {
272 $placeholders[$placeholder] = isset($this->placeholders[$name])
273 ? $this->placeholders[$name]
274 : [$this, 'generate' . $name];
277 foreach ($placeholders as & $placeholder) {
278 if (is_callable($placeholder)) {
279 $placeholder = call_user_func($placeholder, $class);
283 $proxyCode = strtr($this->proxyClassTemplate, $placeholders);
286 $proxyClassName = $this->generateNamespace($class) . '\\' . $this->generateProxyShortClassName($class);
288 if ( ! class_exists($proxyClassName)) {
289 eval(substr($proxyCode, 5));
295 $parentDirectory = dirname($fileName);
297 if ( ! is_dir($parentDirectory) && (false === @mkdir($parentDirectory, 0775, true))) {
298 throw UnexpectedValueException::proxyDirectoryNotWritable($this->proxyDirectory);
301 if ( ! is_writable($parentDirectory)) {
302 throw UnexpectedValueException::proxyDirectoryNotWritable($this->proxyDirectory);
305 $tmpFileName = $fileName . '.' . uniqid('', true);
307 file_put_contents($tmpFileName, $proxyCode);
308 @chmod($tmpFileName, 0664);
309 rename($tmpFileName, $fileName);
313 * @param ClassMetadata $class
315 * @throws InvalidArgumentException
317 private function verifyClassCanBeProxied(ClassMetadata $class)
319 if ($class->getReflectionClass()->isFinal()) {
320 throw InvalidArgumentException::classMustNotBeFinal($class->getName());
323 if ($class->getReflectionClass()->isAbstract()) {
324 throw InvalidArgumentException::classMustNotBeAbstract($class->getName());
329 * Generates the proxy short class name to be used in the template.
331 * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
335 private function generateProxyShortClassName(ClassMetadata $class)
337 $proxyClassName = ClassUtils::generateProxyClassName($class->getName(), $this->proxyNamespace);
338 $parts = explode('\\', strrev($proxyClassName), 2);
340 return strrev($parts[0]);
344 * Generates the proxy namespace.
346 * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
350 private function generateNamespace(ClassMetadata $class)
352 $proxyClassName = ClassUtils::generateProxyClassName($class->getName(), $this->proxyNamespace);
353 $parts = explode('\\', strrev($proxyClassName), 2);
355 return strrev($parts[1]);
359 * Generates the original class name.
361 * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
365 private function generateClassName(ClassMetadata $class)
367 return ltrim($class->getName(), '\\');
371 * Generates the array representation of lazy loaded public properties and their default values.
373 * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
377 private function generateLazyPropertiesDefaults(ClassMetadata $class)
379 $lazyPublicProperties = $this->getLazyLoadedPublicProperties($class);
382 foreach ($lazyPublicProperties as $key => $value) {
383 $values[] = var_export($key, true) . ' => ' . var_export($value, true);
386 return implode(', ', $values);
390 * Generates the constructor code (un-setting public lazy loaded properties, setting identifier field values).
392 * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
396 private function generateConstructorImpl(ClassMetadata $class)
398 $constructorImpl = <<<'EOT'
400 * @param \Closure $initializer
401 * @param \Closure $cloner
403 public function __construct($initializer = null, $cloner = null)
409 foreach ($this->getLazyLoadedPublicProperties($class) as $lazyPublicProperty => $unused) {
410 $toUnset[] = '$this->' . $lazyPublicProperty;
413 $constructorImpl .= (empty($toUnset) ? '' : ' unset(' . implode(', ', $toUnset) . ");\n")
416 $this->__initializer__ = $initializer;
417 $this->__cloner__ = $cloner;
421 return $constructorImpl;
425 * Generates the magic getter invoked when lazy loaded public properties are requested.
427 * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
431 private function generateMagicGet(ClassMetadata $class)
433 $lazyPublicProperties = array_keys($this->getLazyLoadedPublicProperties($class));
434 $reflectionClass = $class->getReflectionClass();
435 $hasParentGet = false;
436 $returnReference = '';
439 if ($reflectionClass->hasMethod('__get')) {
440 $hasParentGet = true;
441 $inheritDoc = '{@inheritDoc}';
443 if ($reflectionClass->getMethod('__get')->returnsReference()) {
444 $returnReference = '& ';
448 if (empty($lazyPublicProperties) && ! $hasParentGet) {
455 * @param string \$name
457 public function {$returnReference}__get(\$name)
462 if ( ! empty($lazyPublicProperties)) {
463 $magicGet .= <<<'EOT'
464 if (array_key_exists($name, $this->__getLazyProperties())) {
465 $this->__initializer__ && $this->__initializer__->__invoke($this, '__get', [$name]);
475 $magicGet .= <<<'EOT'
476 $this->__initializer__ && $this->__initializer__->__invoke($this, '__get', [$name]);
478 return parent::__get($name);
482 $magicGet .= <<<'EOT'
483 trigger_error(sprintf('Undefined property: %s::$%s', __CLASS__, $name), E_USER_NOTICE);
494 * Generates the magic setter (currently unused).
496 * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
500 private function generateMagicSet(ClassMetadata $class)
502 $lazyPublicProperties = $this->getLazyLoadedPublicProperties($class);
503 $hasParentSet = $class->getReflectionClass()->hasMethod('__set');
505 if (empty($lazyPublicProperties) && ! $hasParentSet) {
509 $inheritDoc = $hasParentSet ? '{@inheritDoc}' : '';
513 * @param string \$name
514 * @param mixed \$value
516 public function __set(\$name, \$value)
521 if ( ! empty($lazyPublicProperties)) {
522 $magicSet .= <<<'EOT'
523 if (array_key_exists($name, $this->__getLazyProperties())) {
524 $this->__initializer__ && $this->__initializer__->__invoke($this, '__set', [$name, $value]);
526 $this->$name = $value;
536 $magicSet .= <<<'EOT'
537 $this->__initializer__ && $this->__initializer__->__invoke($this, '__set', [$name, $value]);
539 return parent::__set($name, $value);
542 $magicSet .= " \$this->\$name = \$value;";
551 * Generates the magic issetter invoked when lazy loaded public properties are checked against isset().
553 * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
557 private function generateMagicIsset(ClassMetadata $class)
559 $lazyPublicProperties = array_keys($this->getLazyLoadedPublicProperties($class));
560 $hasParentIsset = $class->getReflectionClass()->hasMethod('__isset');
562 if (empty($lazyPublicProperties) && ! $hasParentIsset) {
566 $inheritDoc = $hasParentIsset ? '{@inheritDoc}' : '';
570 * @param string \$name
573 public function __isset(\$name)
578 if ( ! empty($lazyPublicProperties)) {
579 $magicIsset .= <<<'EOT'
580 if (array_key_exists($name, $this->__getLazyProperties())) {
581 $this->__initializer__ && $this->__initializer__->__invoke($this, '__isset', [$name]);
583 return isset($this->$name);
590 if ($hasParentIsset) {
591 $magicIsset .= <<<'EOT'
592 $this->__initializer__ && $this->__initializer__->__invoke($this, '__isset', [$name]);
594 return parent::__isset($name);
598 $magicIsset .= " return false;";
601 return $magicIsset . "\n }";
605 * Generates implementation for the `__sleep` method of proxies.
607 * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
611 private function generateSleepImpl(ClassMetadata $class)
613 $hasParentSleep = $class->getReflectionClass()->hasMethod('__sleep');
614 $inheritDoc = $hasParentSleep ? '{@inheritDoc}' : '';
620 public function __sleep()
625 if ($hasParentSleep) {
626 return $sleepImpl . <<<'EOT'
627 $properties = array_merge(['__isInitialized__'], parent::__sleep());
629 if ($this->__isInitialized__) {
630 $properties = array_diff($properties, array_keys($this->__getLazyProperties()));
638 $allProperties = ['__isInitialized__'];
640 /* @var $prop \ReflectionProperty */
641 foreach ($class->getReflectionClass()->getProperties() as $prop) {
642 if ($prop->isStatic()) {
646 $allProperties[] = $prop->isPrivate()
647 ? "\0" . $prop->getDeclaringClass()->getName() . "\0" . $prop->getName()
651 $lazyPublicProperties = array_keys($this->getLazyLoadedPublicProperties($class));
652 $protectedProperties = array_diff($allProperties, $lazyPublicProperties);
654 foreach ($allProperties as &$property) {
655 $property = var_export($property, true);
658 foreach ($protectedProperties as &$property) {
659 $property = var_export($property, true);
662 $allProperties = implode(', ', $allProperties);
663 $protectedProperties = implode(', ', $protectedProperties);
665 return $sleepImpl . <<<EOT
666 if (\$this->__isInitialized__) {
667 return [$allProperties];
670 return [$protectedProperties];
676 * Generates implementation for the `__wakeup` method of proxies.
678 * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
682 private function generateWakeupImpl(ClassMetadata $class)
684 $unsetPublicProperties = [];
685 $hasWakeup = $class->getReflectionClass()->hasMethod('__wakeup');
687 foreach (array_keys($this->getLazyLoadedPublicProperties($class)) as $lazyPublicProperty) {
688 $unsetPublicProperties[] = '$this->' . $lazyPublicProperty;
691 $shortName = $this->generateProxyShortClassName($class);
692 $inheritDoc = $hasWakeup ? '{@inheritDoc}' : '';
697 public function __wakeup()
699 if ( ! \$this->__isInitialized__) {
700 \$this->__initializer__ = function ($shortName \$proxy) {
701 \$proxy->__setInitializer(null);
702 \$proxy->__setCloner(null);
704 \$existingProperties = get_object_vars(\$proxy);
706 foreach (\$proxy->__getLazyProperties() as \$property => \$defaultValue) {
707 if ( ! array_key_exists(\$property, \$existingProperties)) {
708 \$proxy->\$property = \$defaultValue;
715 if ( ! empty($unsetPublicProperties)) {
716 $wakeupImpl .= "\n unset(" . implode(', ', $unsetPublicProperties) . ");";
719 $wakeupImpl .= "\n }";
722 $wakeupImpl .= "\n parent::__wakeup();";
725 $wakeupImpl .= "\n }";
731 * Generates implementation for the `__clone` method of proxies.
733 * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
737 private function generateCloneImpl(ClassMetadata $class)
739 $hasParentClone = $class->getReflectionClass()->hasMethod('__clone');
740 $inheritDoc = $hasParentClone ? '{@inheritDoc}' : '';
741 $callParentClone = $hasParentClone ? "\n parent::__clone();\n" : '';
747 public function __clone()
749 \$this->__cloner__ && \$this->__cloner__->__invoke(\$this, '__clone', []);
755 * Generates decorated methods by picking those available in the parent class.
757 * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
761 private function generateMethods(ClassMetadata $class)
765 $reflectionMethods = $class->getReflectionClass()->getMethods(\ReflectionMethod::IS_PUBLIC);
775 foreach ($reflectionMethods as $method) {
776 $name = $method->getName();
779 $method->isConstructor() ||
780 isset($skippedMethods[strtolower($name)]) ||
781 isset($methodNames[$name]) ||
782 $method->isFinal() ||
783 $method->isStatic() ||
784 ( ! $method->isPublic())
789 $methodNames[$name] = true;
790 $methods .= "\n /**\n"
791 . " * {@inheritDoc}\n"
793 . ' public function ';
795 if ($method->returnsReference()) {
799 $methods .= $name . '(' . $this->buildParametersString($method->getParameters()) . ')';
800 $methods .= $this->getMethodReturnType($method);
801 $methods .= "\n" . ' {' . "\n";
803 if ($this->isShortIdentifierGetter($method, $class)) {
804 $identifier = lcfirst(substr($name, 3));
805 $fieldType = $class->getTypeOfField($identifier);
806 $cast = in_array($fieldType, ['integer', 'smallint']) ? '(int) ' : '';
808 $methods .= ' if ($this->__isInitialized__ === false) {' . "\n";
810 $methods .= $this->shouldProxiedMethodReturn($method) ? 'return ' : '';
811 $methods .= $cast . ' parent::' . $method->getName() . "();\n";
812 $methods .= ' }' . "\n\n";
815 $invokeParamsString = implode(', ', $this->getParameterNamesForInvoke($method->getParameters()));
816 $callParamsString = implode(', ', $this->getParameterNamesForParentCall($method->getParameters()));
818 $methods .= "\n \$this->__initializer__ "
819 . "&& \$this->__initializer__->__invoke(\$this, " . var_export($name, true)
820 . ", [" . $invokeParamsString . "]);"
822 . ($this->shouldProxiedMethodReturn($method) ? 'return ' : '')
823 . "parent::" . $name . '(' . $callParamsString . ');'
824 . "\n" . ' }' . "\n";
831 * Generates the Proxy file name.
833 * @param string $className
834 * @param string $baseDirectory Optional base directory for proxy file name generation.
835 * If not specified, the directory configured on the Configuration of the
836 * EntityManager will be used by this factory.
840 public function getProxyFileName($className, $baseDirectory = null)
842 $baseDirectory = $baseDirectory ?: $this->proxyDirectory;
844 return rtrim($baseDirectory, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . Proxy::MARKER
845 . str_replace('\\', '', $className) . '.php';
849 * Checks if the method is a short identifier getter.
851 * What does this mean? For proxy objects the identifier is already known,
852 * however accessing the getter for this identifier usually triggers the
853 * lazy loading, leading to a query that may not be necessary if only the
854 * ID is interesting for the userland code (for example in views that
855 * generate links to the entity, but do not display anything else).
857 * @param \ReflectionMethod $method
858 * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
862 private function isShortIdentifierGetter($method, ClassMetadata $class)
864 $identifier = lcfirst(substr($method->getName(), 3));
865 $startLine = $method->getStartLine();
866 $endLine = $method->getEndLine();
868 $method->getNumberOfParameters() == 0
869 && substr($method->getName(), 0, 3) == 'get'
870 && in_array($identifier, $class->getIdentifier(), true)
871 && $class->hasField($identifier)
872 && (($endLine - $startLine) <= 4)
876 $code = file($method->getDeclaringClass()->getFileName());
877 $code = trim(implode(' ', array_slice($code, $startLine - 1, $endLine - $startLine + 1)));
879 $pattern = sprintf(self::PATTERN_MATCH_ID_METHOD, $method->getName(), $identifier);
881 if (preg_match($pattern, $code)) {
890 * Generates the list of public properties to be lazy loaded, with their default values.
892 * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $class
896 private function getLazyLoadedPublicProperties(ClassMetadata $class)
898 $defaultProperties = $class->getReflectionClass()->getDefaultProperties();
901 foreach ($class->getReflectionClass()->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
902 $name = $property->getName();
904 if (($class->hasField($name) || $class->hasAssociation($name)) && ! $class->isIdentifier($name)) {
905 $properties[$name] = $defaultProperties[$name];
913 * @param \ReflectionParameter[] $parameters
917 private function buildParametersString(array $parameters)
919 $parameterDefinitions = [];
921 /* @var $param \ReflectionParameter */
922 foreach ($parameters as $param) {
923 $parameterDefinition = '';
925 if ($parameterType = $this->getParameterType($param)) {
926 $parameterDefinition .= $parameterType . ' ';
929 if ($param->isPassedByReference()) {
930 $parameterDefinition .= '&';
933 if ($param->isVariadic()) {
934 $parameterDefinition .= '...';
937 $parameterDefinition .= '$' . $param->getName();
939 if ($param->isDefaultValueAvailable()) {
940 $parameterDefinition .= ' = ' . var_export($param->getDefaultValue(), true);
943 $parameterDefinitions[] = $parameterDefinition;
946 return implode(', ', $parameterDefinitions);
950 * @param ClassMetadata $class
951 * @param \ReflectionMethod $method
952 * @param \ReflectionParameter $parameter
954 * @return string|null
956 private function getParameterType(\ReflectionParameter $parameter)
958 if ( ! $parameter->hasType()) {
962 return $this->formatType($parameter->getType(), $parameter->getDeclaringFunction(), $parameter);
966 * @param \ReflectionParameter[] $parameters
970 private function getParameterNamesForInvoke(array $parameters)
973 function (\ReflectionParameter $parameter) {
974 return '$' . $parameter->getName();
981 * @param \ReflectionParameter[] $parameters
985 private function getParameterNamesForParentCall(array $parameters)
988 function (\ReflectionParameter $parameter) {
991 if ($parameter->isVariadic()) {
995 $name .= '$' . $parameter->getName();
1004 * @param \ReflectionMethod $method
1008 private function getMethodReturnType(\ReflectionMethod $method)
1010 if ( ! $method->hasReturnType()) {
1014 return ': ' . $this->formatType($method->getReturnType(), $method);
1018 * @param \ReflectionMethod $method
1022 private function shouldProxiedMethodReturn(\ReflectionMethod $method)
1024 if ( ! $method->hasReturnType()) {
1028 return 'void' !== strtolower($this->formatType($method->getReturnType(), $method));
1032 * @param \ReflectionType $type
1033 * @param \ReflectionMethod $method
1034 * @param \ReflectionParameter|null $parameter
1038 private function formatType(
1039 \ReflectionType $type,
1040 \ReflectionMethod $method,
1041 \ReflectionParameter $parameter = null
1043 $name = (string) $type;
1044 $nameLower = strtolower($name);
1046 if ('self' === $nameLower) {
1047 $name = $method->getDeclaringClass()->getName();
1050 if ('parent' === $nameLower) {
1051 $name = $method->getDeclaringClass()->getParentClass()->getName();
1054 if ( ! $type->isBuiltin() && ! class_exists($name) && ! interface_exists($name)) {
1055 if (null !== $parameter) {
1056 throw UnexpectedValueException::invalidParameterTypeHint(
1057 $method->getDeclaringClass()->getName(),
1059 $parameter->getName()
1063 throw UnexpectedValueException::invalidReturnTypeHint(
1064 $method->getDeclaringClass()->getName(),
1069 if ( ! $type->isBuiltin()) {
1070 $name = '\\' . $name;
1073 if ($type->allowsNull()
1074 && (null === $parameter || ! $parameter->isDefaultValueAvailable() || null !== $parameter->getDefaultValue())
1076 $name = '?' . $name;