You are here

public function EncryptionProfile::validate in Encrypt 8.3

Validate the EncryptionProfile entity.

Parameters

string $text: The text to be encrypted / decrypted.

Return value

array An array of validation errors. Empty if no errors.

Overrides EncryptionProfileInterface::validate

1 call to EncryptionProfile::validate()
EncryptionProfile::preSave in src/Entity/EncryptionProfile.php
Acts on an entity before the presave hook is invoked.

File

src/Entity/EncryptionProfile.php, line 193

Class

EncryptionProfile
Defines the EncryptionProfile entity.

Namespace

Drupal\encrypt\Entity

Code

public function validate($text = NULL) {
  $errors = [];

  // Check if the object properties are set correctly.
  if (!$this
    ->getEncryptionMethodId()) {
    $errors[] = $this
      ->t('No encryption method selected.');
  }
  if (!$this
    ->getEncryptionKeyId()) {
    $errors[] = $this
      ->t('No encryption key selected.');
  }

  // If the properties are set, continue validation.
  if ($this
    ->getEncryptionMethodId() && $this
    ->getEncryptionKeyId()) {

    // Check if the linked encryption method is valid.
    $encryption_method = $this
      ->getEncryptionMethod();
    if (!$encryption_method) {
      $errors[] = $this
        ->t('The encryption method linked to this encryption profile does not exist.');
    }

    // Check if the linked encryption key is valid.
    $selected_key = $this
      ->getEncryptionKey();
    if (!$selected_key) {
      $errors[] = $this
        ->t('The key linked to this encryption profile does not exist.');
    }

    // If the encryption method and key are valid, continue validation.
    if (empty($errors)) {

      // Check if the selected key type matches encryption method settings.
      $allowed_key_types = $encryption_method
        ->getPluginDefinition()['key_type'];
      if (!empty($allowed_key_types)) {
        $selected_key_type = $selected_key
          ->getKeyType();
        if (!in_array($selected_key_type
          ->getPluginId(), $allowed_key_types)) {
          $errors[] = $this
            ->t('The selected key cannot be used with the selected encryption method.');
        }
      }

      // Check if encryption method dependencies are met.
      $encryption_method = $this
        ->getEncryptionMethod();
      if (!$text) {
        $text = Crypt::randomBytesBase64();
      }
      $dependency_errors = $encryption_method
        ->checkDependencies($text, $selected_key
        ->getKeyValue());
      $errors = array_merge($errors, $dependency_errors);
    }
  }
  return $errors;
}