1
0
Fork 0
mirror of https://github.com/archtechx/virtualcolumn.git synced 2025-12-12 18:44:04 +00:00

Handle and test 'encrypted' casts

This commit is contained in:
lukinovec 2023-08-08 09:40:40 +02:00
parent 3213a8e856
commit 874a697d21
2 changed files with 19 additions and 4 deletions

View file

@ -4,6 +4,8 @@ declare(strict_types=1);
namespace Stancl\VirtualColumn;
use Illuminate\Support\Facades\Crypt;
/**
* This trait lets you add a "data" column functionality to any Eloquent model.
* It serializes attributes which don't exist as columns on the model's table
@ -31,6 +33,10 @@ trait VirtualColumn
}
foreach ($model->getAttribute(static::getDataColumn()) ?? [] as $key => $value) {
if ($model->hasCast($key, 'encrypted')) {
$value = Crypt::decryptString($value);
}
$model->setAttribute($key, $value);
$model->syncOriginalAttribute($key);
}

View file

@ -2,9 +2,10 @@
namespace Stancl\VirtualColumn\Tests;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Orchestra\Testbench\TestCase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Database\Eloquent\Model;
use Stancl\VirtualColumn\VirtualColumn;
class VirtualColumnTest extends TestCase
@ -112,7 +113,15 @@ class VirtualColumnTest extends TestCase
$model = MyModel::create(['password' => $password = 'foo']);
// Virtual column gets encrypted
// todo1 check what value actually got saved in $model->password (should be encrypted 'foo')
$rawEncryptedPassword = (array) DB::table('my_models')
->select('data->password')
->where('id', $model->id)
->first();
$encryptedPassword = $rawEncryptedPassword[array_key_first((array) $rawEncryptedPassword)];
$this->assertNotSame($encryptedPassword, $password);
$this->assertSame(Crypt::decryptString($encryptedPassword), $password);
// Virtual column gets decrypted
$this->assertSame($model->password, $password);
@ -128,7 +137,7 @@ class MyModel extends Model
protected $guarded = [];
public $timestamps = false;
public $casts = [
'password'
'password' => 'encrypted'
];
public static function getCustomColumns(): array