PreUpdate event listener.

Only computes password change if password is one of file to be changed

@param PreUpdateEventArgs $eventArgs Event args
504462
public function preUpdate(PreUpdateEventArgs $eventArgs)
    {
        $entity = $eventArgs->getEntity();

        if ($this->checkEntityType($entity)) {
            if ($eventArgs->hasChangedField('password')) {
                $password = $entity->getPassword();
                if (!empty($password)) {
                    $encodedPassword = $this->encryptPassword($password);
                    $eventArgs->setNewValue('password', $encodedPassword);
                }
            }
        }
    }
985486
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
    {
        $metadata = $eventArgs->getClassMetadata();

        if ($metadata->getName() === self::ROOT_CHARACTERISTICS_CLASS) {
            $metadata->setDiscriminatorMap($this->characteristicsClassesMap);
        }
    }
22318
public function preRemove(EventArgs $eventArgs)
    {
        if (method_exists($eventArgs, 'getEntity')) {
            $this->_triggerEvent(Events::preRemove, $eventArgs->getEntity(), $eventArgs);
        }
    }
59479
private function executeUpdates($documents, $dispatchEvents = true)
    {
        foreach ($documents as $oid => $document) {
            if (!$this->contains($oid)) {
                continue;
            }

            $class = $this->dm->getClassMetadata(get_class($document));
            $node = $this->session->getNode($this->getDocumentId($document));

            if ($this->writeMetadata) {
                $this->documentClassMapper->writeMetadata($this->dm, $node, $class->name);
            }

            if ($dispatchEvents) {
                if ($invoke = $this->eventListenersInvoker->getSubscribedSystems($class, Event::preUpdate)) {
                    $this->eventListenersInvoker->invoke(
                        $class,
                        Event::preUpdate,
                        $document,
                        new PreUpdateEventArgs($document, $this->dm, $this->documentChangesets[$oid]),
                        $invoke
                    );
                    $this->changesetComputed = array_diff($this->changesetComputed, [$oid]);
                    $this->computeChangeSet($class, $document);
                }
            }

            $fields = $this->documentChangesets[$oid]['fields'] ?? [];
            foreach ($fields as $fieldName => $data) {
                $fieldValue = $data[1];

                // PHPCR does not validate nullable unless we would start to
                // generate custom node types, which we at the moment don't.
                // the ORM can delegate this validation to the relational database
                // that is using a strict schema.
                // do this after the preUpdate events to give listener a last
                // chance to provide values
                if (null === $fieldValue
                    && in_array($fieldName, $class->fieldMappings) // only care about non-virtual fields
                    && !$class->isNullable($fieldName)
                    && !$this->isAutocreatedProperty($class, $fieldName)
                ) {
                    throw new PHPCRException(sprintf('Field "%s" of class "%s" is not nullable', $fieldName, $class->name));
                }

                // Ignore translatable fields (they will be persisted by the translation strategy)
                if (in_array($fieldName, $class->translatableFields)) {
                    continue;
                }

                $mapping = $class->mappings[$fieldName];
                if (in_array($fieldName, $class->fieldMappings)) {
                    $type = PropertyType::valueFromName($mapping['type']);
                    if ($mapping['multivalue']) {
                        $value = empty($fieldValue) ? null : ($fieldValue instanceof Collection ? $fieldValue->toArray() : $fieldValue);
                        if ($value && isset($mapping['assoc'])) {
                            $value = $this->processAssoc($node, $mapping, $value);
                        }
                    } else {
                        $value = $fieldValue;
                    }
                    $node->setProperty($mapping['property'], $value, $type);
                } elseif ($mapping['type'] === $class::MANY_TO_ONE
                    || $mapping['type'] === $class::MANY_TO_MANY
                ) {
                    if (!$this->writeMetadata) {
                        continue;
                    }
                    if ($node->hasProperty($mapping['property']) && is_null($fieldValue)) {
                        $node->getProperty($mapping['property'])->remove();
                        if (isset($mapping['assoc'])) {
                            $this->removeAssoc($node, $mapping);
                        }
                        continue;
                    }

                    switch ($mapping['strategy']) {
                        case 'hard':
                            $strategy = PropertyType::REFERENCE;
                            break;
                        case 'path':
                            $strategy = PropertyType::PATH;
                            break;
                        default:
                            $strategy = PropertyType::WEAKREFERENCE;
                            break;
                    }

                    if ($mapping['type'] === $class::MANY_TO_MANY) {
                        if (isset($fieldValue)) {
                            $refNodesIds = [];
                            foreach ($fieldValue as $fv) {
                                if ($fv === null) {
                                    continue;
                                }

                                $associatedNode = $this->session->getNode($this->getDocumentId($fv));
                                if ($strategy === PropertyType::PATH) {
                                    $refNodesIds[] = $associatedNode->getPath();
                                } else {
                                    $refClass = $this->dm->getClassMetadata(get_class($fv));
                                    $this->setMixins($refClass, $associatedNode, $fv);
                                    if (!$associatedNode->isNodeType('mix:referenceable')) {
                                        throw new PHPCRException(sprintf('Referenced document %s is not referenceable. Use referenceable=true in Document annotation: '.self::objToStr($document, $this->dm), ClassUtils::getClass($fv)));
                                    }
                                    $refNodesIds[] = $associatedNode->getIdentifier();
                                }
                            }

                            $refNodesIds = empty($refNodesIds) ? null : $refNodesIds;
                            $node->setProperty($mapping['property'], $refNodesIds, $strategy);
                        }
                    } elseif ($mapping['type'] === $class::MANY_TO_ONE) {
                        if (isset($fieldValue)) {
                            $associatedNode = $this->session->getNode($this->getDocumentId($fieldValue));

                            if ($strategy === PropertyType::PATH) {
                                $node->setProperty($fieldName, $associatedNode->getPath(), $strategy);
                            } else {
                                $refClass = $this->dm->getClassMetadata(get_class($fieldValue));
                                $this->setMixins($refClass, $associatedNode, $document);
                                if (!$associatedNode->isNodeType('mix:referenceable')) {
                                    throw new PHPCRException(sprintf('Referenced document %s is not referenceable. Use referenceable=true in Document annotation: '.self::objToStr($document, $this->dm), ClassUtils::getClass($fieldValue)));
                                }
                                $node->setProperty($mapping['property'], $associatedNode->getIdentifier(), $strategy);
                            }
                        }
                    }
                } elseif ('referrers' === $mapping['type']) {
                    if (isset($fieldValue)) {

                        /*
                         * each document in referrers field is supposed to
                         * reference this document, so we have to update its
                         * referencing property to contain the uuid of this
                         * document
                         */
                        foreach ($fieldValue as $fv) {
                            if ($fv === null) {
                                continue;
                            }

                            if (!$fv instanceof $mapping['referringDocument']) {
                                throw new PHPCRException(sprintf('%s is not an instance of %s for document %s field %s', self::objToStr($fv, $this->dm), $mapping['referencedBy'], self::objToStr($document, $this->dm), $mapping['fieldName']));
                            }

                            $referencingNode = $this->session->getNode($this->getDocumentId($fv));
                            $referencingMeta = $this->dm->getClassMetadata($mapping['referringDocument']);
                            $referencingField = $referencingMeta->getAssociation($mapping['referencedBy']);

                            $uuid = $node->getIdentifier();
                            $strategy = $referencingField['strategy'] == 'weak' ? PropertyType::WEAKREFERENCE : PropertyType::REFERENCE;
                            switch ($referencingField['type']) {
                                case ClassMetadata::MANY_TO_ONE:
                                    $ref = $referencingMeta->getFieldValue($fv, $referencingField['fieldName']);
                                    if ($ref !== null && $ref !== $document) {
                                        throw new PHPCRException(sprintf('Conflicting settings for referrer and reference: Document %s field %s points to %s but document %s has set first document as referrer on field %s', self::objToStr($fv, $this->dm), $referencingField['fieldName'], self::objToStr($ref, $this->dm), self::objToStr($document, $this->dm), $mapping['fieldName']));
                                    }
                                    // update the referencing document field to point to this document
                                    $referencingMeta->setFieldValue($fv, $referencingField['fieldName'], $document);
                                    // and make sure the reference is not deleted in this change because the field could be null
                                    unset($this->documentChangesets[spl_object_hash($fv)]['fields'][$referencingField['fieldName']]);
                                    // store the change in PHPCR
                                    $referencingNode->setProperty($referencingField['property'], $uuid, $strategy);
                                    break;
                                case ClassMetadata::MANY_TO_MANY:
                                    /** @var $collection ReferenceManyCollection */
                                    $collection = $referencingMeta->getFieldValue($fv, $referencingField['fieldName']);
                                    if ($collection instanceof PersistentCollection && $collection->isDirty()) {
                                        throw new PHPCRException(sprintf('You may not modify the reference and referrer collections of interlinked documents as this is ambiguous. Reference %s on document %s and referrers %s on document %s are both modified', self::objToStr($fv, $this->dm), $referencingField['fieldName'], self::objToStr($document, $this->dm), $mapping['fieldName']));
                                    }
                                    if ($collection) {
                                        // make sure the reference is not deleted in this change because the field could be null
                                        unset($this->documentChangesets[spl_object_hash($fv)]['fields'][$referencingField['fieldName']]);
                                    } else {
                                        $collection = new ReferenceManyCollection($this->dm, $fv, $referencingField['property'], [$node], $class->name, null, $this->getReferenceManyCollectionTypeFromMetadata($mapping));
                                        $referencingMeta->setFieldValue($fv, $referencingField['fieldName'], $collection);
                                    }

                                    if ($referencingNode->hasProperty($referencingField['property'])) {
                                        if (!in_array($uuid, $referencingNode->getProperty($referencingField['property'])->getString())) {
                                            if (!$collection instanceof PersistentCollection || !$collection->isDirty()) {
                                                // update the reference collection: add us to it
                                                $collection->add($document);
                                            }
                                            // store the change in PHPCR
                                            $referencingNode->getProperty($referencingField['property'])->addValue($uuid); // property should be correct type already
                                        }
                                    } else {
                                        // store the change in PHPCR
                                        $referencingNode->setProperty($referencingField['property'], [$uuid], $strategy);
                                    }

                                    // avoid confusion later, this change to the reference collection is already saved
                                    $collection->setDirty(false);
                                    break;
                                default:
                                    // in class metadata we only did a santiy check but not look at the actual mapping
                                    throw new MappingException(sprintf('Field "%s" of document "%s" is not a reference field. Error in referrer annotation: '.self::objToStr($document, $this->dm), $mapping['referencedBy'], ClassUtils::getClass($fv)));
                            }
                        }
                    }
                } elseif ('child' === $mapping['type']) {
                    if ($fieldValue === null && $node->hasNode($mapping['nodeName'])) {
                        $child = $node->getNode($mapping['nodeName']);
                        $childDocument = $this->getOrCreateDocument(null, $child);
                        $this->purgeChildren($childDocument);
                        $child->remove();
                    }
                }
            }

            if (!empty($this->documentChangesets[$oid]['reorderings'])) {
                foreach ($this->documentChangesets[$oid]['reorderings'] as $reorderings) {
                    foreach ($reorderings as $srcChildRelPath => $destChildRelPath) {
                        $node->orderBefore($srcChildRelPath, $destChildRelPath);
                    }
                }
            }

            $this->doSaveTranslation($document, $node, $class);

            if ($dispatchEvents) {
                if ($invoke = $this->eventListenersInvoker->getSubscribedSystems($class, Event::postUpdate)) {
                    $this->eventListenersInvoker->invoke(
                        $class,
                        Event::postUpdate,
                        $document,
                        new LifecycleEventArgs($document, $this->dm),
                        $invoke
                    );
                }
            }
        }
    }
557978
public function changePassword($username, $password)
    {
        $user = $this->findUserByUsernameOrThrowException($username);
        $user->setPlainPassword($password);
        $this->userManager->updateUser($user);

        $event = new UserEvent($user, $this->getRequest());
        $this->dispatcher->dispatch(Events::USER_PASSWORD_CHANGED, $event);
    }
796321
public function onFlush(OnFlushEventArgs $eventArgs)
    {
        if (!$this->eventEmittingService->isEnabled()) {
            return;
        }

        $entityManager = $eventArgs->getEntityManager();
        $unitOfWork = $entityManager->getUnitOfWork();

        foreach ($unitOfWork->getScheduledEntityInsertions() as $entity) {
            $className = get_class($entity);
            if (isset($this->monitorEntitiesSetting[$className])) {
                $entityMonitoringConfiguration = $this->monitorEntitiesSetting[$className];

                if (isset($entityMonitoringConfiguration['events']['created'])) {
                    $data = [];
                    foreach ($entityMonitoringConfiguration['data'] as $key => $eelExpression) {
                        $data[$key] = Utility::evaluateEelExpression($eelExpression, $this->eelEvaluator, ['entity' => $entity]);
                    }

                    $event = $this->eventEmittingService->emit($entityMonitoringConfiguration['events']['created'], $data);
                    $unitOfWork->computeChangeSet($entityManager->getClassMetadata(Event::class), $event);
                }
            }
        }

        foreach ($unitOfWork->getScheduledEntityDeletions() as $entity) {
            $className = get_class($entity);
            if (isset($this->monitorEntitiesSetting[$className])) {
                $entityMonitoringConfiguration = $this->monitorEntitiesSetting[$className];

                if (isset($entityMonitoringConfiguration['events']['deleted'])) {
                    $data = [];
                    foreach ($entityMonitoringConfiguration['data'] as $key => $eelExpression) {
                        $data[$key] = Utility::evaluateEelExpression($eelExpression, $this->eelEvaluator, ['entity' => $entity]);
                    }

                    $event = $this->eventEmittingService->emit($entityMonitoringConfiguration['events']['deleted'], $data);
                    $unitOfWork->computeChangeSet($entityManager->getClassMetadata(Event::class), $event);
                }
            }
        }
    }
436785
public function preFlush(PreFlushEventArgs $eventArgs)
    {
        $entityManager = $eventArgs->getEntityManager();
        $unitOfWork = $entityManager->getUnitOfWork();

        foreach ($unitOfWork->getScheduledEntityInsertions() as $object) {
            $this->updateObjectTranslations($entityManager, $object);
        }

        foreach ($unitOfWork->getIdentityMap() as $entities) {
            foreach ($entities as $object) {
                $this->updateObjectTranslations($entityManager, $object);
            }
        }
    }
842467
public function onFlush(OnFlushEventArgs $eventArgs)
    {
        $this->em = $eventArgs->getEntityManager();
        $this->quoteStrategy = $this->em->getConfiguration()->getQuoteStrategy();
        $this->conn = $this->em->getConnection();
        $this->uow = $this->em->getUnitOfWork();
        $this->platform = $this->conn->getDatabasePlatform();
        $this->revisionId = null; // reset revision

        $processedEntities = [];

        foreach ($this->uow->getScheduledEntityDeletions() as $entity) {
            //doctrine is fine deleting elements multiple times. We are not.
            $hash = $this->getHash($entity);

            if (\in_array($hash, $processedEntities, true)) {
                continue;
            }

            $processedEntities[] = $hash;

            $class = $this->em->getClassMetadata(\get_class($entity));
            if (!$this->metadataFactory->isAudited($class->name)) {
                continue;
            }

            $entityData = array_merge($this->getOriginalEntityData($entity), $this->uow->getEntityIdentifier($entity));
            $this->saveRevisionEntityData($class, $entityData, 'DEL');
        }

        foreach ($this->uow->getScheduledEntityInsertions() as $entity) {
            if (!$this->metadataFactory->isAudited(\get_class($entity))) {
                continue;
            }

            $this->extraUpdates[spl_object_hash($entity)] = $entity;
        }

        foreach ($this->uow->getScheduledEntityUpdates() as $entity) {
            if (!$this->metadataFactory->isAudited(\get_class($entity))) {
                continue;
            }

            $this->extraUpdates[spl_object_hash($entity)] = $entity;
        }
    }
400878
public function postFlush(PostFlushEventArgs $eventArgs)
    {        
        foreach ($this->getScheduledForCopyFiles() as $entity){
            $this->fileManager->copyFileToPermanentDirectory($entity);
            $this->fileManager->removeFileFromTemporaryDirectory($entity);
        }
     
        foreach ($this->getScheduledForDeleteFiles() as $entity){
            $this->fileManager->removeAllFiles($entity);
        } 
    }
176814
public function preUpdate(UpdateEvent $event)
    {
        $oldData = $event->getOldData();
        $user = $event->getObject();

        if (!empty($oldData) && $oldData['username'] !== $user->getUsername()) {
            $userRole = $this->roleManager->getUserRole($oldData['username']);
            $this->roleManager->renameUserRole($userRole, $user->getUsername());
            // TODO : rename personal WS if user is renamed
        }
    }
531968
public function beforeUpdate($event)
    {
        $fields = $this->fields;
        $nowDate = gmdate($this->databaseTimeFormat);
        if (!$this->isActuallyDirty()) {
            return;
        }

        if (isset($this->fields['modifiedField']) && !$this->owner->isAttributeChanged($this->fields['modifiedField'])) {
            $this->owner->{$this->fields['modifiedField']} = $nowDate;
        }
        if (isset($this->fields['modifiedByField']) && !$this->owner->isAttributeChanged($this->fields['modifiedByField'])) {
            $this->owner->{$this->fields['modifiedByField']} = self::_getUserId();
        }
    }
372328
public function preUpdate($eventArgs)
    {
        $entity = $eventArgs->getEntity();
        $changeset = $eventArgs->getEntityChangeSet();

        foreach ($this->metadata->getManagedFields($entity) as $field) {
            if (isset($changeset[$field])) {
                list($old, $new) = $changeset[$field];

                if ($old) {
                    $tempFilePath = $this->fileManager->getFilePath($entity, $field, $old);

                    if ($new && ((string)$new) && (string)$new == $tempFilePath) {
                        /** @var File $new */
                        // in this case the file was wrapped in a file object, but not actually changed.
                        // We "unwrap" the value here.
                        $new = $new->getBasename();
                    } else {
                        $filepath = $this->fileManager->getFilePath($entity, $field, $old);
                        $this->unitOfWork[spl_object_hash($entity)][$field]['delete'] =
                            function (FileManager $fm) use ($filepath) {
                                $fm->delete($filepath);
                            };
                    }
                }

                if (is_string($new)) {
                    $eventArgs->setNewValue($field, $new);
                } else {
                    if (null !== $new) {
                        $eventArgs->setNewValue($field, $this->scheduleForUpload($new, $entity, $field));
                    }
                }
            }
        }
    }
1261075
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
    {
        $classMetadata = $eventArgs->getClassMetadata();
        $reflClass = $classMetadata->reflClass;

        if (!$reflClass) {
            return;
        }

        if ($reflClass->implementsInterface('Prezent\Doctrine\Translatable\TranslatableInterface')) {
            $this->mapTranslatable($classMetadata);
        }

        if ($reflClass->implementsInterface('Prezent\Doctrine\Translatable\TranslationInterface')) {
            $this->mapTranslation($classMetadata);
        }
    }
814767
public function onFlush(OnFlushEventArgs $eventArgs)
    {
        $this->entityManager = $eventArgs->getEntityManager();
        $validatedInstancesContainer = new \SplObjectStorage();

        $this->deduplicateValueObjectInsertions();

        $unitOfWork = $this->entityManager->getUnitOfWork();
        foreach ($unitOfWork->getScheduledEntityInsertions() as $entity) {
            $this->validateObject($entity, $validatedInstancesContainer);
        }

        foreach ($unitOfWork->getScheduledEntityUpdates() as $entity) {
            $this->validateObject($entity, $validatedInstancesContainer);
        }
    }
452721
public function prePersist(LifecycleEventArgs $eventArgs)
    {
        $entity = $eventArgs->getObject();

        if (!$this->hasTrait($entity, 'Librinfo\UserBundle\Entity\Traits\Traceable'))
            return;

        $this->logger->debug("[TraceableListener] Entering TraceableListener for « prePersist » event");
        $user = $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : NULL;
        $now = new DateTime('NOW');

        if ($user instanceof UserInterface) {
            $entity->setCreatedBy($user);
            $entity->setUpdatedBy($user);
        }
        $entity->setCreatedAt($now);
        $entity->setUpdatedAt($now);
    }
393895
public function onClear($eventArgs)
    {
        parent::onClear($eventArgs);

        $aliases = array_keys($this->identifierMap);

        $this->identifierMap = array_fill_keys($aliases, []);
    }
1231522
public function onFlush(OnFlushEventArgs $eventArgs)
	{
		$em = $eventArgs->getEntityManager();
		$uow = $em->getUnitOfWork();

		foreach ($uow->getScheduledEntityUpdates() as $entity) {
			if ($entity instanceof TimestampableInterface) {
				$entity->setModificationTime();
				$className = get_class($entity);
				$class = $em->getClassMetadata($className);
				$uow->recomputeSingleEntityChangeSet($class, $entity);
			}
		}
	}