/** * Generate Remote API from a list of controllers */ public function generateRemotingApi() { $list = array(); foreach ($this->remotingBundles as $bundle) { $bundleRef = new \ReflectionClass($bundle); $controllerDir = new Finder(); $controllerDir->files()->in(dirname($bundleRef->getFileName()) . '/Controller/')->name('/.*Controller\\.php$/'); foreach ($controllerDir as $controllerFile) { /** @var SplFileInfo $controllerFile */ $controller = $bundleRef->getNamespaceName() . "\\Controller\\" . substr($controllerFile->getFilename(), 0, -4); $controllerRef = new \ReflectionClass($controller); foreach ($controllerRef->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { /** @var $methodDirectAnnotation Direct */ $methodDirectAnnotation = $this->annoReader->getMethodAnnotation($method, 'Tpg\\ExtjsBundle\\Annotation\\Direct'); if ($methodDirectAnnotation !== null) { $nameSpace = str_replace("\\", ".", $bundleRef->getNamespaceName()); $className = str_replace("Controller", "", $controllerRef->getShortName()); $methodName = str_replace("Action", "", $method->getName()); $list[$nameSpace][$className][] = array('name' => $methodName, 'len' => count($method->getParameters())); } } } } return $list; }
public function onKernelRequest(GetResponseEvent $event) { $request = $event->getRequest(); $method = $request->attributes->get('_controller'); $class_full = explode("::", $method); if (sizeof($class_full) != 2) { return; } if ($class_full[1] != "indexAction") { return; } $class = trim($class_full[0]); $reflectionClass = new \ReflectionClass($class); $reader = new AnnotationReader(); $hdata = $reader->getClassAnnotation($reflectionClass, 'BOS\\ApiBundle\\Annotations\\BOSApiController'); if ($hdata) { $i = -1; $methods = array(); $methodsArray = $reflectionClass->getMethods(); foreach ($methodsArray as $m) { $currentFullMethod = $class . "::" . $m->getName(); $collection = $this->router->getRouteCollection()->all(); $url = null; foreach ($collection as $route => $params) { $defaults = $params->getDefaults(); if (isset($defaults['_controller'])) { if ($currentFullMethod == $defaults['_controller']) { $url = $this->router->generate($route); } } } //die("ffFF"); $rm = new \ReflectionMethod($class . "::" . $m->getName()); $data = $reader->getMethodAnnotation($rm, 'BOS\\ApiBundle\\Annotations\\BOSApiMethod'); if ($data) { /* Method data, POST OR GET OR ANY */ $mData = $reader->getMethodAnnotation($rm, "Sensio\\Bundle\\FrameworkExtraBundle\\Configuration\\Method"); $nMethods = array(); if ($mData) { $nMethods = $mData->getMethods(); } if (!$url) { die("BOSApiBundle fatal error: couldn't generate route for: " . $rm->getName()); } $i++; $data->url = $url; $data->methods = $nMethods; $methods[$i] = $data; } } $message = $this->render->render("BOSApiBundle:Default:index.html.twig", array("api_header" => $hdata, "api_methods" => $methods)); $response = new Response($message); $event->setResponse($response); } }
/** * * @param \ReflectionClass $class * @param Object $c_ann */ public function addMethods(\ReflectionClass $class, $c_ann) { if ($this->isEvent($c_ann)) { foreach ($class->getMethods() as $ref_met) { $annotation = $this->reader->getMethodAnnotation($ref_met, 'DIPcom\\AnnEvents\\Mapping\\Target'); if ($annotation) { $this->guideline->addEvent($ref_met, $annotation); } } } }
/** * @Pdf() */ public function testPdfAnnotationIsCorrectlyCreatedByReader() { $reader = new AnnotationReader(); $method = new \ReflectionMethod($this, 'testPdfAnnotationIsCorrectlyCreatedByReader'); $pdf = $reader->getMethodAnnotation($method, 'Ps\\PdfBundle\\Annotation\\Pdf'); $this->assertNotNull($pdf); }
/** * {@inheritdoc} */ public function invoke(MethodInvocation $invocation) { $object = $invocation->getThis(); $method = $invocation->getMethod(); $write = ['onPut', 'onDelete', 'onPost']; $connectionParams = in_array($method->name, $write) ? $this->masterDb : $this->slaveDb; $pagerAnnotation = $this->reader->getMethodAnnotation($method, 'BEAR\\Sunday\\Annotation\\DbPager'); $db = $this->getDb($pagerAnnotation, $connectionParams); /* @var $db \BEAR\Package\Module\Database\Dbal\PagerConnection */ if ($this->sqlLogger instanceof SQLLogger) { $db->getConfiguration()->setSQLLogger($this->sqlLogger); } $object->setDb($db); $result = $invocation->proceed(); if ($this->sqlLogger instanceof DebugStack) { $this->sqlLogger->stopQuery(); $object->headers['x-sql'] = [$this->sqlLogger->queries]; } elseif ($this->sqlLogger instanceof SQLLogger) { $this->sqlLogger->stopQuery(); } if (!$pagerAnnotation) { return $result; } $pagerData = $db->getPager(); if ($pagerData) { $object->headers['pager'] = $pagerData; } return $result; }
/** * (non-PHPdoc) * @see Ray\Aop.MethodInterceptor::invoke() */ public function invoke(MethodInvocation $invocation) { $object = $invocation->getThis(); $method = $invocation->getMethod(); $connectionParams = $method->name !== 'onGet' ? $this->slaveDb : $this->masterDb; $pagerAnnotation = $this->reader->getMethodAnnotation($method, 'BEAR\\Sunday\\Annotation\\DbPager'); if ($pagerAnnotation) { $connectionParams['wrapperClass'] = 'BEAR\\Package\\Module\\Database\\DoctrineDbalModule\\Connection'; $db = DriverManager::getConnection($connectionParams); $db->setMaxPerPage($pagerAnnotation->limit); } else { $db = DriverManager::getConnection($connectionParams); } /* @var $db \BEAR\Package\Module\Database\DoctrineDbalModule\Connection */ if ($this->sqlLogger instanceof SQLLogger) { $db->getConfiguration()->setSQLLogger($this->sqlLogger); } $object->setDb($db); $result = $invocation->proceed(); if ($this->sqlLogger instanceof SQLLogger) { $this->sqlLogger->stopQuery(); $object->headers['x-sql'] = [$this->sqlLogger->queries]; } if ($pagerAnnotation) { $pagerData = $db->getPager(); if ($pagerData) { $object->headers['pager'] = $pagerData; } } return $result; }
public function getMethodAnnotation(\ReflectionMethod $method, $type) { $annotation = parent::getMethodAnnotation($method, $type); if ($annotation !== null && count($annotation) > 1) { throw new \LogicException(sprintf("There is more than one annotation of type '%s'!", $type)); } return $annotation !== null ? $annotation[0] : null; }
/** * @param PHPUnit_Framework_Test $test * @param AnnotationReader $annotationReader * @param string $arrangeMethod * @return string */ private function getArrangeDescription(PHPUnit_Framework_Test $test, AnnotationReader $annotationReader, $arrangeMethod) { $arrangeMethodAnnotation = $annotationReader->getMethodAnnotation(new \ReflectionMethod($test, $arrangeMethod), Arrange::class); if ($arrangeMethodAnnotation === null) { throw new \DomainException('The arrange method does not have an annotation itself'); } return $arrangeMethodAnnotation->getMethods()['describe']; }
/** * Returns if the given method is a ServiceCall * @static * @param \ReflectionMethod $reflectionMethod The method to reflect on * @param \Doctrine\Common\Annotations\AnnotationReader $reader The annotation reader * @return bool true if the method is a service call, false otherwise */ public static function isServiceCall(\ReflectionMethod $reflectionMethod, \Doctrine\Common\Annotations\AnnotationReader $reader) { if ($reader->getMethodAnnotation($reflectionMethod, "PartKeepr\\Service\\Annotations\\ServiceCall") === null) { return false; } else { return true; } }
/** * @param $object * @return array */ public function convert($object) : array { $reflectionObject = new \ReflectionObject($object); $owners = []; foreach ($reflectionObject->getProperties() as $property) { /** @var Owner $annotation */ $annotation = $this->reader->getPropertyAnnotation($property, $this->annotationClass); if (null !== $annotation) { $owners[] = $annotation->value; } } foreach ($reflectionObject->getMethods() as $method) { $annotation = $this->reader->getMethodAnnotation($method, $this->annotationClass); if (null !== $annotation) { $owners[] = $method->invoke($object); } } return $owners; }
/** * Try to extract the RelationAnnotation from the method. * If it is found then we set the informations in the static property <code>static::$relationsMapping</code> * * @param \ReflectionMethod $method * * @throws \Exception */ protected function processProperty(\ReflectionMethod $method) { $reader = new AnnotationReader(); $relation = $reader->getMethodAnnotation($method, RelationAnnotation::class); /* @var RelationAnnotation $relation */ if ($relation) { $class = $this->extractAndCorrectClassIdNeeded($relation, $method); static::$relationsMapping[$class] = array('class' => $method->class, 'method' => $method->name); } }
/** * @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; }
/** * @return void */ protected function registerRoutes() { $reader = new AnnotationReader(); $class = new \ReflectionClass($this); /** @var RouteCollection $router */ $router = $this->getContainer()->get(Application::CONTAINER_ID_ROUTER); /** @var \ReflectionMethod $method */ foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { $this->registerRoute($router, $class, $method, $reader->getMethodAnnotation($method, '\\Phprest\\Annotation\\Route')); } }
/** * Uses the underlying evaluator to extract the endpoint class method * and its Validator\Validate annotation. If an annotation exists, the * validateArguments() method is called for the actual validation. * * @param string $method Method name * @param array $arguments Positional or associative argument array * @throws JsonRpc\Exception\Argument If the validation fails on any of the arguments */ private function validate($method, $arguments) { /** @var Validate $validateAnnotation */ $reader = new AnnotationReader(); $callable = $this->mapper->getCallable($method); $filledArguments = $this->mapper->getArguments($callable, $arguments); $reflectMethod = new ReflectionMethod($callable[0], $callable[1]); $validateAnnotation = $reader->getMethodAnnotation($reflectMethod, self::VALIDATE_CLASS_NAME); if ($validateAnnotation) { $this->validateArguments($filledArguments, $validateAnnotation, $reflectMethod); } }
/** * Try to extract the MethodAnnotation from the method. * If it is found then we set the informations in the static property <code>static::$pathsMapping</code> * * @param \ReflectionMethod $method * * @throws \Exception */ protected function processProperty(\ReflectionMethod $method) { $reader = new AnnotationReader(); $methodAnnotation = $reader->getMethodAnnotation($method, MethodAnnotation::class); if ($methodAnnotation instanceof MethodAnnotation) { $this->testParametersValid($method); $paths = explode('/', $methodAnnotation->path); $path = '[' . implode('][', $paths) . ']'; $propertyAccessor = PropertyAccess::createPropertyAccessor(); $propertyAccessor->setValue(static::$pathsMapping, $path, array('class' => $method->class, 'method' => $method->name, 'use_key' => $methodAnnotation->key)); } }
/** * @param DomainEventMessageInterface $event */ public function findAndInvokeEventHandlers(DomainEventMessageInterface $event) { // !!! TODO revisit foreach (ReflectionUtils::getMethods($this->reflectionClass) as $method) { $annotation = $this->reader->getMethodAnnotation($method, EventHandler::class); if (null !== $annotation) { $parameter = current($method->getParameters()); if (null !== $parameter->getClass() && $parameter->getClass()->name === $event->getPayloadType()) { $method->invokeArgs($this->targetObject, array($event->getPayload())); } } } }
public function onKernelController(FilterControllerEvent $event) { $controller = $event->getController(); if (!is_array($controller) || !$controller[0] instanceof RestController) { return; } $action = $controller[1]; $controller = $controller[0]; $reflection = new \ReflectionObject($controller); $reader = new AnnotationReader(); $authorize = $reader->getClassAnnotation($reflection, Authorize::class); $methodAuthorize = $reader->getMethodAnnotation($reflection->getMethod($action), Authorize::class); if ($methodAuthorize != null) { $authorize = $methodAuthorize; } $config = $this->container->getParameter("rest.config")["authentication"]; if ($authorize != null && $config["enabled"]) { $authHeader = $event->getRequest()->headers->get("authorization", "null null"); $explode = explode(" ", $authHeader); $type = $explode[0]; $token = $explode[1]; if ($authHeader == "null null") { $this->unauth(); } if (strtolower($type) != "bearer") { $this->unauth(); } $type = $config["oauth_type"]; if ($type == "own") { /** @var OAuthService $oauthService */ $oauthService = $this->container->get("rest.oauth_service"); $authToken = $oauthService->getAuthToken($token); if ($authToken == null) { $this->unauth(); } $session = new Session(new MockArraySessionStorage()); $session->set("token", $authToken); $session->set("consumer", $authToken->getConsumer()); $session->set("user", $authToken->getUser()); $event->getRequest()->setSession($session); } else { if ($type == "static") { $tokens = $config["oauth"]["static_tokens"]; if (!in_array($token, $tokens)) { $this->unauth(); } } } } }
private function getAnnotatedTargetValue($annotationName, CommandMessageInterface $command, AnnotationReader $reader, \ReflectionClass $reflClass) { foreach (ReflectionUtils::getProperties($reflClass) as $property) { if (null !== ($annot = $reader->getPropertyAnnotation($property, $annotationName))) { $property->setAccessible(true); return $property->getValue($command->getPayload()); } } foreach (ReflectionUtils::getMethods($reflClass) as $method) { if (null !== ($annot = $reader->getMethodAnnotation($method, $annotationName))) { $method->setAccessible(true); return $method->invoke($command->getPayload()); } } return null; }
/** * Cria as rotas definidas para o controlador. * * @param \Silex\ControllerCollection $controller * @param String $controllerService * @param \ReflectionClass $reflectionClass */ private function mapRoutes($controller, $controllerService, $reflectionClass) { $methods = $reflectionClass->getMethods(); foreach ($methods as $reflectionMethod) { $route = $this->reader->getMethodAnnotation($reflectionMethod, 'Neton\\Silex\\Framework\\Annotation\\Route'); $direct = $this->reader->getMethodAnnotation($reflectionMethod, 'Neton\\Silex\\Framework\\Annotation\\Direct'); $beforeFilters = $this->reader->getMethodAnnotation($reflectionMethod, 'Neton\\Silex\\Framework\\Annotation\\Before'); $afterFilters = $this->reader->getMethodAnnotation($reflectionMethod, 'Neton\\Silex\\Framework\\Annotation\\After'); if ($route) { $this->mapBasicRoute($route, $controller, $controllerService, $reflectionClass, $reflectionMethod, $beforeFilters, $afterFilters); } if ($direct) { $this->mapDirectRoute($direct, $controller, $controllerService, $reflectionClass, $reflectionMethod, $beforeFilters, $afterFilters); } } }
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); }
/** * @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); }
/** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if ($this->guard->guest()) { if ($request->ajax() || $request->wantsJson()) { return response('Unauthorized.', 401); } else { return redirect()->guest(URL::route('backend.auth')); } } $user = $this->guard->user(); if (!$user instanceof HasAccessEntity || count($user->getPermissions()) === 0) { throw new AccessDeniedHttpException(); } else { $routeResolver = $request->getRouteResolver(); /* @var Route $route */ $route = $routeResolver(); $action = $route->getAction(); if (is_string($action['uses'])) { list($class, $method) = explode('@', $action['uses']); $reader = new AnnotationReader(); $class = new ReflectionClass($class); $annotation = $reader->getClassAnnotation($class, PermissionAnnotation::class); if ($annotation instanceof PermissionAnnotation && !$user->hasAccess($annotation->permissions, $annotation->all)) { if ($request->ajax()) { return new JsonResponse([], Response::HTTP_FORBIDDEN); } else { return $this->forbiddenRequest(); } } if ($method = $class->getMethod($method)) { $annotation = $reader->getMethodAnnotation($method, PermissionAnnotation::class); if ($annotation instanceof PermissionAnnotation && !$user->hasAccess($annotation->permissions, $annotation->all)) { if ($request->ajax()) { return new JsonResponse([], Response::HTTP_FORBIDDEN); } else { return $this->forbiddenRequest(); } } } } } return $next($request); }
/** * Load RPC method metadata from class. * * @param string $class Class * @return array|null * @throws InvalidMappingException */ public function loadClassMetadata($class) { if (array_key_exists($class, $this->meta)) { return $this->meta[$class]; } $meta = null; if (class_exists($class)) { $reflectionClass = new \ReflectionClass($class); if ($method = $this->reader->getClassAnnotation($reflectionClass, 'Timiki\\Bundle\\RpcServerBundle\\Mapping\\Method')) { $meta = []; if (empty($method->value)) { throw new InvalidMappingException(sprintf('@Method annotation must have name in class "%s", @Method("method name")', $class)); } $meta['method'] = $method; $meta['class'] = $class; $meta['file'] = $reflectionClass->getFileName(); // Cache $meta['cache'] = $this->reader->getClassAnnotation($reflectionClass, 'Timiki\\Bundle\\RpcServerBundle\\Mapping\\Cache'); // Roles $meta['roles'] = $this->reader->getClassAnnotation($reflectionClass, 'Timiki\\Bundle\\RpcServerBundle\\Mapping\\Roles'); // Method execute. On in class $meta['executeMethod'] = null; foreach ($reflectionClass->getMethods() as $reflectionMethod) { if ($paramMeta = $this->reader->getMethodAnnotation($reflectionMethod, 'Timiki\\Bundle\\RpcServerBundle\\Mapping\\Execute')) { $meta['executeMethod'] = $reflectionMethod->name; } } if (empty($meta['executeMethod'])) { throw new InvalidMappingException(sprintf('Method need have @Execute annotation in class "%s", @Execute()', $class)); } // Params $meta['params'] = []; foreach ($reflectionClass->getProperties() as $reflectionProperty) { if ($paramMeta = $this->reader->getPropertyAnnotation($reflectionProperty, 'Timiki\\Bundle\\RpcServerBundle\\Mapping\\Param')) { $meta['params'][$reflectionProperty->name] = $paramMeta; } } } } return $meta; }
public function registerAspects(MvcEvent $event) { $application = $event->getApplication(); $config = $application->getConfig(); Annotations\AnnotationRegistry::registerAutoloadNamespace(__NAMESPACE__ . '\\Annotation'); foreach ($config['aop']['aspect_class_paths'] as $path) { foreach (new ClassFileLocator($path) as $classInfoFile) { foreach ($classInfoFile->getClasses() as $class) { $aspect = new $class(); $reader = new Annotations\AnnotationReader(); $reflection = new \ReflectionClass($aspect); foreach ($reflection->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { $annotation = $reader->getMethodAnnotation($method, 'AOP\\Annotation\\Pointcut'); if (!$annotation) { continue; } $advice = $method->getName(); $pointcuts = $annotation->rule; foreach ($pointcuts as $pointcut) { list($trigger, $rule) = sscanf($pointcut, "%s %s"); switch ($trigger) { case 'before': aop_add_before($rule, array($aspect, $advice)); break; case 'after': aop_add_after($rule, array($aspect, $advice)); break; case 'around': aop_add_around($rule, array($aspect, $advice)); break; } } if ($aspect instanceof \Zend\ServiceManager\ServiceLocatorAwareInterface) { $aspect->setServiceLocator($application->getServiceManager()); } } } } } }
/** * Execute an action on the controller. * * @param string $method * @param array $parameters * * @return \Symfony\Component\HttpFoundation\Response */ public function callAction($method, $parameters) { /** * @var HasAccessEntity|PermissionsTrait|null $user * @var Permissions $annotation */ try { $user = \Auth::guard(property_exists($this, 'guard') ? $this->guard : null)->user(); $reader = new AnnotationReader(); $class = new \ReflectionClass($this); $annotation = $reader->getClassAnnotation($class, Permissions::class); if ($annotation instanceof Permissions) { if ($user instanceof HasAccessEntity) { if (!$user->hasAccess($annotation->permissions, $annotation->all)) { throw new AccessDeniedHttpException(); } } else { throw new \RuntimeException('User must implements HasAccessEntity'); } } $method = $class->getMethod($method); $annotation = $reader->getMethodAnnotation($method, Permissions::class); if ($annotation instanceof Permissions) { if ($user instanceof HasAccessEntity) { if (!$user->hasAccess($annotation->permissions, $annotation->all)) { throw new AccessDeniedHttpException(); } } else { throw new \RuntimeException('User must implements HasAccessEntity'); } } } catch (AccessDeniedHttpException $e) { if (\Request::ajax()) { return \Response::json(['error' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()], 403, [], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); } else { return view(property_exists($this, 'denyView') ? $this->denyView : 'deny'); } } return $method->invokeArgs($this, $parameters); }
/** * Loads routes from source code * @return array Array of routes */ private function loadRoutesFromSource() { $routeAnnotation = new Route(); $annotationReader = new AnnotationReader(); $routes = array(); foreach ($this->getAllClasses() as $class) { foreach ($class->getMethodInfos() as $method) { $className = $class->getName(); $methodName = $method->getName(); $reflectionMethod = new \ReflectionMethod($className, $methodName); $methodAnnotation = $annotationReader->getMethodAnnotation($reflectionMethod, $routeAnnotation); if (!is_null($methodAnnotation) && $this->validatePattern($methodAnnotation->pattern)) { $this->addRoutePattern($routes, $methodAnnotation->pattern, $className, $methodName); } } } return $routes; }
/** * {@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); } } } } }
/** * {@inheritDoc} * @throws InvalidProxiedClassException * @throws InvalidArgumentException */ public function generate(ReflectionClass $originalClass, ClassGenerator $classGenerator) { CanProxyAssertion::assertClassCanBeProxied($originalClass, false); $annotation = null; $forceLazyInitProperty = new ForceLazyInitProperty(); $sessionBeansProperty = new SessionBeansProperty(); $postProcessorsProperty = new BeanPostProcessorsProperty(); $parameterValuesProperty = new ParameterValuesProperty(); $beanFactoryConfigurationProperty = new BeanFactoryConfigurationProperty(); $aliasesProperty = new AliasesProperty(); $getParameterMethod = new GetParameter($originalClass, $parameterValuesProperty); $wrapBeanAsLazyMethod = new WrapBeanAsLazy($originalClass, $beanFactoryConfigurationProperty); try { $reader = new AnnotationReader(); $annotation = $reader->getClassAnnotation($originalClass, Configuration::class); } catch (Exception $e) { throw new InvalidProxiedClassException($e->getMessage(), $e->getCode(), $e); } if (null === $annotation) { throw new InvalidProxiedClassException(sprintf('"%s" seems not to be a valid configuration class. @Configuration annotation missing!', $originalClass->getName())); } $classGenerator->setExtendedClass($originalClass->getName()); $classGenerator->setImplementedInterfaces([AliasContainerInterface::class]); $classGenerator->addPropertyFromGenerator($forceLazyInitProperty); $classGenerator->addPropertyFromGenerator($sessionBeansProperty); $classGenerator->addPropertyFromGenerator($postProcessorsProperty); $classGenerator->addPropertyFromGenerator($parameterValuesProperty); $classGenerator->addPropertyFromGenerator($beanFactoryConfigurationProperty); $classGenerator->addPropertyFromGenerator($aliasesProperty); $postProcessorMethods = []; $aliases = []; $methods = $originalClass->getMethods(ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED); foreach ($methods as $method) { if (null !== $reader->getMethodAnnotation($method, BeanPostProcessor::class)) { $postProcessorMethods[] = $method->getName(); continue; } /* @var \bitExpert\Disco\Annotations\Bean $beanAnnotation */ $beanAnnotation = $reader->getMethodAnnotation($method, Bean::class); if (null === $beanAnnotation) { throw new InvalidProxiedClassException(sprintf('Method "%s" on "%s" is missing the @Bean annotation!', $method->getName(), $originalClass->getName())); } // if alias is defined append it to the aliases list if ($beanAnnotation->getAlias() !== '' && !isset($aliases[$beanAnnotation->getAlias()])) { $aliases[$beanAnnotation->getAlias()] = $method->getName(); } /* @var \bitExpert\Disco\Annotations\Parameters $parametersAnnotation */ $parametersAnnotation = $reader->getMethodAnnotation($method, Parameters::class); if (null === $parametersAnnotation) { $parametersAnnotation = new Parameters(); } $beanType = $method->getReturnType(); if (null === $beanType) { throw new InvalidProxiedClassException(sprintf('Method "%s" on "%s" is missing the return typehint!', $method->getName(), $originalClass->getName())); } $beanType = (string) $beanType; if (!in_array($beanType, ['array', 'callable', 'bool', 'float', 'int', 'string']) && !class_exists($beanType) && !interface_exists($beanType)) { throw new InvalidProxiedClassException(sprintf('Return type of method "%s" on "%s" cannot be found! Did you use the full qualified name?', $method->getName(), $originalClass->getName())); } $methodReflection = new MethodReflection($method->class, $method->getName()); $proxyMethod = BeanMethod::generateMethod($methodReflection, $beanAnnotation, $parametersAnnotation, $beanType, $forceLazyInitProperty, $sessionBeansProperty, $postProcessorsProperty, $beanFactoryConfigurationProperty, $getParameterMethod, $wrapBeanAsLazyMethod); $classGenerator->addMethodFromGenerator($proxyMethod); } $aliasesProperty->setDefaultValue($aliases); $classGenerator->addMethodFromGenerator(new Constructor($originalClass, $parameterValuesProperty, $sessionBeansProperty, $beanFactoryConfigurationProperty, $postProcessorsProperty, $postProcessorMethods)); $classGenerator->addMethodFromGenerator($wrapBeanAsLazyMethod); $classGenerator->addMethodFromGenerator($getParameterMethod); $classGenerator->addMethodFromGenerator(new MagicSleep($originalClass, $sessionBeansProperty)); $classGenerator->addMethodFromGenerator(new GetAlias($originalClass, $aliasesProperty)); $classGenerator->addMethodFromGenerator(new HasAlias($originalClass, $aliasesProperty)); }
/** * checks if given class should be remotable * * @param string $class the class name to check * * @return bool|ClassInterface * @throws ExtDirectException */ protected function processClass($class) { if (!class_exists('\\' . $class)) { throw new ExtDirectException(" '{$class}' does not exist!"); } $annotationReader = new AnnotationReader(); AnnotationRegistry::registerLoader('class_exists'); $reflectionClass = new ReflectionClass($class); $classAnnotation = $annotationReader->getClassAnnotation($reflectionClass, 'ExtDirect\\Annotations\\Direct'); if ($classAnnotation instanceof \ExtDirect\Annotations\Direct) { $classAnnotation->setClassName($class); $methodCollection = new RemotableCollection(); foreach ($reflectionClass->getMethods() as $reflectionMethod) { $methodAnnotation = $annotationReader->getMethodAnnotation($reflectionMethod, 'ExtDirect\\Annotations\\Remotable'); if ($methodAnnotation instanceof \ExtDirect\Annotations\Remotable) { $methodAnnotation->setMethodName($reflectionMethod->getName()); $methodCollection->add($methodAnnotation); } } $classAnnotation->setMethods($methodCollection); return $classAnnotation; } return false; }
/** * @test * @expectedException \InvalidArgumentException * @expectedExceptionMessage Roles MUST be defined */ public function WithoutRole_ThrowException() { $class = new \ReflectionClass(new SecurityClassDummy()); $this->reader->getMethodAnnotation($class->getMethod('method'), 'security'); }