Once populated, ClassMetadata instances are usually cached in a serialized form. IMPORTANT NOTE: The fields of this class are only public for 2 reasons: 1) To allow fast READ access. 2) To drastically reduce the size of a serialized instance (private/protected members get the whole class name, namespace inclusive, prepended to every property in the serialized representation).
Since: 1.0
Author: Jonathan H. Wage (jonwage@gmail.com)
Author: Roman Borschel (roman@code-factory.org)
Example #1
0
 /**
  * @param ClassMetadata $classMetadata
  * @return $this
  *
  * @throws MappingException
  */
 private function fromDocument(ClassMetadata $classMetadata)
 {
     if ($classMetadata->isSharded()) {
         throw MappingException::cannotUseShardedCollectionInOutStage($classMetadata->name);
     }
     return parent::out($classMetadata->getCollection());
 }
Example #2
0
 /**
  * @param string $fieldName
  * @return $this
  * @throws MappingException
  */
 private function fromReference($fieldName)
 {
     if (!$this->class->hasReference($fieldName)) {
         MappingException::referenceMappingNotFound($this->class->name, $fieldName);
     }
     $referenceMapping = $this->class->getFieldMapping($fieldName);
     $targetMapping = $this->dm->getClassMetadata($referenceMapping['targetDocument']);
     parent::from($targetMapping->getCollection());
     if ($referenceMapping['isOwningSide']) {
         if ($referenceMapping['storeAs'] !== ClassMetadataInfo::REFERENCE_STORE_AS_ID) {
             throw MappingException::cannotLookupNonIdReference($this->class->name, $fieldName);
         }
         $this->foreignField('_id')->localField($referenceMapping['name']);
     } else {
         if (isset($referenceMapping['repositoryMethod'])) {
             throw MappingException::repositoryMethodLookupNotAllowed($this->class->name, $fieldName);
         }
         $mappedByMapping = $targetMapping->getFieldMapping($referenceMapping['mappedBy']);
         if ($mappedByMapping['storeAs'] !== ClassMetadataInfo::REFERENCE_STORE_AS_ID) {
             throw MappingException::cannotLookupNonIdReference($this->class->name, $fieldName);
         }
         $this->localField('_id')->foreignField($mappedByMapping['name']);
     }
     return $this;
 }
Example #3
0
 /**
  * @param string                 $class
  * @param DocumentManager        $documentManager
  * @param ClassMetadata          $metadata
  * @param ResourceInterface|null $resource
  *
  * @return ObjectRepository
  */
 protected function createResourceRepository($class, DocumentManager $documentManager, ClassMetadata $metadata, ResourceInterface $resource = null)
 {
     if ($resource !== null && is_a($class, BaseRepositoryInterface::class, true)) {
         return new $class($documentManager, $documentManager->getUnitOfWork(), $metadata, $resource);
     }
     return parent::createRepository($documentManager, $metadata->getName());
 }
 /**
  * {@inheritdoc}
  */
 public function __construct(DocumentManager $dm, UnitOfWork $uow, ClassMetadata $class)
 {
     if ($class->getReflectionClass()->isSubclassOf('Gedmo\\Translatable\\Document\\MappedSuperclass\\AbstractPersonalTranslation')) {
         throw new \Gedmo\Exception\UnexpectedValueException('This repository is useless for personal translations');
     }
     parent::__construct($dm, $uow, $class);
 }
 protected function getQueryArray(ClassMetadata $metadata, $document, $path)
 {
     $class = $metadata->name;
     $field = $this->getFieldNameFromPropertyPath($path);
     if (!isset($metadata->fieldMappings[$field])) {
         throw new \LogicException('Mapping for \'' . $path . '\' doesn\'t exist for ' . $class);
     }
     $mapping = $metadata->fieldMappings[$field];
     if (isset($mapping['reference']) && $mapping['reference']) {
         throw new \LogicException('Cannot determine uniqueness of referenced document values');
     }
     switch ($mapping['type']) {
         case 'one':
             // TODO: implement support for embed one documents
         // TODO: implement support for embed one documents
         case 'many':
             // TODO: implement support for embed many documents
             throw new \RuntimeException('Not Implemented.');
         case 'hash':
             $value = $metadata->getFieldValue($document, $mapping['fieldName']);
             return array($path => $this->getFieldValueRecursively($path, $value));
         case 'collection':
             return array($mapping['fieldName'] => array('$in' => $metadata->getFieldValue($document, $mapping['fieldName'])));
         default:
             return array($mapping['fieldName'] => $metadata->getFieldValue($document, $mapping['fieldName']));
     }
 }
Example #6
0
 /**
  * Checks that the current field includes a reference to the supplied document.
  */
 public function includesReferenceTo($document)
 {
     if ($this->currentField) {
         $this->query[$this->currentField][$this->cmd . 'elemMatch'] = $this->class ? $this->dm->createDBRef($document, $this->class->getFieldMapping($this->currentField)) : $this->dm->createDBRef($document);
     } else {
         $this->query[$this->cmd . 'elemMatch'] = $this->dm->createDBRef($document);
     }
     return $this;
 }
Example #7
0
 /**
  * Hydrate array of MongoDB document data into the given document object
  * based on the mapping information provided in the ClassMetadata instance.
  *
  * @param ClassMetadata $metadata  The ClassMetadata instance for mapping information.
  * @param string $document  The document object to hydrate the data into.
  * @param array $data The array of document data.
  * @return array $values The array of hydrated values.
  */
 public function hydrate(ClassMetadata $metadata, $document, $data)
 {
     $values = array();
     foreach ($metadata->fieldMappings as $mapping) {
         if (!isset($data[$mapping['fieldName']])) {
             continue;
         }
         if (isset($mapping['embedded'])) {
             $embeddedMetadata = $this->_dm->getClassMetadata($mapping['targetDocument']);
             $embeddedDocument = $embeddedMetadata->newInstance();
             if ($mapping['type'] === 'many') {
                 $documents = new ArrayCollection();
                 foreach ($data[$mapping['fieldName']] as $docArray) {
                     $doc = clone $embeddedDocument;
                     $this->hydrate($embeddedMetadata, $doc, $docArray);
                     $documents->add($doc);
                 }
                 $metadata->setFieldValue($document, $mapping['fieldName'], $documents);
                 $value = $documents;
             } else {
                 $value = clone $embeddedDocument;
                 $this->hydrate($embeddedMetadata, $value, $data[$mapping['fieldName']]);
                 $metadata->setFieldValue($document, $mapping['fieldName'], $value);
             }
         } elseif (isset($mapping['reference'])) {
             $targetMetadata = $this->_dm->getClassMetadata($mapping['targetDocument']);
             $targetDocument = $targetMetadata->newInstance();
             $value = isset($data[$mapping['fieldName']]) ? $data[$mapping['fieldName']] : null;
             if ($mapping['type'] === 'one' && isset($value['$id'])) {
                 $id = (string) $value['$id'];
                 $proxy = $this->_dm->getReference($mapping['targetDocument'], $id);
                 $metadata->setFieldValue($document, $mapping['fieldName'], $proxy);
             } elseif ($mapping['type'] === 'many' && (is_array($value) || $value instanceof Collection)) {
                 $documents = new PersistentCollection($this->_dm, $targetMetadata, new ArrayCollection());
                 $documents->setInitialized(false);
                 foreach ($value as $v) {
                     $id = (string) $v['$id'];
                     $proxy = $this->_dm->getReference($mapping['targetDocument'], $id);
                     $documents->add($proxy);
                 }
                 $metadata->setFieldValue($document, $mapping['fieldName'], $documents);
             }
         } else {
             $value = $data[$mapping['fieldName']];
             $value = Type::getType($mapping['type'])->convertToPHPValue($value);
             $metadata->setFieldValue($document, $mapping['fieldName'], $value);
         }
         if (isset($value)) {
             $values[$mapping['fieldName']] = $value;
         }
     }
     if (isset($data['_id'])) {
         $metadata->setIdentifierValue($document, (string) $data['_id']);
     }
     return $values;
 }
 /**
  * @param ClassMetadata $metadata
  */
 private function setCustomRepositoryClass(ClassMetadata $metadata)
 {
     try {
         $resourceMetadata = $this->resourceRegistry->getByClass($metadata->getName());
     } catch (\InvalidArgumentException $exception) {
         return;
     }
     if ($resourceMetadata->hasClass('repository')) {
         $metadata->setCustomRepositoryClass($resourceMetadata->getClass('repository'));
     }
 }
Example #9
0
 /** {@inheritdoc} */
 public function getId($object)
 {
     if (!is_a($object, $this->getClass())) {
         throw new MetadataException("Object isn't subclass of '{$this->getClass()}', given '" . (is_object($object) ? get_class($object) : gettype($object)) . "'.");
     }
     if ($this->classMetadata->isEmbeddedDocument) {
         throw new MetadataException("Embedded document '{$this->getClass()}' hasn't ID.");
     }
     $identifier = $this->classMetadata->getIdentifierValue($object);
     return empty($identifier) ? NULL : $identifier;
 }
 public function testCreateQueryBuilderForCollection()
 {
     $this->classMetadata->expects($this->once())->method('getFieldNames')->will($this->returnValue([]));
     $this->classMetadata->expects($this->once())->method('getAssociationTargetClass')->with($this->identicalTo('translations'))->will($this->returnValue($translationClass = TranslationTest::class));
     $translationClassMetadata = $this->createClassMetadataMock();
     $translationClassMetadata->expects($this->once())->method('getFieldNames')->will($this->returnValue(['locale']));
     $this->documentManager->expects($this->once())->method('getClassMetadata')->with($this->identicalTo($translationClass))->will($this->returnValue($translationClassMetadata));
     $this->documentManager->expects($this->once())->method('createQueryBuilder')->will($this->returnValue($queryBuilder = $this->createQueryBuilderMock()));
     $queryBuilder->expects($this->once())->method('field')->with($this->identicalTo('translations.locale'))->will($this->returnSelf());
     $this->localeContext->expects($this->once())->method('getLocales')->will($this->returnValue($locales = ['fr']));
     $this->localeContext->expects($this->once())->method('getFallbackLocale')->will($this->returnValue($fallbackLocale = 'en'));
     $queryBuilder->expects($this->once())->method('in')->with($this->identicalTo(array_merge($locales, [$fallbackLocale])))->will($this->returnSelf());
     $this->assertSame($queryBuilder, $this->translatableRepository->createQueryBuilderForCollection());
 }
 /**
  * Prepares a query value and converts the php value to the database value if it is an identifier.
  * It also handles converting $fieldName to the database name if they are different.
  *
  * @param string $fieldName
  * @param string $value
  * @return mixed $value
  */
 private function prepareQueryValue(&$fieldName, $value)
 {
     // Process "association.fieldName"
     if (strpos($fieldName, '.') !== false) {
         $e = explode('.', $fieldName);
         $mapping = $this->class->getFieldMapping($e[0]);
         if ($this->class->hasField($e[0])) {
             $name = $this->class->fieldMappings[$e[0]]['name'];
             if ($name !== $e[0]) {
                 $e[0] = $name;
             }
         }
         if (isset($mapping['targetDocument'])) {
             $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']);
             if ($targetClass->hasField($e[1])) {
                 if ($targetClass->identifier === $e[1] || $e[1] === '$id') {
                     $fieldName = $e[0] . '.$id';
                     $value = $targetClass->getDatabaseIdentifierValue($value);
                 }
             }
         }
         // Process all non identifier fields
     } elseif ($this->class->hasField($fieldName) && !$this->class->isIdentifier($fieldName)) {
         $name = $this->class->fieldMappings[$fieldName]['name'];
         $mapping = $this->class->fieldMappings[$fieldName];
         if ($name !== $fieldName) {
             $fieldName = $name;
         }
         // Process identifier
     } elseif ($fieldName === $this->class->identifier || $fieldName === '_id') {
         $fieldName = '_id';
         $value = $this->class->getDatabaseIdentifierValue($value);
     }
     return $value;
 }
Example #12
0
 public function getFieldsMetadata($class)
 {
     $result = array();
     foreach ($this->odmMetadata->getReflectionProperties() as $property) {
         $name = $property->getName();
         $mapping = $this->odmMetadata->getFieldMapping($name);
         $values = array('title' => $name, 'source' => true);
         if (isset($mapping['fieldName'])) {
             $values['field'] = $mapping['fieldName'];
         }
         if (isset($mapping['id']) && $mapping['id'] == 'id') {
             $values['primary'] = true;
         }
         switch ($mapping['type']) {
             case 'id':
             case 'int':
             case 'string':
             case 'float':
             case 'many':
                 $values['type'] = 'text';
                 break;
             case 'boolean':
                 $values['type'] = 'boolean';
                 break;
             case 'date':
                 $values['type'] = 'date';
                 break;
         }
         $result[$name] = $values;
     }
     return $result;
 }
 /**
  * Executes all queued document insertions and returns any generated post-insert
  * identifiers that were created as a result of the insertions.
  *
  * If no inserts are queued, invoking this method is a NOOP.
  *
  * @return array An array of any generated post-insert IDs. This will be an empty array
  *               if the document class does not use the IDENTITY generation strategy.
  */
 public function executeInserts()
 {
     if (!$this->_queuedInserts) {
         return;
     }
     $postInsertIds = array();
     $inserts = array();
     foreach ($this->_queuedInserts as $oid => $document) {
         $data = $this->prepareInsertData($document);
         if (!$data) {
             continue;
         }
         $inserts[$oid] = $data;
     }
     if (empty($inserts)) {
         return;
     }
     $this->_collection->batchInsert($inserts);
     foreach ($inserts as $oid => $data) {
         $document = $this->_queuedInserts[$oid];
         $postInsertIds[(string) $data['_id']] = $document;
         if ($this->_class->isFile()) {
             $this->_dm->getHydrator()->hydrate($this->_class, $document, $data);
         }
     }
     $this->_queuedInserts = array();
     return $postInsertIds;
 }
Example #14
0
 /**
  * Gets reference mapping for current field from current class or its descendants.
  *
  * @return array
  * @throws MappingException
  */
 private function getReferenceMapping()
 {
     $mapping = null;
     try {
         $mapping = $this->class->getFieldMapping($this->currentField);
     } catch (MappingException $e) {
         if (empty($this->class->discriminatorMap)) {
             throw $e;
         }
         $foundIn = null;
         foreach ($this->class->discriminatorMap as $child) {
             $childClass = $this->dm->getClassMetadata($child);
             if ($childClass->hasAssociation($this->currentField)) {
                 if ($mapping !== null && $mapping !== $childClass->getFieldMapping($this->currentField)) {
                     throw MappingException::referenceFieldConflict($this->currentField, $foundIn->name, $childClass->name);
                 }
                 $mapping = $childClass->getFieldMapping($this->currentField);
                 $foundIn = $childClass;
             }
         }
         if ($mapping === null) {
             throw MappingException::mappingNotFoundInClassNorDescendants($this->class->name, $this->currentField);
         }
     }
     return $mapping;
 }
 /**
  * Prepares a query value and converts the php value to the database value if it is an identifier.
  * It also handles converting $fieldName to the database name if they are different.
  *
  * @param string $fieldName
  * @param string $value
  * @return mixed $value
  */
 private function prepareQueryValue(&$fieldName, $value)
 {
     // Process "association.fieldName"
     if (strpos($fieldName, '.') !== false) {
         $e = explode('.', $fieldName);
         $mapping = $this->class->getFieldMapping($e[0]);
         $name = $mapping['name'];
         if ($name !== $e[0]) {
             $e[0] = $name;
         }
         if (isset($mapping['targetDocument'])) {
             $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']);
             if ($targetClass->hasField($e[1])) {
                 if ($targetClass->identifier === $e[1]) {
                     $e[1] = '$id';
                     if (is_array($value)) {
                         foreach ($value as $k => $v) {
                             $value[$k] = $targetClass->getDatabaseIdentifierValue($v);
                         }
                     } else {
                         $value = $targetClass->getDatabaseIdentifierValue($value);
                     }
                 } else {
                     $targetMapping = $targetClass->getFieldMapping($e[1]);
                     $targetName = $targetMapping['name'];
                     if ($targetName !== $e[1]) {
                         $e[1] = $targetName;
                     }
                 }
                 $fieldName = $e[0] . '.' . $e[1];
             }
         }
         // Process all non identifier fields
         // We only change the field names here to the mongodb field name used for persistence
     } elseif ($this->class->hasField($fieldName) && !$this->class->isIdentifier($fieldName)) {
         $name = $this->class->fieldMappings[$fieldName]['name'];
         $mapping = $this->class->fieldMappings[$fieldName];
         if ($name !== $fieldName) {
             $fieldName = $name;
         }
         // Process identifier
     } elseif ($this->class->hasField($fieldName) && $this->class->isIdentifier($fieldName) || $fieldName === '_id') {
         $fieldName = '_id';
         if (is_array($value)) {
             foreach ($value as $k => $v) {
                 if ($k[0] === '$' && is_array($v)) {
                     foreach ($v as $k2 => $v2) {
                         $value[$k][$k2] = $this->class->getDatabaseIdentifierValue($v2);
                     }
                 } else {
                     $value[$k] = $this->class->getDatabaseIdentifierValue($v);
                 }
             }
         } else {
             $value = $this->class->getDatabaseIdentifierValue($value);
         }
     }
     return $value;
 }
 /**
  * Get shard key aware query for single document.
  *
  * @param object $document
  *
  * @return array
  */
 private function getQueryForDocument($document)
 {
     $id = $this->uow->getDocumentIdentifier($document);
     $id = $this->class->getDatabaseIdentifierValue($id);
     $shardKeyQueryPart = $this->getShardKeyQuery($document);
     $query = array_merge(array('_id' => $id), $shardKeyQueryPart);
     return $query;
 }
 /**
  * Lood document by its identifier.
  *
  * @param string $id
  * @return object|null
  */
 public function loadById($id)
 {
     $result = $this->_collection->findOne(array('_id' => $this->_class->getDatabaseIdentifierValue($id)));
     if ($result !== null) {
         return $this->_uow->getOrCreateDocument($this->_documentName, $result);
     }
     return null;
 }
Example #18
0
 public function getFieldsMetadata($class, $group = 'default')
 {
     $result = array();
     foreach ($this->odmMetadata->getReflectionProperties() as $property) {
         $name = $property->getName();
         $mapping = $this->odmMetadata->getFieldMapping($name);
         $values = array('title' => $name, 'source' => true);
         if (isset($mapping['fieldName'])) {
             $values['field'] = $mapping['fieldName'];
             $values['id'] = $mapping['fieldName'];
         }
         if (isset($mapping['id']) && $mapping['id'] == 'id') {
             $values['primary'] = true;
         }
         switch ($mapping['type']) {
             case 'id':
             case 'string':
             case 'bin_custom':
             case 'bin_func':
             case 'bin_md5':
             case 'bin':
             case 'bin_uuid':
             case 'file':
             case 'key':
             case 'increment':
                 $values['type'] = 'text';
                 break;
             case 'int':
             case 'float':
                 $values['type'] = 'number';
                 break;
                 /*case 'hash':
                   $values['type'] = 'array';*/
             /*case 'hash':
               $values['type'] = 'array';*/
             case 'boolean':
                 $values['type'] = 'boolean';
                 break;
             case 'date':
             case 'timestamp':
                 $values['type'] = 'date';
                 break;
             case 'collection':
                 $values['type'] = 'array';
                 break;
             case 'one':
                 $values['type'] = 'array';
                 break;
             case 'many':
                 $values['type'] = 'array';
                 break;
             default:
                 $values['type'] = 'text';
         }
         $result[$name] = $values;
     }
     return $result;
 }
 public function testGetMetadataForSingleClass()
 {
     // Self-made metadata
     $cm1 = new ClassMetadata('Doctrine\\ODM\\MongoDB\\Tests\\Mapping\\TestDocument1');
     $cm1->setCollection('group');
     // Add a mapped field
     $cm1->mapField(array('fieldName' => 'name', 'type' => 'string'));
     // Add a mapped field
     $cm1->mapField(array('fieldName' => 'id', 'id' => true));
     // and a mapped association
     $cm1->mapOneEmbedded(array('fieldName' => 'other', 'targetDocument' => 'Other'));
     $cm1->mapOneEmbedded(array('fieldName' => 'association', 'targetDocument' => 'Other'));
     // SUT
     $cmf = new ClassMetadataFactoryTestSubject();
     $cmf->setMetadataFor('Doctrine\\ODM\\MongoDB\\Tests\\Mapping\\TestDocument1', $cm1);
     // Prechecks
     $this->assertEquals(array(), $cm1->parentClasses);
     $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_NONE, $cm1->inheritanceType);
     $this->assertTrue($cm1->hasField('name'));
     $this->assertEquals(4, count($cm1->fieldMappings));
     // Go
     $cm1 = $cmf->getMetadataFor('Doctrine\\ODM\\MongoDB\\Tests\\Mapping\\TestDocument1');
     $this->assertEquals('group', $cm1->collection);
     $this->assertEquals(array(), $cm1->parentClasses);
     $this->assertTrue($cm1->hasField('name'));
 }
 /**
  * @param array $options
  *
  * @return array
  */
 private function getWriteOptions(array $options = array())
 {
     $defaultOptions = $this->dm->getConfiguration()->getDefaultCommitOptions();
     $documentOptions = [];
     if ($this->class->hasWriteConcern()) {
         $documentOptions['w'] = $this->class->getWriteConcern();
     }
     return array_merge($defaultOptions, $documentOptions, $options);
 }
Example #21
0
 /**
  * Checks that the current field includes a reference to the supplied document.
  */
 public function includesReferenceTo($document)
 {
     $dbRef = $this->dm->createDBRef($document);
     if ($this->currentField) {
         $keys = array('ref' => true, 'id' => true, 'db' => true);
         if ($this->class) {
             $mapping = $this->class->getFieldMapping($this->currentField);
             if (isset($mapping['targetDocument'])) {
                 unset($keys['ref'], $keys['db']);
             }
         }
         foreach ($keys as $key => $value) {
             $this->query[$this->currentField][$this->cmd . 'elemMatch'][$this->cmd . $key] = $dbRef[$this->cmd . $key];
         }
     } else {
         $this->query[$this->cmd . 'elemMatch'] = $dbRef;
     }
     return $this;
 }
 /**
  * Add mapping data to a translation entity.
  *
  * @param ClassMetadata $metadata
  */
 private function mapTranslation(ClassMetadata $metadata)
 {
     // In the case A -> B -> TranslationInterface, B might not have mapping defined as it
     // is probably defined in A, so in that case, we just return.
     if (!isset($this->configs[$metadata->name])) {
         return;
     }
     $metadata->mapManyToOne(array('fieldName' => 'translatable', 'targetEntity' => $this->configs[$metadata->name]['model'], 'inversedBy' => 'translations', 'joinColumns' => array(array('name' => 'translatable_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE', 'nullable' => false))));
     if (!$metadata->hasField('locale')) {
         $metadata->mapField(array('fieldName' => 'locale', 'type' => 'string', 'nullable' => false));
     }
     // Map unique index.
     $columns = array($metadata->getSingleAssociationJoinColumnName('translatable'), 'locale');
     if (!$this->hasUniqueConstraint($metadata, $columns)) {
         $constraints = isset($metadata->table['uniqueConstraints']) ? $metadata->table['uniqueConstraints'] : array();
         $constraints[$metadata->getTableName() . '_uniq_trans'] = array('columns' => $columns);
         $metadata->setPrimaryTable(array('uniqueConstraints' => $constraints));
     }
 }
 /**
  * Lood document by its identifier.
  *
  * @param string $id
  * @return object|null
  */
 public function loadById($id)
 {
     $result = $this->_collection->findOne(array('_id' => $this->_class->getDatabaseIdentifierValue($id)));
     if ($result !== null) {
         $document = $this->_uow->getOrCreateDocument($this->_documentName, $result);
         $this->_uow->registerManaged($document, $this->_class->getPHPIdentifierValue($result['_id']), $result);
         return $document;
     }
     return null;
 }
 /**
  * @param ClassMetadataInfo $metadata
  * @param $configuration
  */
 private function setAssociationMappings(ClassMetadataInfo $metadata, $configuration)
 {
     foreach (class_parents($metadata->getName()) as $parent) {
         if (false === in_array($parent, $configuration->getMetadataDriverImpl()->getAllClassNames())) {
             continue;
         }
         $parentMetadata = new ClassMetadata($parent, $configuration->getNamingStrategy());
         // Wakeup Reflection
         $parentMetadata->wakeupReflection($this->getReflectionService());
         // Load Metadata
         $configuration->getMetadataDriverImpl()->loadMetadataForClass($parent, $parentMetadata);
         if (false === $this->isResource($parentMetadata)) {
             continue;
         }
         if ($parentMetadata->isMappedSuperclass) {
             foreach ($parentMetadata->associationMappings as $key => $value) {
                 if ($this->hasRelation($value['association'])) {
                     $metadata->associationMappings[$key] = $value;
                 }
             }
         }
     }
 }
 /**
  * Prepares insert data for document
  *
  * @param mixed $document
  * @return array
  */
 public function prepareInsertData($document)
 {
     $oid = spl_object_hash($document);
     $changeset = $this->uow->getDocumentChangeSet($document);
     $insertData = array();
     foreach ($this->class->fieldMappings as $mapping) {
         if (isset($mapping['notSaved']) && $mapping['notSaved'] === true) {
             continue;
         }
         $new = isset($changeset[$mapping['fieldName']][1]) ? $changeset[$mapping['fieldName']][1] : null;
         if ($new === null && $mapping['nullable'] === false) {
             continue;
         }
         if ($this->class->isIdentifier($mapping['fieldName'])) {
             $insertData['_id'] = $this->prepareValue($mapping, $new);
             continue;
         }
         $value = $this->prepareValue($mapping, $new);
         if ($value === null && $mapping['nullable'] === false) {
             continue;
         }
         $insertData[$mapping['name']] = $value;
         if (isset($mapping['reference'])) {
             $scheduleForUpdate = false;
             if ($mapping['type'] === 'one') {
                 if (!isset($insertData[$mapping['name']][$this->cmd . 'id'])) {
                     $scheduleForUpdate = true;
                 }
             } elseif ($mapping['type'] === 'many') {
                 foreach ($insertData[$mapping['name']] as $ref) {
                     if (!isset($ref[$this->cmd . 'id'])) {
                         $scheduleForUpdate = true;
                         break;
                     }
                 }
             }
             if ($scheduleForUpdate) {
                 unset($insertData[$mapping['name']]);
                 $id = spl_object_hash($document);
                 $this->documentsToUpdate[$id] = $document;
                 $this->fieldsToUpdate[$id][$mapping['fieldName']] = array($mapping, $new);
             }
         }
     }
     // add discriminator if the class has one
     if ($this->class->hasDiscriminator()) {
         $insertData[$this->class->discriminatorField['name']] = $this->class->discriminatorValue;
     }
     return $insertData;
 }
 /**
  * @param ClassMetadata $classMetadata
  * @param array $mapping
  */
 private function remapAssociation(ClassMetadata $classMetadata, array $mapping)
 {
     $newMapping = $this->resolveTargetDocuments[$mapping['targetDocument']];
     $newMapping = array_replace_recursive($mapping, $newMapping);
     $newMapping['fieldName'] = $mapping['fieldName'];
     // clear reference case of duplicate exception
     unset($classMetadata->fieldMappings[$mapping['fieldName']]);
     unset($classMetadata->associationMappings[$mapping['fieldName']]);
     switch ($mapping['association']) {
         case ClassMetadata::REFERENCE_ONE:
             $classMetadata->mapOneReference($newMapping);
             break;
         case ClassMetadata::REFERENCE_MANY:
             $classMetadata->mapManyReference($newMapping);
             break;
         case ClassMetadata::EMBED_ONE:
             $classMetadata->mapOneEmbedded($newMapping);
             break;
         case ClassMetadata::EMBED_MANY:
             $classMetadata->mapManyEmbedded($newMapping);
             break;
     }
 }
 protected function buildMetadata(ClassMetadata $source, ClassMetadata $target, $eventManager)
 {
     $sourceReflClass = $source->getReflectionClass();
     $targetReflClass = $target->getReflectionClass();
     //Document annotations
     foreach ($this->annotationReader->getClassAnnotations($sourceReflClass) as $annotation) {
         if (defined(get_class($annotation) . '::event')) {
             // Raise annotation event
             if ($eventManager->hasListeners($annotation::event)) {
                 $eventManager->dispatchEvent($annotation::event, new AnnotationEventArgs($target, EventType::document, $annotation, $targetReflClass, $eventManager));
             }
         }
     }
     //Field annotations
     foreach ($sourceReflClass->getProperties() as $reflField) {
         foreach ($this->annotationReader->getPropertyAnnotations($reflField) as $annotation) {
             if (defined(get_class($annotation) . '::event')) {
                 // Raise annotation event
                 if ($eventManager->hasListeners($annotation::event)) {
                     $eventManager->dispatchEvent($annotation::event, new AnnotationEventArgs($target, EventType::field, $annotation, $reflField, $eventManager));
                 }
             }
         }
     }
     //Method annotations
     foreach ($sourceReflClass->getMethods() as $reflMethod) {
         foreach ($this->annotationReader->getMethodAnnotations($reflMethod) as $annotation) {
             if (defined(get_class($annotation) . '::event')) {
                 // Raise annotation event
                 if ($eventManager->hasListeners($annotation::event)) {
                     $eventManager->dispatchEvent($annotation::event, new AnnotationEventArgs($target, EventType::method, $annotation, $reflMethod, $eventManager));
                 }
             }
         }
     }
 }
Example #28
0
 /**
  * @param $object
  * @param $fieldName
  * @return ArrayCollection|mixed
  * @throws \NForms\Exceptions\MetadataException
  */
 protected function getCollection($object, $fieldName)
 {
     if ($this->isSingleValuedAssociation($fieldName)) {
         throw new MetadataException("Can't get collection from association toOne.");
     }
     $collection = $this->classMetadata->getFieldValue($object, $fieldName);
     if ($collection === NULL) {
         $collection = new ArrayCollection();
         $this->classMetadata->setFieldValue($object, $fieldName, $collection);
     }
     if (!$collection instanceof Collection) {
         throw new MetadataException('Expected Doctrine\\Common\\Collections\\Collection, given ' . (is_object($collection) ? get_class($collection) : gettype($collection)));
     }
     return $collection;
 }
    /**
     * Prepare where values converting document object field names to the document collection
     * field name.
     *
     * @param string $fieldName
     * @param string $value
     * @return string $value
     */
    private function prepareWhereValue(&$fieldName, $value)
    {
        if (strpos($fieldName, '.') !== false) {
            $e = explode('.', $fieldName);

            $mapping = $this->class->getFieldMapping($e[0]);

            if ($this->class->hasField($e[0])) {
                $name = $this->class->fieldMappings[$e[0]]['name'];
                if ($name !== $e[0]) {
                    $e[0] = $name;
                }
            }

            if (isset($mapping['targetDocument'])) {
                $targetClass = $this->dm->getClassMetadata($mapping['targetDocument']);
                if ($targetClass->hasField($e[1]) && $targetClass->identifier === $e[1]) {
                    $fieldName = $e[0] . '.$id';
                    $value = $targetClass->getDatabaseIdentifierValue($value);
                } elseif ($e[1] === '$id') {
                    $value = $targetClass->getDatabaseIdentifierValue($value);
                }
            }
        } elseif ($this->class->hasField($fieldName) && ! $this->class->isIdentifier($fieldName)) {
            $name = $this->class->fieldMappings[$fieldName]['name'];
            if ($name !== $fieldName) {
                $fieldName = $name;
            }
        } else {
            if ($fieldName === $this->class->identifier || $fieldName === '_id') {
                $fieldName = '_id';
                if (is_array($value)) {
                    if (isset($value[$this->cmd.'in'])) {
                        foreach ($value[$this->cmd.'in'] as $k => $v) {
                            $value[$this->cmd.'in'][$k] = $this->class->getDatabaseIdentifierValue($v);
                        }
                    } else {
                        foreach ($value as $k => $v) {
                            $value[$k] = $this->class->getDatabaseIdentifierValue($v);
                        }
                    }
                } else {
                    $value = $this->class->getDatabaseIdentifierValue($value);
                }
            }
        }
        return $value;
    }
 /**
  * Determines which fields get serialized.
  *
  * @return array The names of all the fields that should be serialized.
  */
 public function __sleep()
 {
     $serialized = parent::__sleep();
     if (isset($this->accessControl)) {
         $serialized[] = 'accessControl';
     }
     if (isset($this->crypt)) {
         $serialized[] = 'crypt';
     }
     if (isset($this->generator)) {
         $serialized[] = 'generator';
     }
     if (isset($this->freeze)) {
         $serialized[] = 'freeze';
     }
     if (isset($this->owner)) {
         $serialized[] = 'owner';
     }
     if (isset($this->permissions)) {
         $serialized[] = 'permissions';
     }
     if (isset($this->rest)) {
         $serialized[] = 'rest';
     }
     if (isset($this->roles)) {
         $serialized[] = 'roles';
     }
     if (isset($this->serializer)) {
         $serialized[] = 'serializer';
     }
     if (isset($this->softDelete)) {
         $serialized[] = 'softDelete';
     }
     if (isset($this->stamp)) {
         $serialized[] = 'stamp';
     }
     if (isset($this->state)) {
         $serialized[] = 'state';
     }
     if (isset($this->validator)) {
         $serialized[] = 'validator';
     }
     if (isset($this->zones)) {
         $serialized[] = 'zones';
     }
     return $serialized;
 }