. */ namespace SP\DataModel; use SP\Domain\Core\Crypt\CryptInterface; use SP\Domain\Core\Exceptions\CryptException; use SP\Domain\Core\Exceptions\NoSuchPropertyException; /** * Trait EncryptedModel */ trait EncryptedModel { protected ?string $key = null; /** * @param string $key * @param CryptInterface $crypt * @param string $property * * @return EncryptedModel * @throws CryptException * @throws NoSuchPropertyException */ public function encrypt(string $key, CryptInterface $crypt, string $property = 'data'): static { if (property_exists($this, $property)) { if ($this->{$property} === null) { return $this; } $this->key = $crypt->makeSecuredKey($key); $this->{$property} = $crypt->encrypt($this->{$property}, $this->key, $key); return $this; } throw new NoSuchPropertyException($property); } /** * @param string $key * @param CryptInterface $crypt * @param string $property * * @return EncryptedModel * @throws CryptException * @throws NoSuchPropertyException */ public function decrypt(string $key, CryptInterface $crypt, string $property = 'data'): static { if (property_exists($this, $property) && !empty($this->key)) { if ($this->{$property} === null) { return $this; } $this->{$property} = $crypt->decrypt($this->{$property}, $this->key, $key); return $this; } throw new NoSuchPropertyException($property); } public function getKey(): ?string { return $this->key; } }