getClassAnnotations() public method

{@inheritDoc}
public getClassAnnotations ( ReflectionClass $class )
$class ReflectionClass
コード例 #1
0
 /**
  * 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;
 }
コード例 #2
0
ファイル: AnnotationDAO.php プロジェクト: fezfez/keep-update
 /**
  * @param string|object $class
  * @return array
  */
 public function getClassAnnotations($class)
 {
     $reflectionClass = new \ReflectionClass($class);
     $classAnotation = array();
     foreach ($this->annotationReader->getClassAnnotations($reflectionClass) as $contraint) {
         if ($contraint instanceof Annotations\Synchronizer) {
             $classAnotation[] = $contraint;
         }
     }
     return $classAnotation;
 }
コード例 #3
0
 /**
  * Parse all of the annotations for a given ClassMetadata object
  *
  * @param ClassMetadata $metadata
  */
 public function loadClassMetadata(ClassMetadata $metadata)
 {
     $reflClass = $metadata->getReflectionClass();
     $className = $reflClass->getName();
     foreach ($this->reader->getClassAnnotations($reflClass) as $annotation) {
         if ($annotation instanceof XmlObject) {
             $this->loadClassAttributes($metadata);
             $this->loadClassElements($metadata);
             $this->loadClassLists($metadata);
             $this->loadClassValue($metadata);
         }
     }
 }
コード例 #4
0
ファイル: Loader.php プロジェクト: brainexe/annotations
 /**
  * @param ReflectionClass $reflection
  * @return Definition[]|Generator
  */
 private function getDefinitions(ReflectionClass $reflection)
 {
     $annotations = $this->reader->getClassAnnotations($reflection);
     /** @var ServiceDefinition $builder */
     foreach ($annotations as $class => $annotation) {
         if (isset($this->builders[$class])) {
             $builder = $this->builders[$class];
         } else {
             /** @var string|Service $class */
             $this->builders[$class] = $builder = $class::getBuilder($this->reader);
         }
         list($id, $definition) = $builder->build($reflection, $annotation);
         (yield $id => $definition);
     }
 }
コード例 #5
0
 /**
  * @param ReflectionClass $class
  *
  * @return ClassMetadata
  */
 public function loadMetadataForClass(ReflectionClass $class)
 {
     $classMetadata = new ClassMetadata($class->getName());
     $classAnnotations = $this->reader->getClassAnnotations($class);
     foreach ($classAnnotations as $annotation) {
         if ($annotation instanceof Document) {
             $classMetadata->collection = $annotation->collection ?: strtolower($class->getShortName());
             $classMetadata->repository = $annotation->repository ?: DocumentRepository::class;
         }
     }
     $classMetadata->identifier = $this->findIdentifer($class);
     foreach ($class->getProperties() as $property) {
         $classMetadata->addPropertyMetadata($this->loadPropertyMetadata($property));
     }
     return $classMetadata;
 }
コード例 #6
0
 /**
  * @param string $className
  * @return Datagrid
  */
 public function create($className)
 {
     /** @var \Doctrine\ORM\EntityManager $entityManager */
     $entityManager = $this->getServiceLocator()->get('Doctrine\\ORM\\EntityManager');
     $metadata = $entityManager->getClassMetadata($className);
     $reflection = $metadata->getReflectionClass();
     $datagridSpec = new ArrayObject(array('className' => $className, 'primaryKey' => $metadata->getSingleIdentifierFieldName(), 'name' => array('singular' => '', 'plural' => ''), 'defaultSort' => null, 'headerColumns' => array(), 'searchColumns' => array(), 'suggestColumns' => array()));
     $reader = new AnnotationReader();
     foreach ($reader->getClassAnnotations($reflection) as $annotation) {
         $params = compact('datagridSpec', 'annotation');
         $this->getEventManager()->trigger('discoverTitle', $this, $params);
     }
     foreach ($reflection->getProperties() as $property) {
         foreach ($reader->getPropertyAnnotations($property) as $annotation) {
             $params = compact('datagridSpec', 'annotation', 'property');
             $this->getEventManager()->trigger('configureColumn', $this, $params);
         }
     }
     foreach ($reflection->getMethods() as $method) {
         foreach ($reader->getMethodAnnotations($method) as $annotation) {
             $params = compact('datagridSpec', 'annotation', 'method');
             $this->getEventManager()->trigger('configureColumn', $this, $params);
         }
     }
     $this->datagrids[$className] = new Datagrid($entityManager, $datagridSpec->getArrayCopy());
     return $this->datagrids[$className];
 }
コード例 #7
0
ファイル: EntityIndexer.php プロジェクト: tomvlk/sweet-orm
 /**
  * Entity Indexer
  * @param string|EntityClass $entityClassName
  *
  * @throws InvalidAnnotationException Invalid annotations used
  */
 public function __construct($entityClassName)
 {
     $this->entityClass = new \ReflectionClass($entityClassName);
     if (!$this->entityClass->isSubclassOf("\\SweetORM\\Entity")) {
         throw new \UnexpectedValueException("The className for getTable should be a class that is extending the SweetORM Entity class");
         // @codeCoverageIgnore
     }
     $this->entity = new EntityStructure();
     $this->entity->name = $this->entityClass->getName();
     // Reader
     $reader = new AnnotationReader();
     $this->classAnnotations = $reader->getClassAnnotations($this->entityClass);
     $this->entityAnnotation = $reader->getClassAnnotation($this->entityClass, EntityClass::class);
     // Validate Entity annotation
     if ($this->entityAnnotation === null || !$this->entityAnnotation instanceof EntityClass) {
         throw new InvalidAnnotationException("Entity '" . $this->entityClass->getName() . "' should use Annotations to use it! Please look at the documentation for help.");
         // @codeCoverageIgnore
     }
     // Run all the indexers
     foreach (self::$indexers as $indexerClass) {
         $indexerFullClass = "\\SweetORM\\Structure\\Indexer\\" . $indexerClass;
         /** @var Indexer $instance */
         $instance = new $indexerFullClass($this->entityClass, $reader);
         $instance->indexEntity($this->entity);
     }
 }
コード例 #8
0
ファイル: AnnotationDriver.php プロジェクト: nacef/doctrine2
    /**
     * Whether the class with the specified name is transient. Only non-transient
     * classes, that is entities and mapped superclasses, should have their metadata loaded.
     * A class is non-transient if it is annotated with either @Entity or
     * @MappedSuperclass in the class doc block.
     *
     * @param string $className
     * @return boolean
     */
    public function isTransient($className)
    {
        $classAnnotations = $this->_reader->getClassAnnotations(new \ReflectionClass($className));

        return ! isset($classAnnotations['Doctrine\ORM\Mapping\Entity']) &&
               ! isset($classAnnotations['Doctrine\ORM\Mapping\MappedSuperclass']);
    }
コード例 #9
0
ファイル: DCOM55Test.php プロジェクト: eltondias/Relogio
 public function testParseAnnotationDocblocks()
 {
     $class = new \ReflectionClass(__NAMESPACE__ . '\\DCOM55Annotation');
     $reader = new AnnotationReader();
     $annots = $reader->getClassAnnotations($class);
     $this->assertEquals(0, count($annots));
 }
コード例 #10
0
 public function getContentFiles($object)
 {
     $reflectedClass = new \ReflectionClass($object);
     $reader = new AnnotationReader();
     $annotations = $reader->getClassAnnotations($reflectedClass);
     $isContentFiledClass = false;
     foreach ($annotations as $annotation) {
         if ($annotation instanceof ContentFiled) {
             $isContentFiledClass = true;
         }
     }
     if (!$isContentFiledClass) {
         throw new \InvalidArgumentException('Only @ContentFiled annotated classes are supported!');
     }
     $contentFiles = [];
     foreach ($reflectedClass->getProperties() as $property) {
         foreach ($reader->getPropertyAnnotations($property) as $annotation) {
             if ($annotation instanceof ContentFileAnnotation) {
                 $mappingType = $object->{$annotation->mappingTypeMethod}();
                 $contentFiles = array_merge($contentFiles, $this->contentFileManager->findFilesByMappingType($mappingType));
             }
         }
     }
     return $contentFiles;
 }
コード例 #11
0
 /**
  * @param string $classname
  * @return array
  */
 public function getClassMetadata($classname)
 {
     $classMetadata = [];
     $reflexionClass = $this->getReflectionClass($classname);
     $classAnnotations = $this->reader->getClassAnnotations($reflexionClass);
     foreach ($classAnnotations as $classAnnotation) {
         if (!isset($classMetadata[get_class($classAnnotation)])) {
             $classMetadata[get_class($classAnnotation)] = [];
         }
         $classMetadata[get_class($classAnnotation)][] = $classAnnotation;
     }
     if ($this->reader->getClassAnnotation($reflexionClass, ParentClass::class)) {
         $classMetadata = array_merge_recursive($this->getClassMetadata(get_parent_class($classname)), $classMetadata);
     }
     return $classMetadata;
 }
コード例 #12
0
 /**
  * @param ReflectionClass      $reflectionClass
  * @param ControllerCollection $controllerCollection
  */
 public function processClassAnnotations(ReflectionClass $reflectionClass, ControllerCollection $controllerCollection)
 {
     foreach ($this->reader->getClassAnnotations($reflectionClass) as $annotation) {
         if ($annotation instanceof RouteAnnotation) {
             $annotation->process($controllerCollection);
         }
     }
 }
コード例 #13
0
 /**
  * @param AnnotationReader $reader
  * @param ReflectionClass $reflClass
  */
 protected function loadClassAnnotations(AnnotationReader $reader, ReflectionClass $reflClass)
 {
     foreach ($reader->getClassAnnotations($reflClass) as $annotation) {
         if ($annotation instanceof Prefix) {
             $this->metadata->setPrefix($annotation->value);
         }
     }
 }
コード例 #14
0
    /**
     * Whether the class with the specified name is transient. Only non-transient
     * classes, that is entities and mapped superclasses, should have their metadata loaded.
     * A class is non-transient if it is annotated with either @Entity or
     * @MappedSuperclass in the class doc block.
     *
     * @param string $className
     * @return boolean
     */
    public function isTransient($className)
    {
        $classAnnotations = $this->reader->getClassAnnotations(new \ReflectionClass($className));

        return ! isset($classAnnotations['Doctrine\ODM\MongoDB\Mapping\Document']) &&
               ! isset($classAnnotations['Doctrine\ODM\MongoDB\Mapping\MappedSuperclass']) &&
               ! isset($classAnnotations['Doctrine\ODM\MongoDB\Mapping\EmbeddedDocument']);
    }
コード例 #15
0
 public function testGivenAnObjectShouldProcessIt()
 {
     a\AnnotationRegistry::registerFile(__DIR__ . "/resource/AnnotationSample.php");
     $someObj = new AnnotatedClass();
     $reader = new a\AnnotationReader("/tmp/", $debug = true);
     $classAnnots = $reader->getClassAnnotations(new ReflectionObject($someObj));
     $this->assertNotEmpty($classAnnots);
     $this->assertEquals($classAnnots[0]->property, "some");
 }
コード例 #16
0
ファイル: DCOM58Test.php プロジェクト: eltondias/Relogio
 public function testIssue()
 {
     $reader = new AnnotationReader();
     $result = $reader->getClassAnnotations(new \ReflectionClass(__NAMESPACE__ . "\\MappedClass"));
     foreach ($result as $annot) {
         $classAnnotations[get_class($annot)] = $annot;
     }
     $this->assertTrue(!isset($classAnnotations['']), 'Class "xxx" is not a valid entity or mapped super class.');
 }
コード例 #17
0
 /**
  * Whether the class with the specified name is transient. Only non-transient
  * classes, that is entities and mapped superclasses, should have their metadata loaded.
  *
  * A class is non-transient if it is annotated with an annotation
  * from the {@see AnnotationDriver::entityAnnotationClasses}.
  *
  * @param string $className
  * @return boolean
  */
 public function isTransient($className)
 {
     $classAnnotations = $this->reader->getClassAnnotations(new \ReflectionClass($className));
     foreach ($classAnnotations as $annot) {
         if (isset($this->entityAnnotationClasses[get_class($annot)])) {
             return false;
         }
     }
     return true;
 }
コード例 #18
0
 /**
  * Whether the class with the specified name is transient. Only non-transient
  * classes, that is entities and mapped superclasses, should have their metadata loaded.
  * A class is non-transient if it is annotated with either @XmlEntity or
  * @MappedSuperclass in the class doc block.
  *
  * @param string $className
  * @return boolean
  */
 public function isTransient($className)
 {
     $classAnnotations = $this->reader->getClassAnnotations(new \ReflectionClass($className));
     // Compatibility with Doctrine Common 3.x
     if ($classAnnotations && is_int(key($classAnnotations))) {
         foreach ($classAnnotations as $annot) {
             $classAnnotations[get_class($annot)] = $annot;
         }
     }
     return !isset($classAnnotations['Doctrine\\OXM\\Mapping\\XmlEntity']) && !isset($classAnnotations['Doctrine\\OXM\\Mapping\\XmlRootEntity']) && !isset($classAnnotations['Doctrine\\OXM\\Mapping\\XmlMappedSuperclass']);
 }
コード例 #19
0
 /**
  * @return void
  * @throws AnnotationBuilderException
  */
 private function buildForClass()
 {
     $class = $this->reflectionClass();
     $webServiceAnnotation = $this->annotationReader->getClassAnnotation($class, '\\WSDL\\Annotation\\WebService');
     if ($webServiceAnnotation === null) {
         throw new AnnotationBuilderException('Class must have @WebService annotation');
     }
     /** @var ClassAnnotation[] $classAnnotations */
     $classAnnotations = $this->annotationReader->getClassAnnotations($class);
     foreach ($classAnnotations as $classAnnotation) {
         $classAnnotation->build($this->builder, $class);
     }
 }
コード例 #20
0
 /**
  * Map entity class names to their JSON object type (kind).
  */
 protected function mapClassAnnotations()
 {
     // Load entities for annotation mappings
     $dir_iterator = new \RecursiveDirectoryIterator(self::BASE_PATH . 'Nerdstorm/GoogleBooks/Entity/');
     $regex_iterator = new \RegexIterator($dir_iterator, '/^.+\\.php$/i', \RecursiveRegexIterator::GET_MATCH);
     // Map class annotations
     foreach ($regex_iterator as $entity_file) {
         $class_name = self::ENTITY_NAMESPACE . substr(basename($entity_file[0]), 0, -4);
         // Ignore interfaces
         if (Entity\EntityInterface::class == $class_name) {
             continue;
         }
         $class = new $class_name();
         $reflection_object = new \ReflectionObject($class);
         /** @var Object $annotation */
         $annotations = $this->reader->getClassAnnotations($reflection_object);
         if (!$annotations) {
             continue;
         }
         $this->entity_mappings[$annotations[0]->getName()] = $class_name;
     }
 }
コード例 #21
0
ファイル: AnnotationDriver.php プロジェクト: ptheberge/drest
 /**
  * Load metadata for a class name
  * @param  object|string         $class - Pass in either the class name, or an instance of that class
  * @return Mapping\ClassMetaData $metaData - return null if metadata couldn't be populated from annotations
  * @throws DrestException
  */
 public function loadMetadataForClass($class)
 {
     $resourceFound = false;
     if (is_string($class)) {
         $class = new \ReflectionClass($class);
     }
     $metadata = new Mapping\ClassMetaData($class);
     foreach ($this->reader->getClassAnnotations($class) as $annotatedObject) {
         if ($annotatedObject instanceof Annotation\Resource) {
             $resourceFound = true;
             if ($annotatedObject->routes === null) {
                 throw DrestException::annotatedResourceRequiresAtLeastOneServiceDefinition($class->name);
             }
             if (is_array($annotatedObject->representations)) {
                 $metadata->addRepresentations($annotatedObject->representations);
             }
             $this->processRoutes($annotatedObject->routes, $metadata);
             $this->processMethods($class->getMethods(), $metadata);
             $this->checkHandleCalls($metadata->getRoutesMetaData());
         }
     }
     return $resourceFound ? $metadata : null;
 }
コード例 #22
0
ファイル: Annotation.php プロジェクト: jgat2012/hp_oms
 /**
  * (non-PHPdoc)
  * @see Gedmo\Mapping.Driver::readExtendedMetadata()
  */
 public function readExtendedMetadata(ClassMetadataInfo $meta, array &$config)
 {
     require_once __DIR__ . '/../Annotations.php';
     $reader = new AnnotationReader();
     $reader->setAnnotationNamespaceAlias('Gedmo\\Translatable\\Mapping\\', 'gedmo');
     $class = $meta->getReflectionClass();
     // class annotations
     $classAnnotations = $reader->getClassAnnotations($class);
     if (isset($classAnnotations[self::ANNOTATION_ENTITY_CLASS])) {
         $annot = $classAnnotations[self::ANNOTATION_ENTITY_CLASS];
         if (!class_exists($annot->class)) {
             throw MappingException::translationClassNotFound($annot->class);
         }
         $config['translationClass'] = $annot->class;
     }
     // property annotations
     foreach ($class->getProperties() as $property) {
         if ($meta->isMappedSuperclass && !$property->isPrivate() || $meta->isInheritedField($property->name) || $meta->isInheritedAssociation($property->name)) {
             continue;
         }
         // translatable property
         if ($translatable = $reader->getPropertyAnnotation($property, self::ANNOTATION_TRANSLATABLE)) {
             $field = $property->getName();
             if (!$meta->hasField($field)) {
                 throw MappingException::fieldMustBeMapped($field, $meta->name);
             }
             if (!$this->_isValidField($meta, $field)) {
                 throw MappingException::notValidFieldType($field, $meta->name);
             }
             // fields cannot be overrided and throws mapping exception
             $config['fields'][] = $field;
         }
         // locale property
         if ($locale = $reader->getPropertyAnnotation($property, self::ANNOTATION_LOCALE)) {
             $field = $property->getName();
             if ($meta->hasField($field)) {
                 throw MappingException::fieldMustNotBeMapped($field, $meta->name);
             }
             $config['locale'] = $field;
         } elseif ($language = $reader->getPropertyAnnotation($property, self::ANNOTATION_LANGUAGE)) {
             $field = $property->getName();
             if ($meta->hasField($field)) {
                 throw MappingException::fieldMustNotBeMapped($field, $meta->name);
             }
             $config['locale'] = $field;
         }
     }
 }
コード例 #23
0
 /**
  * Whether the class with the specified name is transient. Only non-transient
  * classes, that is entities and mapped superclasses, should have their metadata loaded.
  * A class is non-transient if it is annotated with either @Entity or
  * @MappedSuperclass in the class doc block.
  *
  * @param string $className
  * @return boolean
  */
 public function isTransient($className)
 {
     $classAnnotations = $this->_reader->getClassAnnotations(new \ReflectionClass($className));
     if ($classAnnotations && is_numeric(key($classAnnotations))) {
         foreach ($classAnnotations as $annot) {
             if ($annot instanceof \Doctrine\ORM\Mapping\Entity) {
                 return false;
             }
             if ($annot instanceof \Doctrine\ORM\Mapping\MappedSuperclass) {
                 return false;
             }
         }
         return true;
     }
     return !isset($classAnnotations['Doctrine\\ORM\\Mapping\\Entity']) && !isset($classAnnotations['Doctrine\\ORM\\Mapping\\MappedSuperclass']);
 }
コード例 #24
0
 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);
 }
コード例 #25
0
 public function postUpdate(LifecycleEventArgs $args)
 {
     $reader = new AnnotationReader();
     $entity = $args->getEntity();
     $reflectionClass = new \ReflectionClass(get_class($entity));
     $classAnnotations = $reader->getClassAnnotations($reflectionClass);
     foreach ($classAnnotations as $annotation) {
         if ($annotation instanceof \FS\SolrBundle\Doctrine\Annotation\Document) {
             $this->logger->info('Synchornizing entity "' . get_class($entity) . '" with id:' . $entity->getId());
             try {
                 $this->solrClient->synchronizeIndex($entity);
             } catch (\Exception $e) {
                 $this->logger->error('Error: ' . $e->getCode() . ' - ' . $e->getMessage());
             }
             $this->logger->info('Entity "' . get_class($entity) . '" with id:' . $entity->getId() . ' was successfully synchronized.');
             break;
         }
     }
 }
コード例 #26
0
 /**
  * Returns true is $entityClass is contextualizable on context $context
  *
  * Checks for annotations on entity and bigfoot_context configuration
  *
  * @param string $entityClass
  * @param string $context
  */
 public function isEntityContextualizable($entityClass, $context)
 {
     // Annotations
     $reflClass = new \ReflectionClass($entityClass);
     $reader = new AnnotationReader();
     $annotations = $reader->getClassAnnotations($reflClass);
     foreach ($annotations as $annotation) {
         if (get_class($annotation) == 'Bigfoot\\Bundle\\ContextBundle\\Annotation\\Bigfoot\\Context') {
             return true;
         }
     }
     // Configuration
     foreach ($this->contextualizedEntities as $contextualizedEntity) {
         foreach ($contextualizedEntity['contexts'] as $entityContext) {
             if ($entityContext['value'] == $context) {
                 return true;
             }
         }
     }
     return false;
 }
コード例 #27
0
 /**
  * Aciona a inicialização do framework.
  */
 public function initialize()
 {
     $app = $this->app;
     $this->configLoader->loadConfigs();
     $this->autoRequire->requires();
     foreach ($app['neton.framework.bundles'] as $bundle => $namespace) {
         $bundleDir = str_replace('\\', DIRECTORY_SEPARATOR, $namespace);
         $dir = $app['neton.framework.src_dir'] . DIRECTORY_SEPARATOR . $bundleDir;
         $finder = new Finder();
         foreach ($finder->in($dir)->files() as $file) {
             $className = str_replace("." . $file->getExtension(), '', $file->getRelativePathname());
             $fullClass = $namespace . "\\" . str_replace("/", "\\", $className);
             if (class_exists($fullClass)) {
                 $reflClass = new \ReflectionClass($fullClass);
                 $classAnnotations = $this->reader->getClassAnnotations($reflClass);
                 foreach ($classAnnotations as $annot) {
                     $this->compile($annot, $reflClass, $bundle);
                 }
             }
         }
     }
 }
コード例 #28
0
 /**
  * Parse an embedded class.
  *
  * @param string $name
  * @param \ProAI\Datamapper\Annotations\Annotation $annotation
  * @param \ProAI\Datamapper\Metadata\Definitions\Entity $entityMetadata
  * @return \ProAI\Datamapper\Metadata\Definitions\EmbeddedClass
  */
 protected function parseEmbeddedClass($name, Annotation $annotation, EntityDefinition &$entityMetadata, $primaryKeyOnly = false)
 {
     // check if related class is valid
     $annotation->class = $this->getRealEntity($annotation->class, $entityMetadata['class']);
     $reflectionClass = new ReflectionClass($annotation->class);
     $classAnnotations = $this->reader->getClassAnnotations($reflectionClass);
     // check if class is embedded class
     $this->validator->validateEmbeddedClass($annotation->class, $classAnnotations);
     $embeddedColumnPrefix = $annotation->columnPrefix || $annotation->columnPrefix === false ? $annotation->columnPrefix : $name;
     $embeddedClassMetadata = new EmbeddedClassDefinition(['name' => $name, 'class' => $annotation->class, 'columnPrefix' => $embeddedColumnPrefix, 'attributes' => []]);
     // scan property annotations
     foreach ($reflectionClass->getProperties() as $reflectionProperty) {
         $name = $this->getSanitizedName($reflectionProperty->getName(), $entityMetadata['class']);
         $propertyAnnotations = $this->reader->getPropertyAnnotations($reflectionProperty);
         foreach ($propertyAnnotations as $annotation) {
             // property is column
             if ($annotation instanceof \ProAI\Datamapper\Annotations\Column) {
                 $this->setAdditionalColumnProperties($name, $annotation, $propertyAnnotations, true, $embeddedColumnPrefix);
                 $embeddedClassMetadata['attributes'][] = $this->parseColumn($name, $annotation, $entityMetadata, true, $primaryKeyOnly);
             }
         }
     }
     return $embeddedClassMetadata;
 }
コード例 #29
0
 /**
  * Loads the metadata for the specified class into the provided container.
  *
  * @param string $className
  * @param ClassMetadata $metadata
  * @return void
  * @throws MappingException
  * @throws \UnexpectedValueException
  * @todo adjust when Doctrine 2.5 is used, see http://www.doctrine-project.org/jira/browse/DDC-93
  */
 public function loadMetadataForClass($className, ClassMetadata $metadata)
 {
     /**
      * This is the actual type we have at this point, but we cannot change the
      * signature due to inheritance.
      *
      * @var OrmClassMetadata $metadata
      */
     $class = $metadata->getReflectionClass();
     $classSchema = $this->getClassSchema($class->getName());
     $classAnnotations = $this->reader->getClassAnnotations($class);
     // Evaluate Entity annotation
     if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\MappedSuperclass'])) {
         $mappedSuperclassAnnotation = $classAnnotations['Doctrine\\ORM\\Mapping\\MappedSuperclass'];
         if ($mappedSuperclassAnnotation->repositoryClass !== null) {
             $metadata->setCustomRepositoryClass($mappedSuperclassAnnotation->repositoryClass);
         }
         $metadata->isMappedSuperclass = true;
     } elseif (isset($classAnnotations[\TYPO3\Flow\Annotations\Entity::class]) || isset($classAnnotations['Doctrine\\ORM\\Mapping\\Entity'])) {
         $entityAnnotation = isset($classAnnotations[\TYPO3\Flow\Annotations\Entity::class]) ? $classAnnotations[\TYPO3\Flow\Annotations\Entity::class] : $classAnnotations['Doctrine\\ORM\\Mapping\\Entity'];
         if ($entityAnnotation->repositoryClass !== null) {
             $metadata->setCustomRepositoryClass($entityAnnotation->repositoryClass);
         } elseif ($classSchema->getRepositoryClassName() !== null) {
             if ($this->reflectionService->isClassImplementationOf($classSchema->getRepositoryClassName(), 'Doctrine\\ORM\\EntityRepository')) {
                 $metadata->setCustomRepositoryClass($classSchema->getRepositoryClassName());
             }
         }
         if ($entityAnnotation->readOnly) {
             $metadata->markReadOnly();
         }
     } elseif ($classSchema->getModelType() === ClassSchema::MODELTYPE_VALUEOBJECT) {
         // also ok... but we make it read-only
         $metadata->markReadOnly();
     } else {
         throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className);
     }
     // Evaluate Table annotation
     $primaryTable = array();
     if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\Table'])) {
         $tableAnnotation = $classAnnotations['Doctrine\\ORM\\Mapping\\Table'];
         $primaryTable = array('name' => $tableAnnotation->name, 'schema' => $tableAnnotation->schema);
         if ($tableAnnotation->indexes !== null) {
             foreach ($tableAnnotation->indexes as $indexAnnotation) {
                 $index = array('columns' => $indexAnnotation->columns);
                 if (!empty($indexAnnotation->name)) {
                     $primaryTable['indexes'][$indexAnnotation->name] = $index;
                 } else {
                     $primaryTable['indexes'][] = $index;
                 }
             }
         }
         if ($tableAnnotation->uniqueConstraints !== null) {
             foreach ($tableAnnotation->uniqueConstraints as $uniqueConstraint) {
                 $uniqueConstraint = array('columns' => $uniqueConstraint->columns);
                 if (!empty($uniqueConstraint->name)) {
                     $primaryTable['uniqueConstraints'][$uniqueConstraint->name] = $uniqueConstraint;
                 } else {
                     $primaryTable['uniqueConstraints'][] = $uniqueConstraint;
                 }
             }
         }
         if ($tableAnnotation->options !== null) {
             $primaryTable['options'] = $tableAnnotation->options;
         }
     }
     if (!isset($primaryTable['name'])) {
         $className = $classSchema->getClassName();
         $primaryTable['name'] = $this->inferTableNameFromClassName($className);
     }
     // Evaluate NamedNativeQueries annotation
     if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\NamedNativeQueries'])) {
         $namedNativeQueriesAnnotation = $classAnnotations['Doctrine\\ORM\\Mapping\\NamedNativeQueries'];
         foreach ($namedNativeQueriesAnnotation->value as $namedNativeQuery) {
             $metadata->addNamedNativeQuery(array('name' => $namedNativeQuery->name, 'query' => $namedNativeQuery->query, 'resultClass' => $namedNativeQuery->resultClass, 'resultSetMapping' => $namedNativeQuery->resultSetMapping));
         }
     }
     // Evaluate SqlResultSetMappings annotation
     if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\SqlResultSetMappings'])) {
         $sqlResultSetMappingsAnnotation = $classAnnotations['Doctrine\\ORM\\Mapping\\SqlResultSetMappings'];
         foreach ($sqlResultSetMappingsAnnotation->value as $resultSetMapping) {
             $entities = array();
             $columns = array();
             foreach ($resultSetMapping->entities as $entityResultAnnotation) {
                 $entityResult = array('fields' => array(), 'entityClass' => $entityResultAnnotation->entityClass, 'discriminatorColumn' => $entityResultAnnotation->discriminatorColumn);
                 foreach ($entityResultAnnotation->fields as $fieldResultAnnotation) {
                     $entityResult['fields'][] = array('name' => $fieldResultAnnotation->name, 'column' => $fieldResultAnnotation->column);
                 }
                 $entities[] = $entityResult;
             }
             foreach ($resultSetMapping->columns as $columnResultAnnotation) {
                 $columns[] = array('name' => $columnResultAnnotation->name);
             }
             $metadata->addSqlResultSetMapping(array('name' => $resultSetMapping->name, 'entities' => $entities, 'columns' => $columns));
         }
     }
     // Evaluate NamedQueries annotation
     if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\NamedQueries'])) {
         $namedQueriesAnnotation = $classAnnotations['Doctrine\\ORM\\Mapping\\NamedQueries'];
         if (!is_array($namedQueriesAnnotation->value)) {
             throw new \UnexpectedValueException('@NamedQueries should contain an array of @NamedQuery annotations.');
         }
         foreach ($namedQueriesAnnotation->value as $namedQuery) {
             if (!$namedQuery instanceof 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'])) {
         $inheritanceTypeAnnotation = $classAnnotations['Doctrine\\ORM\\Mapping\\InheritanceType'];
         $inheritanceType = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::INHERITANCE_TYPE_' . strtoupper($inheritanceTypeAnnotation->value));
         if ($inheritanceType !== OrmClassMetadata::INHERITANCE_TYPE_NONE) {
             // Evaluate DiscriminatorColumn annotation
             if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorColumn'])) {
                 $discriminatorColumnAnnotation = $classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorColumn'];
                 $discriminatorColumn = array('name' => $discriminatorColumnAnnotation->name, 'type' => $discriminatorColumnAnnotation->type, 'length' => $discriminatorColumnAnnotation->length, 'columnDefinition' => $discriminatorColumnAnnotation->columnDefinition);
             } else {
                 $discriminatorColumn = array('name' => 'dtype', 'type' => 'string', 'length' => 255);
             }
             // Evaluate DiscriminatorMap annotation
             if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorMap'])) {
                 $discriminatorMapAnnotation = $classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorMap'];
                 $discriminatorMap = $discriminatorMapAnnotation->value;
             } else {
                 $discriminatorMap = array();
                 $subclassNames = $this->reflectionService->getAllSubClassNamesForClass($className);
                 if (!$this->reflectionService->isClassAbstract($className)) {
                     $mappedClassName = strtolower(str_replace('Domain_Model_', '', str_replace('\\', '_', $className)));
                     $discriminatorMap[$mappedClassName] = $className;
                 }
                 foreach ($subclassNames as $subclassName) {
                     $mappedSubclassName = strtolower(str_replace('Domain_Model_', '', str_replace('\\', '_', $subclassName)));
                     $discriminatorMap[$mappedSubclassName] = $subclassName;
                 }
             }
             if ($discriminatorMap !== array()) {
                 $metadata->setDiscriminatorColumn($discriminatorColumn);
                 $metadata->setDiscriminatorMap($discriminatorMap);
             } else {
                 $inheritanceType = OrmClassMetadata::INHERITANCE_TYPE_NONE;
             }
         }
         $metadata->setInheritanceType($inheritanceType);
     }
     // Evaluate DoctrineChangeTrackingPolicy annotation
     if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\ChangeTrackingPolicy'])) {
         $changeTrackingAnnotation = $classAnnotations['Doctrine\\ORM\\Mapping\\ChangeTrackingPolicy'];
         $metadata->setChangeTrackingPolicy(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::CHANGETRACKING_' . strtoupper($changeTrackingAnnotation->value)));
     } else {
         $metadata->setChangeTrackingPolicy(OrmClassMetadata::CHANGETRACKING_DEFERRED_EXPLICIT);
     }
     // Evaluate annotations on properties/fields
     try {
         $this->evaluatePropertyAnnotations($metadata);
     } catch (MappingException $exception) {
         throw new MappingException(sprintf('Failure while evaluating property annotations for class "%s": %s', $metadata->getName(), $exception->getMessage()), 1382003497, $exception);
     }
     // build unique index for table
     if (!isset($primaryTable['uniqueConstraints'])) {
         $idProperties = array_keys($classSchema->getIdentityProperties());
         if (array_diff($idProperties, $metadata->getIdentifierFieldNames()) !== array()) {
             $uniqueIndexName = $this->truncateIdentifier('flow_identity_' . $primaryTable['name']);
             foreach ($idProperties as $idProperty) {
                 $primaryTable['uniqueConstraints'][$uniqueIndexName]['columns'][] = isset($metadata->columnNames[$idProperty]) ? $metadata->columnNames[$idProperty] : strtolower($idProperty);
             }
         }
     }
     $metadata->setPrimaryTable($primaryTable);
     // Evaluate AssociationOverrides annotation
     $this->evaluateOverridesAnnotations($classAnnotations, $metadata);
     // Evaluate EntityListeners annotation
     $this->evaluateEntityListenersAnnotation($class, $metadata, $classAnnotations);
     // Evaluate @HasLifecycleCallbacks annotation
     $this->evaluateLifeCycleAnnotations($class, $metadata);
 }
コード例 #30
0
 public function process(ContainerBuilder $container)
 {
     if (!$container->hasParameter($this->configKey)) {
         throw new \InvalidArgumentException("Container doesn't have parameter '{$this->configKey}', SkrzBunnyExtension probably haven't processed config.");
     }
     $config = $container->getParameter($this->configKey);
     $parameterBag = $container->getParameterBag();
     $consumers = [];
     $producers = [];
     foreach ($container->getDefinitions() as $serviceId => $definition) {
         if ($definition->isAbstract() || !$definition->isPublic() || !$definition->getClass()) {
             continue;
         }
         $className = $parameterBag->resolveValue($definition->getClass());
         if (!class_exists($className)) {
             continue;
         }
         $rc = new \ReflectionClass($className);
         if (strpos($rc->getDocComment(), "@Consumer") === false && strpos($rc->getDocComment(), "@Producer") === false) {
             continue;
         }
         foreach ($this->annotationReader->getClassAnnotations($rc) as $annotation) {
             if ($annotation instanceof Consumer) {
                 if (empty($annotation->queue) === empty($annotation->exchange)) {
                     throw new BunnyException("Either 'queue', or 'exchange' (but not both) has to be specified {$className} (service: {$serviceId}).");
                 }
                 $annotation->name = $serviceId;
                 $annotation->className = $className;
                 $consumerName = $rc->getShortName();
                 if (substr($consumerName, -8) === "Consumer") {
                     $consumerName = substr($consumerName, 0, -8);
                 }
                 $consumerName = strtolower($consumerName);
                 if (isset($consumers[$consumerName]) && $consumers[$consumerName][0]["className"] !== $className) {
                     throw new BunnyException("Multiple consumer services would result in same name: " . "{$consumers[$consumerName][0]["name"]} ({$consumers[$consumerName][0]["className"]}) " . "and {$serviceId} ({$className}).");
                 } elseif (!isset($consumers[$consumerName])) {
                     $consumers[$consumerName] = [];
                 }
                 $consumers[$consumerName][] = (array) $annotation;
             } elseif ($annotation instanceof Producer) {
                 $annotation->name = $serviceId;
                 $annotation->className = $className;
                 $producerName = $rc->getShortName();
                 if (substr($producerName, -8) === "Producer") {
                     $producerName = substr($producerName, 0, -8);
                 }
                 $producerName = strtolower($producerName);
                 if (isset($producers[$producerName])) {
                     throw new BunnyException("Multiple producer services would result in same name: " . "{$producers[$producerName]["name"]} ({$producers[$producerName]["className"]}) " . "and {$serviceId} ({$className}).");
                 }
                 if (empty($annotation->contentType)) {
                     $annotation->contentType = ContentTypes::APPLICATION_JSON;
                 }
                 $producers[$producerName] = (array) $annotation;
                 $definition->setArguments([$annotation->exchange, $annotation->routingKey, $annotation->mandatory, $annotation->immediate, $annotation->meta, $annotation->beforeMethod, $annotation->contentType, new Reference($this->managerServiceId)]);
             }
         }
     }
     $container->setDefinition($this->clientServiceId, new Definition("Bunny\\Client", [["host" => $config["host"], "port" => $config["port"], "vhost" => $config["vhost"], "user" => $config["user"], "password" => $config["password"], "heartbeat" => $config["heartbeat"]]]));
     $container->setDefinition($this->managerServiceId, new Definition("Skrz\\Bundle\\BunnyBundle\\BunnyManager", [new Reference("service_container"), $this->clientServiceId, $config]));
     $channel = new Definition("Bunny\\Channel");
     $channel->setFactory([new Reference($this->managerServiceId), "getChannel"]);
     $container->setDefinition($this->channelServiceId, $channel);
     $container->setDefinition($this->setupCommandServiceId, new Definition("Skrz\\Bundle\\BunnyBundle\\Command\\SetupCommand", [new Reference($this->managerServiceId)]));
     $container->setDefinition($this->consumerCommandServiceId, new Definition("Skrz\\Bundle\\BunnyBundle\\Command\\ConsumerCommand", [new Reference("service_container"), new Reference($this->managerServiceId), $consumers]));
     $container->setDefinition($this->producerCommandServiceId, new Definition("Skrz\\Bundle\\BunnyBundle\\Command\\ProducerCommand", [new Reference("service_container"), new Reference($this->managerServiceId), $producers]));
 }