getPropertyAnnotations() public method

{@inheritDoc}
public getPropertyAnnotations ( ReflectionProperty $property )
$property ReflectionProperty
 /**
  * @param ReflectionProperty $property
  * @return PropertyMetadata
  */
 private function loadPropertyMetadata(ReflectionProperty $property)
 {
     $propertyMetadata = new PropertyMetadata($property->getDeclaringClass()->getName(), $property->getName());
     foreach ($this->reader->getPropertyAnnotations($property) as $propertyAnnotation) {
         if ($propertyAnnotation instanceof Type) {
             $propertyMetadata->type = $propertyAnnotation->name;
         }
         if ($propertyAnnotation instanceof ReferenceOne) {
             $propertyMetadata->reference = PropertyMetadata::REFERENCE_ONE;
             $propertyMetadata->target = $propertyAnnotation->target;
         }
         if ($propertyAnnotation instanceof ReferenceMany) {
             $propertyMetadata->reference = PropertyMetadata::REFERENCE_MANY;
             $propertyMetadata->target = $propertyAnnotation->target;
         }
         if ($propertyAnnotation instanceof ReferenceKey) {
             $propertyMetadata->reference = PropertyMetadata::REFERENCE_KEY;
             $propertyMetadata->target = $propertyAnnotation->target;
             if ($propertyAnnotation->value instanceof Type) {
                 $propertyMetadata->value = ['type' => 'type', 'name' => $propertyAnnotation->value->name];
             }
         }
         if ($propertyAnnotation instanceof EmbedOne) {
             $propertyMetadata->embed = PropertyMetadata::EMBED_ONE;
             $propertyMetadata->target = $propertyAnnotation->target;
             $propertyMetadata->mapping = $propertyAnnotation->mapping;
         }
         if ($propertyAnnotation instanceof EmbedMany) {
             $propertyMetadata->embed = PropertyMetadata::EMBED_MANY;
             $propertyMetadata->target = $propertyAnnotation->target;
             $propertyMetadata->mapping = $propertyAnnotation->mapping;
         }
     }
     return $propertyMetadata;
 }
 /**
  * @param string $classname
  * @return array
  */
 public function getFieldsMetadata($classname)
 {
     foreach ($this->getReflectionClass($classname)->getProperties() as $property) {
         $properties = array_reduce($this->reader->getPropertyAnnotations($property), function ($reduced, $current) use($property, $classname) {
             if ($current instanceof AbstractField) {
                 $current->name = $property->getName();
                 if (is_object($classname)) {
                     $property->setAccessible(true);
                     $current->value = $property->getValue($classname);
                 }
                 $key = get_class($current);
                 if (isset($reduced[$key])) {
                     if (!is_array($reduced[$key])) {
                         $reduced[$key] = [$reduced[$key]];
                     }
                     $reduced[$key][] = $current;
                 } else {
                     $reduced[$key] = $current;
                 }
                 return $reduced;
             }
         });
         if (!is_null($properties)) {
             $fields[$property->getName()] = $properties;
         }
     }
     return $fields;
 }
 public function loadMetadataForClass($className)
 {
     $metadata = new ClassMetadata($className);
     $reflectionClass = new \ReflectionClass($className);
     $reflectionProperties = $reflectionClass->getProperties();
     foreach ($reflectionProperties as $reflectionProperty) {
         $name = $reflectionProperty->getName();
         $pMetadata = new PropertyMetadata($name);
         $annotations = $this->reader->getPropertyAnnotations($reflectionProperty);
         foreach ($annotations as $annotation) {
             if ($annotation instanceof Annotations\Expose) {
                 $pMetadata->setExpose((bool) $annotation->value);
             } elseif ($annotation instanceof Annotations\Type) {
                 $pMetadata->setType((string) $annotation->value);
             } elseif ($annotation instanceof Annotations\Groups) {
                 $pMetadata->setGroups($annotation->value);
             } elseif ($annotation instanceof Annotations\SerializedName) {
                 $pMetadata->setSerializedName((string) $annotation->value);
             } elseif ($annotation instanceof Annotations\SinceVersion) {
                 $pMetadata->setSinceVersion((string) $annotation->value);
             } elseif ($annotation instanceof Annotations\UntilVersion) {
                 $pMetadata->setUntilVersion((string) $annotation->value);
             }
         }
         $metadata->addPropertyMetadata($pMetadata);
     }
     return $metadata;
 }
Beispiel #4
0
 public function getPropertyAnnotationClassNames($className, $propertyName = NULL)
 {
     $reflectionProperty = new \ReflectionProperty($className, $propertyName);
     $annotations = $this->annotationReader->getPropertyAnnotations($reflectionProperty);
     $classNames = array();
     foreach ($annotations as $annotation) {
         $classNames[] = get_class($annotation);
     }
     return array_unique($classNames);
 }
Beispiel #5
0
 /**
  * @param array $properties
  * @param object $class
  * @return array
  */
 public function getPropertyAnnotations(array $properties, $class)
 {
     $contraints = array();
     // Foreach the sync and retrieve the anotation
     foreach ($properties as $property) {
         $propertyReflection = new \ReflectionProperty($class, $property);
         $annotation = $this->annotationReader->getPropertyAnnotations($propertyReflection);
         if (empty($annotation) === false) {
             $contraints[$property] = $annotation;
         }
     }
     return $contraints;
 }
Beispiel #6
0
 /**
  * {@inheritdoc}
  */
 public function parse(TransportableInterface $transport)
 {
     $resource = new ResourceMapping();
     //  Gain a reflection instance of the given class and retrieve all the properties marked as protected.
     $class = new ReflectionObject($transport);
     $properties = $class->getProperties(ReflectionProperty::IS_PROTECTED);
     foreach ($properties as $property) {
         $annotations = new ArrayCollection($this->reader->getPropertyAnnotations($property));
         $this->processFieldAnnotationsForResourceMapping($resource, $property, $annotations);
     }
     $this->validateResourceMapping($resource);
     return $resource;
 }
Beispiel #7
0
 /**
  * {@inheritdoc}
  */
 public function fillEntity(Utils\ArrayHash $values, Entities\IEntity $entity, $isNew = FALSE)
 {
     $classMetadata = $this->managerRegistry->getManagerForClass(get_class($entity))->getClassMetadata(get_class($entity));
     foreach (array_merge($classMetadata->getFieldNames(), $classMetadata->getAssociationNames()) as $fieldName) {
         $propertyReflection = new Nette\Reflection\Property(get_class($entity), $fieldName);
         /** @var Doctrine\Mapping\Annotation\Crud $crud */
         if ($crud = $this->annotationReader->getPropertyAnnotation($propertyReflection, self::EXTENSION_ANNOTATION)) {
             if ($isNew && $crud->isRequired() && !$values->offsetExists($fieldName)) {
                 throw new Exceptions\InvalidStateException('Missing required key "' . $fieldName . '"');
             }
             if (!$values->offsetExists($fieldName) || !$isNew && !$crud->isWritable() || $isNew && !$crud->isRequired()) {
                 continue;
             }
             $value = $values->offsetGet($fieldName);
             if ($value instanceof Utils\ArrayHash || is_array($value)) {
                 if (!$classMetadata->getFieldValue($entity, $fieldName) instanceof Entities\IEntity) {
                     $propertyAnnotations = $this->annotationReader->getPropertyAnnotations($propertyReflection);
                     $annotations = array_map(function ($annotation) {
                         return get_class($annotation);
                     }, $propertyAnnotations);
                     if (in_array('Doctrine\\ORM\\Mapping\\OneToOne', $annotations, TRUE)) {
                         $className = $this->annotationReader->getPropertyAnnotation($propertyReflection, 'Doctrine\\ORM\\Mapping\\OneToOne')->targetEntity;
                     } elseif (in_array('Doctrine\\ORM\\Mapping\\ManyToOne', $annotations, TRUE)) {
                         $className = $this->annotationReader->getPropertyAnnotation($propertyReflection, 'Doctrine\\ORM\\Mapping\\ManyToOne')->targetEntity;
                     } else {
                         $className = $propertyReflection->getAnnotation('var');
                     }
                     // Check if class is callable
                     if (class_exists($className)) {
                         $classMetadata->setFieldValue($entity, $fieldName, new $className());
                     } else {
                         $classMetadata->setFieldValue($entity, $fieldName, $value);
                     }
                 }
                 // Check again if entity was created
                 if (($fieldValue = $classMetadata->getFieldValue($entity, $fieldName)) && $fieldValue instanceof Entities\IEntity) {
                     $classMetadata->setFieldValue($entity, $fieldName, $this->fillEntity(Utils\ArrayHash::from((array) $value), $fieldValue, $isNew));
                 }
             } else {
                 if ($crud->validator !== NULL) {
                     $value = $this->validateProperty($crud->validator, $value);
                 }
                 $classMetadata->setFieldValue($entity, $fieldName, $value);
             }
         }
     }
     return $entity;
 }
 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;
 }
Beispiel #9
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];
 }
 /**
  * Load all of the @XmlValue annotations
  * 
  * @param ClassMetadata $metadata
  */
 protected function loadClassValue(ClassMetadata $metadata)
 {
     $reflClass = $metadata->getReflectionClass();
     foreach ($reflClass->getProperties() as $property) {
         foreach ($this->reader->getPropertyAnnotations($property) as $annotation) {
             if ($annotation instanceof XmlValue) {
                 $metadata->setValue($property->getName());
             }
         }
     }
 }
 public function testAnnotations()
 {
     $reader = new AnnotationReader(new \Doctrine\Common\Cache\ArrayCache());
     $reader->setDefaultAnnotationNamespace('Doctrine\\Tests\\Common\\Annotations\\');
     $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);
 }
Beispiel #12
0
 public static function fromReflection(ReflectionProperty $reflection = NULL)
 {
     if (!defined('PHP_VERSION_ID')) {
         $v = explode('.', PHP_VERSION);
         define('PHP_VERSION_ID', $v[0] * 10000 + $v[1] * 100 + $v[2]);
     }
     if ($reflection === null) {
         return null;
     }
     if (func_num_args() > 1) {
         $stack = func_get_arg(1);
     } else {
         $stack = new \ArrayObject();
     }
     $stackExpression = $reflection->getDeclaringClass()->getName() . '::' . $reflection->getName();
     if (isset($stack[$stackExpression])) {
         return $stack[$stackExpression];
     }
     $stack[$stackExpression] = $instance = new Property($reflection);
     if (func_num_args() > 2) {
         $reader = func_get_arg(2);
     } else {
         $reader = new AnnotationReader();
     }
     if (func_num_args() > 3) {
         $phpParser = func_get_arg(3);
     } else {
         $phpParser = new PhpParser();
     }
     $instance->name = $reflection->getName();
     $instance->public = $reflection->isPublic();
     $instance->private = $reflection->isPrivate();
     $instance->protected = $reflection->isProtected();
     $instance->static = $reflection->isStatic();
     $instance->default = $reflection->isDefault();
     $instance->modifiers = $reflection->getModifiers();
     $instance->docComment = $reflection->getDocComment();
     $instance->annotations = $reader->getPropertyAnnotations($reflection);
     $instance->declaringClass = Type::fromReflection($reflection->getDeclaringClass() ? $reflection->getDeclaringClass() : null, $stack, $reader, $phpParser);
     $defaultProperties = $reflection->getDeclaringClass()->getDefaultProperties();
     if (isset($defaultProperties[$instance->name])) {
         $instance->defaultValue = $defaultProperties[$instance->name];
     }
     if (preg_match('/@var\\s+([a-zA-Z0-9\\\\\\[\\]_]+)/', $instance->docComment, $m)) {
         $typeString = $m[1];
     }
     if (isset($typeString)) {
         $instance->type = MixedType::fromString($typeString, $stack, $reader, $phpParser, $instance->declaringClass);
     } else {
         $instance->type = MixedType::getInstance();
     }
     return $instance;
 }
 /**
  * Get BuilderDefinition from entity property
  *
  * @param string $propertyName
  * @param bool $fillValues
  * @return BuilderDefinition|null
  * @throws InvalidStateException
  */
 private function getPropertyRule($propertyName, $fillValues = TRUE)
 {
     $property = $this->entityReflection->getProperty($propertyName);
     $annotations = $this->annotationReader->getPropertyAnnotations($property);
     $rule = new BuilderDefinition($propertyName);
     foreach ($annotations as $annotation) {
         switch (get_class($annotation)) {
             case 'Doctrine\\ORM\\Mapping\\Column':
                 if ($this->getEntityPrimaryKeyName($this->entity) === $propertyName) {
                     $rule->setComponentType(BuilderDefinition::COMPONENT_TYPE_HIDDEN);
                     $rule->setRequired(FALSE);
                 } else {
                     $type = BuilderDefinition::COMPONENT_TYPE_TEXT;
                     $rule->setRequired(!$annotation->nullable);
                     /** @var Column $annotation */
                     if ($annotation->type === 'boolean') {
                         $type = BuilderDefinition::COMPONENT_TYPE_CHECKBOX;
                     }
                     // is numeric?
                     if ($annotation->type === 'integer' || $annotation->type === 'float' || $annotation->type === 'bigint' || $annotation->type === 'decimal' || $annotation->type === 'smallint') {
                         $rule->addValidationRule(Form::NUMERIC, 'This is required in numeric format', TRUE);
                     }
                     $rule->setComponentType($type);
                 }
                 break;
             case 'Doctrine\\ORM\\Mapping\\ManyToOne':
                 /** @var ManyToOne $annotation */
                 $rule->setComponentType(BuilderDefinition::COMPONENT_TYPE_SELECT);
                 if ($fillValues) {
                     $rule->setValues($this->getPossibleValues($annotation->targetEntity));
                 }
                 $rule->setTargetEntity($annotation->targetEntity);
                 $rule->setRequired(TRUE);
                 break;
             case 'Doctrine\\ORM\\Mapping\\ManyToMany':
                 /** @var OneToMany $annotation */
                 $rule->setComponentType(BuilderDefinition::COMPONENT_TYPE_MULTI_SELECT);
                 if ($fillValues) {
                     $rule->setValues($this->getPossibleValues($annotation->targetEntity));
                 }
                 $rule->setRequired(TRUE);
                 $rule->setTargetEntity($annotation->targetEntity);
                 break;
             case 'Doctrine\\ORM\\Mapping\\JoinColumn':
                 /** @var JoinColumn $annotation */
                 $rule->setRequired(!$annotation->nullable);
                 break;
         }
     }
     return $rule->getComponentType() === NULL ? NULL : $rule;
 }
 /**
  * Get all annotation and add validators
  */
 protected function getAnnotationValidator()
 {
     $reader = new AnnotationReader();
     $classReflection = new \ReflectionClass($this->object);
     $propertiesReflection = $classReflection->getProperties();
     foreach ($propertiesReflection as $property) {
         $annotations = $reader->getPropertyAnnotations($property);
         $propertyName = $property->getName();
         foreach ($annotations as $annotation) {
             if ($annotation instanceof ValidatorInterface) {
                 $this->addValidator($propertyName, $annotation);
             }
         }
     }
 }
 public static function getJsonSchema()
 {
     $reader = new AnnotationReader();
     $schema = array();
     $reflection = new \ReflectionClass(static::class);
     foreach ($reflection->getProperties() as $property) {
         $annotations = $reader->getPropertyAnnotations($property);
         foreach ($annotations as $annotation) {
             if ($annotation instanceof Property) {
                 var_dump($annotation);
             } else {
                 var_dump($annotation);
             }
         }
     }
 }
 /**
  * Validate value with annotation.
  *
  * @param object $value
  *
  * @throws ValidationException
  */
 public function validateWithAnnotation($value)
 {
     if (!is_object($value)) {
         throw new ValidationException('To validate with annotation, value should be object but got "%s".', gettype($value));
     }
     $reader = new AnnotationReader();
     $values = $this->getValues($value);
     foreach ($this->getProperties($value) as $prop) {
         foreach ($reader->getPropertyAnnotations($prop) as $annotation) {
             if ($annotation instanceof AbstractConstraint) {
                 $name = $prop->getName();
                 $val = isset($values[$name]) ? $values[$name] : null;
                 $this->validate($val, $annotation, array('attribute' => trim(implode(' ', preg_split('/(?=[A-Z])/', $name)))));
             }
         }
     }
 }
Beispiel #17
0
 protected function processObjectProperties(AnnotationReader $reader, $object, array $properties)
 {
     $values = array();
     foreach ($properties as $property) {
         // Get the annotation for this property.
         $annotations = $reader->getPropertyAnnotations($property);
         if (empty($annotations)) {
             continue;
         }
         foreach ($annotations as $annotation) {
             // Check if the annotation is parseble, if not, get the next one.
             if (!$annotation instanceof Annotation\AnnotationInterface) {
                 continue;
             }
             // If the annotation has a 'name' attribute then use that, otherwise
             // use the property name (class member) as the value key.
             $name = $annotation->name;
             if (empty($name)) {
                 $name = $property->name;
             }
             // Get the value of the property.
             $value = $annotation->getPropertyValue($property, $object);
             if ($annotation instanceof Annotation\Object) {
                 // If $value is an object then recurse into it.
                 $values[$name] = $this->toArray($value);
             } else {
                 if ($annotation instanceof Annotation\Collection) {
                     // $value is a collection, iterate through it.
                     foreach ($value as $item) {
                         if (is_object($item)) {
                             // If the item is an object then we want to recurse into it.
                             $values[$name][] = $this->toArray($item);
                         } else {
                             // Other wise just add the $item value.
                             $values[$name][] = $item;
                         }
                     }
                 } else {
                     // $value is just a simple value.
                     $values[$name] = $value;
                 }
             }
         }
     }
     return $values;
 }
 /**
  * @param FormEvent $event
  *
  * @return ResourceAnnotationInterface|null
  */
 private function getPropertyConfig(FormEvent $event)
 {
     if (null === ($class = $event->getForm()->getParent()->getConfig()->getDataClass())) {
         return null;
     }
     $property = $event->getForm()->getName();
     if (!property_exists($class, $property)) {
         return null;
     }
     $reflectionProperty = new \ReflectionProperty($class, $property);
     $propertyAnnotations = $this->reader->getPropertyAnnotations($reflectionProperty);
     foreach ($propertyAnnotations as $propertyAnnotation) {
         if ($propertyAnnotation instanceof ResourceAnnotationInterface) {
             return $propertyAnnotation;
         }
     }
     return null;
 }
Beispiel #19
0
 /**
  * Processes Maam annotations in class files and writes new classes with the generated
  * getters and setters.
  *
  * @param string $filePath Path to the file to generate
  * @return array|null Array consisting of the class and path if generated, or null if not because there were no
  *                    Maam annotations.
  */
 protected function generateClass($filePath)
 {
     $newMethods = [];
     $reflectionClass = $this->getReflectionClass($filePath);
     $annotationReader = new AnnotationReader();
     /** @var \ReflectionProperty $property */
     foreach ($reflectionClass->getProperties() as $property) {
         $annotations = $annotationReader->getPropertyAnnotations($property);
         if (count($annotations) === 0) {
             return null;
         }
         $newMethods = array_merge($newMethods, $this->generateMethods($annotations, $property->getName()));
     }
     if (count($newMethods) === 0) {
         return null;
     }
     return ['class' => $reflectionClass->getName(), 'path' => $this->writeNewCode($filePath, $newMethods)];
 }
Beispiel #20
0
 /**
  * Expects to receive an array from which it will extract
  * the values it recognizes to stored them in this class.
  *
  * @param array
  */
 public function exchangeArray(array $data = array())
 {
     $annotationReader = new AnnotationReader();
     foreach ($data as $key => $value) {
         if (property_exists(get_class($this), $key)) {
             $reflectionProperty = new \ReflectionProperty(get_class($this), $key);
             $propertyAnnotations = $annotationReader->getPropertyAnnotations($reflectionProperty);
             if (property_exists(get_class($propertyAnnotations[0]), 'targetEntity')) {
                 $namespace = $this->_getNameSpace();
                 $newClass = $namespace . $propertyAnnotations[0]->targetEntity;
                 $this->{$key} = new $newClass();
                 $this->{$key}->exchangeArray($value);
             } else {
                 if ($key === 'fecha' && is_string($value)) {
                     $this->{$key} = new \DateTime($value);
                 } else {
                     $this->{$key} = $value;
                 }
             }
         }
     }
 }
Beispiel #21
0
 /**
  * @param Repository[] $repositories
  *
  * @return Repository[]
  */
 public function compare(array $repositories, $options = [])
 {
     if (count($repositories) < 2) {
         throw new \InvalidArgumentException('At least two Repositories must be specified!');
     }
     $reflectedClass = new \ReflectionClass(Repository::class);
     $reader = new AnnotationReader();
     $propertyAccessor = PropertyAccess::createPropertyAccessor();
     $totalWeight = 0.0;
     foreach ($repositories as $repository) {
         /* @var Repository $repository */
         foreach ($reflectedClass->getProperties() as $property) {
             foreach ($reader->getPropertyAnnotations($property) as $annotation) {
                 if ($annotation instanceof Weight) {
                     $optionName = strtolower(preg_replace('/([^A-Z])([A-Z])/', '$1_$2', $property->name));
                     $factor = isset($options[$optionName]) ? floatval($options[$optionName]) : $annotation->value;
                     $repository->addWeight($propertyAccessor->getValue($repository, $property->name) * $factor);
                 }
             }
         }
         $totalWeight += $repository->getWeight();
     }
     // Sort in ascending order according to repository's weight
     usort($repositories, function (Repository $a, Repository $b) {
         return $b->getWeight() - $a->getWeight();
     });
     // Calculate rating
     $left = 100;
     foreach ($repositories as $repository) {
         /* @var Repository $repository */
         $rating = floor(100 * $repository->getWeight() / $totalWeight);
         $repository->setRating($rating);
         $left -= $rating;
     }
     // The leader is rated better than others
     $repositories[0]->addRating($left);
     return $repositories;
 }
Beispiel #22
0
 public static function processClass($class)
 {
     if ($class instanceof \ReflectionClass) {
         $reflection = $class;
     } else {
         $reflection = new \ReflectionClass($class);
     }
     $format = array();
     $reader = new AnnotationReader();
     foreach ($reflection->getProperties() as $property) {
         $annotations = $reader->getPropertyAnnotations($property);
         foreach ($annotations as $annotation) {
             if ($annotation instanceof PropertyFormatter) {
                 $format[$property->getName()] = $annotation;
                 break;
             }
         }
     }
     if (empty($format)) {
         static::$reflectionCache[$reflection->getName()] = new DefaultClassFormatter($reflection);
     } else {
         static::$reflectionCache[$reflection->getName()] = new ClassFormatterImp($reflection, $format);
     }
 }
 /**
  * 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;
 }
Beispiel #24
0
 /**
  * @param $entityName
  *
  * @return array Entity class name, null if not found
  * @throws \Doctrine\ORM\ORMException
  * @internal param string $table Table name
  * @internal param EntityManager $em Entity manager
  */
 protected function getEntityStringColumns($entityName)
 {
     // Go through all the classes
     $classNames = $this->dqlConverter->getAvailableEntities();
     $annotationReader = new AnnotationReader();
     $searchingEntityName = strtolower($entityName);
     foreach ($classNames as $i => $className) {
         $className = $classNames[$i];
         $classMetaData = $this->em->getClassMetadata($className);
         $currentEntityName = strtolower($classMetaData->getReflectionClass()->getName());
         if ($currentEntityName === $searchingEntityName) {
             /** @var array $allColumnNames */
             $allColumnNames = $classMetaData->getFieldNames();
             $columnNames = [];
             foreach ($allColumnNames as $columnName) {
                 try {
                     $annotations = $annotationReader->getPropertyAnnotations(new \ReflectionProperty($classMetaData->getName(), $columnName));
                     if ($classMetaData->getTypeOfField($columnName) === 'string') {
                         $isEnum = false;
                         foreach ($annotations as $annotation) {
                             if ($annotation instanceof Choice) {
                                 $isEnum = true;
                                 break;
                             }
                         }
                         if (!$isEnum) {
                             $columnNames[] = $columnName;
                         }
                     }
                 } catch (\ReflectionException $e) {
                     //@todo @MartinMatejka what here, return false or return null or log?
                 }
             }
             return $columnNames;
         }
     }
     return [];
 }
Beispiel #25
0
 /**
  * {@inheritdoc}
  */
 public function loadMetadataForClass($className, ClassMetadataInfo $metadata)
 {
     $reflClass = $metadata->getReflectionClass();
     $classAnnotations = $this->reader->getClassAnnotations($reflClass);
     // Compatibility with Doctrine Common 3.x
     if ($classAnnotations && is_int(key($classAnnotations))) {
         foreach ($classAnnotations as $annot) {
             $classAnnotations[get_class($annot)] = $annot;
         }
     }
     // Evaluate XmlEntity Annotations
     if (isset($classAnnotations['Doctrine\\OXM\\Mapping\\XmlEntity'])) {
         $entityAnnot = $classAnnotations['Doctrine\\OXM\\Mapping\\XmlEntity'];
     } elseif (isset($classAnnotations['Doctrine\\OXM\\Mapping\\XmlRootEntity'])) {
         $entityAnnot = $classAnnotations['Doctrine\\OXM\\Mapping\\XmlRootEntity'];
         $metadata->isRoot = true;
     } elseif (isset($classAnnotations['Doctrine\\OXM\\Mapping\\XmlMappedSuperclass'])) {
         $entityAnnot = $classAnnotations['Doctrine\\OXM\\Mapping\\XmlMappedSuperclass'];
         $metadata->isMappedSuperclass = true;
     } else {
         throw MappingException::classIsNotAValidXmlEntity($className);
     }
     $metadata->setName($reflClass->getName());
     if (isset($entityAnnot->xml)) {
         $metadata->setXmlName($entityAnnot->xml);
     } else {
         $metadata->setXmlName(Inflector::xmlize($reflClass->getShortName()));
     }
     if (isset($entityAnnot->repositoryClass)) {
         $metadata->setCustomRepositoryClass($entityAnnot->repositoryClass);
     }
     // Evaluate XmlChangeTrackingPolicy annotation
     if (isset($classAnnotations['Doctrine\\OXM\\Mapping\\XmlChangeTrackingPolicy'])) {
         $changeTrackingAnnot = $classAnnotations['Doctrine\\OXM\\Mapping\\XmlChangeTrackingPolicy'];
         $metadata->setChangeTrackingPolicy(constant('Doctrine\\OXM\\Mapping\\ClassMetadata::CHANGETRACKING_' . $changeTrackingAnnot->value));
     }
     // Check for XmlNamespace/XmlNamespaces annotations
     $xmlNamespaces = array();
     if (isset($classAnnotations['Doctrine\\OXM\\Mapping\\XmlNamespace'])) {
         $xmlNamespaceAnnot = $classAnnotations['Doctrine\\OXM\\Mapping\\XmlNamespace'];
         $xmlNamespaces[] = array('url' => $xmlNamespaceAnnot->url, 'prefix' => $xmlNamespaceAnnot->prefix);
     } else {
         if (isset($classAnnotations['Doctrine\\OXM\\Mapping\\XmlNamespaces'])) {
             $xmlNamespaceAnnot = $classAnnotations['Doctrine\\OXM\\Mapping\\XmlNamespaces'];
             foreach ($xmlNamespaceAnnot->value as $xmlNamespace) {
                 $xmlNamespaces[] = array('url' => $xmlNamespace->url, 'prefix' => $xmlNamespace->prefix);
             }
         }
     }
     $metadata->setXmlNamespaces($xmlNamespaces);
     foreach ($reflClass->getProperties() as $property) {
         if ($metadata->isMappedSuperclass && !$property->isPrivate() || $metadata->isInheritedField($property->name)) {
             continue;
         }
         $mapping = array();
         $mapping['fieldName'] = $property->getName();
         if ($idAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\OXM\\Mapping\\XmlId')) {
             $mapping['id'] = true;
         }
         if ($generatedValueAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\OXM\\Mapping\\XmlGeneratedValue')) {
             $metadata->setIdGeneratorType(constant('Doctrine\\OXM\\Mapping\\ClassMetadata::GENERATOR_TYPE_' . $generatedValueAnnot->strategy));
         }
         $referenceAnnot = $this->reader->getPropertyAnnotation($property, 'Doctrine\\OXM\\Mapping\\XmlReferences');
         if (isset($referenceAnnot->entityName)) {
             $mapping['references'] = $referenceAnnot->entityName;
         }
         // todo add Id Generator strategy support
         foreach ($this->reader->getPropertyAnnotations($property) as $fieldAnnot) {
             if ($fieldAnnot instanceof \Doctrine\OXM\Mapping\XmlField) {
                 if ($fieldAnnot->type == null) {
                     throw MappingException::propertyTypeIsRequired($className, $property->getName());
                 }
                 $mapping = array_merge($mapping, (array) $fieldAnnot);
                 $metadata->mapField($mapping);
             }
         }
     }
     // Evaluate @HasLifecycleCallbacks annotations
     if (isset($classAnnotations['Doctrine\\OXM\\Mapping\\HasLifecycleCallbacks'])) {
         foreach ($reflClass->getMethods() as $method) {
             // filter for the declaring class only, callbacks from parents will already be registered.
             if ($method->isPublic() && $method->getDeclaringClass()->getName() == $reflClass->name) {
                 $annotations = $this->reader->getMethodAnnotations($method);
                 // Compatibility with Doctrine Common 3.x
                 if ($annotations && is_int(key($annotations))) {
                     foreach ($annotations as $annot) {
                         $annotations[get_class($annot)] = $annot;
                     }
                 }
                 if (isset($annotations['Doctrine\\OXM\\Mapping\\PreMarshal'])) {
                     $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::preMarshal);
                 }
                 if (isset($annotations['Doctrine\\OXM\\Mapping\\PostMarshal'])) {
                     $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::postMarshal);
                 }
                 if (isset($annotations['Doctrine\\OXM\\Mapping\\PreUnmarshal'])) {
                     $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::preUnmarshal);
                 }
                 if (isset($annotations['Doctrine\\OXM\\Mapping\\PostUnmarshal'])) {
                     $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::postUnmarshal);
                 }
                 if (isset($annotations['Doctrine\\OXM\\Mapping\\PrePersist'])) {
                     $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::prePersist);
                 }
                 if (isset($annotations['Doctrine\\OXM\\Mapping\\PostPersist'])) {
                     $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::postPersist);
                 }
                 if (isset($annotations['Doctrine\\OXM\\Mapping\\PreUpdate'])) {
                     $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::preUpdate);
                 }
                 if (isset($annotations['Doctrine\\OXM\\Mapping\\PostUpdate'])) {
                     $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::postUpdate);
                 }
                 if (isset($annotations['Doctrine\\OXM\\Mapping\\PreRemove'])) {
                     $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::preRemove);
                 }
                 if (isset($annotations['Doctrine\\OXM\\Mapping\\PostRemove'])) {
                     $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::postRemove);
                 }
                 if (isset($annotations['Doctrine\\OXM\\Mapping\\PreLoad'])) {
                     $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::preLoad);
                 }
                 if (isset($annotations['Doctrine\\OXM\\Mapping\\PostLoad'])) {
                     $metadata->addLifecycleCallback($method->getName(), \Doctrine\OXM\Events::postLoad);
                 }
             }
         }
     }
 }
Beispiel #26
0
 /**
  * {@inheritdoc}
  */
 public function loadMetadataForClass($className, ClassMetadata $class)
 {
     $reflClass = $class->getReflectionClass();
     $classAnnotations = $this->reader->getClassAnnotations($reflClass);
     if (isset($classAnnotations['Doctrine\\ODM\\CouchDB\\Mapping\\Document'])) {
         $documentAnnot = $classAnnotations['Doctrine\\ODM\\CouchDB\\Mapping\\Document'];
         if ($documentAnnot->indexed) {
             $class->indexed = true;
         }
         $class->setCustomRepositoryClass($documentAnnot->repositoryClass);
     } elseif (isset($classAnnotations['Doctrine\\ODM\\CouchDB\\Mapping\\EmbeddedDocument'])) {
         $documentAnnot = $classAnnotations['Doctrine\\ODM\\CouchDB\\Mapping\\EmbeddedDocument'];
         $class->isEmbeddedDocument = true;
     } else {
         if (isset($classAnnotations['Doctrine\\ODM\\CouchDB\\Mapping\\MappedSuperclass'])) {
             $class->isMappedSuperclass = true;
         } else {
             throw MappingException::classIsNotAValidDocument($className);
         }
     }
     foreach ($reflClass->getProperties() as $property) {
         $mapping = array();
         $mapping['fieldName'] = $property->getName();
         foreach ($this->reader->getPropertyAnnotations($property) as $fieldAnnot) {
             if ($fieldAnnot instanceof \Doctrine\ODM\CouchDB\Mapping\Field) {
                 if ($fieldAnnot instanceof \Doctrine\ODM\CouchDB\Mapping\Version) {
                     $mapping['isVersionField'] = true;
                 }
                 $mapping = array_merge($mapping, (array) $fieldAnnot);
                 unset($mapping['value']);
                 $class->mapField($mapping);
             } else {
                 if ($fieldAnnot instanceof \Doctrine\ODM\CouchDB\Mapping\ReferenceOne) {
                     $cascade = 0;
                     foreach ($fieldAnnot->cascade as $cascadeMode) {
                         $cascade += constant('Doctrine\\ODM\\CouchDB\\Mapping\\ClassMetadata::CASCADE_' . strtoupper($cascadeMode));
                     }
                     $fieldAnnot->cascade = $cascade;
                     $mapping = array_merge($mapping, (array) $fieldAnnot);
                     unset($mapping['value']);
                     $class->mapManyToOne($mapping);
                 } else {
                     if ($fieldAnnot instanceof \Doctrine\ODM\CouchDB\Mapping\ReferenceMany) {
                         $cascade = 0;
                         foreach ($fieldAnnot->cascade as $cascadeMode) {
                             $cascade += constant('Doctrine\\ODM\\CouchDB\\Mapping\\ClassMetadata::CASCADE_' . strtoupper($cascadeMode));
                         }
                         $fieldAnnot->cascade = $cascade;
                         $mapping = array_merge($mapping, (array) $fieldAnnot);
                         unset($mapping['value']);
                         $class->mapManyToMany($mapping);
                     } else {
                         if ($fieldAnnot instanceof \Doctrine\ODM\CouchDB\Mapping\Attachments) {
                             $class->mapAttachments($mapping['fieldName']);
                         } else {
                             if ($fieldAnnot instanceof \Doctrine\ODM\CouchDB\Mapping\EmbedOne || $fieldAnnot instanceof \Doctrine\ODM\CouchDB\Mapping\EmbedMany) {
                                 $mapping = array_merge($mapping, (array) $fieldAnnot);
                                 unset($mapping['value']);
                                 $class->mapEmbedded($mapping);
                             }
                         }
                     }
                 }
             }
         }
     }
 }
 protected function createFixtureAnnotation($entity, &$fieldMappings)
 {
     $anotationReader = new AnnotationReader();
     foreach ($fieldMappings as $fieldName => $fieldValue) {
         $propertyAnnotations = $anotationReader->getPropertyAnnotations(new \ReflectionProperty($entity, $fieldName));
         foreach ($propertyAnnotations as $annotation) {
             if ($annotation instanceof FixtureDataType) {
                 $fieldMappings[$fieldName]["fixtureDataType"] = $annotation->value;
             }
         }
     }
 }
 /**
  * {@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);
                 }
             }
         }
     }
 }
Beispiel #29
0
    {
        return $this->getProperty();
    }
}
// Lets parse the annotations
use Doctrine\Common\Annotations\AnnotationReader;
$annotationReader = new AnnotationReader();
//Get class annotation
$reflectionClass = new ReflectionClass('AnnotationDemo');
$classAnnotations = $annotationReader->getClassAnnotations($reflectionClass);
echo "<pre>";
echo "========= CLASS ANNOTATIONS =========" . PHP_EOL;
var_dump($classAnnotations);
// You can also pass ReflectionObject to the same method to read annotations in runtime
$annotationDemoObject = new AnnotationDemo();
$reflectionObject = new ReflectionObject($annotationDemoObject);
$objectAnnotations = $annotationReader->getClassAnnotations($reflectionObject);
echo "========= OBJECT ANNOTATIONS =========" . PHP_EOL;
var_dump($objectAnnotations);
//Property Annotations
$reflectionProperty = new ReflectionProperty('AnnotationDemo', 'property');
$propertyAnnotations = $annotationReader->getPropertyAnnotations($reflectionProperty);
echo "=========   PROPERTY ANNOTATIONS =========" . PHP_EOL;
var_dump($propertyAnnotations);
var_dump($reflectionProperty);
var_dump($annotationReader->getPropertyAnnotation($reflectionProperty, 'var'));
// Method Annotations
$reflectionMethod = new ReflectionMethod('AnnotationDemo', 'getProperty');
$methodAnnotations = $annotationReader->getMethodAnnotations($reflectionMethod);
echo "=========   Method ANNOTATIONS =========" . PHP_EOL;
var_dump($methodAnnotations);
 /**
  * @param \ReflectionProperty $property
  * @param $structure
  * @throws \Exception
  * @return array
  */
 protected function buildPropertyAnnotation($property, &$structure)
 {
     $field = array('name' => $this->convertNaming($property->getName()), 'type' => 'string');
     $association = array();
     $validators = array();
     $skipValidator = false;
     $saveField = false;
     $fieldIsId = false;
     $useMapping = false;
     $annotations = $this->annoReader->getPropertyAnnotations($property);
     foreach ($annotations as $annotation) {
         if (get_class($annotation) === 'Tpg\\ExtjsBundle\\Annotation\\UseMapping') {
             $useMapping = true;
             break;
         }
     }
     foreach ($annotations as $annotation) {
         $className = get_class($annotation);
         /** Get Constraints from Symfony Validator */
         if (strpos(get_class($annotation), 'Symfony\\Component\\Validator\\Constraints') === 0) {
             $validators[] = array_merge(array('field' => $this->convertNaming($property->getName())), $this->getValidator(substr($className, 40), $annotation));
         }
         switch (get_class($annotation)) {
             case 'Tpg\\ExtjsBundle\\Annotation\\Model\\Field':
                 $field['type'] = $annotation->type;
                 break;
             case 'Tpg\\ExtjsBundle\\Annotation\\DefaultValue':
                 $field['defaultValue'] = $annotation->value;
                 break;
             case 'Doctrine\\ORM\\Mapping\\Id':
             case 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\Id':
                 $field['useNull'] = true;
                 $field['persist'] = false;
                 $skipValidator = true;
                 $fieldIsId = true;
                 break;
             case 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\Timestamp':
             case 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\Date':
                 $field['type'] = "date";
                 break;
             case 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\Float':
                 $field['type'] = "float";
                 break;
             case 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\Boolean':
                 $field['type'] = "boolean";
                 break;
             case 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\Hash':
                 $field['type'] = "auto";
                 break;
             case 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\Int':
             case 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\Increment':
                 $field['type'] = "int";
                 break;
             case 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\String':
                 $field['type'] = "string";
                 break;
             case 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\Field':
                 $field['type'] = $this->getColumnType($annotation->type);
                 break;
             case 'Doctrine\\ORM\\Mapping\\Column':
                 $field['type'] = $this->getColumnType($annotation->type);
                 if ($field['type'] === "date") {
                     $field['dateFormat'] = \DateTime::ISO8601;
                 }
                 $validators[] = array('type' => 'presence', 'field' => $this->convertNaming($property->getName()));
                 if ($annotation->nullable) {
                     $field['useNull'] = true;
                 }
                 foreach ($annotations as $annotationToSearchUseNull) {
                     if (get_class($annotationToSearchUseNull) == 'Tpg\\ExtjsBundle\\Annotation\\UseNull') {
                         $field['useNull'] = $annotationToSearchUseNull->value;
                     }
                 }
                 break;
             case 'JMS\\Serializer\\Annotation\\SerializedName':
                 $field['name'] = $annotation->name;
                 break;
             case 'JMS\\Serializer\\Annotation\\Type':
                 if (stripos($annotation->name, "DateTime") === 0) {
                     $type = $annotation->name;
                     if ($type === "DateTime") {
                         $field['dateFormat'] = \DateTime::ISO8601;
                     } else {
                         $format = explode(',', substr($type, stripos($type, '<') + 2, -2));
                         $field['dateFormat'] = $format[0];
                     }
                 }
                 break;
             case 'Doctrine\\ORM\\Mapping\\OneToOne':
                 $association['type'] = substr(get_class($annotation), 21);
                 $association['name'] = $property->getName();
                 $association['model'] = $this->getModelName($annotation->targetEntity);
                 $association['entity'] = $annotation->targetEntity;
                 if (!isset($association['key']) || empty($association['key'])) {
                     $association['key'] = $this->tryToGetJoinColumnNameOfMappedBy($annotation);
                 }
                 break;
             case 'Doctrine\\ORM\\Mapping\\OneToMany':
                 $association['type'] = substr(get_class($annotation), 21);
                 $association['name'] = $property->getName();
                 $association['model'] = $this->getModelName($annotation->targetEntity);
                 $association['entity'] = $annotation->targetEntity;
                 $association['key'] = $this->tryToGetJoinColumnNameOfMappedBy($annotation);
                 break;
             case 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\EmbedMany':
             case 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\EmbedOne':
             case 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\ReferenceMany':
             case 'Doctrine\\ODM\\MongoDB\\Mapping\\Annotations\\ReferenceOne':
                 if ($annotation->targetDocument) {
                     $association['type'] = substr(get_class($annotation), 41);
                     $association['name'] = $property->getName();
                     $association['model'] = $this->getModelName($annotation->targetDocument);
                     $association['entity'] = $annotation->targetDocument;
                 } else {
                     $field['type'] = "auto";
                 }
                 break;
             case 'Doctrine\\ORM\\Mapping\\ManyToOne':
                 $association['type'] = substr(get_class($annotation), 21);
                 $association['name'] = $property->getName();
                 $association['model'] = $this->getModelName($annotation->targetEntity);
                 $association['entity'] = $annotation->targetEntity;
                 break;
             case 'Doctrine\\ORM\\Mapping\\ManyToMany':
                 $association['type'] = 'ManyToMany';
                 $association['name'] = $property->getName();
                 $association['model'] = $this->getModelName($annotation->targetEntity);
                 $association['entity'] = $annotation->targetEntity;
                 break;
             case 'Doctrine\\ORM\\Mapping\\JoinColumns':
                 if (count($annotation->value) > 1) {
                     throw new \Exception('Multiple foreign key is not supported');
                 }
                 $saveField = true;
                 $field['name'] = $this->convertNaming($annotation->value[0]->name);
                 $field['type'] = $this->getEntityColumnType($association['entity'], $annotation->value[0]->referencedColumnName);
                 $field['useNull'] = true;
                 $association['key'] = $this->convertNaming($annotation->value[0]->name);
                 break;
             case 'Doctrine\\ORM\\Mapping\\JoinColumn':
                 $saveField = true;
                 $field['name'] = $this->convertNaming($annotation->name);
                 $field['type'] = $this->getEntityColumnType($association['entity'], $annotation->referencedColumnName);
                 $field['useNull'] = true;
                 $association['key'] = $this->convertNaming($annotation->name);
                 if ($useMapping) {
                     $field['mapping'] = $property->getName() . '.' . $annotation->referencedColumnName;
                 }
                 break;
         }
     }
     if ($fieldIsId) {
         $structure['idProperty'] = $field['name'];
     }
     /** Add the ability to override field parameter */
     if (isset($this->fieldsParams[$field['type']])) {
         $field = array_merge($field, $this->fieldsParams[$field['type']]);
     }
     if (!empty($association)) {
         if ($association['model'] === null) {
             /** Related model is not available, skip this field. */
             return array();
         }
         $structure['associations'][] = $association;
     }
     if ($saveField || empty($association)) {
         $structure['fields'][$field['name']] = $field;
     }
     if (!empty($validators) && !$skipValidator) {
         $structure['validators'] = array_merge($structure['validators'], $validators);
     }
     return $field;
 }