You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.3 KiB
PHTML

2 years ago
<?php
namespace App\Libs;
use Illuminate\Support\Facades\Crypt;
trait Encryptable
{
public function getCryptData()
{
if($this->_crypt_data == null && $this->_cryptable) {
$cryptValue = $this->{$this->_cryptable};
// logger($cryptValue);
// print_r($cryptValue);
if($cryptValue) {
try {
$decryptValue = Crypt::decryptString($cryptValue);
$this->_crypt_data = json_decode($decryptValue, true);
} catch (\Exception $e) {
logger($e->getTraceAsString());
$this->_crypt_data = [];
}
// print_r($this->_crypt_data);
}
else $this->_crypt_data = [];
// logger($this->_crypt_data);
// print_r($this->_crypt_data);
}
return $this->_crypt_data;
}
public function cryptData($data)
{
if($data == null || count($data) == 0) {
$this->{$this->_cryptable} = null;
$this->_crypt_data = null;
return;
}
// print_r($data);
$jsonText = json_encode($data);
// AES-256-CBC
try {
$encryptValue = Crypt::encryptString($jsonText);
$this->{$this->_cryptable} = $encryptValue;
$this->_crypt_data = null;
} catch (\Exception $e) {
logger($e->getTraceAsString());
$this->{$this->_cryptable} = null;
$this->_crypt_data = null;
}
}
public function getAttribute($key)
{
if (in_array($key, $this->encryptable)) {
return $this->getEncryptValue($key);
}
return parent::getAttribute($key);
}
private function getEncryptValue($key)
{
if (in_array($key, $this->encryptable)) {
$data = $this->getCryptData();
if(isset($data[$key])) return $data[$key];
return null;
}
return null;
}
public function setAttribute($key, $value)
{
// logger('--------EncrypUser------');
if (in_array($key, $this->encryptable)) {
$data = $this->getCryptData();
if($value) $data[$key] = $value;
$this->cryptData($data);
}
else parent::setAttribute($key, $value);
}
}