File: custom/Espo/Custom/Entities/EncryptedEntity.php
PHP Code:
<?php
namespace Espo\Custom\Entities;
use Espo\ORM\BaseEntity;
use Espo\ORM\EntityManager;
use Espo\ORM\Value\ValueAccessorFactory;
use Espo\Core\Utils\Crypt;
abstract class EncryptedEntity extends BaseEntity
{
private $isEncrypted;
public function __construct(
string $entityType,
array $defs,
?EntityManager $entityManager = null,
?ValueAccessorFactory $valueAccessorFactory = null,
private Crypt $crypt,
) {
parent::__construct(
$entityType,
$defs,
$entityManager,
$valueAccessorFactory
);
$this->isEncrypted = [];
foreach ($defs['fields'] as $field => $value) {
if (array_key_exists('isEncrypted', $value) && $value['isEncrypted']) {
$this->isEncrypted[] = $field;
}
}
}
protected function setInContainer(string $attribute, $value): void
{
if (in_array($attribute, $this->isEncrypted)) {
$value = $this->crypt->encrypt($value);
}
parent::setInContainer($attribute, $value);
return;
}
public function setFetched(string $attribute, $value): void
{
if (in_array($attribute, $this->isEncrypted)) {
$value = $this->crypt->decrypt($value);
parent::setInContainer($attribute, $value);
}
parent::setFetched($attribute, $value);
}
protected function getFromContainer(string $attribute)
{
$value = parent::getFromContainer($attribute);
if (in_array($attribute, $this->isEncrypted)) {
return $this->crypt->decrypt($value);
}
return $value;
}
public function getFetched(string $attribute)
{
$value = parent::getFetched($attribute);
if (in_array($attribute, $this->isEncrypted) && !is_null($value)) {
$value = $this->crypt->decrypt($value);
}
return $value;
}
}PHP Code:
{
"fields": {
/** other definitions **/
"<field name>": {
/** field attributes **/
"isEncrypted": true
},
},
"indexes": {
/** index definitions **/
}
}
PHP Code:
namespace Espo/Custom/Entities;
use Espo/Custom/Entities/EncryptedEntity;
class MyEntity extends EncryptedEntity
{}
If anyone has any input or suggestions, please share.

Leave a comment: