コード例 #1
1
 /**
  * Modifies the Request object to apply configuration information found in
  * controllers annotations like the template to render or HTTP caching
  * configuration.
  *
  * @param FilterControllerEvent $event A FilterControllerEvent instance
  */
 public function onKernelController(FilterControllerEvent $event)
 {
     if (!is_array($controller = $event->getController())) {
         return;
     }
     $className = class_exists('Doctrine\\Common\\Util\\ClassUtils') ? ClassUtils::getClass($controller[0]) : get_class($controller[0]);
     $object = new \ReflectionClass($className);
     $method = $object->getMethod($controller[1]);
     $classConfigurations = $this->getConfigurations($this->reader->getClassAnnotations($object));
     $methodConfigurations = $this->getConfigurations($this->reader->getMethodAnnotations($method));
     $configurations = array();
     foreach (array_merge(array_keys($classConfigurations), array_keys($methodConfigurations)) as $key) {
         if (!array_key_exists($key, $classConfigurations)) {
             $configurations[$key] = $methodConfigurations[$key];
         } elseif (!array_key_exists($key, $methodConfigurations)) {
             $configurations[$key] = $classConfigurations[$key];
         } else {
             if (is_array($classConfigurations[$key])) {
                 if (!is_array($methodConfigurations[$key])) {
                     throw new \UnexpectedValueException('Configurations should both be an array or both not be an array');
                 }
                 $configurations[$key] = array_merge($classConfigurations[$key], $methodConfigurations[$key]);
             } else {
                 // method configuration overrides class configuration
                 $configurations[$key] = $methodConfigurations[$key];
             }
         }
     }
     $request = $event->getRequest();
     foreach ($configurations as $key => $attributes) {
         $request->attributes->set($key, $attributes);
     }
 }
コード例 #2
0
 /**
  * @param GetResponseEvent $event
  * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
  * @return bool
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     if (strpos($event->getRequest()->attributes->get('_controller'), 'Api\\Resource') !== false) {
         header('Access-Control-Allow-Origin: *');
         $controller = explode('::', $event->getRequest()->attributes->get('_controller'));
         $reflection = new \ReflectionMethod($controller[0], $controller[1]);
         $scopeAnnotation = $this->reader->getMethodAnnotation($reflection, 'Etu\\Core\\ApiBundle\\Framework\\Annotation\\Scope');
         if ($scopeAnnotation) {
             $requiredScope = $scopeAnnotation->value;
         } else {
             $requiredScope = null;
         }
         if (!$requiredScope) {
             $requiredScope = 'public';
         }
         $request = $event->getRequest();
         $token = $request->query->get('access_token');
         $access = $this->server->checkAccess($token, $requiredScope);
         if (!$access->isGranted()) {
             $event->setResponse($this->formatter->format($event->getRequest(), ['error' => $access->getError(), 'error_message' => $access->getErrorMessage()], 403));
         } else {
             $event->getRequest()->attributes->set('_oauth_token', $access->getToken());
         }
     }
 }
コード例 #3
0
 public static function loadClass(ReflectionClass $refl, Reader $reader, Router $router)
 {
     $annotation = $reader->getClassAnnotation($refl, 'Destiny\\Common\\Annotation\\Controller');
     if (empty($annotation)) {
         return;
     }
     $methods = $refl->getMethods(ReflectionMethod::IS_PUBLIC);
     foreach ($methods as $method) {
         /** @var Route[] $routes */
         $routes = array();
         $annotations = $reader->getMethodAnnotations($method);
         for ($i = 0; $i < count($annotations); ++$i) {
             /** @noinspection PhpUnnecessaryFullyQualifiedNameInspection */
             if ($annotations[$i] instanceof \Destiny\Common\Annotation\Route) {
                 $routes[] = $annotations[$i];
             }
         }
         if (count($routes) <= 0) {
             continue;
         }
         /** @var \Destiny\Common\Annotation\HttpMethod $feature */
         $httpMethod = $reader->getMethodAnnotation($method, 'Destiny\\Common\\Annotation\\HttpMethod');
         /** @var \Destiny\Common\Annotation\Secure $feature */
         $secure = $reader->getMethodAnnotation($method, 'Destiny\\Common\\Annotation\\Secure');
         for ($i = 0; $i < count($routes); ++$i) {
             $router->addRoute(new Route(array('path' => $routes[$i]->path, 'classMethod' => $method->name, 'class' => $refl->name, 'httpMethod' => $httpMethod ? $httpMethod->allow : null, 'secure' => $secure ? $secure->roles : null)));
         }
     }
 }
コード例 #4
0
ファイル: Entity.php プロジェクト: rohankadam/Neo4j-PHP-OGM
 /**
  * @param AnnotationReader $reader
  * @param string $className
  * @return Entity
  * @throws \HireVoice\Neo4j\Exception
  */
 public static function fromClass(AnnotationReader $reader, $className)
 {
     $class = new \ReflectionClass($className);
     if ($class->implementsInterface('HireVoice\\Neo4j\\Proxy\\Entity')) {
         $class = $class->getParentClass();
         $className = $class->getName();
     }
     if (!($entity = $reader->getClassAnnotation($class, 'HireVoice\\Neo4j\\Annotation\\Entity'))) {
         throw new Exception("Class {$className} is not declared as an entity.");
     }
     $object = new self($class->getName());
     if ($entity->repositoryClass) {
         $object->repositoryClass = $entity->repositoryClass;
     }
     if ($entity->labels) {
         $object->labels = explode(",", $entity->labels);
     }
     foreach (self::getClassProperties($class->getName()) as $prop) {
         $prop = new Property($reader, $prop);
         if ($prop->isPrimaryKey()) {
             $object->setPrimaryKey($prop);
         } elseif ($prop->isProperty($prop)) {
             $object->properties[] = $prop;
             if ($prop->isIndexed()) {
                 $object->indexedProperties[] = $prop;
             }
         } elseif ($prop->isRelationList()) {
             $object->manyToManyRelations[] = $prop;
         } elseif ($prop->isRelation()) {
             $object->manyToOneRelations[] = $prop;
         }
     }
     $object->validate();
     return $object;
 }
コード例 #5
0
 /**
  * @param LifecycleEventArgs $args
  * @return bool
  * @throws \Exception
  */
 public function checkBadWords(LifecycleEventArgs $args)
 {
     $entity = $args->getEntity();
     if (!$entity instanceof BadWordDetectorInterface) {
         return true;
     }
     $badWords = $args->getEntityManager()->getRepository('RenowazeBundle:BadWord')->findAll();
     /** @var BadWordDetector $annotationParams */
     $annotationParams = $this->reader->getClassAnnotation(new \ReflectionClass($entity), 'RenowazeBundle\\Annotation\\BadWordDetector');
     foreach ($annotationParams->fields as $field) {
         $methodName = 'get' . ucfirst($field);
         if (!method_exists($entity, $methodName)) {
             throw new \Exception(sprintf('Field "%s" not found in entity "%s"', $methodName, get_class($entity)));
         }
         /** @var BadWord $badWord */
         foreach ($badWords as $badWord) {
             if (strpos($entity->{$methodName}(), $badWord->getWord()) !== false) {
                 $entity->setHasBadWords(true);
                 return true;
             }
         }
     }
     $entity->setHasBadWords(false);
     return true;
 }
コード例 #6
0
 /**
  * Modifies the Request object to apply configuration information found in
  * controllers annotations like the template to render or HTTP caching
  * configuration.
  *
  * @param FilterControllerEvent $event A FilterControllerEvent instance
  *
  * @return void
  */
 public function onKernelController(FilterControllerEvent $event)
 {
     if (!is_array($controller = $event->getController())) {
         return;
     }
     $className = class_exists('Doctrine\\Common\\Util\\ClassUtils') ? ClassUtils::getClass($controller[0]) : get_class($controller[0]);
     $object = new \ReflectionClass($className);
     $transactional = $this->reader->getClassAnnotation($object, Transactional::NAME);
     if (!$transactional instanceof Transactional) {
         return;
     }
     $avoidTransaction = $this->reader->getMethodAnnotation($object->getMethod($controller[1]), AvoidTransaction::NAME);
     if (!is_null($avoidTransaction)) {
         return;
     }
     $request = $event->getRequest();
     $modelName = $transactional->model;
     $model = new $modelName();
     $this->transactionBuilder->setRequestMethod($request->getRealMethod());
     $this->transactionBuilder->setRequestSource(Transaction::SOURCE_REST);
     $this->transactionBuilder->setRelatedRoute($transactional->relatedRoute);
     $ids = [];
     foreach ($model->getIds() as $field => $value) {
         $ids[$field] = $request->attributes->get($field);
     }
     $this->transactionBuilder->setRelatedIds($ids);
     $this->transactionBuilder->setModel($transactional->model);
     $transaction = $this->transactionBuilder->build();
     $request->attributes->set('transaction', $transaction);
 }
コード例 #7
0
 /**
  * @internal
  * @param Reader $annotationReader
  * @return string
  * @throws InvalidAnnotationException
  */
 static function getEntityClassName(Reader $annotationReader)
 {
     $reflect = new ReflectionClass(get_called_class());
     $annotation = $annotationReader->getClassAnnotation($reflect, Entity::class);
     InvalidAnnotationException::assert($annotation, Entity::class);
     return $annotation->className;
 }
コード例 #8
0
 /**
  * @param string $className
  *
  * @return array
  */
 public function processClass($className, $path)
 {
     $reflection = new \ReflectionClass($className);
     if (null === $this->reader->getClassAnnotation($reflection, $this->annotationClass)) {
         return array();
     }
     $mappings = array();
     $this->output->writeln("Found class: {$className}");
     foreach ($reflection->getMethods() as $method) {
         /** @var Method[] $annotations */
         $annotations = $this->reader->getMethodAnnotations($method);
         if (0 == count($annotations)) {
             continue;
         }
         $this->output->writeln(sprintf("Found annotations for method %s::%s.", $method->class, $method->getName()));
         foreach ($annotations as $annotation) {
             if (!$annotation instanceof Method) {
                 continue;
             }
             $this->output->writeln(sprintf("Found mapping: %s::%s --> %s::%s", $method->class, $method->getName(), $annotation->getClass(), $annotation->getMethod()));
             $mapping = new Mapping();
             $moduleFile = $reflection->getFileName();
             $moduleFile = substr($moduleFile, strpos($moduleFile, $path));
             $mapping->setOxidClass($annotation->getClass())->setOxidMethod($annotation->getMethod())->setModuleClass($className)->setModuleMethod($method->getName())->setReturn($annotation->hasReturnValue())->setParentExecution($annotation->getParentExecution())->setModuleFile($moduleFile);
             $mappings[] = $mapping;
         }
     }
     return $mappings;
 }
コード例 #9
0
ファイル: AnnotationDriver.php プロジェクト: conjecto/nemrod
 /**
  * @param \ReflectionClass $class
  *
  * @return \Metadata\ClassMetadata
  */
 public function loadMetadataForClass(\ReflectionClass $class)
 {
     $metadata = new ClassMetadata($class->getName());
     // Resource annotation
     $annotation = $this->reader->getClassAnnotation($class, 'Conjecto\\Nemrod\\ResourceManager\\Annotation\\Resource');
     if (null !== $annotation) {
         $types = $annotation->types;
         $pattern = $annotation->uriPattern;
         if (!is_array($types)) {
             $types = array($types);
         }
         $metadata->types = $types;
         $metadata->uriPattern = $pattern;
     }
     foreach ($class->getProperties() as $reflectionProperty) {
         $propMetadata = new PropertyMetadata($class->getName(), $reflectionProperty->getName());
         // Property annotation
         $annotation = $this->reader->getPropertyAnnotation($reflectionProperty, 'Conjecto\\Nemrod\\ResourceManager\\Annotation\\Property');
         if (null !== $annotation) {
             $propMetadata->value = $annotation->value;
             $propMetadata->cascade = $annotation->cascade;
         }
         $metadata->addPropertyMetadata($propMetadata);
     }
     return $metadata;
 }
コード例 #10
0
 public function invoke(MethodInvocation $invocation)
 {
     $resource = $invocation->getThis();
     $result = $invocation->proceed();
     $annotation = $this->reader->getMethodAnnotation($invocation->getMethod(), Annotation\ResourceDelegate::class);
     if (isset($annotation)) {
         $class = $this->getDelegateClassName($annotation, $resource);
         if (!class_exists($class)) {
             throw new InvalidAnnotationException('Resource Delegate class is not found.');
         }
         $method = isset($resource->uri->query['_override']) ? $resource->uri->query['_override'] : $resource->uri->method;
         if (stripos($method, $resource->uri->method) !== 0) {
             throw new InvalidMatcherException('Overriden method must match to original method');
         }
         $call = $this->resolveDelegateMethod($method);
         if (!method_exists($class, $call)) {
             throw new InvalidMatcherException('Resource Delegate method is not found');
         }
         $delegate = new $class($resource);
         $params = $this->paramHandler->getParameters([$delegate, $call], $resource->uri->query);
         return call_user_func_array([$delegate, $call], $params);
     } else {
         $result;
     }
 }
 /**
  * This event will fire during any controller call.
  *
  * @param FilterControllerEvent $event
  *
  * @return type
  *
  * @throws AccessDeniedHttpException
  */
 public function onKernelController(FilterControllerEvent $event)
 {
     if (!is_array($controller = $event->getController())) {
         //return if no controller
         return;
     }
     $object = new \ReflectionObject($controller[0]);
     // get controller
     $method = $object->getMethod($controller[1]);
     // get method
     $configurations = $this->reader->getMethodAnnotations($method);
     foreach ($configurations as $configuration) {
         //Start of annotations reading
         if (isset($configuration->grantType) && $controller[0] instanceof BaseProjectController) {
             //Found our annotation
             $controller[0]->setProjectGrantType($configuration->grantType);
             $request = $controller[0]->get('request_stack')->getCurrentRequest();
             $id = $request->get('id', false);
             if ($id !== false) {
                 $redirectUrl = $controller[0]->initAction($id, $configuration->grantType);
                 if ($redirectUrl) {
                     $event->setController(function () use($redirectUrl) {
                         return new RedirectResponse($redirectUrl);
                     });
                 }
             }
         }
     }
 }
コード例 #12
0
ファイル: ApiListener.php プロジェクト: reva2/jsonapi
 /**
  * Load JSON API configuration from controller annotations
  *
  * @param FilterControllerEvent $event
  */
 public function onKernelController(FilterControllerEvent $event)
 {
     $controller = $event->getController();
     if (!is_array($controller)) {
         return;
     }
     $config = null;
     $refClass = new \ReflectionClass($controller[0]);
     if (null !== ($annotation = $this->reader->getClassAnnotation($refClass, ApiRequest::class))) {
         /* @var $annotation ApiRequest */
         $config = $annotation->toArray();
     }
     $refMethod = $refClass->getMethod($controller[1]);
     if (null !== ($annotation = $this->reader->getMethodAnnotation($refMethod, ApiRequest::class))) {
         if (null !== $config) {
             $config = array_replace($config, $annotation->toArray());
         } else {
             $config = $annotation->toArray();
         }
     }
     if (null !== $config) {
         if (!array_key_exists('matcher', $config)) {
             $config['matcher'] = $this->defMatcher;
         }
         $event->getRequest()->attributes->set('_jsonapi', $this->factory->createEnvironment($config));
     }
 }
コード例 #13
0
ファイル: Populator.php プロジェクト: progrupa/edifact
 /**
  * @param $object
  * @param $classRefl
  * @param $segmentData
  * @throws MandatorySegmentPieceMissing
  */
 protected function fillFromArray($object, $classRefl, $segmentData)
 {
     foreach ($classRefl->getProperties() as $propRefl) {
         $isSegmentPiece = $this->annotationReader->getPropertyAnnotation($propRefl, SegmentPiece::class);
         if ($isSegmentPiece) {
             $piece = isset($segmentData[$isSegmentPiece->position]) ? $segmentData[$isSegmentPiece->position] : null;
             $propRefl->setAccessible(true);
             if ($isSegmentPiece->parts) {
                 $value = array();
                 $i = 0;
                 foreach ($isSegmentPiece->parts as $k => $part) {
                     if (!is_numeric($k) && is_array($part)) {
                         $partName = $k;
                         if (!empty($piece) && in_array("@mandatory", $part) && $this->isEmpty($piece[$i])) {
                             throw new MandatorySegmentPieceMissing(sprintf("Segment %s part %s missing value at offset %d", $segmentData[0], $partName, $i));
                         }
                     } else {
                         $partName = $part;
                     }
                     $value[$partName] = isset($piece[$i]) ? $piece[$i] : null;
                     ++$i;
                 }
                 $propRefl->setValue($object, $value);
             } else {
                 $propRefl->setValue($object, $piece);
             }
         }
     }
 }
コード例 #14
0
 /**
  * @expectedException \Doctrine\Search\Exception\Driver\PropertyDoesNotExistsInMetadataException
  */
 public function testLoadMetadataForClassAddValuesToMetadata()
 {
     $this->reflectionClass->expects($this->once())->method('getProperties')->will($this->returnValue(array()));
     $this->reader->expects($this->once())->method('getClassAnnotations')->will($this->returnValue(array(0, new TestSearchable(array()))));
     $this->classMetadata->expects($this->once())->method('getReflectionClass')->will($this->returnValue($this->reflectionClass));
     $this->annotationDriver->loadMetadataForClass('Doctrine\\Tests\\Models\\Blog\\BlogPost', $this->classMetadata);
 }
コード例 #15
0
 /**
  * {@inheritDoc}
  */
 public function loadForMethod($class, $method, $group)
 {
     $methodReflection = Reflection::loadMethodReflection($class, $method);
     $methodAnnotations = $this->reader->getMethodAnnotations($methodReflection);
     $securityMethodAnnotation = null;
     $rules = array();
     foreach ($methodAnnotations as $methodAnnotation) {
         if ($methodAnnotation instanceof MethodSecurityAnnotation && $group == $methodAnnotation->group) {
             if ($securityMethodAnnotation) {
                 throw new \RuntimeException(sprintf('The @MethodSecurity annotation already defined in method "%s::%s".', $class, $method));
             }
             $securityMethodAnnotation = $methodAnnotation;
         }
         if ($rule = $this->transformAnnotationToRule($methodAnnotation, $group, $class)) {
             $rules[] = $rule;
         }
     }
     if (!$securityMethodAnnotation && !count($rules)) {
         return null;
     }
     if ($securityMethodAnnotation) {
         $strategy = $securityMethodAnnotation->strategy;
     } else {
         $strategy = Security::STRATEGY_AFFIRMATIVE;
     }
     $securityMethod = new MethodSecurity($class, $method, $strategy, $rules, $group);
     return $securityMethod;
 }
コード例 #16
0
 public function onKernelController(FilterControllerEvent $event)
 {
     if (!is_array($controller = $event->getController())) {
         return;
     }
     $object = new \ReflectionObject($controller[0]);
     $method = $object->getMethod($controller[1]);
     $classConfigurations = $this->reader->getClassAnnotations($object);
     $methodConfigurations = $this->reader->getMethodAnnotations($method);
     foreach (array_merge($classConfigurations, $methodConfigurations) as $configuration) {
         if ($configuration instanceof OAuth2) {
             $token = $this->token_storage->getToken();
             // If no access token is found by the firewall, then returns an authentication error
             if (!$token instanceof OAuth2Token) {
                 $this->createAuthenticationException($event, 'OAuth2 authentication required');
                 return;
             }
             foreach ($this->getCheckers() as $checker) {
                 $result = $checker->check($token, $configuration);
                 if (null !== $result) {
                     $this->createAccessDeniedException($event, $result);
                     return;
                 }
             }
         }
     }
 }
コード例 #17
0
 /**
  * @param \ReflectionClass $class
  *
  * @return \Metadata\ClassMetadata
  */
 public function loadMetadataForClass(\ReflectionClass $class)
 {
     $metadata = $this->driver->loadMetadataForClass($class);
     foreach ($metadata->propertyMetadata as $key => $propertyMetadata) {
         $type = $propertyMetadata->type['name'];
         if (!$propertyMetadata->reflection) {
             continue;
         }
         /** @var PropertyMetadata $propertyMetadata */
         /** @var HandledType $annot */
         $annot = $this->reader->getPropertyAnnotation($propertyMetadata->reflection, HandledType::class);
         if (!$annot) {
             continue;
         }
         $isCollection = false;
         $collectionType = null;
         if (in_array($type, ['array', 'ArrayCollection'], true)) {
             $isCollection = true;
             $collectionType = $type;
             $type = $propertyMetadata->type['params'][0]['name'];
         }
         $handler = $annot->handler ?: 'Relation';
         $newType = sprintf('%s<%s>', $handler, $type);
         if ($isCollection) {
             $newType = sprintf('%s<%s<%s>>', $collectionType, $handler, $type);
         }
         $propertyMetadata->setType($newType);
     }
     return $metadata;
 }
コード例 #18
0
ファイル: FormResolver.php プロジェクト: uebb/hateoas-bundle
 public function getForm(ResourceInterface $resource)
 {
     $resourceClassName = \Doctrine\Common\Util\ClassUtils::getClass($resource);
     $resourceParts = explode("\\", $resourceClassName);
     $resourceParts[count($resourceParts) - 2] = 'Form';
     $resourceParts[count($resourceParts) - 1] .= 'Type';
     $formType = implode("\\", $resourceParts);
     if (class_exists($formType)) {
         return $this->formFactory->create(new $formType(), $resource);
     }
     $options = array('data_class' => $resourceClassName);
     $builder = $this->formFactory->createBuilder('form', $resource, $options);
     $reflectionClass = new \ReflectionClass($resourceClassName);
     $annotationClass = 'uebb\\HateoasBundle\\Annotation\\FormField';
     foreach ($reflectionClass->getProperties() as $propertyReflection) {
         /**
          * @var \uebb\HateoasBundle\Annotation\FormField $annotation
          */
         $annotation = $this->annotationReader->getPropertyAnnotation($propertyReflection, $annotationClass);
         if ($annotation) {
             $builder->add($propertyReflection->getName(), $annotation->type, is_array($annotation->options) ? $annotation->options : array());
         }
     }
     $form = $builder->getForm();
     return $form;
 }
コード例 #19
0
 /**
  * @param \ReflectionClass  $class
  * @param \ReflectionMethod $method
  * @return null|MethodMetadata
  */
 private function loadMetadataForMethod(\ReflectionClass $class, \ReflectionMethod $method)
 {
     $methodAnnotation = $this->reader->getMethodAnnotation($method, Method::class);
     if ($methodAnnotation === null) {
         return null;
     }
     /** @var Method $methodAnnotation */
     $methodMetadata = new MethodMetadata($class->name, $method->name);
     $methodMetadata->isMethod = true;
     $methodMetadata->isFormHandler = $methodAnnotation->formHandler;
     $methodMetadata->hasNamedParams = $methodAnnotation->namedParams;
     $methodMetadata->isStrict = $methodAnnotation->strict;
     $methodMetadata->hasSession = $methodAnnotation->session;
     $methodMetadata->addParameters($method->getParameters());
     foreach ($this->reader->getMethodAnnotations($method) as $annotation) {
         if ($annotation instanceof Parameter) {
             if (!empty($annotation->constraints)) {
                 $methodMetadata->addParameterMetadata($annotation->name, $annotation->constraints, $annotation->validationGroups, $annotation->strict, $annotation->serializationGroups, $annotation->serializationAttributes, $annotation->serializationVersion);
             }
         }
     }
     /** @var Result $resultAnnotation */
     $resultAnnotation = $this->reader->getMethodAnnotation($method, Result::class);
     if ($resultAnnotation) {
         $methodMetadata->setResult($resultAnnotation->groups, $resultAnnotation->attributes, $resultAnnotation->version);
     }
     /** @var Security $securityAnnotation */
     $securityAnnotation = $this->reader->getMethodAnnotation($method, Security::class);
     if ($securityAnnotation) {
         $methodMetadata->authorizationExpression = $securityAnnotation->expression;
     }
     return $methodMetadata;
 }
コード例 #20
0
 /**
  * {@inheritDoc}
  */
 public function loadMetadata($class)
 {
     // Try get object annotation from class
     $objectAnnotation = null;
     $classAnnotations = Reflection::loadClassAnnotations($this->reader, $class, true);
     foreach ($classAnnotations as $classAnnotation) {
         if ($classAnnotation instanceof ObjectAnnotation) {
             if ($objectAnnotation) {
                 throw new \RuntimeException(sprintf('Many @Transformer\\Object annotation in class "%s".', $class));
             }
             $objectAnnotation = $classAnnotation;
         }
     }
     if (!$objectAnnotation) {
         throw new TransformAnnotationNotFoundException(sprintf('Not found @Object annotations in class "%s".', $class));
     }
     // Try get properties annotations
     $properties = [];
     $classProperties = Reflection::getClassProperties($class, true);
     foreach ($classProperties as $classProperty) {
         $propertyAnnotations = $this->reader->getPropertyAnnotations($classProperty);
         foreach ($propertyAnnotations as $propertyAnnotation) {
             if ($propertyAnnotation instanceof PropertyAnnotation) {
                 $property = new PropertyMetadata($propertyAnnotation->propertyName ?: $classProperty->getName(), $propertyAnnotation->groups, $propertyAnnotation->shouldTransform, $propertyAnnotation->expressionValue);
                 $properties[$classProperty->getName()] = $property;
             }
         }
     }
     return new ObjectMetadata($objectAnnotation->transformedClass, $properties);
 }
コード例 #21
0
 /**
  * The interceptor is activated for public methods in Transactional annotated components.
  *
  * {@inheritDoc}
  */
 public function matchesMethod(ReflectionMethod $method)
 {
     $transactionalEnabled = false;
     if ($method->isPublic()) {
         // Gets method-level annotation.
         /** @var Transactional $annotation */
         $annotation = $this->reader->getMethodAnnotation($method, Transactional::class);
         $transactionalEnabled = $annotation !== null;
         if (!$transactionalEnabled) {
             // If there is no method-level annotation, gets class-level annotation.
             $annotation = $this->reader->getClassAnnotation($method->getDeclaringClass(), Transactional::class);
             $transactionalEnabled = $annotation !== null;
         }
         if ($transactionalEnabled) {
             switch ($annotation->getPolicy()) {
                 case Transactional::NOT_REQUIRED:
                     $policyName = 'not required';
                     break;
                 case Transactional::REQUIRED:
                     $policyName = 'required';
                     break;
                 case Transactional::NESTED:
                     $policyName = 'nested';
                     break;
                 default:
                     $policyName = 'default';
             }
             $methodString = $method->getDeclaringClass()->name . '::' . $method->name;
             $this->logger->debug('TX policy for \'' . $methodString . '\': ' . $policyName);
             $noRollbackExceptionsStr = implode(', ', $annotation->getNoRollbackExceptions() === null ? ['default'] : $annotation->getNoRollbackExceptions());
             $this->logger->debug('TX no-rollback exceptions for \'' . $methodString . '\': ' . $noRollbackExceptionsStr);
         }
     }
     return $transactionalEnabled;
 }
コード例 #22
0
 protected function setUp()
 {
     AnnotationRegistry::registerLoader('class_exists');
     $this->reader = new SimpleAnnotationReader();
     $this->reader->addNamespace('Bazinga\\Bundle\\GeocoderBundle\\Mapping\\Annotations');
     $this->driver = new AnnotationDriver($this->reader);
 }
コード例 #23
0
 public function onPostSerialize(ObjectEvent $event)
 {
     /**
      * @var JsonSerializationVisitor $visitor
      */
     $visitor = $event->getVisitor();
     $object = $event->getObject();
     $annotations = $this->annotationReader->getClassAnnotations(new \ReflectionObject($object));
     $links = array();
     foreach ($annotations as $annotation) {
         if ($annotation instanceof Link) {
             if ($annotation->url) {
                 $uri = $this->evaluate($annotation->url, $object);
             } else {
                 $uri = $this->router->generate($annotation->route, $this->resolveParams($annotation->params, $object));
             }
             // allow a blank URI to be an optional link
             if ($uri) {
                 $links[$annotation->name] = $uri;
             }
         }
     }
     if ($links) {
         $visitor->addData('_links', $links);
     }
 }
コード例 #24
0
 /**
  * {@inheritdoc}
  */
 public function loadClassMetadata(ClassMetadata $metadata)
 {
     $reflClass = $metadata->getReflectionClass();
     $className = $reflClass->name;
     $loaded = false;
     foreach ($reflClass->getProperties() as $property) {
         if ($property->getDeclaringClass()->name == $className) {
             foreach ($this->reader->getPropertyAnnotations($property) as $groups) {
                 if ($groups instanceof Groups) {
                     foreach ($groups->getGroups() as $group) {
                         $metadata->addAttributeGroup($property->name, $group);
                     }
                 }
                 $loaded = true;
             }
         }
     }
     foreach ($reflClass->getMethods() as $method) {
         if ($method->getDeclaringClass()->name == $className) {
             foreach ($this->reader->getMethodAnnotations($method) as $groups) {
                 if ($groups instanceof Groups) {
                     if (preg_match('/^(get|is)(.+)$/i', $method->name, $matches)) {
                         foreach ($groups->getGroups() as $group) {
                             $metadata->addAttributeGroup(lcfirst($matches[2]), $group);
                         }
                     } else {
                         throw new \BadMethodCallException(sprintf('Groups on "%s::%s" cannot be added. Groups can only be added on methods beginning with "get" or "is".', $className, $method->name));
                     }
                 }
                 $loaded = true;
             }
         }
     }
     return $loaded;
 }
コード例 #25
0
 public function setUp()
 {
     $this->reflectionService = $this->getAccessibleMock(\TYPO3\Flow\Reflection\ReflectionService::class, null);
     $this->mockAnnotationReader = $this->getMockBuilder(\Doctrine\Common\Annotations\Reader::class)->disableOriginalConstructor()->getMock();
     $this->mockAnnotationReader->expects($this->any())->method('getClassAnnotations')->will($this->returnValue(array()));
     $this->inject($this->reflectionService, 'annotationReader', $this->mockAnnotationReader);
 }
コード例 #26
0
 private static function readFormType(\Doctrine\Common\Annotations\Reader $reader, \ReflectionClass $rc, array &$out, array &$non_deep_fields)
 {
     $as = $reader->getClassAnnotations($rc);
     $annot = null;
     if ($as) {
         foreach ($as as $_annot) {
             if ($_annot instanceof \Symforce\AdminBundle\Compiler\Annotation\FormType) {
                 if (null !== $annot) {
                     throw new \Exception(sprintf("sf_admin.form.type ( class: %s ) has multi form annotation", $rc->getName()));
                 }
                 $annot = $_annot;
             }
         }
     }
     if ($annot) {
         foreach ($annot as $key => $value) {
             if (!isset($out[$key]) || null === $out[$key]) {
                 if (!$out['deep'] || !in_array($key, $non_deep_fields)) {
                     $out[$key] = $value;
                 }
             }
         }
     }
     $parent = $rc->getParentClass();
     if ($parent && !$parent->isAbstract()) {
         $out['deep']++;
         self::readFormType($reader, $parent, $out, $non_deep_fields);
     }
 }
コード例 #27
0
 /**
  * Reads the "@Access" annotations from the controller stores them in the "access" route option.
  */
 public function onConfigureRoute($event, $route)
 {
     if (!$this->reader) {
         $this->reader = new SimpleAnnotationReader();
         $this->reader->addNamespace('Pagekit\\User\\Annotation');
     }
     if (!$route->getControllerClass()) {
         return;
     }
     $access = [];
     foreach (array_merge($this->reader->getClassAnnotations($route->getControllerClass()), $this->reader->getMethodAnnotations($route->getControllerMethod())) as $annot) {
         if (!$annot instanceof Access) {
             continue;
         }
         if ($expression = $annot->getExpression()) {
             $access[] = $expression;
         }
         if ($admin = $annot->getAdmin() !== null) {
             $route->setPath('admin' . rtrim($route->getPath(), '/'));
             $permission = 'system: access admin area';
             if ($admin) {
                 $access[] = $permission;
             } else {
                 if ($key = array_search($permission, $access)) {
                     unset($access[$key]);
                 }
             }
         }
     }
     if ($access) {
         $route->setDefault('_access', array_unique($access));
     }
 }
コード例 #28
0
 /**
  * Load metadata class
  *
  * @param \ReflectionClass $class
  * @return ClassMetadata
  */
 public function loadMetadataForClass(\ReflectionClass $class)
 {
     $classMetadata = new ClassMetadata($class->name);
     $classMetadata->fileResources[] = $class->getFileName();
     foreach ($this->reader->getClassAnnotations($class) as $annotation) {
         if ($annotation instanceof NamespaceNode) {
             $classMetadata->addGraphNamespace($annotation);
         }
         if ($annotation instanceof GraphNode) {
             $classMetadata->addGraphMetadata($annotation, new MetadataValue($annotation->value));
         }
     }
     foreach ($class->getProperties() as $property) {
         foreach ($this->reader->getPropertyAnnotations($property) as $annotation) {
             if ($annotation instanceof GraphNode) {
                 $classMetadata->addGraphMetadata($annotation, new PropertyMetadata($class->name, $property->name));
             }
         }
     }
     foreach ($class->getMethods() as $method) {
         foreach ($this->reader->getMethodAnnotations($method) as $annotation) {
             if ($annotation instanceof GraphNode) {
                 $classMetadata->addGraphMetadata($annotation, new MethodMetadata($class->name, $method->name));
             }
         }
     }
     return $classMetadata;
 }
コード例 #29
0
 /**
  * {@inheritdoc}
  */
 public function loadMetadataForClass(\ReflectionClass $class)
 {
     $annotations = $this->reader->getClassAnnotations($class);
     if (0 === count($annotations)) {
         return null;
     }
     $classMetadata = new ClassMetadata($class->getName());
     $classMetadata->fileResources[] = $class->getFileName();
     foreach ($annotations as $annotation) {
         if ($annotation instanceof Annotation\Resource) {
             // auto transform type from class name
             if (!$annotation->type) {
                 $annotation->type = String::dasherize($class->getShortName());
             }
             $classMetadata->setResource(new Resource($annotation->type, $annotation->showLinkSelf));
         }
     }
     $classProperties = $class->getProperties();
     foreach ($classProperties as $property) {
         $annotations = $this->reader->getPropertyAnnotations($property);
         foreach ($annotations as $annotation) {
             if ($annotation instanceof Annotation\Id) {
                 $classMetadata->setIdField($property->getName());
             } else {
                 if ($annotation instanceof Annotation\Relationship) {
                     $classMetadata->addRelationship(new Relationship($property->getName(), $annotation->includeByDefault, $annotation->showLinkSelf, $annotation->showLinkRelated));
                 }
             }
         }
     }
     return $classMetadata;
 }
コード例 #30
0
 private function extractAnnotation(\ReflectionMethod $m, $typeName)
 {
     if (($a = $this->reader->getMethodAnnotation($m, $typeName)) === null) {
         throw new NotFound("Annotation: {$typeName} is not found.");
     }
     return $a;
 }