You are here

protected function ProcessEntities::setEncryptedFieldValues in Field Encryption 3.0.x

Sets an entity's encrypted fields to a value.

Parameters

\Drupal\Core\Entity\ContentEntityInterface $entity: The entity to set the values on.

string|null $method: (optional) The method call to set the value. By default, this code sets the encrypted field to the decrypted value. If $method is set then it is called with the entity, the field and the property name.

2 calls to ProcessEntities::setEncryptedFieldValues()
ProcessEntities::decryptEntity in src/ProcessEntities.php
Decrypts an entity's encrypted fields.
ProcessEntities::encryptEntity in src/ProcessEntities.php
Encrypts an entity's encrypted fields.

File

src/ProcessEntities.php, line 171

Class

ProcessEntities
Service class to process entities and fields for encryption.

Namespace

Drupal\field_encrypt

Code

protected function setEncryptedFieldValues(ContentEntityInterface $entity, string $method = NULL) {
  $storage = $entity
    ->get(static::ENCRYPTED_FIELD_STORAGE_NAME)->decrypted_value ?? [];
  foreach ($storage as $field_name => $decrypted_field) {
    if (!$entity
      ->hasField($field_name)) {
      continue;
    }
    $field = $entity
      ->get($field_name);
    $field_value = $field
      ->getValue();

    // Process each of the field properties that exist.
    foreach ($field_value as $delta => &$value) {
      if (!isset($storage[$field_name][$delta])) {
        continue;
      }

      // Process each of the field properties that exist.
      foreach ($decrypted_field[$delta] as $property_name => $decrypted_value) {
        if ($method) {

          // @see \Drupal\field_encrypt\ProcessEntities::getUnencryptedPlaceholderValue()
          $value[$property_name] = $this
            ->{$method}($entity, $field, $property_name);
        }
        else {
          $value[$property_name] = $decrypted_value;
        }
      }
    }

    // Set the new value. Calling setValue() updates the entity too.
    $field
      ->setValue($field_value);
  }
}