Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save saeedvir/1a360b39989862d9550cad02e8c1e3b9 to your computer and use it in GitHub Desktop.
Save saeedvir/1a360b39989862d9550cad02e8c1e3b9 to your computer and use it in GitHub Desktop.
Laravel Data Masking (Encode & Decode Model fields ) Trait
/*
** saeed abdollahian
** Freelance PHP developer & consultant. Laravel specialist.
** Freelance (available)
** https://t.me/PhpWebDeveloper
*/
<?php
namespace App;
/*
Usage:
only add this lines to your model(s):
use App\EncoderTrait;
use EncoderTrait
#filds name for encode/decode
private static $encode_cols =[
'email',
'phone',
];
*/
trait EncoderTrait
{
protected static function boot()
{
parent::boot();
#On retrieved Event
static::retrieved(function ($model) {
if (isset($model::$encode_cols)) {
$encode_cols = $model::$encode_cols;
foreach ($encode_cols as $key => $value) {
$model->$value = self::decode_item($model->$value);
}
}
});
#On creating Event
static::creating(function ($model) {
if (isset($model::$encode_cols)) {
$encode_cols = $model::$encode_cols;
$original = $model->getAttributes();
$original = array_keys($original);
foreach ($encode_cols as $key => $value) {
if (in_array($value, $original)) {
$model->$value = self::encode_item($model->$value);
}
}
}
});
#On updating Event
static::updating(function ($model) {
if (isset($model::$encode_cols)) {
$encode_cols = $model::$encode_cols;
$changes = $model->getDirty();
$changes = array_keys($changes);
if (count($changes) > 0) {
foreach ($encode_cols as $key => $value) {
if (in_array($value, $changes)) {
$model->$value = self::encode_item($model->$value);
}
}
}
}
});
}
/*
change encode/Decode Functions
*/
protected static function encode_item($string)
{
//return base64_encode($string);
if (!$string) {
return false;
}
$key = sha1(env('APP_KEY','abcd123'));
$strLen = strlen($string);
$keyLen = strlen($key);
$j = 0;
$crypttext = "";
for ($i = 0; $i < $strLen; $i++) {
$ordStr = ord(substr($string, $i, 1));
if ($j == $keyLen) {
$j = 0;
}
$ordKey = ord(substr($key, $j, 1));
$j++;
$crypttext .= strrev(base_convert(dechex($ordStr + $ordKey), 16, 36));
}
return $crypttext;
}
protected static function decode_item($string)
{
//return base64_decode($string);
if (!$string) {
return false;
}
$key = sha1(env('APP_KEY','abcd123'));
$strLen = strlen($string);
$keyLen = strlen($key);
$j = 0;
$decrypttext = "";
for ($i = 0; $i < $strLen; $i += 2) {
$ordStr = hexdec(base_convert(strrev(substr($string, $i, 2)), 36, 16));
if ($j == $keyLen) {
$j = 0;
}
$ordKey = ord(substr($key, $j, 1));
$j++;
$decrypttext .= chr($ordStr - $ordKey);
}
return $decrypttext;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment