encryptor = $encryptor; } public function getSubscribedEvents(): array { return [ Events::postLoad, Events::preFlush, ]; } /** * After loading an entity, populate the decrypted properties by decrypting the encrypted tracked property. * * Track the entity so that we also update fields in preFlush. */ public function postLoad(LifecycleEventArgs $args): void { $entity = $args->getEntity(); if (!$entity instanceof EncryptingEntityInterface) { return; } $entity->decrypt($this->encryptor); } /** * Encrypt properties of entities that are newly inserted into the database or that have previously been loaded from the database. */ public function preFlush(PreFlushEventArgs $preFlushEventArgs): void { // encrypt entities that we are about to insert $unitOfWork = $preFlushEventArgs->getEntityManager()->getUnitOfWork(); foreach ($unitOfWork->getScheduledEntityInsertions() as $entity) { if ($entity instanceof EncryptingEntityInterface) { $entity->encrypt($this->encryptor); } } } }