vendor/specshaper/encrypt-bundle/Subscribers/EncryptEventSubscriber.php line 76

Open in your IDE?
  1. <?php
  2. namespace SpecShaper\EncryptBundle\Subscribers;
  3. use SpecShaper\EncryptBundle\Encryptors\EncryptorInterface;
  4. use SpecShaper\EncryptBundle\Event\EncryptEventInterface;
  5. use SpecShaper\EncryptBundle\Event\EncryptEvents;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. /**
  8.  * Doctrine event subscriber which encrypt/decrypt entities.
  9.  */
  10. class EncryptEventSubscriber implements EventSubscriberInterface
  11. {
  12.     /**
  13.      * Encryptor created by the factory service.
  14.      */
  15.     protected EncryptorInterface $encryptor;
  16.     /**
  17.      * Store if the encryption is enabled or disabled in config.
  18.      */
  19.     private bool $isDisabled;
  20.     /**
  21.      * EncryptSubscriber constructor.
  22.      *
  23.      * @param $isDisabled
  24.      */
  25.     public function __construct(EncryptorInterface $encryptorbool $isDisabled)
  26.     {
  27.         $this->encryptor $encryptor;
  28.         $this->isDisabled $isDisabled;
  29.     }
  30.     /**
  31.      * Return the encryptor.
  32.      */
  33.     public function getEncryptor(): EncryptorInterface
  34.     {
  35.         return $this->encryptor;
  36.     }
  37.     /**
  38.      * Realization of EventSubscriber interface method.
  39.      *
  40.      * @return array Return all events which this subscriber is listening
  41.      */
  42.     public static function getSubscribedEvents(): array
  43.     {
  44.         return [
  45.             EncryptEvents::ENCRYPT => 'encrypt',
  46.             EncryptEvents::DECRYPT => 'decrypt',
  47.         ];
  48.     }
  49.     /**
  50.      * Use an Encrypt even to encrypt a value.
  51.      */
  52.     public function encrypt(EncryptEventInterface $event): EncryptEventInterface
  53.     {
  54.         $value $event->getValue();
  55.         if (false === $this->isDisabled) {
  56.             $value $this->encryptor->encrypt($value);
  57.         }
  58.         $event->setValue($value);
  59.         return $event;
  60.     }
  61.     /**
  62.      * Use a decrypt event to decrypt a single value.
  63.      */
  64.     public function decrypt(EncryptEventInterface $event): EncryptEventInterface
  65.     {
  66.         $value $event->getValue();
  67.         $decrypted $this->getEncryptor()->decrypt($value);
  68.         $event->setValue($decrypted);
  69.         return $event;
  70.     }
  71.     /**
  72.      * Decrypt a value.
  73.      *
  74.      * If the value is an object, or if it does not contain the suffic <ENC> then return the value iteslf back.
  75.      * Otherwise, decrypt the value and return.
  76.      */
  77.     public function decryptValue(?string $value): ?string
  78.     {
  79.         return $this->getEncryptor()->decrypt($value);
  80.     }
  81. }