. */ namespace SP\DataModel; use Defuse\Crypto\Exception\CryptoException; use SP\Core\Crypt\Crypt; use SP\Core\Exceptions\NoSuchPropertyException; /** * Trait EncryptedModel * * @package SP\DataModel */ trait EncryptedModel { /** * @var string */ private $key; /** * @param string $key * @param string $property * * @return static|null * @throws NoSuchPropertyException * @throws CryptoException */ public function encrypt(string $key, string $property = 'data') { if (property_exists($this, $property)) { if ($this->$property === null) { return null; } $this->key = Crypt::makeSecuredKey($key); $this->$property = Crypt::encrypt($this->$property, $this->key, $key); return $this; } throw new NoSuchPropertyException($property); } /** * @param string $key * @param string $property * * @return static|null * @throws NoSuchPropertyException * @throws CryptoException */ public function decrypt(string $key, string $property = 'data') { if (property_exists($this, $property) && !empty($this->key) ) { if ($this->$property === null) { return null; } $this->$property = Crypt::decrypt($this->$property, $this->key, $key); return $this; } throw new NoSuchPropertyException($property); } /** * @return string */ public function getKey(): string { return $this->key; } }