/** * Parse the docblock of the property to get the class of the var annotation. * * @param \ReflectionProperty $property * * @throws AnnotationException Non exists class. * * @return null|ObjectDefinition */ public function getPropertyClass(\ReflectionProperty $property) { $propertyComment = $property->getDocComment(); if (!preg_match('/@var\\s+([^\\s\\(\\*\\/]+)/', $propertyComment, $matches)) { return; } $className = end($matches); if (!is_string($className) || in_array($className, static::$ignoredTypes)) { return; } $classWithNamespace = $className; if ($this->namespaceExists($classWithNamespace) === false) { $classWithNamespace = $this->namespace . '\\' . $className; } if (!$this->classExists($classWithNamespace)) { $declaringClass = $property->getDeclaringClass(); throw new AnnotationException(sprintf('The @var annotation on %s::%s contains a non existent class "%s"', $declaringClass->name, $property->getName(), $className)); } $createNewObject = function ($propertyComment, $className, $classWithNamespace) { $classParameters = $this->propertyClassParameters($propertyComment, $className); if (is_array($classParameters)) { $values = []; foreach ($classParameters as $value) { $values[] = static::parseValue($value); } $object = new ObjectDefinition($classWithNamespace, $className); $object->setConstructorInjection($values); return $object; } return new $classWithNamespace(); }; return $createNewObject($propertyComment, $className, $classWithNamespace); }
/** * Browse the object's methods looking for annotated methods. * * @param \ReflectionClass $class * @param ObjectDefinition $objectDefinition * * @return object|\ReflectionClass */ private function setMethods(\ReflectionClass $class, ObjectDefinition $objectDefinition) { $isConstructor = false; $methodName = []; foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { if ($method->isStatic()) { continue; } $methodParameters = $this->getMethodParameters($method); if ($methodParameters === null) { continue; } $isMethod = true; if ($method->isConstructor()) { $objectDefinition->setConstructorInjection($methodParameters); $isConstructor = true; $isMethod = false; } if ($isMethod) { $objectDefinition->addMethodInjection($method->getName(), $methodParameters); $methodName[] = $method->getName(); } } $object = $objectDefinition->getNewInstance($isConstructor); foreach ($methodName as $name) { $methodReflection = new \ReflectionMethod($object, $name); $args = $objectDefinition->getMethodParameters($name); $methodReflection->invokeArgs($object, $args); } return $object; }