/** * Save settings * * @param Newscoop\News\Item $item * @return void */ public function save(array $values, Settings $settings) { $settings->setArticleTypeName($values['article_type']); $settings->setPublicationId($values['publication']); $settings->setSectionNumber($values['section']); $this->odm->persist($settings); $this->odm->flush(); }
/** * 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; }
public function testFindBy() { $this->assertEquals(0, count($this->service->findBy(array()))); $item = new NewsItem('item:1'); $this->service->save($item); $item = new PackageItem('item:2'); $this->service->save($item); $this->odm->clear(); $items = $this->service->findBy(array(), array('id' => 'asc')); $this->assertEquals(2, count($items)); $this->assertInstanceOf('Newscoop\\News\\NewsItem', $items->getNext()); $this->assertInstanceOf('Newscoop\\News\\PackageItem', $items->getNext()); }
public function testTwoDiferentManager() { $meta = $this->dm1->getClassMetadata('Sluggable\\Fixture\\Document\\Article'); $dmArticle = new \Sluggable\Fixture\Document\Article(); $dmArticle->setCode('code'); $dmArticle->setTitle('title'); $this->dm1->persist($dmArticle); $this->dm1->flush(); $this->assertEquals('title-code', $dmArticle->getSlug()); $em1Article = new \Sluggable\Fixture\Article(); $em1Article->setCode('code'); $em1Article->setTitle('title'); $this->em1->persist($em1Article); $this->em1->flush(); $this->assertEquals('title-code', $em1Article->getSlug()); }
/** * Create the document database for a mapped class. * * @param string $documentName */ public function createDocumentDatabase($documentName) { $class = $this->dm->getClassMetadata($documentName); if ($class->isMappedSuperclass || $class->isEmbeddedDocument) { throw new InvalidArgumentException('Cannot delete document indexes for mapped super classes or embedded documents.'); } $this->dm->getDocumentDatabase($documentName)->execute("function() { return true; }"); }
/** * Marks this collection as changed/dirty. */ private function changed() { if (!$this->isDirty) { $this->isDirty = true; if ($this->dm && $this->mapping !== null && $this->mapping['isOwningSide'] && $this->dm->getClassMetadata(get_class($this->owner))->isChangeTrackingNotify()) { $this->uow->scheduleForDirtyCheck($this->owner); } } }
/** * Publish package item * * @param Newscoop\News\PackageItem $item * @return void */ private function publishPackage(PackageItem $item) { $root = $item->getGroupSet()->getRootGroup(); foreach ($root->getRefs() as $ref) { $this->publishGroup($ref, $item); } $item->setPublished(new \DateTime()); $this->odm->flush(); }
/** * {@inheritdoc} */ public function clear() { $this->_initialize(); $result = $this->_coll->clear(); if ($this->_mapping->isOwningSide) { $this->_changed(); $this->_dm->getUnitOfWork()->scheduleCollectionDeletion($this); } return $result; }
public function initialize($parameters = array()) { parent::initialize($parameters); $schema = $this->getParameter('schema'); $connectionName = $this->getParameter('name'); $connectionOptions = $this->getParameter('options'); $plugins = (array) $this->getParameter('plugins'); $config = new \Doctrine\ORM\Configuration(); $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache()); $configuration = sfProjectConfiguration::getActive(); $paths = array(); if ($schema) { $paths[] = $schema; } $paths[] = realpath(__DIR__ . '/../config/doctrine'); $paths[] = realpath(sfConfig::get('sf_config_dir') . '/doctrine'); $enabledPlugins = $configuration->getPlugins(); foreach ($configuration->getAllPluginPaths() as $plugin => $path) { if (!in_array($plugin, $enabledPlugins) || !in_array($plugin, $plugins)) { continue; } $paths[] = $path . '/config/doctrine'; } $paths = array_unique($paths); $config->setMetadataDriverImpl(new YamlDriver($paths)); $config->setProxyDir(sfConfig::get('sf_lib_dir') . '/Proxies'); $config->setProxyNamespace('Proxies'); $configuration = sfProjectConfiguration::getActive(); if (sfConfig::get('sf_debug')) { $config->setSqlLogger(new sfDoctrineSqlLogger($configuration->getEventDispatcher())); } $method = sprintf('configureDoctrineConnection%s', $connectionName); $methodExists = method_exists($configuration, $method); if (method_exists($configuration, 'configureDoctrineConnection') && !$methodExists) { $configuration->configureDoctrineConnection($config); } else { if ($methodExists) { $configuration->{$method}($config); } } $this->em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config); if (method_exists($configuration, 'configureEntityManager')) { $configuration->configureEntityManager($this->em); } ActiveEntity::setEntityManager($this->em); // ODM MongoDB $config = new Doctrine\ODM\MongoDB\Configuration(); $config->setProxyDir(sfConfig::get('sf_lib_dir') . '/Proxies'); $config->setProxyNamespace('Proxies'); $reader = new Doctrine\Common\Annotations\AnnotationReader(); $reader->setDefaultAnnotationNamespace('Doctrine\\ODM\\MongoDB\\Mapping\\'); $config->setMetadataDriverImpl(new Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver($reader, sfConfig::get('sf_lib_dir') . DIRECTORY_SEPARATOR . 'Documents')); $this->dm = Doctrine\ODM\MongoDB\DocumentManager::create(new \Doctrine\ODM\MongoDB\Mongo(), $config); }
/** * @group odm */ public function testODMNewInstance() { $fileManager = new FileManager($this->odmStorage, self::ENTITY_FILE_CLASS, $this->rootDir); $manager = new TransUnitManager($this->odmStorage, $fileManager, $this->rootDir); $transUnit = $manager->newInstance(); $this->assertEquals(ORMUnitOfWork::STATE_NEW, $this->dm->getUnitOfWork()->getDocumentState($transUnit)); $this->assertEquals(0, $transUnit->getTranslations()->count()); $transUnit = $manager->newInstance(array('fr', 'en')); $this->assertEquals(ORMUnitOfWork::STATE_NEW, $this->dm->getUnitOfWork()->getDocumentState($transUnit)); $this->assertEquals('fr', $transUnit->getTranslations()->get(0)->getLocale()); $this->assertEquals('en', $transUnit->getTranslations()->get(1)->getLocale()); }
/** * Initializes the collection by loading its contents from the database * if the collection is not yet initialized. */ private function _initialize() { if (!$this->_initialized) { $collection = $this->_dm->getDocumentCollection($this->_typeClass->name); $ids = array(); foreach ($this->_coll as $document) { $ids[] = $this->_typeClass->getIdentifierObject($document); } $data = $collection->find(array('_id' => array('$in' => $ids))); $hints = array(Query::HINT_REFRESH => Query::HINT_REFRESH); foreach ($data as $id => $document) { $document = $this->_dm->getUnitOfWork()->getOrCreateDocument($this->_typeClass->name, $document, $hints); if ($document instanceof Proxy) { $document->__isInitialized__ = true; unset($document->__dm); unset($document->__identifier); } } $this->_initialized = true; } }
/** * Notifies this UnitOfWork of a property change in an document. * * @param object $document The document that owns the property. * @param string $propertyName The name of the property that changed. * @param mixed $oldValue The old value of the property. * @param mixed $newValue The new value of the property. */ public function propertyChanged($document, $propertyName, $oldValue, $newValue) { $oid = spl_object_hash($document); $class = $this->dm->getClassMetadata(get_class($document)); if (!isset($class->fieldMappings[$propertyName])) { return; // ignore non-persistent fields } // Update changeset and mark document for synchronization $this->documentChangeSets[$oid][$propertyName] = array($oldValue, $newValue); if (!isset($this->scheduledForDirtyCheck[$class->rootDocumentName][$oid])) { $this->scheduleForDirtyCheck($document); } }
private function doGenericHydration(ClassMetadata $metadata, $document, $data) { foreach ($metadata->fieldMappings as $mapping) { // Find the raw value. It may be in one of the mapped alsoLoadFields. $found = false; if (isset($mapping['alsoLoadFields']) && $mapping['alsoLoadFields']) { foreach ($mapping['alsoLoadFields'] as $name) { if (isset($data[$name])) { $rawValue = $data[$name]; $found = true; break; } } } // If nothing then lets get it from the default mapping field name if ($found === false) { $rawValue = isset($data[$mapping['name']]) ? $data[$mapping['name']] : null; } $value = null; // Prepare the different types of mapped values converting them from the MongoDB // types to the portable Doctrine types. // @Field if (!isset($mapping['association'])) { $value = Type::getType($mapping['type'])->convertToPHPValue($rawValue); // @ReferenceOne } elseif ($mapping['association'] === ClassMetadata::REFERENCE_ONE) { $reference = $rawValue; if ($reference === null || !isset($reference[$this->cmd . 'id'])) { continue; } $className = $this->dm->getClassNameFromDiscriminatorValue($mapping, $reference); $targetMetadata = $this->dm->getClassMetadata($className); $id = $targetMetadata->getPHPIdentifierValue($reference[$this->cmd . 'id']); $value = $this->dm->getReference($className, $id); // @ReferenceMany and @EmbedMany } elseif ($mapping['association'] === ClassMetadata::REFERENCE_MANY || $mapping['association'] === ClassMetadata::EMBED_MANY) { $value = new PersistentCollection(new ArrayCollection(), $this->dm, $this->unitOfWork, $this->cmd); $value->setOwner($document, $mapping); $value->setInitialized(false); if ($rawValue) { $value->setMongoData($rawValue); } // @EmbedOne } elseif ($mapping['association'] === ClassMetadata::EMBED_ONE) { if ($rawValue === null) { continue; } $embeddedDocument = $rawValue; $className = $this->dm->getClassNameFromDiscriminatorValue($mapping, $embeddedDocument); $embeddedMetadata = $this->dm->getClassMetadata($className); $value = $embeddedMetadata->newInstance(); $embeddedHydratedData = $this->hydrate($value, $embeddedDocument); $this->unitOfWork->registerManaged($value, null, $embeddedHydratedData); $this->unitOfWork->setParentAssociation($value, $mapping, $document, $mapping['name']); } unset($data[$mapping['name']]); // Hydrate the prepared value to the document if ($value !== null) { $metadata->reflFields[$mapping['fieldName']]->setValue($document, $value); $data[$mapping['fieldName']] = $value; } } return $data; }
/** * Hydrate array of MongoDB document data into the given document object. * * @param object $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($document, &$data) { $metadata = $this->dm->getClassMetadata(get_class($document)); if (isset($metadata->alsoLoadMethods)) { foreach ($metadata->alsoLoadMethods as $fieldName => $method) { if (isset($data[$fieldName])) { $document->{$method}($data[$fieldName]); } } } foreach ($metadata->fieldMappings as $mapping) { if (isset($mapping['alsoLoadFields'])) { $rawValue = null; $names = isset($mapping['alsoLoadFields']) ? $mapping['alsoLoadFields'] : array(); array_unshift($names, $mapping['name']); foreach ($names as $name) { if (isset($data[$name])) { $rawValue = $data[$name]; break; } } } else { $rawValue = isset($data[$mapping['name']]) ? $data[$mapping['name']] : null; } if ($rawValue === null) { continue; } $value = null; // Hydrate embedded if (isset($mapping['embedded'])) { if ($mapping['type'] === 'one') { $embeddedDocument = $rawValue; $className = $this->dm->getClassNameFromDiscriminatorValue($mapping, $embeddedDocument); $embeddedMetadata = $this->dm->getClassMetadata($className); $value = $embeddedMetadata->newInstance(); $this->hydrate($value, $embeddedDocument); $this->dm->getUnitOfWork()->registerManagedEmbeddedDocument($value, $embeddedDocument); } elseif ($mapping['type'] === 'many') { $embeddedDocuments = $rawValue; $coll = new PersistentCollection(new ArrayCollection()); foreach ($embeddedDocuments as $embeddedDocument) { $className = $this->dm->getClassNameFromDiscriminatorValue($mapping, $embeddedDocument); $embeddedMetadata = $this->dm->getClassMetadata($className); $embeddedDocumentObject = $embeddedMetadata->newInstance(); $this->hydrate($embeddedDocumentObject, $embeddedDocument); $this->dm->getUnitOfWork()->registerManagedEmbeddedDocument($embeddedDocumentObject, $embeddedDocument); $coll->add($embeddedDocumentObject); } $coll->setOwner($document, $mapping); $coll->takeSnapshot(); $value = $coll; } // Hydrate reference } elseif (isset($mapping['reference'])) { $reference = $rawValue; if ($mapping['type'] === 'one' && isset($reference[$this->cmd . 'id'])) { $className = $this->dm->getClassNameFromDiscriminatorValue($mapping, $reference); $targetMetadata = $this->dm->getClassMetadata($className); $id = $targetMetadata->getPHPIdentifierValue($reference[$this->cmd . 'id']); $value = $this->dm->getReference($className, $id); } elseif ($mapping['type'] === 'many' && (is_array($reference) || $reference instanceof Collection)) { $references = $reference; $value = new PersistentCollection(new ArrayCollection(), $this->dm); $value->setInitialized(false); $value->setOwner($document, $mapping); // Delay any hydration of reference objects until the collection is // accessed and initialized for the first ime $value->setReferences($references); } // Hydrate regular field } else { $value = Type::getType($mapping['type'])->convertToPHPValue($rawValue); } // Set hydrated field value to document if ($value !== null) { $data[$mapping['name']] = $value; $metadata->setFieldValue($document, $mapping['fieldName'], $value); } } // Set the document identifier if (isset($data['_id'])) { $metadata->setIdentifierValue($document, $data['_id']); $data[$metadata->identifier] = $data['_id']; unset($data['_id']); } return $document; }
/** * {@inheritdoc} */ public function getUserByPrincipal($principal) { return $this->documentManager->getRepository($this->documentName)->findOneBy(array($this->principalField => $principal)); }
/** * Hydrate array of MongoDB document data into the given document object. * * @param object $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($document, &$data) { $metadata = $this->dm->getClassMetadata(get_class($document)); if (isset($metadata->lifecycleCallbacks[Events::preLoad])) { $args = array(&$data); $metadata->invokeLifecycleCallbacks(Events::preLoad, $document, $args); } if ($this->evm->hasListeners(Events::preLoad)) { $this->evm->dispatchEvent(Events::preLoad, new PreLoadEventArgs($document, $this->dm, $data)); } if (isset($metadata->alsoLoadMethods)) { foreach ($metadata->alsoLoadMethods as $fieldName => $method) { if (isset($data[$fieldName])) { $document->$method($data[$fieldName]); } } } foreach ($metadata->fieldMappings as $mapping) { if (isset($mapping['alsoLoadFields'])) { $rawValue = null; $names = isset($mapping['alsoLoadFields']) ? $mapping['alsoLoadFields'] : array(); array_unshift($names, $mapping['name']); foreach ($names as $name) { if (isset($data[$name])) { $rawValue = $data[$name]; break; } } } else { $rawValue = isset($data[$mapping['name']]) ? $data[$mapping['name']] : null; } $value = null; if (isset($mapping['embedded'])) { $uow = $this->dm->getUnitOfWork(); if ($mapping['type'] === 'one') { if ($rawValue === null) { continue; } $embeddedDocument = $rawValue; $className = $this->dm->getClassNameFromDiscriminatorValue($mapping, $embeddedDocument); $embeddedMetadata = $this->dm->getClassMetadata($className); $value = $embeddedMetadata->newInstance(); // unset a potential discriminator map field (unless it's a persisted property) $discriminatorField = isset($mapping['discriminatorField']) ? $mapping['discriminatorField'] : '_doctrine_class_name'; if (!isset($embeddedMetadata->fieldMappings[$discriminatorField])) { unset($embeddedDocument[$discriminatorField]); } $this->hydrate($value, $embeddedDocument); $uow->registerManaged($value, null, $embeddedDocument); $uow->setParentAssociation($value, $mapping, $document, $mapping['name']); } elseif ($mapping['type'] === 'many') { $embeddedDocuments = $rawValue; $coll = new PersistentCollection(new ArrayCollection(), $this->dm, $this->dm->getConfiguration()); if ($embeddedDocuments) { foreach ($embeddedDocuments as $key => $embeddedDocument) { $className = $this->dm->getClassNameFromDiscriminatorValue($mapping, $embeddedDocument); $embeddedMetadata = $this->dm->getClassMetadata($className); $embeddedDocumentObject = $embeddedMetadata->newInstance(); // unset a potential discriminator map field (unless it's a persisted property) $discriminatorField = isset($mapping['discriminatorField']) ? $mapping['discriminatorField'] : '_doctrine_class_name'; if (!isset($embeddedMetadata->fieldMappings[$discriminatorField])) { unset($embeddedDocument[$discriminatorField]); } $this->hydrate($embeddedDocumentObject, $embeddedDocument); $uow->registerManaged($embeddedDocumentObject, null, $embeddedDocument); $uow->setParentAssociation($embeddedDocumentObject, $mapping, $document, $mapping['name'].'.'.$key); $coll->add($embeddedDocumentObject); } } $coll->setOwner($document, $mapping); $coll->takeSnapshot(); $value = $coll; } // Hydrate reference } elseif (isset($mapping['reference'])) { $reference = $rawValue; if ($mapping['type'] === 'one' && isset($reference[$this->cmd . 'id'])) { if ($reference === null) { continue; } $className = $this->dm->getClassNameFromDiscriminatorValue($mapping, $reference); $targetMetadata = $this->dm->getClassMetadata($className); $id = $targetMetadata->getPHPIdentifierValue($reference[$this->cmd . 'id']); $value = $this->dm->getReference($className, $id); } elseif ($mapping['type'] === 'many' && (is_array($reference) || $reference instanceof Collection)) { $references = $reference; $value = new PersistentCollection(new ArrayCollection(), $this->dm, $this->dm->getConfiguration()); $value->setInitialized(false); $value->setOwner($document, $mapping); // Delay any hydration of reference objects until the collection is // accessed and initialized for the first ime $value->setReferences($references); } // Hydrate regular field } else { $value = Type::getType($mapping['type'])->convertToPHPValue($rawValue); } unset($data[$mapping['name']]); // Set hydrated field value to document if ($value !== null) { $metadata->setFieldValue($document, $mapping['fieldName'], $value); $data[$mapping['fieldName']] = $value; } } // Set the document identifier if (isset($data['_id'])) { $metadata->setIdentifierValue($document, $data['_id']); $data[$metadata->identifier] = Type::getType($metadata->fieldMappings[$metadata->identifier]['type'])->convertToPHPValue($data['_id']); unset($data['_id']); } if (isset($metadata->lifecycleCallbacks[Events::postLoad])) { $metadata->invokeLifecycleCallbacks(Events::postLoad, $document); } if ($this->evm->hasListeners(Events::postLoad)) { $this->evm->dispatchEvent(Events::postLoad, new LifecycleEventArgs($document, $this->dm)); } return $document; }