mirror of
https://github.com/archtechx/virtualcolumn.git
synced 2025-12-12 08:04:04 +00:00
Merge 5426e41a5c into 4664d00099
This commit is contained in:
commit
316a8241cc
3 changed files with 44 additions and 2 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -2,3 +2,4 @@
|
|||
composer.lock
|
||||
.phpunit.result.cache
|
||||
.php-cs-fixer.cache
|
||||
.idea/
|
||||
|
|
|
|||
|
|
@ -31,9 +31,11 @@ trait VirtualColumn
|
|||
*/
|
||||
public bool $dataEncoded = false;
|
||||
|
||||
public bool $dataNotLoaded = false;
|
||||
|
||||
protected function decodeVirtualColumn(): void
|
||||
{
|
||||
if (! $this->dataEncoded) {
|
||||
if (! $this->dataEncoded || ! $this->dataNotLoaded) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -65,6 +67,10 @@ trait VirtualColumn
|
|||
return;
|
||||
}
|
||||
|
||||
if ($this->dataNotLoaded) {
|
||||
throw new \Exception('Data column was not loaded from the database. Make sure the data column is selected in the query.');
|
||||
}
|
||||
|
||||
$dataColumn = static::getDataColumn();
|
||||
$customColumns = static::getCustomColumns();
|
||||
$attributes = array_filter($this->getAttributes(), fn ($key) => ! in_array($key, $customColumns), ARRAY_FILTER_USE_KEY);
|
||||
|
|
@ -107,7 +113,14 @@ trait VirtualColumn
|
|||
return [
|
||||
'retrieved' => [
|
||||
function () {
|
||||
// Always decode after model retrieval
|
||||
// If the data column wasn't retrieved, don't decode it
|
||||
if (($this->attributes[static::getDataColumn()] ?? null) === null) {
|
||||
$this->dataNotLoaded = true;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Mark the data as encoded so that it doesn't get encoded again
|
||||
$this->dataEncoded = true;
|
||||
|
||||
$this->decodeVirtualColumn();
|
||||
|
|
|
|||
|
|
@ -129,6 +129,34 @@ class VirtualColumnTest extends TestCase
|
|||
$this->assertSame($encodedBar->bar, 'bar');
|
||||
}
|
||||
|
||||
/** @test */
|
||||
public function model_doesnt_overwrite_when_selectively_fetching() {
|
||||
$this->expectExceptionMessage('Data column was not loaded from the database. Make sure the data column is selected in the query.');
|
||||
|
||||
FooModel::create([
|
||||
'id' => 1,
|
||||
'foo' => 'bar'
|
||||
]);
|
||||
|
||||
$foo = FooModel::query()->first(['id']);
|
||||
$foo->bar = 'baz';
|
||||
$foo->save();
|
||||
}
|
||||
|
||||
/** @test */
|
||||
public function decoding_works_with_strict_mode_enabled() {
|
||||
FooModel::shouldBeStrict();
|
||||
|
||||
FooModel::create([
|
||||
'id' => 1,
|
||||
'foo' => 'bar'
|
||||
]);
|
||||
|
||||
$id = FooModel::query()->pluck('id')->first();
|
||||
|
||||
$this->assertSame(1, $id);
|
||||
}
|
||||
|
||||
// maybe add an explicit test that the saving() and updating() listeners don't run twice?
|
||||
|
||||
#[Test]
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue