Symfony 4 - encrypt/decrypt fields used in doctrine with a Service?
17:36 02 Oct 2018

So I have fields in my database in an entity

class Person
{
    // other fields

    /**
     * @var string
     *
     * @ORM\Column(name="last_name", type="string", length=50, nullable=false)
     */
    private $lastName;

    /**
     * @var string
     *
     * @ORM\Column(name="first_name", type="string", length=50, nullable=false)
     */
    private $firstName;

   // getters and setters
}

I have a Service called SecureEncryptor. That has Decrypt() and Encrypt() functions - basically you just pass the encrypted/unencrypted (respectively) string to it and it'll do the according.

Problem is I'm not sure how to use that Service in conjunction with the Entity - specifically when taking into account Forms (Types). I mean I know I could just get the field and call the Decrypt function but that wouldn't work with a Type bound to the Person Entity.

I started down the road of making a separate Entity for the decrypted Person and then I would switch it over when it was time to deal with the database but that seemed wrong. My other idea was to call the service from the Entity but I've read that's wrong too.

Any ideas?

Edit:

This is basically what I want to do:

$builder->get('dateOfBirth')
   ->addModelTransformer(new CallbackTransformer(
       function ($encryptedDOB) {
           return $this->encryptor->decrypt($encryptedDOB, salt); // How do I get the salt value here?
       },
      function ($decryptedDOB) {
         return $this->encryptor->encrypt($decryptedDOB, salt); // How do I get the salt value here?
      }
 ));

or perhaps decrypt/encrypt the data BEFORE this step but not sure how to accomplish that.

EDIT 2:

I found this which shows you can get to the entity data in the PRE_SET_DATA event, but you can't add a Data Transformer in there so not sure how that could work.

php symfony encryption symfony4