/**
  * @param CryptableInterface $entity
  * @param EntityManager $em
  * @return bool
  */
 protected function cryptEntity(CryptableInterface $entity, EntityManager $em)
 {
     if (!$this->getUser()) {
         $this->logError("Cannot encrypt entity with no user in security context", $entity);
         return false;
     }
     if (true === $entity->getIsEncrypted()) {
         $this->logError("Entity already encrypted", $entity);
         return false;
     }
     try {
         $ownershipId = $this->encryptionManager->getEncryptionOwnershipId();
     } catch (EmptyOwnershipIdException $e) {
         $this->logError("Missing ownership ID on entity", $entity, $e);
         return false;
     }
     if ((string) $entity->getEncryptionOwnershipId() !== (string) $ownershipId) {
         $this->logError("Wrong ownership ID on entity", $entity);
         return false;
     }
     $uow = $em->getUnitOfWork();
     $cs = $uow->getEntityChangeSet($entity);
     $hasChanges = false;
     foreach ($entity->getEncryptedProperties() as $property) {
         $iv = null;
         // If Entity was already decrypted, we need to encrypt all properties even if there is no change
         if (!$this->alreadyDecryptedEntities->contains($entity)) {
             if (!isset($cs[$property])) {
                 continue;
             }
             $oldValue = $cs[$property][0];
             if ($oldValue) {
                 // If existing iv, use this one
                 $iv = $this->encryptionManager->parseIv($oldValue);
                 if (strlen($iv) !== $this->encryptionManager->getIvSize()) {
                     $iv = null;
                 }
             }
         }
         $getter = 'get' . ucfirst($property);
         $setter = 'set' . ucfirst($property);
         $newEncryptedValue = $this->encryptionManager->encryptString($entity->{$getter}(), $iv);
         $entity->{$setter}(base64_encode($newEncryptedValue));
         $hasChanges = true;
     }
     $entity->setIsEncrypted(true);
     if ($hasChanges) {
         $class = $em->getClassMetadata(get_class($entity));
         $uow->recomputeSingleEntityChangeSet($class, $entity);
     }
     $this->flushedEntities->add($entity);
     return $hasChanges;
 }