/** * {@inheritdoc} */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator) { CanProxyAssertion::assertClassCanBeProxied($originalClass); $classGenerator->setExtendedClass($originalClass->getName()); $additionalInterfaces = ['OpenClassrooms\\ServiceProxy\\ServiceProxyInterface']; $additionalProperties['proxy_realSubject'] = new PropertyGenerator('proxy_realSubject', null, PropertyGenerator::FLAG_PRIVATE); $additionalMethods['setProxy_realSubject'] = new MethodGenerator('setProxy_realSubject', [['name' => 'realSubject']], MethodGenerator::FLAG_PUBLIC, '$this->proxy_realSubject = $realSubject;'); $methods = $originalClass->getMethods(\ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { $preSource = ''; $postSource = ''; $exceptionSource = ''; $methodAnnotations = $this->annotationReader->getMethodAnnotations($method); foreach ($methodAnnotations as $methodAnnotation) { if ($methodAnnotation instanceof Cache) { $this->addCacheAnnotation($classGenerator); $additionalInterfaces['cache'] = 'OpenClassrooms\\ServiceProxy\\ServiceProxyCacheInterface'; $response = $this->cacheStrategy->execute($this->serviceProxyStrategyRequestBuilder->create()->withAnnotation($methodAnnotation)->withClass($originalClass)->withMethod($method)->build()); foreach ($response->getMethods() as $methodToAdd) { $additionalMethods[$methodToAdd->getName()] = $methodToAdd; } foreach ($response->getProperties() as $propertyToAdd) { $additionalProperties[$propertyToAdd->getName()] = $propertyToAdd; } $preSource .= $response->getPreSource(); $postSource .= $response->getPostSource(); $exceptionSource .= $response->getExceptionSource(); } } $classGenerator->addMethodFromGenerator($this->generateProxyMethod($method, $preSource, $postSource, $exceptionSource)); } $classGenerator->setImplementedInterfaces($additionalInterfaces); $classGenerator->addProperties($additionalProperties); $classGenerator->addMethods($additionalMethods); }
/** * @param \ReflectionClass $class * * @return \Metadata\ClassMetadata */ public function loadMetadataForClass(\ReflectionClass $class) { $classMetadata = new ClassMetadata($class->getName()); foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflectionMethod) { if (false === strpos($reflectionMethod->getName(), 'Action')) { continue; } if ($reflectionMethod->isAbstract()) { continue; } $methodMetadata = new ActionMetadata($class->getName(), $reflectionMethod->getName()); $annotations = $this->reader->getMethodAnnotations($reflectionMethod); foreach ($annotations as $annotation) { if ($annotation instanceof \BackBee\Rest\Controller\Annotations\QueryParam) { $data = array('name' => $annotation->name, 'key' => $annotation->key ? $annotation->key : $annotation->name, 'default' => $annotation->default, 'description' => $annotation->description, 'requirements' => $annotation->requirements); $methodMetadata->queryParams[] = $data; } elseif ($annotation instanceof \BackBee\Rest\Controller\Annotations\RequestParam) { $data = array('name' => $annotation->name, 'key' => $annotation->key ? $annotation->key : $annotation->name, 'default' => $annotation->default, 'description' => $annotation->description, 'requirements' => $annotation->requirements); $methodMetadata->requestParams[] = $data; } elseif ($annotation instanceof \BackBee\Rest\Controller\Annotations\Pagination) { $methodMetadata->default_start = $annotation->default_start; $methodMetadata->default_count = $annotation->default_count; $methodMetadata->max_count = $annotation->max_count; $methodMetadata->min_count = $annotation->min_count; } elseif ($annotation instanceof \BackBee\Rest\Controller\Annotations\ParamConverter) { $methodMetadata->param_converter_bag[] = $annotation; } elseif ($annotation instanceof \BackBee\Rest\Controller\Annotations\Security) { $methodMetadata->security[] = $annotation; } } $classMetadata->addMethodMetadata($methodMetadata); } return $classMetadata; }
/** * Parse a controller class. * * @param string $class * @return array */ public function parseController($class) { $reflectionClass = new ReflectionClass($class); $classAnnotations = $this->reader->getClassAnnotations($reflectionClass); $controllerMetadata = []; $middleware = []; // find entity parameters and plugins foreach ($classAnnotations as $annotation) { // controller attributes if ($annotation instanceof \ProAI\Annotations\Annotations\Controller) { $prefix = $annotation->prefix; $middleware = $this->addMiddleware($middleware, $annotation->middleware); } if ($annotation instanceof \ProAI\Annotations\Annotations\Middleware) { $middleware = $this->addMiddleware($middleware, $annotation->value); } // resource controller if ($annotation instanceof \ProAI\Annotations\Annotations\Resource) { $resourceMethods = ['index', 'create', 'store', 'show', 'edit', 'update', 'destroy']; if (!empty($annotation->only)) { $resourceMethods = array_intersect($resourceMethods, $annotation->only); } elseif (!empty($annotation->except)) { $resourceMethods = array_diff($resourceMethods, $annotation->except); } $resource = ['name' => $annotation->value, 'methods' => $resourceMethods]; } } // find routes foreach ($reflectionClass->getMethods() as $reflectionMethod) { $name = $reflectionMethod->getName(); $methodAnnotations = $this->reader->getMethodAnnotations($reflectionMethod); $routeMetadata = []; // controller method is resource route if (!empty($resource) && in_array($name, $resource['methods'])) { $routeMetadata = ['uri' => $resource['name'] . $this->getResourcePath($name), 'controller' => $class, 'controllerMethod' => $name, 'httpMethod' => $this->getResourceHttpMethod($name), 'as' => $resource['name'] . '.' . $name, 'middleware' => '']; } // controller method is route if ($route = $this->hasHttpMethodAnnotation($name, $methodAnnotations)) { $routeMetadata = ['uri' => $route['uri'], 'controller' => $class, 'controllerMethod' => $name, 'httpMethod' => $route['httpMethod'], 'as' => $route['as'], 'middleware' => $route['middleware']]; } // add more route options to route metadata if (!empty($routeMetadata)) { if (!empty($middleware)) { $routeMetadata['middleware'] = $middleware; } // add other method annotations foreach ($methodAnnotations as $annotation) { if ($annotation instanceof \ProAI\Annotations\Annotations\Middleware) { $middleware = $this->addMiddleware($middleware, $routeMetadata['middleware']); } } // add global prefix and middleware if (!empty($prefix)) { $routeMetadata['uri'] = $prefix . '/' . $routeMetadata['uri']; } $controllerMetadata[$name] = $routeMetadata; } } return $controllerMetadata; }
public function testAnnotationReader() { $reader = new AnnotationReader(); $method = new \ReflectionMethod('FOS\\RestBundle\\Tests\\Fixtures\\Controller\\ParamsAnnotatedController', 'getArticlesAction'); $params = $reader->getMethodAnnotations($method); // Param 1 (query) $this->assertEquals('page', $params[0]->name); $this->assertEquals('\\d+', $params[0]->requirements); $this->assertEquals('1', $params[0]->default); $this->assertEquals('Page of the overview.', $params[0]->description); $this->assertFalse($params[0]->map); $this->assertFalse($params[0]->strict); // Param 2 (request) $this->assertEquals('byauthor', $params[1]->name); $this->assertEquals('[a-z]+', $params[1]->requirements); $this->assertEquals('by author', $params[1]->description); $this->assertEquals(['search'], $params[1]->incompatibles); $this->assertFalse($params[1]->map); $this->assertTrue($params[1]->strict); // Param 3 (query) $this->assertEquals('filters', $params[2]->name); $this->assertTrue($params[2]->map); $this->assertEquals(new NotNull(), $params[2]->requirements); // Param 4 (file) $this->assertEquals('avatar', $params[3]->name); $this->assertEquals(['mimeTypes' => 'application/json'], $params[3]->requirements); $this->assertTrue($params[3]->image); $this->assertTrue($params[3]->strict); // Param 5 (file) $this->assertEquals('foo', $params[4]->name); $this->assertEquals(new NotNull(), $params[4]->requirements); $this->assertFalse($params[4]->image); $this->assertFalse($params[4]->strict); }
/** * Process the method * @param $methods * @param Mapping\ClassMetaData $metadata * @throws DrestException */ protected function processMethods($methods, Mapping\ClassMetaData $metadata) { // Set the handle calls foreach ($methods as $method) { /* @var \ReflectionMethod $method */ if ($method->isPublic()) { foreach ($this->reader->getMethodAnnotations($method) as $methodAnnotation) { if ($methodAnnotation instanceof Annotation\Handle) { // Make sure the for is not empty if (empty($methodAnnotation->for) || !is_string($methodAnnotation->for)) { throw DrestException::handleForCannotBeEmpty(); } if (($routeMetaData = $metadata->getRouteMetaData($methodAnnotation->for)) === false) { throw DrestException::handleAnnotationDoesntMatchRouteName($methodAnnotation->for); } if ($routeMetaData->hasHandleCall()) { // There is already a handle set for this route throw DrestException::handleAlreadyDefinedForRoute($routeMetaData); } $routeMetaData->setHandleCall($method->getName()); } } } } }
/** * Returns an array of callbacks for lifecycle annotations on the given method. * * @param \ReflectionMethod $method * @return array */ protected function getMethodCallbacks(\ReflectionMethod $method) { $callbacks = array(); $annotations = $this->reader->getMethodAnnotations($method); foreach ($annotations as $annotation) { if ($annotation instanceof \Doctrine\ORM\Mapping\PrePersist) { $callbacks[] = array($method->name, Events::prePersist); } if ($annotation instanceof \Doctrine\ORM\Mapping\PostPersist) { $callbacks[] = array($method->name, Events::postPersist); } if ($annotation instanceof \Doctrine\ORM\Mapping\PreUpdate) { $callbacks[] = array($method->name, Events::preUpdate); } if ($annotation instanceof \Doctrine\ORM\Mapping\PostUpdate) { $callbacks[] = array($method->name, Events::postUpdate); } if ($annotation instanceof \Doctrine\ORM\Mapping\PreRemove) { $callbacks[] = array($method->name, Events::preRemove); } if ($annotation instanceof \Doctrine\ORM\Mapping\PostRemove) { $callbacks[] = array($method->name, Events::postRemove); } if ($annotation instanceof \Doctrine\ORM\Mapping\PostLoad) { $callbacks[] = array($method->name, Events::postLoad); } if ($annotation instanceof \Doctrine\ORM\Mapping\PreFlush) { $callbacks[] = array($method->name, Events::preFlush); } } return $callbacks; }
private function getMaxQueryAnnotation() { foreach (debug_backtrace() as $step) { if ('test' === substr($step['function'], 0, 4)) { //TODO: handle tests with the @test annotation $annotations = $this->annotationReader->getMethodAnnotations(new \ReflectionMethod($step['class'], $step['function'])); foreach ($annotations as $annotationClass) { if ($annotationClass instanceof QueryCount && isset($annotationClass->maxQueries)) { /* @var $annotations \Liip\FunctionalTestBundle\Annotations\QueryCount */ return $annotationClass->maxQueries; } } } } return false; }
/** * @covers \Weasel\JsonMarshaller\Config\DoctrineAnnotations\JsonAnySetter */ public function testBasicClassAnnotations() { AnnotationRegistry::registerFile(__DIR__ . '/../../../../../lib/Weasel/JsonMarshaller/Config/DoctrineAnnotations/JsonAnySetter.php'); $annotationReader = new AnnotationReader(); $got = $annotationReader->getMethodAnnotations(new \ReflectionMethod(__NAMESPACE__ . '\\JsonAnySetterTestVictim', 'basic')); $this->assertEquals(array(new JsonAnySetter()), $got); }
public function getMethodAnnotations(\ReflectionMethod $method) { $this->setAutoloadAnnotations(true); $this->setAnnotationCreationFunction(function ($name, $values) { $r = new \ReflectionClass($name); if (!$r->implementsInterface('Bundle\\Sensio\\FrameworkExtraBundle\\Configuration\\ConfigurationInterface')) { return null; } $configuration = new $name(); foreach ($values as $key => $value) { if (!method_exists($configuration, $method = 'set'.$key)) { throw new \BadMethodCallException(sprintf("Unknown annotation attribute '%s' for '%s'.", ucfirst($key), get_class($this))); } $configuration->$method($value); } return $configuration; }); $this->setDefaultAnnotationNamespace('Bundle\\Sensio\\FrameworkExtraBundle\\Configuration\\'); $configurations = parent::getMethodAnnotations($method); $this->setAnnotationCreationFunction(function ($name, $values) { return null; }); return $configurations; }
public function __construct($consumerWorker, ConnectionFactory $connectionFactory) { $this->connectionFactory = $connectionFactory; $className = get_class($consumerWorker); $reflectionClass = new \ReflectionClass($className); $reader = new AnnotationReader(); $methods = $reflectionClass->getMethods(); foreach ($methods as $method) { $methodAnnotations = $reader->getMethodAnnotations($method); foreach ($methodAnnotations as $annotation) { if ($annotation instanceof Annotation\Consumer) { $parameters = $method->getParameters(); $taskClassName = false; if (!empty($parameters)) { $taskClass = $parameters[0]->getClass(); $isMessage = $taskClass->implementsInterface('IvixLabs\\RabbitmqBundle\\Message\\MessageInterface'); if (!$isMessage) { throw new \InvalidArgumentException('Task must implmenet IvixLabs\\RabbitmqBundle\\Message\\MessageInterface'); } $taskClassName = $taskClass->getName(); } $key = $annotation->connectionName . '_' . $annotation->channelName . '_' . $annotation->exchangeName . '_' . $annotation->routingKey; if (!isset($this->taskClasses[$key])) { $this->taskClasses[$key] = []; } $this->taskClasses[$key][] = [$taskClassName, $method->getClosure($consumerWorker), $annotation]; } } } }
/** * @covers \Weasel\JsonMarshaller\Config\DoctrineAnnotations\JsonCreator * @covers \Weasel\JsonMarshaller\Config\DoctrineAnnotations\JsonProperty */ public function testConstructorClassAnnotations() { AnnotationRegistry::registerFile(__DIR__ . '/../../../../../lib/Weasel/JsonMarshaller/Config/DoctrineAnnotations/JsonCreator.php'); AnnotationRegistry::registerFile(__DIR__ . '/../../../../../lib/Weasel/JsonMarshaller/Config/DoctrineAnnotations/JsonProperty.php'); $annotationReader = new AnnotationReader(); $got = $annotationReader->getMethodAnnotations(new \ReflectionMethod(__NAMESPACE__ . '\\JsonCreatorTestVictim', '__construct')); $this->assertEquals(array(new JsonCreator(array("params" => array(new JsonProperty(array("name" => "foo", "type" => "int")), new JsonProperty(array("name" => "bar", "type" => "int")))))), $got); }
/** * Constructor * * @param IReflectionMethod $method */ public function __construct(IReflectionMethod $method) { parent::__construct($method); $methodName = $this->reflection->getName(); $reader = new AnnotationReader(); $this->doctrineAnnotations = $reader->getMethodAnnotations(new \ReflectionMethod($this->reflection->getDeclaringClassName(), $methodName)); list($this->name, $this->httpMethod) = $this->processMethodName($methodName); $this->processAnnotations(); }
/** * @param Application $app * @return \Silex\ControllerCollection */ public function connect(Application $app) { /** @var \Silex\ControllerCollection $controllers */ $controllers = $app['controllers_factory']; // Routes are already cached using Flint if (file_exists($app['sys_temp_path'] . 'ProjectUrlMatcher.php')) { return $controllers; } $reflection = new \ReflectionClass($app[$this->controllerName]); $className = $reflection->getName(); // Needed in order to get annotations $annotationReader = new AnnotationReader(); //$classAnnotations = $annotationReader->getClassAnnotations($reflection); $routeAnnotation = new Route(array()); $methodAnnotation = new Method(array()); $methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC); foreach ($methods as $method) { $methodName = $method->getName(); $controllerName = $this->controllerName . ':' . $methodName; // Parse only function with the "Action" suffix if (strpos($methodName, 'Action') === false) { continue; } // Getting all annotations $routeObjects = $annotationReader->getMethodAnnotations($method); /** @var Method $routeObject */ $methodObject = $annotationReader->getMethodAnnotation($method, $methodAnnotation); $methodsToString = 'GET'; if ($methodObject) { $methodsToString = implode('|', $methodObject->getMethods()); } /** @var Route $routeObject */ foreach ($routeObjects as $routeObject) { if ($routeObject && is_a($routeObject, 'Symfony\\Component\\Routing\\Annotation\\Route')) { $match = $controllers->match($routeObject->getPath(), $controllerName, $methodsToString); // Setting requirements $req = $routeObject->getRequirements(); if (!empty($req)) { foreach ($req as $key => $value) { $match->assert($key, $value); } } // Setting defaults $defaults = $routeObject->getDefaults(); if (!empty($defaults)) { foreach ($defaults as $key => $value) { $match->value($key, $value); } } $match->bind($controllerName); } } } return $controllers; }
/** * @group performance */ public function testReadPerformance() { $method = $this->getMethod(); $time = microtime(true); for ($i = 0, $c = 150; $i < $c; $i++) { $reader = new AnnotationReader(); $reader->getMethodAnnotations($method); } $time = microtime(true) - $time; $this->printResults('reader', $time, $c); }
/** * @param FilterControllerEvent $event */ public function onKernelController(FilterControllerEvent $event) { $controller = $event->getController(); $request = $event->getRequest(); $annotationReader = new AnnotationReader(); $reflectionClass = new \ReflectionClass($controller[0]); $reflectionMethod = $reflectionClass->getMethod($controller[1]); $annotations = $annotationReader->getMethodAnnotations($reflectionMethod); foreach ($annotations as $annotation) { if ($this->supports($annotation)) { $this->parseAnnotation($reflectionMethod, $annotation, $request); } } }
public function resolvedController() { $annotationReader = new AnnotationReader(); $reflectionMethod = new \ReflectionMethod($this->controller, 'widgetAction'); $methodAnnotations = $annotationReader->getMethodAnnotations($reflectionMethod); foreach ($methodAnnotations as $annotation) { if ($annotation instanceof Route) { if (empty($annotation)) { throw new \Exception("The name is not configured in the annotation"); } /** @var \Sensio\Bundle\FrameworkExtraBundle\Configuration\Route $annotation */ return $annotation->getName(); } } throw new \Exception("There is no route annotation"); }
public function testAnnotations() { $reader = new AnnotationReader(new \Doctrine\Common\Cache\ArrayCache()); $reader->setDefaultAnnotationNamespace('Doctrine\\Tests\\Common\\Annotations\\'); $this->assertFalse($reader->getAutoloadAnnotations()); $reader->setAutoloadAnnotations(true); $this->assertTrue($reader->getAutoloadAnnotations()); $reader->setAutoloadAnnotations(false); $this->assertFalse($reader->getAutoloadAnnotations()); $class = new ReflectionClass('Doctrine\\Tests\\Common\\Annotations\\DummyClass'); $classAnnots = $reader->getClassAnnotations($class); $annotName = 'Doctrine\\Tests\\Common\\Annotations\\DummyAnnotation'; $this->assertEquals(1, count($classAnnots)); $this->assertTrue($classAnnots[$annotName] instanceof DummyAnnotation); $this->assertEquals("hello", $classAnnots[$annotName]->dummyValue); $field1Prop = $class->getProperty('field1'); $propAnnots = $reader->getPropertyAnnotations($field1Prop); $this->assertEquals(1, count($propAnnots)); $this->assertTrue($propAnnots[$annotName] instanceof DummyAnnotation); $this->assertEquals("fieldHello", $propAnnots[$annotName]->dummyValue); $getField1Method = $class->getMethod('getField1'); $methodAnnots = $reader->getMethodAnnotations($getField1Method); $this->assertEquals(1, count($methodAnnots)); $this->assertTrue($methodAnnots[$annotName] instanceof DummyAnnotation); $this->assertEquals(array(1, 2, "three"), $methodAnnots[$annotName]->value); $field2Prop = $class->getProperty('field2'); $propAnnots = $reader->getPropertyAnnotations($field2Prop); $this->assertEquals(1, count($propAnnots)); $this->assertTrue(isset($propAnnots['Doctrine\\Tests\\Common\\Annotations\\DummyJoinTable'])); $joinTableAnnot = $propAnnots['Doctrine\\Tests\\Common\\Annotations\\DummyJoinTable']; $this->assertEquals(1, count($joinTableAnnot->joinColumns)); $this->assertEquals(1, count($joinTableAnnot->inverseJoinColumns)); $this->assertTrue($joinTableAnnot->joinColumns[0] instanceof DummyJoinColumn); $this->assertTrue($joinTableAnnot->inverseJoinColumns[0] instanceof DummyJoinColumn); $this->assertEquals('col1', $joinTableAnnot->joinColumns[0]->name); $this->assertEquals('col2', $joinTableAnnot->joinColumns[0]->referencedColumnName); $this->assertEquals('col3', $joinTableAnnot->inverseJoinColumns[0]->name); $this->assertEquals('col4', $joinTableAnnot->inverseJoinColumns[0]->referencedColumnName); $dummyAnnot = $reader->getMethodAnnotation($class->getMethod('getField1'), 'Doctrine\\Tests\\Common\\Annotations\\DummyAnnotation'); $this->assertEquals('', $dummyAnnot->dummyValue); $this->assertEquals(array(1, 2, 'three'), $dummyAnnot->value); $dummyAnnot = $reader->getPropertyAnnotation($class->getProperty('field1'), 'Doctrine\\Tests\\Common\\Annotations\\DummyAnnotation'); $this->assertEquals('fieldHello', $dummyAnnot->dummyValue); $classAnnot = $reader->getClassAnnotation($class, 'Doctrine\\Tests\\Common\\Annotations\\DummyAnnotation'); $this->assertEquals('hello', $classAnnot->dummyValue); }
/** * Localiza o serviço e o método chamado para execução de callback. * * @param String $controllerService * @param String $method * * @return Array */ private function locateService($controllerService, $method) { $app = $this->app; if (strpos($method, ':') !== false) { $methodParts = explode(':', $method); $controllerService = $methodParts[0]; $method = $methodParts[1]; } $refClass = new \ReflectionClass(get_class($app[$controllerService])); if (!$refClass->hasMethod($method)) { throw FrameworkException::controllerMethodNotDefinedError(sprintf("O metodo '%s' nao esta definido no controlador '%s'", $method, $refClass->getName())); } $refMethod = new \ReflectionMethod($refClass->getName(), $method); $annotations = $this->reader->getMethodAnnotations($refMethod); if (!empty($annotations)) { throw FrameworkException::filterHasAnnotationError(sprintf("O metodo '%s' do controlador '%s' esta definido como um filtro mas possui anotacoes.", $method, $refClass->getName())); } return array('service_class' => $controllerService, 'service_method' => $method); }
/** * @return void */ private function buildForMethods() { $classMethods = $this->reflectionClass()->getMethods(); $methods = []; foreach ($classMethods as $classMethod) { $webMethodAnnotation = $this->annotationReader->getMethodAnnotation($classMethod, '\\WSDL\\Annotation\\WebMethod'); if ($webMethodAnnotation === null) { continue; } $methodBuilder = MethodBuilder::instance(); /** @var MethodAnnotation[] $methodAnnotations */ $methodAnnotations = $this->annotationReader->getMethodAnnotations($classMethod); foreach ($methodAnnotations as $methodAnnotation) { $methodAnnotation->build($methodBuilder, $classMethod); } $methods[] = $methodBuilder->build(); } $this->builder->setMethods($methods); }
/** * Register the given instance as a router class. * @param object $routerClass * @throws \Exception */ public function registerRouter($routerClass) { $reflClass = new \ReflectionClass($routerClass); $reflMethods = $reflClass->getMethods(); foreach ($reflMethods as $reflMethod) { $classAnnotations = $this->reader->getMethodAnnotations($reflMethod); $method = null; $url = null; $secured = null; foreach ($classAnnotations as $annot) { if ($annot instanceof GET || $annot instanceof POST || $annot instanceof PUT || $annot instanceof DELETE) { $method = $annot->method(); $url = $annot->value; } elseif ($annot instanceof Secured) { $secured = $annot; } } if ($method !== null && $url !== null) { $callback = $reflMethod->getName(); $this->setRoute($method, $url, $routerClass, $callback, $secured); } } }
/** * @param ReflectionClass $reflectionClass * @param ControllerCollection $controllerCollection */ public function processMethodAnnotations(ReflectionClass $reflectionClass, ControllerCollection $controllerCollection) { $separator = $this->app['annot.useServiceControllers'] ? ":" : "::"; foreach ($reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC) as $reflectionMethod) { if (!$reflectionMethod->isStatic()) { $controllerMethodName = $this->app['annot.controller_factory']($this->app, $reflectionClass->name, $reflectionMethod->name, $separator); $methodAnnotations = $this->reader->getMethodAnnotations($reflectionMethod); foreach ($methodAnnotations as $annotation) { if ($annotation instanceof Route) { $annotation->process($controllerCollection, $controllerMethodName, $this->app); } else { if ($annotation instanceof Request) { $controller = $annotation->process($controllerCollection, $controllerMethodName); foreach ($methodAnnotations as $routeAnnotation) { if ($routeAnnotation instanceof RouteAnnotation) { $routeAnnotation->process($controller); } } } } } } } }
public function scanRoutesAndSaveFile($base_path = null) { $annotationReader = new AnnotationReader(); $routes = $this->containerInterface->get('router')->getRouteCollection()->all(); $this->containerInterface->set('request', new Request()); //, 'request'); $this->ui_state = []; $this->all_routes = $routes; foreach ($routes as $route_key => $route) { if (!empty($base_path) && !$this->hasBasePath($route->getPath(), $base_path)) { continue; } $defaults = $route->getDefaults(); if (isset($defaults['_controller'])) { if (strpos($defaults['_controller'], '::') === false) { list($controllerService, $controllerMethod) = explode(':', $defaults['_controller']); $controllerObject = $this->containerInterface->get($controllerService); $reflectedMethod = new \ReflectionMethod($controllerObject, $controllerMethod); } else { list($controllerClass, $controllerMethod) = explode('::', $defaults['_controller']); $reflectedMethod = new \ReflectionMethod($controllerClass, $controllerMethod); } // the annotations $annotations = $annotationReader->getMethodAnnotations($reflectedMethod); $this->checkAnnotations($annotations, $route, $route_key); } } // clean path avoiding sub-path repetition $sub_states = $this->foldingState($this->ui_state); foreach ($sub_states as $s) { $key = $s['parent'] . '.' . $s['current']; if (array_key_exists($key, $this->ui_state)) { $this->ui_state[$key]['path'] = str_replace($this->ui_state[$s['parent']]['path'], "", $this->ui_state[$key]['path']); } } }
/** * Evaluate the lifecycle annotations and amend the metadata accordingly. * * @param \ReflectionClass $class * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata * @return void */ protected function evaluateLifeCycleAnnotations(\ReflectionClass $class, \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { foreach ($class->getMethods() as $method) { if ($method->isPublic()) { $annotations = $this->reader->getMethodAnnotations($method); if (isset($annotations['Doctrine\\ORM\\Mapping\\PrePersist'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::prePersist); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PostPersist'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postPersist); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PreUpdate'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::preUpdate); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PostUpdate'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postUpdate); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PreRemove'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::preRemove); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PostRemove'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postRemove); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PostLoad'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postLoad); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PreFlush'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::preFlush); } } } // FIXME this can be removed again once Doctrine is fixed (see fixMethodsAndAdvicesArrayForDoctrineProxiesCode()) $metadata->addLifecycleCallback('Flow_Aop_Proxy_fixMethodsAndAdvicesArrayForDoctrineProxies', \Doctrine\ORM\Events::postLoad); // FIXME this can be removed again once Doctrine is fixed (see fixInjectedPropertiesForDoctrineProxiesCode()) $metadata->addLifecycleCallback('Flow_Aop_Proxy_fixInjectedPropertiesForDoctrineProxies', \Doctrine\ORM\Events::postLoad); }
/** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadataInfo $metadata) { $class = $metadata->getReflectionClass(); if (!$class) { // this happens when running annotation driver in combination with // static reflection services. This is not the nicest fix $class = new \ReflectionClass($metadata->name); } $classAnnotations = $this->_reader->getClassAnnotations($class); // Compatibility with Doctrine Common 3.x if ($classAnnotations && is_int(key($classAnnotations))) { foreach ($classAnnotations as $annot) { $classAnnotations[get_class($annot)] = $annot; } } // Evaluate Entity annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\Entity'])) { $entityAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\Entity']; if ($entityAnnot->repositoryClass !== null) { $metadata->setCustomRepositoryClass($entityAnnot->repositoryClass); } if ($entityAnnot->readOnly) { $metadata->markReadOnly(); } } else { if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\MappedSuperclass'])) { $mappedSuperclassAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\MappedSuperclass']; $metadata->setCustomRepositoryClass($mappedSuperclassAnnot->repositoryClass); $metadata->isMappedSuperclass = true; } else { throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className); } } // Evaluate Table annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\Table'])) { $tableAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\Table']; $primaryTable = array('name' => $tableAnnot->name, 'schema' => $tableAnnot->schema); if ($tableAnnot->indexes !== null) { foreach ($tableAnnot->indexes as $indexAnnot) { $primaryTable['indexes'][$indexAnnot->name] = array('columns' => $indexAnnot->columns); } } if ($tableAnnot->uniqueConstraints !== null) { foreach ($tableAnnot->uniqueConstraints as $uniqueConstraint) { $primaryTable['uniqueConstraints'][$uniqueConstraint->name] = array('columns' => $uniqueConstraint->columns); } } if ($tableAnnot->options !== null) { $primaryTable['options'] = $tableAnnot->options; } $metadata->setPrimaryTable($primaryTable); } // Evaluate NamedQueries annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\NamedQueries'])) { $namedQueriesAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\NamedQueries']; if (!is_array($namedQueriesAnnot->value)) { throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); } foreach ($namedQueriesAnnot->value as $namedQuery) { if (!$namedQuery instanceof \Doctrine\ORM\Mapping\NamedQuery) { throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); } $metadata->addNamedQuery(array('name' => $namedQuery->name, 'query' => $namedQuery->query)); } } // Evaluate InheritanceType annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\InheritanceType'])) { $inheritanceTypeAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\InheritanceType']; $metadata->setInheritanceType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceTypeAnnot->value)); if ($metadata->inheritanceType != \Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) { // Evaluate DiscriminatorColumn annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorColumn'])) { $discrColumnAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorColumn']; $metadata->setDiscriminatorColumn(array('name' => $discrColumnAnnot->name, 'type' => $discrColumnAnnot->type, 'length' => $discrColumnAnnot->length, 'columnDefinition' => $discrColumnAnnot->columnDefinition)); } else { $metadata->setDiscriminatorColumn(array('name' => 'dtype', 'type' => 'string', 'length' => 255)); } // Evaluate DiscriminatorMap annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorMap'])) { $discrMapAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorMap']; $metadata->setDiscriminatorMap($discrMapAnnot->value); } } } // Evaluate DoctrineChangeTrackingPolicy annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\ChangeTrackingPolicy'])) { $changeTrackingAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\ChangeTrackingPolicy']; $metadata->setChangeTrackingPolicy(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::CHANGETRACKING_' . $changeTrackingAnnot->value)); } // Evaluate annotations on properties/fields foreach ($class->getProperties() as $property) { if ($metadata->isMappedSuperclass && !$property->isPrivate() || $metadata->isInheritedField($property->name) || $metadata->isInheritedAssociation($property->name)) { continue; } $mapping = array(); $mapping['fieldName'] = $property->getName(); // Check for JoinColummn/JoinColumns annotations $joinColumns = array(); if ($joinColumnAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\JoinColumn')) { $joinColumns[] = array('name' => $joinColumnAnnot->name, 'referencedColumnName' => $joinColumnAnnot->referencedColumnName, 'unique' => $joinColumnAnnot->unique, 'nullable' => $joinColumnAnnot->nullable, 'onDelete' => $joinColumnAnnot->onDelete, 'columnDefinition' => $joinColumnAnnot->columnDefinition); } else { if ($joinColumnsAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\JoinColumns')) { foreach ($joinColumnsAnnot->value as $joinColumn) { $joinColumns[] = array('name' => $joinColumn->name, 'referencedColumnName' => $joinColumn->referencedColumnName, 'unique' => $joinColumn->unique, 'nullable' => $joinColumn->nullable, 'onDelete' => $joinColumn->onDelete, 'columnDefinition' => $joinColumn->columnDefinition); } } } // Field can only be annotated with one of: // @Column, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany if ($columnAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Column')) { if ($columnAnnot->type == null) { throw MappingException::propertyTypeIsRequired($className, $property->getName()); } $mapping['type'] = $columnAnnot->type; $mapping['length'] = $columnAnnot->length; $mapping['precision'] = $columnAnnot->precision; $mapping['scale'] = $columnAnnot->scale; $mapping['nullable'] = $columnAnnot->nullable; $mapping['unique'] = $columnAnnot->unique; if ($columnAnnot->options) { $mapping['options'] = $columnAnnot->options; } if (isset($columnAnnot->name)) { $mapping['columnName'] = $columnAnnot->name; } if (isset($columnAnnot->columnDefinition)) { $mapping['columnDefinition'] = $columnAnnot->columnDefinition; } if ($idAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Id')) { $mapping['id'] = true; } if ($generatedValueAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\GeneratedValue')) { $metadata->setIdGeneratorType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::GENERATOR_TYPE_' . $generatedValueAnnot->strategy)); } if ($versionAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Version')) { $metadata->setVersionMapping($mapping); } $metadata->mapField($mapping); // Check for SequenceGenerator/TableGenerator definition if ($seqGeneratorAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\SequenceGenerator')) { $metadata->setSequenceGeneratorDefinition(array('sequenceName' => $seqGeneratorAnnot->sequenceName, 'allocationSize' => $seqGeneratorAnnot->allocationSize, 'initialValue' => $seqGeneratorAnnot->initialValue)); } else { if ($tblGeneratorAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\TableGenerator')) { throw MappingException::tableIdGeneratorNotImplemented($className); } } } else { if ($oneToOneAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OneToOne')) { if ($idAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Id')) { $mapping['id'] = true; } $mapping['targetEntity'] = $oneToOneAnnot->targetEntity; $mapping['joinColumns'] = $joinColumns; $mapping['mappedBy'] = $oneToOneAnnot->mappedBy; $mapping['inversedBy'] = $oneToOneAnnot->inversedBy; $mapping['cascade'] = $oneToOneAnnot->cascade; $mapping['orphanRemoval'] = $oneToOneAnnot->orphanRemoval; $mapping['fetch'] = $this->getFetchMode($className, $oneToOneAnnot->fetch); $metadata->mapOneToOne($mapping); } else { if ($oneToManyAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OneToMany')) { $mapping['mappedBy'] = $oneToManyAnnot->mappedBy; $mapping['targetEntity'] = $oneToManyAnnot->targetEntity; $mapping['cascade'] = $oneToManyAnnot->cascade; $mapping['indexBy'] = $oneToManyAnnot->indexBy; $mapping['orphanRemoval'] = $oneToManyAnnot->orphanRemoval; $mapping['fetch'] = $this->getFetchMode($className, $oneToManyAnnot->fetch); if ($orderByAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OrderBy')) { $mapping['orderBy'] = $orderByAnnot->value; } $metadata->mapOneToMany($mapping); } else { if ($manyToOneAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\ManyToOne')) { if ($idAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Id')) { $mapping['id'] = true; } $mapping['joinColumns'] = $joinColumns; $mapping['cascade'] = $manyToOneAnnot->cascade; $mapping['inversedBy'] = $manyToOneAnnot->inversedBy; $mapping['targetEntity'] = $manyToOneAnnot->targetEntity; $mapping['fetch'] = $this->getFetchMode($className, $manyToOneAnnot->fetch); $metadata->mapManyToOne($mapping); } else { if ($manyToManyAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\ManyToMany')) { $joinTable = array(); if ($joinTableAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\JoinTable')) { $joinTable = array('name' => $joinTableAnnot->name, 'schema' => $joinTableAnnot->schema); foreach ($joinTableAnnot->joinColumns as $joinColumn) { $joinTable['joinColumns'][] = array('name' => $joinColumn->name, 'referencedColumnName' => $joinColumn->referencedColumnName, 'unique' => $joinColumn->unique, 'nullable' => $joinColumn->nullable, 'onDelete' => $joinColumn->onDelete, 'columnDefinition' => $joinColumn->columnDefinition); } foreach ($joinTableAnnot->inverseJoinColumns as $joinColumn) { $joinTable['inverseJoinColumns'][] = array('name' => $joinColumn->name, 'referencedColumnName' => $joinColumn->referencedColumnName, 'unique' => $joinColumn->unique, 'nullable' => $joinColumn->nullable, 'onDelete' => $joinColumn->onDelete, 'columnDefinition' => $joinColumn->columnDefinition); } } $mapping['joinTable'] = $joinTable; $mapping['targetEntity'] = $manyToManyAnnot->targetEntity; $mapping['mappedBy'] = $manyToManyAnnot->mappedBy; $mapping['inversedBy'] = $manyToManyAnnot->inversedBy; $mapping['cascade'] = $manyToManyAnnot->cascade; $mapping['indexBy'] = $manyToManyAnnot->indexBy; $mapping['orphanRemoval'] = $manyToManyAnnot->orphanRemoval; $mapping['fetch'] = $this->getFetchMode($className, $manyToManyAnnot->fetch); if ($orderByAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OrderBy')) { $mapping['orderBy'] = $orderByAnnot->value; } $metadata->mapManyToMany($mapping); } } } } } } // Evaluate @HasLifecycleCallbacks annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\HasLifecycleCallbacks'])) { foreach ($class->getMethods() as $method) { // filter for the declaring class only, callbacks from parents will already be registered. if ($method->isPublic() && $method->getDeclaringClass()->getName() == $class->name) { $annotations = $this->_reader->getMethodAnnotations($method); // Compatibility with Doctrine Common 3.x if ($annotations && is_int(key($annotations))) { foreach ($annotations as $annot) { $annotations[get_class($annot)] = $annot; } } if (isset($annotations['Doctrine\\ORM\\Mapping\\PrePersist'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::prePersist); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PostPersist'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postPersist); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PreUpdate'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::preUpdate); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PostUpdate'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postUpdate); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PreRemove'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::preRemove); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PostRemove'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postRemove); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PostLoad'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postLoad); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PreFlush'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::preFlush); } } } } }
/** * Uses the annotation reader to get the reflection class method's annotations * @param ReflectionMethod $reflectionMethod * @return array */ public function getMethodAnnotations(ReflectionMethod $reflectionMethod) { return $this->annotationReader->getMethodAnnotations($reflectionMethod); }
/** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadataInfo $metadata) { $reflClass = $metadata->getReflectionClass(); $classAnnotations = $this->reader->getClassAnnotations($reflClass); // Compatibility with Doctrine Common 3.x if ($classAnnotations && is_int(key($classAnnotations))) { foreach ($classAnnotations as $annot) { $classAnnotations[get_class($annot)] = $annot; } } // Evaluate XmlEntity Annotations if (isset($classAnnotations['Doctrine\\OXM\\Mapping\\XmlEntity'])) { $entityAnnot = $classAnnotations['Doctrine\\OXM\\Mapping\\XmlEntity']; } elseif (isset($classAnnotations['Doctrine\\OXM\\Mapping\\XmlRootEntity'])) { $entityAnnot = $classAnnotations['Doctrine\\OXM\\Mapping\\XmlRootEntity']; $metadata->isRoot = true; } elseif (isset($classAnnotations['Doctrine\\OXM\\Mapping\\XmlMappedSuperclass'])) { $entityAnnot = $classAnnotations['Doctrine\\OXM\\Mapping\\XmlMappedSuperclass']; $metadata->isMappedSuperclass = true; } else { throw MappingException::classIsNotAValidXmlEntity($className); } $metadata->setName($reflClass->getName()); if (isset($entityAnnot->xml)) { $metadata->setXmlName($entityAnnot->xml); } else { $metadata->setXmlName(Inflector::xmlize($reflClass->getShortName())); } if (isset($entityAnnot->repositoryClass)) { $metadata->setCustomRepositoryClass($entityAnnot->repositoryClass); } // Evaluate XmlChangeTrackingPolicy annotation if (isset($classAnnotations['Doctrine\\OXM\\Mapping\\XmlChangeTrackingPolicy'])) { $changeTrackingAnnot = $classAnnotations['Doctrine\\OXM\\Mapping\\XmlChangeTrackingPolicy']; $metadata->setChangeTrackingPolicy(constant('Doctrine\\OXM\\Mapping\\ClassMetadata::CHANGETRACKING_' . $changeTrackingAnnot->value)); } // Check for XmlNamespace/XmlNamespaces annotations $xmlNamespaces = array(); if (isset($classAnnotations['Doctrine\\OXM\\Mapping\\XmlNamespace'])) { $xmlNamespaceAnnot = $classAnnotations['Doctrine\\OXM\\Mapping\\XmlNamespace']; $xmlNamespaces[] = array('url' => $xmlNamespaceAnnot->url, 'prefix' => $xmlNamespaceAnnot->prefix); } else { if (isset($classAnnotations['Doctrine\\OXM\\Mapping\\XmlNamespaces'])) { $xmlNamespaceAnnot = $classAnnotations['Doctrine\\OXM\\Mapping\\XmlNamespaces']; foreach ($xmlNamespaceAnnot->value as $xmlNamespace) { $xmlNamespaces[] = array('url' => $xmlNamespace->url, 'prefix' => $xmlNamespace->prefix); } } } $metadata->setXmlNamespaces($xmlNamespaces); foreach ($reflClass->getProperties() as $property) { if ($metadata->isMappedSuperclass && !$property->isPrivate() || $metadata->isInheritedField($property->name)) { continue; } $mapping = array(); $mapping['fieldName'] = $property->getName(); if ($idAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\OXM\\Mapping\\XmlId')) { $mapping['id'] = true; } if ($generatedValueAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\OXM\\Mapping\\XmlGeneratedValue')) { $metadata->setIdGeneratorType(constant('Doctrine\\OXM\\Mapping\\ClassMetadata::GENERATOR_TYPE_' . $generatedValueAnnot->strategy)); } $referenceAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\OXM\\Mapping\\XmlReferences'); if (isset($referenceAnnot->entityName)) { $mapping['references'] = $referenceAnnot->entityName; } // todo add Id Generator strategy support foreach ($this->reader->getPropertyAnnotations($property) as $fieldAnnot) { if ($fieldAnnot instanceof \Doctrine\OXM\Mapping\XmlField) { if ($fieldAnnot->type == null) { throw MappingException::propertyTypeIsRequired($className, $property->getName()); } $mapping = array_merge($mapping, (array) $fieldAnnot); $metadata->mapField($mapping); } } } // Evaluate @HasLifecycleCallbacks annotations if (isset($classAnnotations['Doctrine\\OXM\\Mapping\\HasLifecycleCallbacks'])) { foreach ($reflClass->getMethods() as $method) { // filter for the declaring class only, callbacks from parents will already be registered. if ($method->isPublic() && $method->getDeclaringClass()->getName() == $reflClass->name) { $annotations = $this->reader->getMethodAnnotations($method); // Compatibility with Doctrine Common 3.x if ($annotations && is_int(key($annotations))) { foreach ($annotations as $annot) { $annotations[get_class($annot)] = $annot; } } if (isset($annotations['Doctrine\\OXM\\Mapping\\PreMarshal'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::preMarshal); } if (isset($annotations['Doctrine\\OXM\\Mapping\\PostMarshal'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::postMarshal); } if (isset($annotations['Doctrine\\OXM\\Mapping\\PreUnmarshal'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::preUnmarshal); } if (isset($annotations['Doctrine\\OXM\\Mapping\\PostUnmarshal'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::postUnmarshal); } if (isset($annotations['Doctrine\\OXM\\Mapping\\PrePersist'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::prePersist); } if (isset($annotations['Doctrine\\OXM\\Mapping\\PostPersist'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::postPersist); } if (isset($annotations['Doctrine\\OXM\\Mapping\\PreUpdate'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::preUpdate); } if (isset($annotations['Doctrine\\OXM\\Mapping\\PostUpdate'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::postUpdate); } if (isset($annotations['Doctrine\\OXM\\Mapping\\PreRemove'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::preRemove); } if (isset($annotations['Doctrine\\OXM\\Mapping\\PostRemove'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::postRemove); } if (isset($annotations['Doctrine\\OXM\\Mapping\\PreLoad'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::preLoad); } if (isset($annotations['Doctrine\\OXM\\Mapping\\PostLoad'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::postLoad); } } } } }
/** * Internal function to build the routes for a specific class. * * @param string $path * @param string $file * @param string $module * @param Route[] $routes */ private function buildRoutesForClass($path, $file, $module, $routes, $routesWithParameters) { $class = str_replace(".php", "", $file); include_once $path . $file; $content = file_get_contents($path . $file); $n = substr($content, strpos($content, "namespace ") + 10); $n = substr($n, 0, strpos($n, ";")); $controller = str_replace("Controller", "", $class); $class = $n . "\\" . $class; $controllerNS = $n . "\\" . $controller; $_reflection = new \ReflectionClass($class); $functions = $_reflection->getMethods(); foreach ($functions as $function) { if (substr($function->getName(), strlen($function->getName()) - 6) == "Action") { $reader = new AnnotationReader(); $parameters = $reader->getMethodAnnotations($function, 'Skelpo\\Framework\\Annotations\\Router\\UrlParam'); $functionName = str_replace("Action", "", $function->getName()); $ctlStr = $controllerNS . 'Controller::' . $functionName . "Action"; $moduleStr = $module; $this->buildRoutesIntern($moduleStr, strtolower($controller), $functionName, array(), $ctlStr, $parameters, $routes, $routesWithParameters); } } }
/** * Returns the arguments of a request. * * @param Symfony\Component\HttpFoundation\Request $request * @param Symfony\Bundle\FrameworkBundle\Controller\Controller The controller. * @return string[] */ public function getArguments(Request $request, $controller) { $reflMthd = null; $reflObj = null; if (is_array($controller)) { $reflMthd = new \ReflectionMethod($controller[0], $controller[1]); $reflObj = new \ReflectionObject($controller[0]); } elseif (is_object($controller) && !$controller instanceof \Closure) { $reflObj = new \ReflectionObject($controller); $reflMthd = $reflObj->getMethod('__invoke'); } else { $reflObj = null; $reflMthd = new \ReflectionFunction($controller); } $methodRelations = array(); if ($reflMthd !== null) { $reader = new AnnotationReader(); $methodRelations = $reader->getMethodAnnotations($reflMthd, 'Skelpo\\Framework\\Annotations\\Router\\UrlParam'); foreach ($methodRelations as $key => $v) { $methodRelations[$v->name] = $v; unset($methodRelations[$key]); } } $finalParameters = array(); $realParameters = $reflMthd->getParameters(); foreach ($realParameters as $p) { if (isset($methodRelations[$p->name])) { $finalParameters[] = $methodRelations[$p->name]; } else { $finalParameters[] = $p; } } return $this->doGetArguments($request, $controller, $finalParameters); }
/** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadata $class) { $reflClass = $class->getReflectionClass(); $classAnnotations = $this->reader->getClassAnnotations($reflClass); if (isset($classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\Document'])) { $documentAnnot = $classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\Document']; } elseif (isset($classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\MappedSuperclass'])) { $documentAnnot = $classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\MappedSuperclass']; $class->isMappedSuperclass = true; } elseif (isset($classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\EmbeddedDocument'])) { $documentAnnot = $classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\EmbeddedDocument']; $class->isEmbeddedDocument = true; } else { throw MongoDBException::classIsNotAValidDocument($className); } if (isset($documentAnnot->db)) { $class->setDatabase($documentAnnot->db); } if (isset($documentAnnot->collection)) { $class->setCollection($documentAnnot->collection); } if (isset($documentAnnot->repositoryClass)) { $class->setCustomRepositoryClass($documentAnnot->repositoryClass); } if (isset($classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\Indexes'])) { $indexes = $classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\Indexes']->value; $indexes = is_array($indexes) ? $indexes : array($indexes); foreach ($indexes as $index) { $this->addIndex($class, $index); } } if (isset($classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\Index'])) { $index = $classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\Index']; $this->addIndex($class, $index); } if (isset($classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\UniqueIndex'])) { $index = $classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\UniqueIndex']; $this->addIndex($class, $index); } if (isset($documentAnnot->indexes)) { foreach ($documentAnnot->indexes as $index) { $this->addIndex($class, $index); } } if (isset($classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\InheritanceType'])) { $inheritanceTypeAnnot = $classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\InheritanceType']; $class->setInheritanceType(constant('Doctrine\\ODM\\MongoDB\\Mapping\\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceTypeAnnot->value)); } if (isset($classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\DiscriminatorField'])) { $discrFieldAnnot = $classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\DiscriminatorField']; $class->setDiscriminatorField(array('fieldName' => $discrFieldAnnot->fieldName)); } if (isset($classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\DiscriminatorMap'])) { $discrMapAnnot = $classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\DiscriminatorMap']; $class->setDiscriminatorMap($discrMapAnnot->value); } if (isset($classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\DiscriminatorValue'])) { $discrValueAnnot = $classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\DiscriminatorValue']; $class->setDiscriminatorValue($discrValueAnnot->value); } if (isset($classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\ChangeTrackingPolicy'])) { $changeTrackingAnnot = $classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\ChangeTrackingPolicy']; $class->setChangeTrackingPolicy(constant('Doctrine\\ODM\\MongoDB\\Mapping\\ClassMetadata::CHANGETRACKING_' . $changeTrackingAnnot->value)); } $methods = $reflClass->getMethods(); foreach ($reflClass->getProperties() as $property) { if ($class->isMappedSuperclass && !$property->isPrivate() || $class->isInheritedField($property->name)) { continue; } $mapping = array(); $mapping['fieldName'] = $property->getName(); if ($alsoLoad = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ODM\\MongoDB\\Mapping\\AlsoLoad')) { $mapping['alsoLoadFields'] = (array) $alsoLoad->value; } if ($notSaved = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ODM\\MongoDB\\Mapping\\NotSaved')) { $mapping['notSaved'] = true; } if ($versionAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ODM\\MongoDB\\Mapping\\Version')) { $mapping['version'] = true; } if ($versionAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ODM\\MongoDB\\Mapping\\Lock')) { $mapping['lock'] = true; } $indexes = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ODM\\MongoDB\\Mapping\\Indexes'); $indexes = $indexes ? $indexes : array(); if ($index = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ODM\\MongoDB\\Mapping\\Index')) { $indexes[] = $index; } if ($index = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ODM\\MongoDB\\Mapping\\UniqueIndex')) { $indexes[] = $index; } foreach ($this->reader->getPropertyAnnotations($property) as $fieldAnnot) { if ($fieldAnnot instanceof \Doctrine\ODM\MongoDB\Mapping\Field) { $mapping = array_merge($mapping, (array) $fieldAnnot); $class->mapField($mapping); } } if ($indexes) { foreach ($indexes as $index) { $name = isset($mapping['name']) ? $mapping['name'] : $mapping['fieldName']; $keys = array(); $keys[$name] = 'asc'; if (isset($index->order)) { $keys[$name] = $index->order; } $this->addIndex($class, $index, $keys); } } } foreach ($methods as $method) { if ($method->isPublic()) { if ($alsoLoad = $this->reader->getMethodAnnotation($method, 'Doctrine\\ODM\\MongoDB\\Mapping\\AlsoLoad')) { $fields = (array) $alsoLoad->value; foreach ($fields as $value) { $class->alsoLoadMethods[$value] = $method->getName(); } } } } if (isset($classAnnotations['Doctrine\\ODM\\MongoDB\\Mapping\\HasLifecycleCallbacks'])) { foreach ($methods as $method) { if ($method->isPublic()) { $annotations = $this->reader->getMethodAnnotations($method); if (isset($annotations['Doctrine\\ODM\\MongoDB\\Mapping\\PrePersist'])) { $class->addLifecycleCallback($method->getName(), \Doctrine\ODM\MongoDB\Events::prePersist); } if (isset($annotations['Doctrine\\ODM\\MongoDB\\Mapping\\PostPersist'])) { $class->addLifecycleCallback($method->getName(), \Doctrine\ODM\MongoDB\Events::postPersist); } if (isset($annotations['Doctrine\\ODM\\MongoDB\\Mapping\\PreUpdate'])) { $class->addLifecycleCallback($method->getName(), \Doctrine\ODM\MongoDB\Events::preUpdate); } if (isset($annotations['Doctrine\\ODM\\MongoDB\\Mapping\\PostUpdate'])) { $class->addLifecycleCallback($method->getName(), \Doctrine\ODM\MongoDB\Events::postUpdate); } if (isset($annotations['Doctrine\\ODM\\MongoDB\\Mapping\\PreRemove'])) { $class->addLifecycleCallback($method->getName(), \Doctrine\ODM\MongoDB\Events::preRemove); } if (isset($annotations['Doctrine\\ODM\\MongoDB\\Mapping\\PostRemove'])) { $class->addLifecycleCallback($method->getName(), \Doctrine\ODM\MongoDB\Events::postRemove); } if (isset($annotations['Doctrine\\ODM\\MongoDB\\Mapping\\PreLoad'])) { $class->addLifecycleCallback($method->getName(), \Doctrine\ODM\MongoDB\Events::preLoad); } if (isset($annotations['Doctrine\\ODM\\MongoDB\\Mapping\\PostLoad'])) { $class->addLifecycleCallback($method->getName(), \Doctrine\ODM\MongoDB\Events::postLoad); } } } } }
{ return $this->getProperty(); } } // Lets parse the annotations use Doctrine\Common\Annotations\AnnotationReader; $annotationReader = new AnnotationReader(); //Get class annotation $reflectionClass = new ReflectionClass('AnnotationDemo'); $classAnnotations = $annotationReader->getClassAnnotations($reflectionClass); echo "<pre>"; echo "========= CLASS ANNOTATIONS =========" . PHP_EOL; var_dump($classAnnotations); // You can also pass ReflectionObject to the same method to read annotations in runtime $annotationDemoObject = new AnnotationDemo(); $reflectionObject = new ReflectionObject($annotationDemoObject); $objectAnnotations = $annotationReader->getClassAnnotations($reflectionObject); echo "========= OBJECT ANNOTATIONS =========" . PHP_EOL; var_dump($objectAnnotations); //Property Annotations $reflectionProperty = new ReflectionProperty('AnnotationDemo', 'property'); $propertyAnnotations = $annotationReader->getPropertyAnnotations($reflectionProperty); echo "========= PROPERTY ANNOTATIONS =========" . PHP_EOL; var_dump($propertyAnnotations); var_dump($reflectionProperty); var_dump($annotationReader->getPropertyAnnotation($reflectionProperty, 'var')); // Method Annotations $reflectionMethod = new ReflectionMethod('AnnotationDemo', 'getProperty'); $methodAnnotations = $annotationReader->getMethodAnnotations($reflectionMethod); echo "========= Method ANNOTATIONS =========" . PHP_EOL; var_dump($methodAnnotations);