/**
  * @return TranslatableRepositoryInterface
  * @throws Exception\AnnotationException
  */
 public function getTranslatableRepository()
 {
     $repository = $this->objectManager->getRepository($this->classMetadata->getName());
     if (!$repository instanceof TranslatableRepositoryInterface) {
         throw new Exception\AnnotationException(sprintf('Entity "%s" has "%s" as its "repositoryClass" which does not implement \\FSi\\DoctrineExtensions\\Translatable\\Model\\TranslatableRepositoryInterface', $this->classMetadata->getName(), get_class($repository)));
     }
     return $repository;
 }
예제 #2
0
 /**
  * Insert one new record using the Entity class.
  */
 public function execute($manager, $insertedEntities)
 {
     $class = $this->class->getName();
     $obj = new $class();
     foreach ($this->columnFormatters as $field => $format) {
         if (null !== $format) {
             $value = is_callable($format) ? $format($insertedEntities, $obj) : $format;
             $this->class->reflFields[$field]->setValue($obj, $value);
         }
     }
     $manager->persist($obj);
     return $obj;
 }
예제 #3
0
파일: ORM.php 프로젝트: coolms/doctrine
 /**
  * {@inheritDoc}
  */
 public function mapHierarchy(ClassMetadata $meta)
 {
     if ($meta->isMappedSuperclass || !$meta->isRootEntity()) {
         return;
     }
     $rc = $meta->getReflectionClass();
     if ($rc->hasProperty('parent') && !$meta->hasAssociation('parent')) {
         $meta->mapManyToOne(['targetEntity' => $meta->getName(), 'fieldName' => 'parent', 'inversedBy' => 'children', 'cascade' => ['persist']]);
     }
     if ($rc->hasProperty('children') && !$meta->hasAssociation('children')) {
         $meta->mapOneToMany(['targetEntity' => $meta->getName(), 'fieldName' => 'children', 'mappedBy' => 'parent', 'cascade' => ['persist', 'remove'], 'fetch' => 'EXTRA_LAZY']);
     }
 }
예제 #4
0
 /**
  * Creates a new entity choice list.
  *
  * @param ObjectManager         $manager      An EntityManager instance
  * @param string                $class        The class name
  * @param string                $labelPath    The property path used for the label
  * @param EntityLoaderInterface $entityLoader An optional query builder
  * @param array                 $entities     An array of choices
  * @param string                $groupPath    A property path pointing to the property used
  *                                            to group the choices. Only allowed if
  *                                            the choices are given as flat array.
  */
 public function __construct(ObjectManager $manager, $class, $labelPath = null, EntityLoaderInterface $entityLoader = null, $entities = null, $groupPath = null)
 {
     $this->em = $manager;
     $this->entityLoader = $entityLoader;
     $this->classMetadata = $manager->getClassMetadata($class);
     $this->class = $this->classMetadata->getName();
     $this->identifier = $this->classMetadata->getIdentifierFieldNames();
     $this->loaded = is_array($entities) || $entities instanceof \Traversable;
     if (!$this->loaded) {
         // Make sure the constraints of the parent constructor are
         // fulfilled
         $entities = array();
     }
     parent::__construct($entities, $labelPath, array(), $groupPath);
 }
예제 #5
0
 /**
  * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
  * @param \Doctrine\Common\Persistence\ManagerRegistry $doctrine
  * @param \Doctrine\Common\Persistence\ObjectManager $manager
  * @param \Behat\Behat\Hook\Scope\ScenarioScope $event
  * @param \Behat\Gherkin\Node\FeatureNode $feature
  * @param \Behat\Gherkin\Node\ScenarioNode $scenario
  * @param \Knp\FriendlyContexts\Alice\Loader\Yaml $loader
  * @param \Doctrine\Common\Persistence\Mapping\ClassMetadataFactory $metadataFactory
  * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $userMetadata
  * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $placeMetadata
  * @param \Doctrine\Common\Persistence\Mapping\ClassMetadata $productMetadata
  */
 function let($container, $doctrine, $manager, $event, $loader, $feature, $scenario, $metadataFactory, $userMetadata, $placeMetadata, $productMetadata)
 {
     $doctrine->getManager()->willReturn($manager);
     $feature->getTags()->willReturn(['alice(Place)', 'admin']);
     $scenario->getTags()->willReturn(['alice(User)']);
     $event->getFeature()->willReturn($feature);
     $event->getScenario()->willReturn($scenario);
     $loader->load('user.yml')->willReturn([]);
     $loader->load('product.yml')->willReturn([]);
     $loader->load('place.yml')->willReturn([]);
     $loader->getCache()->willReturn([]);
     $loader->clearCache()->willReturn(null);
     $fixtures = ['User' => 'user.yml', 'Product' => 'product.yml', 'Place' => 'place.yml'];
     $config = ['alice' => ['fixtures' => $fixtures, 'dependencies' => []]];
     $container->has(Argument::any())->willReturn(true);
     $container->hasParameter(Argument::any())->willReturn(true);
     $container->get('friendly.alice.loader.yaml')->willReturn($loader);
     $container->get('doctrine')->willReturn($doctrine);
     $container->getParameter('friendly.alice.fixtures')->willReturn($fixtures);
     $container->getParameter('friendly.alice.dependencies')->willReturn([]);
     $manager->getMetadataFactory()->willReturn($metadataFactory);
     $metadataFactory->getAllMetadata()->willReturn([$userMetadata, $placeMetadata, $productMetadata]);
     $userMetadata->getName()->willReturn('User');
     $placeMetadata->getName()->willReturn('Place');
     $productMetadata->getName()->willReturn('Product');
     $this->initialize($config, $container);
 }
예제 #6
0
 /**
  * Creates a new entity choice list.
  *
  * @param ObjectManager         $manager      An EntityManager instance
  * @param string                $class        The class name
  * @param string                $labelPath    The property path used for the label
  * @param EntityLoaderInterface $entityLoader An optional query builder
  * @param array                 $entities     An array of choices
  * @param string                $groupPath    A property path pointing to the property used
  *                                            to group the choices. Only allowed if
  *                                            the choices are given as flat array.
  */
 public function __construct(ObjectManager $manager, $class, $labelPath = null, EntityLoaderInterface $entityLoader = null, $entities = null, $groupPath = null)
 {
     $this->em = $manager;
     $this->entityLoader = $entityLoader;
     $this->classMetadata = $manager->getClassMetadata($class);
     $this->class = $this->classMetadata->getName();
     $this->loaded = is_array($entities) || $entities instanceof \Traversable;
     $identifier = $this->classMetadata->getIdentifierFieldNames();
     if (1 === count($identifier)) {
         $this->idField = $identifier[0];
         $this->idAsValue = true;
         if ('integer' === $this->classMetadata->getTypeOfField($this->idField)) {
             $this->idAsIndex = true;
         }
     }
     if (!$this->loaded) {
         // Make sure the constraints of the parent constructor are
         // fulfilled
         $entities = array();
     }
     if (version_compare(Kernel::VERSION, '2.1') <= 0) {
         $this->labelPath = $labelPath ? new DepPropertyPath($labelPath) : null;
         $this->groupPath = $groupPath ? new DepPropertyPath($groupPath) : null;
     } else {
         $this->labelPath = $labelPath ? new PropertyPath($labelPath) : null;
         $this->groupPath = $groupPath ? new PropertyPath($groupPath) : null;
     }
     parent::__construct($entities, array(), array());
 }
 /**
  * {@inheritdoc}
  */
 public function getTransformerInfo(ColumnInfoInterface $columnInfo, ClassMetadata $metadata)
 {
     if ($this->class !== $metadata->getName() || !$columnInfo->getAttribute() || $this->backendType !== $columnInfo->getAttribute()->getBackendType()) {
         return;
     }
     return array($this->transformer, array());
 }
예제 #8
0
 /**
  * @param ClassMetadata $metadata
  */
 private function mapManyToMany(ClassMetadata $metadata)
 {
     foreach ($this->variables as $variable => $class) {
         if ($class['variant']['model'] !== $metadata->getName()) {
             continue;
         }
         $metadata->mapManyToOne(array('fieldName' => 'object', 'targetEntity' => $class['variable'], 'inversedBy' => 'variants', 'joinColumns' => array(array('name' => $variable . '_id', 'referencedColumnName' => 'id', 'nullable' => false, 'onDelete' => 'CASCADE'))));
         $metadata->mapManyToMany(array('fieldName' => 'options', 'type' => ClassMetadataInfo::MANY_TO_MANY, 'targetEntity' => $class['option_value']['model'], 'joinTable' => array('name' => sprintf('sylius_%s_variant_option_value', $variable), 'joinColumns' => array(array('name' => 'variant_id', 'referencedColumnName' => 'id', 'unique' => false, 'nullable' => false, 'onDelete' => 'CASCADE')), 'inverseJoinColumns' => array(array('name' => 'option_value_id', 'referencedColumnName' => 'id', 'unique' => false, 'nullable' => false, 'onDelete' => 'CASCADE')))));
     }
 }
예제 #9
0
 /**
  * Returns the first (and only) value of the identifier fields of an entity.
  *
  * Doctrine must know about this entity, that is, the entity must already
  * be persisted or added to the identity map before. Otherwise an
  * exception is thrown.
  *
  * @param object $entity The entity for which to get the identifier
  *
  * @return array The identifier values
  *
  * @throws RuntimeException If the entity does not exist in Doctrine's identity map
  */
 private function getSingleIdentifierValue($entity)
 {
     $value = current($this->getIdentifierValues($entity));
     if ($this->idClassMetadata) {
         $class = $this->idClassMetadata->getName();
         if ($value instanceof $class) {
             $value = current($this->idClassMetadata->getIdentifierValues($value));
         }
     }
     return $value;
 }
 /**
  * Note: The result of this method cannot be cached, as the target table alias might change for different query scenarios
  *
  * @param ClassMetadata $targetEntity
  * @param string $targetTableAlias
  * @return string
  */
 public function getSqlConstraint(ClassMetadata $targetEntity, $targetTableAlias)
 {
     $this->evaluateMatcher();
     /** @var EntityManager $entityManager */
     $entityManager = $this->objectManager->get(ObjectManager::class);
     $sqlFilter = new SqlFilter($entityManager);
     if (!$this->matchesEntityType($targetEntity->getName())) {
         return null;
     }
     return $this->conditionGenerator->getSql($sqlFilter, $targetEntity, $targetTableAlias);
 }
 /**
  * {@inheritdoc}
  */
 public function getTransformerInfo(ColumnInfoInterface $columnInfo, ClassMetadata $metadata)
 {
     if ($this->class !== $metadata->getName()) {
         return;
     }
     foreach ($this->regexps as $regexp) {
         if (preg_match($regexp, $columnInfo->getLabel())) {
             return array($this->transformer, $this->options);
         }
     }
     return;
 }
 /**
  * @param $entity
  * @param ClassMetadata $classMetadata
  * @return array
  */
 private function generateConstructor($entity, $classMetadata)
 {
     $fields = [];
     $fields[] = sprintf("\t\tfunction %s(data) {\n", $entity);
     $fields[] = "\t\t\tif (angular.isDefined(data)) {\n";
     foreach ($classMetadata->getFieldNames() as $item) {
         $item = $this->handleField($item, $classMetadata->getName(), true);
         if ($item !== null) {
             $fields[] = $item;
         }
     }
     $fields[] = "\t\t\t} else {\n";
     foreach ($classMetadata->getFieldNames() as $item) {
         $item = $this->handleField($item, $classMetadata->getName(), false);
         if ($item !== null) {
             $fields[] = $item;
         }
     }
     $fields[] = "\t\t\t}\n";
     $fields[] = "\t\t}\n\n";
     return $fields;
 }
예제 #13
0
 /**
  * {@inheritdoc}
  */
 public function readMetadata(ClassMetadata $doctrineMeta, array &$meta)
 {
     if (!isset($meta['user'])) {
         $meta['user'] = [];
     }
     foreach ($doctrineMeta->getReflectionClass()->getProperties() as $property) {
         $annotation = $this->reader->getPropertyAnnotation($property, User::ANNOTATION);
         if (!$annotation instanceof User) {
             continue;
         }
         if (!empty($meta['user'])) {
             if ($meta['user']['property'] === $property->getName()) {
                 continue;
             }
             throw $this->createPropertyAnnotationInvalidException(User::ANNOTATION, $doctrineMeta->getName(), $property->getName(), sprintf('property "%s" is already annotated with this annotation', $meta['user']['property']));
         }
         if (!$doctrineMeta->hasAssociation($property->getName())) {
             throw $this->createPropertyAnnotationInvalidException(User::ANNOTATION, $doctrineMeta->getName(), $property->getName(), 'property must be mapped association');
         }
         $meta['user'] = ['property' => $property->getName(), 'roles' => $annotation->roles];
     }
 }
 /**
  * {@inheritdoc}
  */
 public function getTransformerInfo(ColumnInfoInterface $columnInfo, ClassMetadata $metadata)
 {
     if ($this->valueClass != $metadata->getName() || !in_array($columnInfo->getPropertyPath(), array('option', 'options'))) {
         return;
     }
     $info = parent::getTransformerInfo($columnInfo, $metadata);
     if ($info) {
         list($transformer, $options) = $info;
         $options['reference_prefix'] = $columnInfo->getName();
         return array($transformer, $options);
     }
     return null;
 }
 /**
  * {@inheritdoc}
  */
 public function readMetadata(ClassMetadata $doctrineMeta, array &$meta)
 {
     if (!isset($meta['customObjects'])) {
         $meta['customObjects'] = [];
     }
     foreach ($doctrineMeta->getReflectionClass()->getProperties() as $reflectionProperty) {
         $customObjectAnnotation = $this->reader->getPropertyAnnotation($reflectionProperty, CustomObject::ANNOTATION);
         if (!$customObjectAnnotation instanceof CustomObject) {
             continue;
         }
         $this->validateAnnotation($customObjectAnnotation, $doctrineMeta->getName(), $reflectionProperty->getName());
         $meta['customObjects'][$reflectionProperty->getName()] = get_object_vars($customObjectAnnotation);
     }
 }
예제 #16
0
 /**
  * {@inheritdoc}
  */
 public function readMetadata(ClassMetadata $doctrineMeta, array &$meta)
 {
     if (!isset($meta['updated_at'])) {
         $meta['updatedAt'] = null;
     }
     foreach ($doctrineMeta->getReflectionClass()->getProperties() as $property) {
         $annotation = $this->reader->getPropertyAnnotation($property, UpdatedAt::ANNOTATION);
         if (!$annotation instanceof UpdatedAt) {
             continue;
         }
         if (!empty($meta['updatedAt'])) {
             if ($meta['updatedAt'] === $property->getName()) {
                 continue;
             }
             throw $this->createPropertyAnnotationInvalidException(UpdatedAt::ANNOTATION, $doctrineMeta->getName(), $property->getName(), sprintf('property "%s" is already annotated with this annotation', $meta['updatedAt']));
         }
         $fieldType = $doctrineMeta->getTypeOfField($property->getName());
         if (Type::DATETIME !== $fieldType) {
             throw $this->createPropertyAnnotationInvalidException(UpdatedAt::ANNOTATION, $doctrineMeta->getName(), $property->getName(), sprintf('field must be of type "%s", "%s" provided', Type::DATETIME, $fieldType));
         }
         $meta['updatedAt'] = $property->getName();
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function prepareData(ClassMetadata $metadata, array $data)
 {
     $writer = new Writer();
     $writer->writeln(sprintf('$fixtures[\'%s\'] = array(', $metadata->getName()));
     foreach ($data as $key => $values) {
         $writer->indent()->writeln(sprintf("'%s' => array(", $key))->indent();
         $arrayValues = array();
         foreach ($values as $k => $value) {
             $arrayValues[] = sprintf("'%s' => %s", $k, $this->convertValue($value));
         }
         $writer->writeln(implode(",\n", $arrayValues))->outdent()->writeln("),")->outdent();
     }
     $writer->writeln(');');
     return $writer->getContent();
 }
 /**
  * {@inheritdoc}
  */
 public function readMetadata(ClassMetadata $doctrineMeta, array &$meta)
 {
     if (!isset($meta['transliteratable'])) {
         $meta['transliteratable'] = [];
     }
     foreach ($doctrineMeta->getReflectionClass()->getProperties() as $reflectionProperty) {
         $transliteratableAnnotation = $this->reader->getPropertyAnnotation($reflectionProperty, Transliteratable::ANNOTATION);
         if ($transliteratableAnnotation instanceof Transliteratable) {
             if (!$doctrineMeta->hasField($reflectionProperty->getName())) {
                 throw $this->createPropertyAnnotationInvalidException(Transliteratable::ANNOTATION, $doctrineMeta->getName(), $reflectionProperty->getName(), 'property must be mapped field');
             }
             $meta['transliteratable'][$reflectionProperty->getName()] = get_object_vars($transliteratableAnnotation);
         }
     }
 }
 protected function dumpSerializationFile(ClassMetadata $metadata, OutputInterface $output, $force = false)
 {
     $targetPath = $this->resolvePath($metadata->getReflectionClass());
     $config = [$metadata->getName() => ['fields' => $this->prepareMetadataFields($metadata), 'associations' => $this->prepareMetadataAssociations($metadata), 'callbacks' => []]];
     $message = 'Dumped serialization config for <info>%s</info>';
     if ($force) {
         $this->filesystem->dumpFile($targetPath, Yaml::dump($config, 6));
     } else {
         if (false === $this->filesystem->exists($targetPath)) {
             $this->filesystem->dumpFile($targetPath, Yaml::dump($config, 6));
         } else {
             $message = 'Skipped dumping serialization config for <info>%s</info>';
         }
     }
     $output->write(sprintf($message, $metadata->getName()), true);
 }
예제 #20
0
 /**
  * {@inheritdoc}
  */
 public function readMetadata(ClassMetadata $doctrineMeta, array &$meta)
 {
     if (!isset($meta['slugs'])) {
         $meta['slugs'] = [];
     }
     foreach ($doctrineMeta->getReflectionClass()->getProperties() as $reflectionProperty) {
         $slugAnnotation = $this->reader->getPropertyAnnotation($reflectionProperty, Slug::ANNOTATION);
         if ($slugAnnotation instanceof Slug) {
             $this->validateAnnotation($slugAnnotation, $doctrineMeta->getName(), $reflectionProperty->getName());
             $meta['slugs'][$reflectionProperty->getName()] = get_object_vars($slugAnnotation);
             if (!empty($slugAnnotation->prefixProvider)) {
                 $meta['slugs'][$reflectionProperty->getName()]['prefixProvider'] = get_object_vars($slugAnnotation->prefixProvider);
             }
         }
     }
 }
 /**
  * Adds an object to a collection.
  *
  * @param string $field
  * @param array  $args
  *
  * @return void
  *
  * @throws \BadMethodCallException
  * @throws \InvalidArgumentException
  */
 private function add($field, $args)
 {
     $this->initializeDoctrine();
     if ($this->cm->hasAssociation($field) && $this->cm->isCollectionValuedAssociation($field)) {
         $targetClass = $this->cm->getAssociationTargetClass($field);
         if (!$args[0] instanceof $targetClass) {
             throw new \InvalidArgumentException("Expected persistent object of type '" . $targetClass . "'");
         }
         if (!$this->{$field} instanceof Collection) {
             $this->{$field} = new ArrayCollection($this->{$field} ?: array());
         }
         $this->{$field}->add($args[0]);
         $this->completeOwningSide($field, $targetClass, $args[0]);
     } else {
         throw new \BadMethodCallException("There is no method add" . $field . "() on " . $this->cm->getName());
     }
 }
예제 #22
0
 /**
  * Builds the entity
  *
  * @param ClassMetadata $metadata
  * @param array         $data
  *
  * @return object
  * @throws \Exception
  */
 private function buildEntity(ClassMetadata $metadata, $data)
 {
     $class = $metadata->getName();
     $entity = new $class();
     foreach ($data as $propertyPath => $value) {
         // Field
         if ($metadata->hasField($propertyPath)) {
             $builtValue = $this->buildFieldValue($metadata, $propertyPath, $value);
             // Association
         } elseif ($metadata->hasAssociation($propertyPath)) {
             $builtValue = $this->buildAssociationValue($metadata, $propertyPath, $value);
         } else {
             throw new \Exception("Unexpected property path '{$propertyPath}'.");
         }
         $this->accessor->setValue($entity, $propertyPath, $builtValue);
     }
     return $entity;
 }
예제 #23
0
 /**
  * Magic methods.
  *
  * @param string $method
  * @param array  $args
  *
  * @return mixed
  *
  * @throws \BadMethodCallException
  */
 public function __call($method, $args)
 {
     $command = substr($method, 0, 3);
     $field = lcfirst(substr($method, 3));
     if ($command == "set") {
         $this->set($field, $args);
     } else {
         if ($command == "get") {
             return $this->get($field);
         } else {
             if ($command == "add") {
                 $this->add($field, $args);
             } else {
                 throw new \BadMethodCallException("There is no method " . $method . " on " . $this->cm->getName());
             }
         }
     }
 }
 protected function getModels(ClassMetadata $metadata)
 {
     /* @var $metadata \Doctrine\ORM\Mapping\ClassMetadataInfo */
     if ($metadata->isMappedSuperclass) {
         return array();
     }
     if (!empty($metadata->subClasses)) {
         $reflection = new \ReflectionClass($metadata->name);
         if ($reflection->isAbstract()) {
             return array();
         }
     }
     $models = $this->getManager()->getRepository($metadata->getName())->findAll();
     foreach ($models as $key => $model) {
         if (get_class($model) !== $metadata->name) {
             unset($models[$key]);
         }
     }
     return $models;
 }
 /**
  * {@inheritdoc}
  */
 public function configure(ClassMetadata $metadata, array $mappingOverrides, $configuration)
 {
     if (!$metadata instanceof ClassMetadataInfo) {
         throw new \InvalidArgumentException('This configurator only handles "Doctrine\\ORM\\Mapping\\ClassMetadataInfo".');
     }
     if (!$configuration instanceof Configuration) {
         throw new \InvalidArgumentException('This configurator only handles "Doctrine\\ORM\\Configuration".');
     }
     foreach ($mappingOverrides as $override) {
         if ($override['override'] === $metadata->getName()) {
             $metadata->isMappedSuperclass = false;
             $this->setAssociationMappings($metadata, $configuration);
         }
         if ($override['original'] === $metadata->getName()) {
             $metadata->isMappedSuperclass = true;
             $this->unsetAssociationMappings($metadata);
         }
     }
     return $metadata;
 }
예제 #26
0
 /**
  * Constructor.
  *
  * @param ObjectManager         $manager           An EntityManager instance
  * @param string                $class        The class name
  * @param string                $property     The property name
  * @param EntityLoaderInterface $entityLoader An optional query builder
  * @param array|\Closure        $choices      An array of choices or a function returning an array
  * @param string                $groupBy
  */
 public function __construct(ObjectManager $manager, $class, $property = null, EntityLoaderInterface $entityLoader = null, $choices = null, $groupBy = null)
 {
     $this->em = $manager;
     $this->class = $class;
     $this->entityLoader = $entityLoader;
     $this->classMetadata = $manager->getClassMetadata($class);
     $this->identifier = $this->classMetadata->getIdentifierFieldNames();
     $this->groupBy = $groupBy;
     // The property option defines, which property (path) is used for
     // displaying entities as strings
     if ($property) {
         $this->propertyPath = new PropertyPath($property);
     } elseif (!method_exists($this->classMetadata->getName(), '__toString')) {
         // Otherwise expect a __toString() method in the entity
         throw new FormException('Entities passed to the choice field must have a "__toString()" method defined (or you can also override the "property" option).');
     }
     if (!is_array($choices) && !$choices instanceof \Closure && !is_null($choices)) {
         throw new UnexpectedTypeException($choices, 'array or \\Closure or null');
     }
     $this->choices = $choices;
 }
 /**
  * Load the metadata for the specified class into the provided container.
  *
  * @param string        $className
  * @param ClassMetadata $metadata
  */
 public function loadMetadataForClass($className, ClassMetadata $metadata)
 {
     $metadataFactory = $this->getObjectManager()->getMetadataFactory();
     $builder = new ClassMetadataBuilder($metadata);
     $identifiers = array();
     // Get the entity this entity audits
     $metadataClassName = $metadata->getName();
     $metadataClass = new $metadataClassName();
     $auditedClassMetadata = $metadataFactory->getMetadataFor($metadataClass->getAuditedEntityClass());
     $builder->addManyToOne('revisionEntity', 'ZF\\Doctrine\\Audit\\Entity\\RevisionEntity');
     $identifiers[] = 'revisionEntity';
     // Add fields from target to audit entity
     foreach ($auditedClassMetadata->getFieldNames() as $fieldName) {
         $builder->addField($fieldName, $auditedClassMetadata->getTypeOfField($fieldName), array('columnName' => $auditedClassMetadata->getColumnName($fieldName), 'nullable' => true, 'quoted' => true));
         if ($auditedClassMetadata->isIdentifier($fieldName)) {
             $identifiers[] = $fieldName;
         }
     }
     foreach ($auditedClassMetadata->getAssociationMappings() as $mapping) {
         if (!$mapping['isOwningSide'] || isset($mapping['joinTable'])) {
             continue;
         }
         if (isset($mapping['joinTableColumns'])) {
             foreach ($mapping['joinTableColumns'] as $field) {
                 // FIXME:  set data type correct for mapping info
                 $builder->addField($mapping['fieldName'], 'bigint', array('nullable' => true, 'columnName' => $field));
             }
         } elseif (isset($mapping['joinColumnFieldNames'])) {
             foreach ($mapping['joinColumnFieldNames'] as $field) {
                 // FIXME:  set data type correct for mapping info
                 $builder->addField($mapping['fieldName'], 'bigint', array('nullable' => true, 'columnName' => $field));
             }
         } else {
             throw new Exception('Unhandled association mapping');
         }
     }
     $metadata->setTableName($this->getAuditOptions()['audit_table_name_prefix'] . $auditedClassMetadata->getTableName() . $this->getAuditOptions()['audit_table_name_suffix']);
     $metadata->setIdentifier($identifiers);
     return;
 }
 /**
  * {@inheritdoc}
  */
 public function readMetadata(ClassMetadata $doctrineMeta, array &$meta)
 {
     if (!isset($meta['newObjectFlag'])) {
         $meta['newObjectFlag'] = null;
     }
     foreach ($doctrineMeta->getReflectionClass()->getProperties() as $reflectionProperty) {
         if (null === $this->reader->getPropertyAnnotation($reflectionProperty, NewObjectFlag::ANNOTATION)) {
             continue;
         }
         $objectClass = $doctrineMeta->getName();
         $property = $reflectionProperty->getName();
         if (!empty($meta['newObjectFlag'])) {
             if ($meta['newObjectFlag'] === $property) {
                 continue;
             }
             throw $this->createPropertyAnnotationInvalidException(NewObjectFlag::ANNOTATION, $objectClass, $property, sprintf('property "%s" is already marked as new object flag', $meta['newObjectFlag']));
         }
         if (!$doctrineMeta->hasField($property)) {
             throw $this->createPropertyAnnotationInvalidException(NewObjectFlag::ANNOTATION, $objectClass, $property, 'property must be mapped field');
         }
         $meta['newObjectFlag'] = $property;
     }
 }
예제 #29
0
 /**
  * Creates a new entity choice list.
  *
  * @param ObjectManager             $manager           An EntityManager instance
  * @param string                    $class             The class name
  * @param string                    $labelPath         The property path used for the label
  * @param EntityLoaderInterface     $entityLoader      An optional query builder
  * @param array                     $entities          An array of choices
  * @param array                     $preferredEntities An array of preferred choices
  * @param string                    $groupPath         A property path pointing to the property used
  *                                                     to group the choices. Only allowed if
  *                                                     the choices are given as flat array.
  * @param PropertyAccessorInterface $propertyAccessor  The reflection graph for reading property paths.
  */
 public function __construct(ObjectManager $manager, $class, $labelPath = null, EntityLoaderInterface $entityLoader = null, $entities = null, array $preferredEntities = array(), $groupPath = null, PropertyAccessorInterface $propertyAccessor = null)
 {
     $this->em = $manager;
     $this->entityLoader = $entityLoader;
     $this->classMetadata = $manager->getClassMetadata($class);
     $this->class = $this->classMetadata->getName();
     $this->loaded = is_array($entities) || $entities instanceof \Traversable;
     $this->preferredEntities = $preferredEntities;
     $identifier = $this->classMetadata->getIdentifierFieldNames();
     if (1 === count($identifier)) {
         $this->idField = $identifier[0];
         $this->idAsValue = true;
         if (in_array($this->classMetadata->getTypeOfField($this->idField), array('integer', 'smallint', 'bigint'))) {
             $this->idAsIndex = true;
         }
     }
     if (!$this->loaded) {
         // Make sure the constraints of the parent constructor are
         // fulfilled
         $entities = array();
     }
     parent::__construct($entities, $labelPath, $preferredEntities, $groupPath, null, $propertyAccessor);
 }
 /**
  * @param ClassMetadata $class
  * @param \ReflectionMethod $method
  * @param \ReflectionParameter $parameter
  *
  * @return string|null
  */
 private function getParameterType(ClassMetadata $class, \ReflectionMethod $method, \ReflectionParameter $parameter)
 {
     // We need to pick the type hint class too
     if ($parameter->isArray()) {
         return 'array';
     }
     if (method_exists($parameter, 'isCallable') && $parameter->isCallable()) {
         return 'callable';
     }
     try {
         $parameterClass = $parameter->getClass();
         if ($parameterClass) {
             return '\\' . $parameterClass->getName();
         }
     } catch (\ReflectionException $previous) {
         throw UnexpectedValueException::invalidParameterTypeHint($class->getName(), $method->getName(), $parameter->getName(), $previous);
     }
     return null;
 }