public function prePersist(LifecycleEventArgs $eventArgs) { $document = $eventArgs->getDocument(); if (!method_exists($document, 'addHistoryEvent')) { return; } $historyRecord = $this->createEvent(); $historyRecord->setType(HistoryEventType::RECORD_CREATED); $historyRecord->setTitle('Record created'); $originalValues = $eventArgs->getDocumentManager()->getUnitOfWork()->getDocumentActualData($document); $historyRecord->setInfo(substr($this->getDetailedCreateInfo($originalValues), 0, 100000)); $document->addHistoryEvent($historyRecord); $eventArgs->getDocumentManager()->persist($historyRecord); }
public function preRemove(LifecycleEventArgs $args) { $dm = $args->getDocumentManager(); $currentDocument = $args->getDocument(); $currentDocumentClass = get_class($currentDocument); $isRefExists = FALSE; $documentClassNames = $dm->getConfiguration()->getMetadataDriverImpl()->getAllClassNames(); foreach ($documentClassNames as $documentClassName) { try { $cm = $dm->getClassMetadata($documentClassName); foreach ($cm->getAssociationNames() as $associationName) { if ($currentDocumentClass == $cm->getAssociationTargetClass($associationName) || is_subclass_of($currentDocumentClass, $cm->getAssociationTargetClass($associationName))) { $searchObj = $dm->getRepository($documentClassName)->findOneBy(array($associationName . '.$id' => new \MongoId($currentDocument->getId()))); if ($searchObj) { $isRefExists = TRUE; } } } } catch (\Exception $e) { } } if ($isRefExists) { throw new \Exception('ref_erro'); } }
public function preUpdate(LifecycleEventArgs $args) { $document = $args->getDocument(); // perhaps you only want to act on some "Product" document if ($document instanceof Project) { $dm = $args->getDocumentManager(); $document->setDateUpdated(new \DateTime("now")); $class = $dm->getClassMetadata("Zeega\\DataBundle\\Document\\Project"); if ($args->hasChangedField("tags")) { $update = true; $oldTags = $args->getOldValue('tags'); foreach ($oldTags as $tag) { $name = $tag->getName(); $id = $tag->getId(); if ($name == 'homepage' && $id !== null) { $update = false; break; } } if ($update === true) { $document->setDateTagsUpdated(new \DateTime("now")); } } $dm->getUnitOfWork()->recomputeSingleDocumentChangeSet($class, $document); } }
/** * Hydrates the given node * @param LifecycleEventArgs $eventArgs */ public function postLoad(LifecycleEventArgs $eventArgs) { if ($eventArgs->getDocument() instanceof Node) { /* * Loading users and group inside the current Node * Using an event suscriber to allow these objects to come from many places */ $node = $eventArgs->getDocument(); $groupId = $node->getGroupId(); /* * If netBS * if(!is_null($groupId)) $node->setGroup($this->em->getRepository('AppBundle:Groupe')->find($groupId)); foreach($node->getUsersId() as $id) $node->addUser($this->em->getRepository('InterneSecurityBundle:User')->find($id)); */ /* * If colibri */ foreach ($node->getUsersId() as $id) { $user = $eventArgs->getDocumentManager()->getRepository('ColibriUserBundle:User')->find($id); $node->addUser($user); } } }
public function preRemove(LifecycleEventArgs $eventArgs) { $document = $eventArgs->getDocument(); if ($document instanceof $this->objectClass) { $this->scheduleForRemoval($document, $eventArgs->getDocumentManager()); } }
/** * @param LifecycleEventArgs $event */ public function preUpdate(LifecycleEventArgs $event) { if (!($object = $event->getDocument()) instanceof ContentInterface || in_array($object->getContentId(), $this->contentManaged)) { return; } $this->contentManaged[] = $object->getContentId(); $contents = $this->getContentRepository()->findByContentId($object->getContentId()); $contentType = $this->getContentTypeRepository()->findOneByContentTypeIdInLastVersion($object->getContentType()); /** @var ContentInterface $content */ foreach ($contents as $content) { if ($content != $object) { foreach ($this->immutableData as $immutableData) { $getter = $this->generateGetter($immutableData, $object); $setter = 'set' . ucfirst($immutableData); $content->{$setter}($object->{$getter}()); } /** @var FieldTypeInterface $field */ foreach ($contentType->getFields() as $field) { if (!$field->isTranslatable()) { $contentAttribute = $this->getContentAttribute($content, $field->getFieldId()); $contentAttribute->setValue($object->getAttributeByName($field->getFieldId())->getValue()); } } } $event->getDocumentManager()->flush($content); } }
/** * * @param \Doctrine\ODM\MongoDB\Event\OnFlushEventArgs $eventArgs */ public function preThaw(LifecycleEventArgs $eventArgs) { if (!($accessController = $this->getAccessController())) { //Access control is not enabled return; } $document = $eventArgs->getDocument(); if (!$accessController->isAllowed(Actions::thaw, null, $document)->getIsAllowed()) { //stop thaw $this->getFreezer()->freeze($document); $eventManager = $eventArgs->getDocumentManager()->getEventManager(); if ($eventManager->hasListeners(Events::thawDenied)) { $eventManager->dispatchEvent(Events::thawDenied, new AccessControlEventArgs($document, $eventArgs->getDocumentManager(), Actions::thaw)); } } }
public function preUpdate(LifecycleEventArgs $eventArgs) { $document = $eventArgs->getDocument(); if (!$document instanceof SearchableEntityInterface) { return; } $dm = $eventArgs->getDocumentManager(); $uow = $dm->getUnitOfWork(); $changeset = $uow->getDocumentChangeset($document); $filter = $this->getKeywordsFilter(); $keywords = array(); $mustUpdate = false; foreach ($document->getSearchableProperties() as $name) { if (isset($changeset[$name])) { $mustUpdate = true; break; } } if (!$mustUpdate) { return; } $keywords = $filter->filter($document); $document->setKeywords($keywords); $uow->recomputeSingleDocumentChangeSet($dm->getClassMetadata(get_class($document)), $document); }
public function postLoad(\Doctrine\ODM\MongoDB\Event\LifecycleEventArgs $eventArgs) { if (!$eventArgs->getDocument() instanceof \Bpi\ApiBundle\Domain\Entity\Author) { return; } $author = $eventArgs->getDocument(); $author->loadAgency($eventArgs->getDocumentManager()->getRepository('BpiApiBundle:Aggregate\\Agency')); }
/** * * @param \Doctrine\ODM\MongoDB\Event\LifecycleEventArgs $eventArgs */ protected function recomputeChangeset(LifecycleEventArgs $eventArgs) { $documentManager = $eventArgs->getDocumentManager(); $document = $eventArgs->getDocument(); $unitOfWork = $documentManager->getUnitOfWork(); $metadata = $documentManager->getClassMetadata(get_class($document)); $unitOfWork->recomputeSingleDocumentChangeSet($metadata, $document); }
/** * Populates identities for stored references * * @param LifecycleEventArgs $args */ public function postPersist(LifecycleEventArgs $args) { $object = $args->getDocument(); if (($name = $this->referenceRepository->getReferenceName($object)) !== false) { $identity = $args->getDocumentManager()->getUnitOfWork()->getDocumentIdentifier($object); $this->referenceRepository->setReferenceIdentity($name, $identity); } }
public function postPersist(LifecycleEventArgs $eventArgs) { $document = $eventArgs->getDocument(); $uow = $eventArgs->getDocumentManager()->getUnitOfWork(); $idmap = $uow->getIdentityMap(); if ($document instanceof User\Document\User) { var_dump($idmap); } }
function it_throws_exception_when_entity_collection_field_has_no_target_entity(LifecycleEventArgs $args, ValueStub $document, DocumentManager $dm, ClassMetadata $documentMetadata) { $args->getDocument()->willReturn($document); $args->getDocumentManager()->willReturn($dm); $dm->getClassMetadata(Argument::any())->willReturn($documentMetadata); $documentMetadata->fieldMappings = ['foo' => ['type' => 'text'], 'bar' => ['type' => 'entity']]; $documentMetadata->name = 'Acme/Document'; $this->shouldThrow(new \RuntimeException('Please provide the "targetEntity" of the Acme/Document::$bar field mapping'))->duringPostLoad($args); }
public function postLoad(LifecycleEventArgs $args) { $dm = $args->getDocumentManager(); $document = $args->getDocument(); if (!$document instanceof GH1152Child) { return; } $document->parentAssociation = $dm->getUnitOfWork()->getParentAssociation($document); }
/** * Dans le cas d'un document nouvellement enregistré, je vais renommer le nom du fichier uploadé si besoin * @param LifecycleEventArgs $eventArgs [description] * @return [type] [description] */ public function postPersist(LifecycleEventArgs $eventArgs) { $document = $eventArgs->getDocument(); $dm = $eventArgs->getDocumentManager(); $is_uploadable = $this->metadata_reader->isUploadable(ClassUtils::getClass($document)); if ($is_uploadable) { // Récupération des champs uploadable $fields = $this->metadata_reader->getUploadableFields(ClassUtils::getClass($document)); // Pour chacun de ces champs, je récupère le mapping associé pour vérifier le namer et le nom du champ foreach ($fields as $field) { $mapping = $this->mapping_factory->fromField($document, $field['propertyName']); if ($mapping->getNamer() instanceof \Redking\Bundle\UploadBundle\Naming\ObjectNamer) { $filename = $mapping->getFileName($document); $file = $mapping->getFile($document); // Si il y a bien un fichier, je vérifie son nom if (!is_null($filename) && $file instanceof File) { $filename_normalized = $mapping->getNamer()->getNormalizedName($document, $filename); // Si les deux noms ne correspondent pas, je renomme et réassigne if (strcmp($filename, $filename_normalized) !== 0) { $base_directory = $mapping->hasDirectoryNamer() ? $mapping->getDirectoryNamer()->directoryName($document, $mapping) . '/' : ''; $adapter = $this->filesystem_map->get($mapping->getUploadDestination())->getAdapter(); $adapter->rename($base_directory . $filename, $base_directory . $filename_normalized); if ($adapter->exists($base_directory . $filename)) { $adapter->delete($base_directory . $filename); } // On vérifie si il y a des fichiers resized à renommer foreach ($this->resizes as $suffix => $resize_conf) { $resize_filename = $base_directory . ResizedNamer::getName($filename, $suffix); $resize_filename_normalized = $base_directory . ResizedNamer::getName($filename_normalized, $suffix); if ($adapter->exists($resize_filename)) { $adapter->rename($resize_filename, $resize_filename_normalized); if ($adapter->exists($resize_filename)) { $adapter->delete($resize_filename); } } } $mapping->setFileName($document, $filename_normalized); // Ré-enregistrement $class = $dm->getClassMetadata(get_class($document)); $dm->getUnitOfWork()->recomputeSingleDocumentChangeSet($class, $document); } } } // Traitement du répertoire basé sur l'id pour voir si le fichier est bien dedans $directory_namer = $mapping->getDirectoryNamer(); if (!is_null($directory_namer) && $directory_namer instanceof BaseDirectoryIdNamer) { $adapter = $this->filesystem_map->get($mapping->getUploadDestination())->getAdapter(); $filename = $mapping->getFileName($document); $good_path = ltrim($directory_namer->directoryName($document, $mapping) . '/' . $filename, '/'); $bad_path = ltrim($directory_namer->directoryNameError($document, $mapping) . '/' . $filename, '/'); if (!$adapter->exists($good_path) && $adapter->exists($bad_path)) { $success = $adapter->rename($bad_path, $good_path); } } } } }
public function preUpdate(LifecycleEventArgs $args) { $document = $args->getDocument(); if ($document instanceof Product) { $document->setName('Oste vednazh Bravo'); $dm = $args->getDocumentManager(); $class = $dm->getClassMetadata(get_class($document)); $dm->getUnitOfWork()->recomputeSingleDocumentChangeSet($class, $document); } }
/** * Set product normalized data before updating it * * @param LifecycleEventArgs $args */ public function preUpdate(LifecycleEventArgs $args) { $document = $args->getDocument(); if ($document instanceof ProductInterface) { $this->updateNormalizedData($document); $dm = $args->getDocumentManager(); $metadata = $dm->getClassMetadata(get_class($document)); $dm->getUnitOfWork()->recomputeSingleDocumentChangeSet($metadata, $document); } }
/** * @param LifecycleEventArgs $args */ public function postLoad(LifecycleEventArgs $args) { $image = $args->getDocument(); if ($image instanceof ContactImage) { $cv = $args->getDocumentManager()->getRepository('Cv\\Entity\\Cv')->findOneBy(['contact.image' => new \MongoId($image->getId())]); if ($cv) { $image->setContact($cv->getContact()); } } }
/** * Removes attachments * * @param LifecycleEventArgs $eventArgs */ public function postRemoveEntity(LifecycleEventArgs $eventArgs) { $file = $eventArgs->getDocument(); if (!$file instanceof Attachment) { return; } $fileId = new \MongoId($file->id); $dm = $eventArgs->getDocumentManager(); $dm->createQueryBuilder('Cv\\Entity\\Cv')->update()->multiple(true)->field('attachments')->equals($fileId)->pull($fileId)->getQuery()->execute(); }
/** * Creates and injects the organization reference to an user entity. * * @param LifecycleEventArgs $args */ public function postLoad(LifecycleEventArgs $args) { $document = $args->getDocument(); if ($document instanceof UserInterface) { $repository = $args->getDocumentManager()->getRepository('Organizations\\Entity\\Organization'); $userId = $document->getId(); $reference = new OrganizationReference($userId, $repository); $document->setOrganization($reference); } }
/** * Fetch entities from the database which permissions are assigned the referral document. * * @param LifecycleEventArgs $args * * @return Collection */ protected function getEntities($args) { $dm = $args->getDocumentManager(); $resource = $args->getDocument(); $repositoryName = $this->getRepositoryName(); $resourceId = $resource->getPermissionsResourceId(); $repository = $dm->getRepository($repositoryName); $criteria = array('permissions.assigned.' . $resourceId => array('$exists' => true)); $entities = $repository->findBy($criteria); return $entities; }
function it_sets_normalized_product_data_before_updating_document(LifecycleEventArgs $args, AbstractProduct $product, NormalizerInterface $normalizer, DocumentManager $dm, ClassMetadata $metadata, UnitOfWork $uow) { $args->getDocument()->willReturn($product); $normalizer->normalize($product, 'mongodb_json')->willReturn('normalized product'); $args->getDocumentManager()->willReturn($dm); $dm->getClassMetadata(Argument::any())->willReturn($metadata); $dm->getUnitOfWork()->willReturn($uow); $product->setNormalizedData('normalized product')->shouldBeCalled(); $uow->recomputeSingleDocumentChangeSet($metadata, $product)->shouldBeCalled(); $this->preUpdate($args); }
/** * * @param \Doctrine\ODM\MongoDB\Event\LifecycleEventArgs $eventArgs */ public function prePersist(LifecycleEventArgs $eventArgs) { $document = $eventArgs->getDocument(); $metadata = $eventArgs->getDocumentManager()->getClassMetadata(get_class($document)); if (isset($metadata->owner)) { $reflField = $metadata->reflFields[$metadata->owner]; $owner = $reflField->getValue($document); if (!isset($owner)) { $reflField->setValue($document, $this->getIdentityName()); } } }
/** * Updates fiile permissions on Flush * * @param OnFlushEventArgs $eventArgs * @return boolean */ public function postRemoveEntity(LifecycleEventArgs $eventArgs) { $file = $eventArgs->getDocument(); if (!$file instanceof Attachment) { return; } $dm = $eventArgs->getDocumentManager(); //$repo = $dm->getRepository('Applications\Entity\Application'); $fileId = new \MongoId($file->id); $dm->createQueryBuilder('Applications\\Entity\\Application')->update()->multiple(true)->field('attachments')->equals($fileId)->pull($fileId)->getQuery()->execute(); $dm->createQueryBuilder('Applications\\Entity\\Application')->update()->multiple(true)->field('contact.image')->equals($fileId)->set(null)->getQuery()->execute(); }
/** * @param LifecycleEventArgs $args */ public function postUpdate(LifecycleEventArgs $args) { $document = $args->getDocument(); try { $doctrineChangeSet = $args->getDocumentManager()->getUnitOfWork()->getDocumentChangeSet($document); if (count($this->solr->computeChangeSet($doctrineChangeSet, $document)) === 0) { return; } $this->solr->updateDocument($document); } catch (\RuntimeException $e) { $this->logger->debug($e->getMessage()); } }
/** * updates references * * @param LifecycleEventArgs $eventArgs */ public function preUpdate(LifecycleEventArgs $eventArgs) { $document = $eventArgs->getDocument(); if (!$document instanceof JobInterface) { return; } $dm = $eventArgs->getDocumentManager(); $changeset = $dm->getUnitOfWork()->getDocumentChangeset($document); if (!isset($changeset['user'])) { return; } $userId = $document->getUser()->getId(); $dm->createQueryBuilder('Applications\\Entity\\Application')->update()->multiple(true)->field('refs.jobs.userId')->set($userId)->field('refs.jobs.__id__')->equals($document->getId())->field('refs.jobs.userId')->notEqual($userId)->getQuery()->execute(); }
/** * @param LifecycleEventArgs $eventArgs eventArgs */ public function postLoad(LifecycleEventArgs $eventArgs) { $entity = $eventArgs->getDocument(); if (!$entity instanceof ComponentInterface || null != $entity->getData()) { return; } try { $entity->setData($eventArgs->getDocumentManager()->getReference($entity->getModel(), $entity->getIdentifier())); } catch (DocumentNotFoundException $e) { // if document has been deleted ... } catch (MappingException $e) { // if document is not a valid document or mapped super class } }
public function postUpdate(LifecycleEventArgs $arg) { if (!$this->container->isScopeActive('request')) { return; } if (!$this->container->get('security.context')->getToken()->isAuthenticated()) { return; } if ($arg->getDocument() instanceof Document\Article) { if ($arg->getDocument()->wereTranslationsModified()) { $this->notifyModification($arg->getDocument(), $arg->getDocumentManager()); } } }
/** * @param LifecycleEventArgs $eventArgs */ public function preRemove(LifecycleEventArgs $eventArgs) { $document = $eventArgs->getDocument(); $dm = $eventArgs->getDocumentManager(); if ($document instanceof Translation) { /** @var Translation $document */ $projectId = $document->getProjectId(); $projectInfo = $dm->getRepository('TranslationsBundle:ProjectInfo')->getProjectInfo($projectId); $projectInfo->subBundle($document->getBundle()); $projectInfo->subCatalog($document->getCatalog()); $dm->persist($projectInfo); $dm->flush(); return; } }
/** * {@inheritdoc} */ public function postLoad(LifecycleEventArgs $args) { $document = $args->getDocument(); $metadata = $args->getDocumentManager()->getClassMetadata(get_class($document)); foreach ($metadata->fieldMappings as $field => $mapping) { if ('entity' === $mapping['type']) { if (!isset($mapping['targetEntity'])) { throw new \RuntimeException(sprintf('Please provide the "targetEntity" of the %s::$%s field mapping', $metadata->name, $field)); } $value = $metadata->reflFields[$field]->getValue($document); if (null !== $value && !$value instanceof $mapping['targetEntity']) { $metadata->reflFields[$field]->setValue($document, $this->entityManager->getReference($mapping['targetEntity'], $value)); } } } }