public function doCascadeRemovePersistentCollections($document, array &$visited) { $oid = spl_object_hash($document); if (isset($visited[$oid])) { return; // Prevent infinite recursion } $visited[$oid] = $document; // mark visited $class = $this->dm->getClassMetadata(get_class($document)); $associationMappings = $class->associationMappings; foreach ($associationMappings as $assoc) { $relatedDocuments = $class->reflFields[$assoc['fieldName']]->getValue($document); if ($relatedDocuments instanceof PersistentCollection) { $relatedDocuments = $relatedDocuments->getValues(); } if (is_array($relatedDocuments)) { $class->reflFields[$assoc['fieldName']]->setValue($document, $relatedDocuments); foreach ($relatedDocuments as $relatedDocument) { $this->doCascadeRemovePersistentCollections($relatedDocument, $visited); } } elseif (is_object($relatedDocuments)) { $this->doCascadeRemovePersistentCollections($relatedDocuments, $visited); } } }
/** * @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()); }
public function create($username, $password, $roles) { $user = new Document\User(); $user->setUsername($username)->setPassword($password)->setRoles($roles); $this->manager->persist($user); $this->manager->flush(); }
/** * Datasource constructor, creates the Configuration, Connection and DocumentManager objects * * ### You can pass the following configuration options * * - server: name of the server that will be used to connect to Mongo (default: `localhost`) * - database: name of the database to use when connecting to Mongo (default: `cake`) * - documentPaths: array containing a list of full path names where Document classes can be located (default: `App::path('Model')`) * - proxyDir: full path to the directory that will contain the generated proxy classes for each document (default: `TMP . 'cache'`) * - proxyNamespace: string representing the namespace the proxy classes will reside in (default: `Proxies`) * - hydratorDir: directory well the hydrator classes will be generated in (default: `TMP . 'cache'`) * - hydratorNamespace: string representing the namespace the hydrator classes will reside in (default: `Hydrators`) * * @param arary $config * @param boolean $autoConnect whether this object should attempt connection on creation * @throws MissingConnectionException if it was not possible to connect to MongoDB */ public function __construct($config = array(), $autoConnect = true) { $modelPaths = $this->_cleanupPaths(App::path('Model')); $this->_baseConfig = array('proxyDir' => TMP . 'cache', 'proxyNamespace' => 'Proxies', 'hydratorDir' => TMP . 'cache', 'hydratorNamespace' => 'Hydrators', 'server' => 'localhost', 'database' => 'cake', 'documentPaths' => $modelPaths, 'prefix' => null); foreach (CakePlugin::loaded() as $plugin) { $this->_baseConfig['documentPaths'] = array_merge($this->_baseConfig['documentPaths'], $this->_cleanupPaths(App::path('Model', $plugin))); } parent::__construct($config); extract($this->config, EXTR_OVERWRITE); $configuration = new Configuration(); $configuration->setProxyDir($proxyDir); $configuration->setProxyNamespace($proxyNamespace); $configuration->setHydratorDir($hydratorDir); $configuration->setHydratorNamespace($hydratorNamespace); $configuration->setDefaultDB($database); $configuration->setMetadataDriverImpl($this->_getMetadataReader($documentPaths)); if (Configure::read('debug') === 0) { $configuration->setAutoGenerateHydratorClasses(false); $configuration->setAutoGenerateProxyClasses(false); $configuration->setMetadataCacheImpl(new ApcCache()); } $this->configuration = $configuration; $this->connection = new Connection($server, array(), $configuration); $this->documentManager = DocumentManager::create($this->connection, $configuration); $this->documentManager->getEventManager()->addEventListener(array(Events::prePersist, Events::preUpdate, Events::preRemove, Events::postPersist, Events::postUpdate, Events::postRemove), $this); try { if ($autoConnect) { $this->connect(); } } catch (Exception $e) { throw new MissingConnectionException(array('class' => get_class($this))); } $this->setupLogger(); }
/** * {@inheritdoc} */ protected function createResourceRepository($class, DocumentManager $documentManager, ClassMetadata $metadata, ResourceInterface $resource = null) { if ($resource !== null && is_a($class, TranslatableRepository::class, true)) { return new $class($documentManager, $documentManager->getUnitOfWork(), $metadata, $resource, $this->getLocaleContext()); } return parent::createResourceRepository($class, $documentManager, $metadata, $resource); }
/** * @param Doctrine\ODM\MongoDB\DocumentManager $documentManager */ private function _save(DocumentManager $documentManager) { try { if ($this->queue->count() <= 0) { $this->getLog()->debug('Queue contains no documents for processing.'); return; } $this->getLog()->debug('Queue contains: ' . $this->queue->count() . ' documents.'); foreach ($this->queue as $object) { $name = $object->getName(); $_id = $object->getId(); if (empty($_id)) { $document = $object->getInstance(); $this->getLog()->info('Saving document: ' . $name . ' (' . $document->__toString() . ')'); //Debug::dump($document, 3); $documentManager->persist($document); $documentManager->flush(); $documentId = $document->getId(); if (!empty($name) && !empty($documentId)) { $this->getLog()->info('Marking document: ' . $name . ' (' . get_class($document) . ') as persisted in cache with ID: ' . $documentId); $this->markAsPersisted($name, $documentId, $document); } } } $this->queue->clear(); $this->getLog()->debug('Finished saving documents, queue now contains: ' . $this->queue->count() . ' documents.'); } catch (\Exception $ex) { $this->getLog()->err('An error occurred while attempting to save one or more documents. ' . get_class($ex) . ' handled, with message: ' . $ex->getMessage()); $documentManager->close(); throw $ex; } }
public function generate(DocumentManager $dm, $document) { $className = get_class($document); $db = $dm->getDocumentDatabase($className); $query = array('_id' => $document->getEtablissement()->getId()); $newObj = array('$inc' => array('numeroPassageIncrement' => 1)); $command = array(); $command['findandmodify'] = "Etablissement"; $command['query'] = $query; $command['update'] = $newObj; $command['upsert'] = true; $command['new'] = true; $result = $db->command($command); $document->setIdentifiant(sprintf("%s-%s-%05d", $document->getEtablissement()->getIdentifiant(), $document->getDatePrevision()->format('Ymd'), $result['value']['numeroPassageIncrement'])); $id = sprintf("%s-%s", Passage::PREFIX, $document->getIdentifiant()); if ($document->getNumeroArchive()) { return $id; } $this->updateNumeroArchive($db); $command = array(); $command['findandmodify'] = 'doctrine_increment_ids'; $command['query'] = array('_id' => "PassageArchive"); $command['update'] = array('$inc' => array('current_id' => 1)); $command['upsert'] = true; $command['new'] = true; $result = $db->command($command); $document->setNumeroArchive($result['value']['current_id']); return $id; }
function delete($entity, $flush = 1) { $this->dm->remove($entity); if (1 == $flush) { $this->dm->flush($entity); } }
public function generate(DocumentManager $dm, $document) { $className = get_class($document); $db = $dm->getDocumentDatabase($className); $query = array('_id' => $document->getSociete()->getId()); $newObj = array('$inc' => array('contratIncrement' => 1)); $command = array(); $command['findandmodify'] = "Societe"; $command['query'] = $query; $command['update'] = $newObj; $command['upsert'] = true; $command['new'] = true; $result = $db->command($command); $document->setIdentifiant(sprintf("%s-%s-%04d", $document->getSociete()->getIdentifiant(), $document->getDateCreation()->format('Ymd'), $result['value']['contratIncrement'])); $id = sprintf("%s-%s", "CONTRAT", $document->getIdentifiant()); if ($document->getNumeroArchive()) { return $id; } $annee = $document->getDateCreation()->format('y'); $command = array(); $command['findandmodify'] = 'doctrine_increment_ids'; $command['query'] = array('_id' => "ContratArchive"); $command['update'] = array('$inc' => array($annee => 1)); $command['upsert'] = true; $command['new'] = true; $result = $db->command($command); $document->setNumeroArchive(sprintf("%s%04d", $annee, $result['value'][$annee])); return $id; }
public function __construct(DocumentManager $dm, $class) { $this->dm = $dm; $this->repository = $dm->getRepository($class); $metadata = $dm->getClassMetadata($class); $this->class = $metadata->name; }
public function __construct(DocumentManager $dm, ClassMetadata $class, Collection $coll) { $this->_coll = $coll; $this->_dm = $dm; $this->_typeClass = $class; $this->_cmd = $dm->getConfiguration()->getMongoCmd(); }
function let(DocumentManager $documentManager, PendingMassPersister $pendingPersister, NormalizerInterface $normalizer, EventDispatcherInterface $eventDispatcher, MongoObjectsFactory $mongoFactory, StepExecution $stepExecution, Collection $collection, CacheClearer $clearer) { $documentManager->getDocumentCollection('pim_product')->willReturn($collection); $collection->getName()->willReturn('pim_product_collection'); $this->beConstructedWith($documentManager, $pendingPersister, $normalizer, $eventDispatcher, $mongoFactory, 'pim_product', $clearer); $this->setStepExecution($stepExecution); }
/** * @param \Symfony\Component\HttpKernel\Bundle\BundleInterface $bundle * @param string $document * @param array $fields * @param Boolean $withRepository * @throws \RuntimeException */ public function generate(BundleInterface $bundle, $document, array $fields, $withRepository) { $config = $this->documentManager->getConfiguration(); $config->addDocumentNamespace($bundle->getName(), $bundle->getNamespace() . '\\Document'); $documentClass = $config->getDocumentNamespace($bundle->getName()) . '\\' . $document; $documentPath = $bundle->getPath() . '/Document/' . str_replace('\\', '/', $document) . '.php'; if (file_exists($documentPath)) { throw new \RuntimeException(sprintf('Document "%s" already exists.', $documentClass)); } $class = new ClassMetadataInfo($documentClass); if ($withRepository) { $class->setCustomRepositoryClass($documentClass . 'Repository'); } $class->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); $class->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); foreach ($fields as $field) { $class->mapField($field); } $documentGenerator = $this->getDocumentGenerator(); $documentCode = $documentGenerator->generateDocumentClass($class); $this->filesystem->mkdir(dirname($documentPath)); file_put_contents($documentPath, rtrim($documentCode) . PHP_EOL, LOCK_EX); if ($withRepository) { $path = $bundle->getPath() . str_repeat('/..', substr_count(get_class($bundle), '\\')); $this->getRepositoryGenerator()->writeDocumentRepositoryClass($class->customRepositoryClassName, $path); } }
function let(DocumentManager $documentManager, UnitOfWork $unitOfWork, ClassMetadata $class, Builder $queryBuilder, Query $query) { $class->name = 'spec\\Sylius\\Bundle\\ResourceBundle\\Fixture\\Document\\TranslatableFoo'; $documentManager->createQueryBuilder($class->name)->willReturn($queryBuilder); $queryBuilder->getQuery()->willReturn($query); $this->beConstructedWith($documentManager, $unitOfWork, $class); }
function let(DocumentManager $manager, ChannelInterface $ecommerce, ChannelInterface $mobile, LocaleInterface $enUs, LocaleInterface $frFr, CategoryInterface $category, ChannelManager $channelManager, CategoryRepositoryInterface $categoryRepository, ProductRepository $productRepository, QueryBuilder $ormQb, Builder $odmQb, Query $odmQuery, Cursor $cursor) { $enUs->getCode()->willReturn('en_US'); $frFr->getCode()->willReturn('fr_FR'); $ecommerce->getCode()->willReturn('ecommerce'); $ecommerce->getLabel()->willReturn('ECommerce'); $ecommerce->getLocales()->willReturn(array($enUs, $frFr)); $ecommerce->getCategory()->willReturn($category); $mobile->getCode()->willReturn('mobile'); $mobile->getLabel()->willReturn('Mobile'); $mobile->getLocales()->willReturn(array($enUs)); $mobile->getCategory()->willReturn($category); $odmQuery->execute()->willReturn($cursor); $productRepository->createQueryBuilder()->willReturn($odmQb); $odmQb->hydrate(Argument::any())->willReturn($odmQb); $odmQb->field(Argument::any())->willReturn($odmQb); $odmQb->in(Argument::any())->willReturn($odmQb); $odmQb->equals(Argument::any())->willReturn($odmQb); $odmQb->select('_id')->willReturn($odmQb); $odmQb->getQuery()->willReturn($odmQuery); $categoryRepository->getAllChildrenQueryBuilder($category, true)->willReturn($ormQb); $categoryRepository->getCategoryIds($category, $ormQb)->willReturn(array(1, 2, 3)); $channelManager->getFullChannels()->willReturn(array($ecommerce, $mobile)); $manager->getRepository('pim_product_class')->willReturn($productRepository); $this->beConstructedWith($manager, $channelManager, $categoryRepository, 'pim_product_class'); }
/** * @param mixed $credentials * @param UserProviderInterface $userProvider * @return null|object */ public function getUser($credentials, UserProviderInterface $userProvider) { $apiKey = $credentials['token']; // if null, authentication will fail // if a User object, checkCredentials() is called return $this->dm->getRepository('Documents:User')->findOneBy(array('apiKey' => $apiKey)); }
/** * Constructor. * * @param DocumentManager $dm * @param CriteriaMerger $cm */ public function __construct(DocumentManager $dm, CriteriaMerger $cm = null) { $this->dm = $dm; $this->cm = $cm ?: new CriteriaMerger(); $this->config = $dm->getConfiguration(); $this->parseConfiguration(); }
/** * Implement loading data for pas-admin * * Use services with tag wealthbot_admin.pas_files_loader * * @param \DateTime $date * @param int $page * @return Array */ public function load(\DateTime $date, $page = 0) { $tableData = array(); $shortDate = $date->format('Y-m-d'); $accounts = $this->mongoManager->getRepository('WealthbotAdminBundle:Portfolio')->findBy(array('importDate' => $shortDate)); $advisorCodes = $this->em->getRepository('WealthbotRiaBundle:AdvisorCode')->findAll(); $advisorByCode = array(); foreach ($advisorCodes as $advisorCode) { $advisorByCode[$advisorCode->getName()] = $advisorCode->getRiaCompany()->getRia(); } foreach ($accounts as $account) { $advisorCode = $account->getAdvisorId(); $advisorName = ''; if (array_key_exists($advisorCode, $advisorByCode)) { $advisorName = $advisorByCode[$advisorCode]->getRiaCompanyInformation()->getName(); } $tableData[] = array('ria' => $advisorName, 'last_name' => $account->getLastName(), 'first_name' => $account->getFirstName(), 'acct_number' => $account->getAccountNumber(), 'type' => $account->getAccountType(), 'warning' => false); } //Find ALL accounts needs to be in this day, add it to list and mark by red color. $transferAccountDate = new \DateTime(); $transferAccountDate->setTime(0, 0, 0); $transferAccountDate = $this->businessCalendar->addBusinessDays($transferAccountDate, -SystemAccount::DAYS_WAIT_TRANSFER_OR_ROLLOVER_ACCOUNT); $newAccountDate = new \DateTime(); $newAccountDate->setTime(0, 0, 0); $newAccountDate = $this->businessCalendar->addBusinessDays($newAccountDate, -SystemAccount::DAYS_WAIT_NEW_ACCOUNT); /** @var SystemAccount[] $notAcceptedAccounts */ $notAcceptedAccounts = $this->em->getRepository('WealthbotClientBundle:SystemAccount')->getMustBeAcceptedAlready($transferAccountDate, $newAccountDate); foreach ($notAcceptedAccounts as $account) { $advisorName = $account->getClient()->getRia()->getRiaCompanyInformation()->getName(); $tableData[] = array('ria' => $advisorName, 'last_name' => $account->getClient()->getLastName(), 'first_name' => $account->getClient()->getFirstName(), 'acct_number' => $account->getAccountNumber(), 'type' => $account->getType(), 'warning' => true); } return array('data' => $tableData); }
/** * Constructor. * * @param EncoderFactoryInterface $encoderFactory * @param string $algorithm * @param CanonicalizerInterface $usernameCanonicalizer * @param CanonicalizerInterface $emailCanonicalizer * @param DocumentManager $dm * @param string $class */ public function __construct(EncoderFactoryInterface $encoderFactory, $algorithm, CanonicalizerInterface $usernameCanonicalizer, CanonicalizerInterface $emailCanonicalizer, DocumentManager $dm, $class) { parent::__construct($encoderFactory, $algorithm, $usernameCanonicalizer, $emailCanonicalizer); $this->dm = $dm; $this->repository = $dm->getRepository($class); $metadata = $dm->getClassMetadata($class); $this->class = $metadata->name; }
/** * {@inheritDoc} */ public function find($id) { $image = $this->dm->getRepository($this->class)->findAll()->getCollection()->findOne(array("_id" => new \MongoId($id))); if (!$image) { throw new NotFoundHttpException(sprintf('Source image not found with id "%s"', $id)); } return $this->imagine->load($image['file']->getBytes()); }
/** * @param Aggregate $aggregate */ public function add(Aggregate $aggregate) { foreach ($aggregate->getEvents() as $event) { $storedEvent = new StoredEvent($aggregate->getAggregateId(), get_class($event), $event); $this->manager->persist($storedEvent); } $this->manager->flush(); }
public function getOne($id) : ImageInterface { $image = $this->dm->getRepository(Image::class)->find($id); if (!$image) { throw new \Exception('Image not found', 404); } return $image; }
/** * Initializes a new BasicDocumentPersister instance. * * @param Doctrine\ODM\MongoDB\DocumentManager $dm * @param Doctrine\ODM\MongoDB\Mapping\ClassMetadata $class */ public function __construct(DocumentManager $dm, ClassMetadata $class) { $this->_dm = $dm; $this->_uow = $dm->getUnitOfWork(); $this->_class = $class; $this->_documentName = $class->getName(); $this->_collection = $dm->getDocumentCollection($class->name); }
protected function tearDown() { $documentClasses = array('Doctrine\\Bundle\\MongoDBBundle\\Tests\\Fixtures\\Form\\Document', 'Doctrine\\Bundle\\MongoDBBundle\\Tests\\Fixtures\\Form\\Category', 'Doctrine\\Bundle\\MongoDBBundle\\Tests\\Fixtures\\Form\\Guesser'); foreach ($documentClasses as $class) { $this->dm->getDocumentCollection($class)->drop(); } parent::tearDown(); }
/** * {@inheritDoc} */ public function find($id) { $image = $this->dm->getRepository($this->class)->find(new \MongoId($id)); if (!$image) { throw new NotLoadableException(sprintf('Source image was not found with id "%s"', $id)); } return $image['file']->getBytes(); }
/** * @param string $id * @return Recipe * @throws NotFoundException If no Recipe found */ public function find($id) { $recipe = $this->dm->find('Hellofresh\\DoctrineTutorial\\Menu\\Recipe', $id); if (!$recipe) { throw new NotFoundException("Recipe not found"); } return $recipe; }
/** * Persists a vote. * * @param VoteInterface $vote * @param VotableCommentInterface $comment * @return void */ public function addVote(VoteInterface $vote, VotableCommentInterface $comment) { $vote->setComment($comment); $comment->setScore($comment->getScore() + $vote->getValue()); $this->dm->persist($comment); $this->dm->persist($vote); $this->dm->flush(); }
/** * @param Projection $projection */ public function remove(Projection $projection) { $storedProjection = $this->repository->find($projection->getProjectionName() . '_' . $projection->getAggregateId()); if (!empty($storedProjection)) { $this->manager->remove($storedProjection); $this->manager->flush(); } }
/** * Get list of results * * @param array $params * * @return array $return */ public function search($params) { $pageRepository = $this->dm->getRepository('AiselPageBundle:Page'); $total = $pageRepository->getTotalFromRequest($params); $collection = $pageRepository->searchFromRequest($params); $return = array('total' => $total, 'collection' => $collection); return $return; }
/** * Create a new MongoCollection instance that wraps a PHP MongoCollection instance * for a given ClassMetadata instance. * * @param MongoCollection $mongoColleciton The MongoCollection instance. * @param ClassMetadata $class The ClassMetadata instance. * @param DocumentManager $dm The DocumentManager instance. */ public function __construct(\MongoCollection $mongoCollection, ClassMetadata $class, DocumentManager $dm) { $this->_mongoCollection = $mongoCollection; $this->_class = $class; $this->_loggerCallable = $dm->getConfiguration()->getLoggerCallable(); $this->_cmd = $dm->getConfiguration()->getMongoCmd(); $this->_eventManager = $dm->getEventManager(); }