Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .styleci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ php:
finder:
not-name:
- bad-syntax-strategy.php
- "*ExcludedFromStyleCiTest.php"
js:
finder:
exclude:
Expand Down
21 changes: 14 additions & 7 deletions src/Illuminate/Database/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -2584,18 +2584,25 @@ public function escapeWhenCastingToString($escape = true)
/**
* Prepare the object for serialization.
*
* @return array
* @return string[]
*/
public function __sleep()
public function __serialize(): array
{
$this->mergeAttributesFromCachedCasts();

$this->classCastCache = [];
$this->attributeCastCache = [];
$this->relationAutoloadCallback = null;
$this->relationAutoloadContext = null;
// When serializing the model, we may accidentally catch up some virtual properties.
// We will transform the instance to an array to skip them, and then we will remove
// the model caches so those values are not serialized with the rest of the model.
$props = get_mangled_object_vars($this);

unset(
$props["\0*\0classCastCache"],
$props["\0*\0attributeCastCache"],
$props["\0*\0relationAutoloadCallback"],
$props["\0*\0relationAutoloadContext"],
);

return array_keys(get_object_vars($this));
return $props;
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

namespace Illuminate\Tests\Database;

use PHPUnit\Framework\TestCase;

class DatabaseEloquentSerializationExcludedFromStyleCiTest extends TestCase
{
public function testModelSkipsVirtualPropertiesOnSerialization()
{
if (version_compare(PHP_VERSION, '8.4.0-dev', '<')) {
$this->markTestSkipped('Requires Virtual Properties.');
}

$model = new EloquentModelWithVirtualPropertiesStub();
$model->foo = 'bar';

$serialized = serialize($model);

$this->assertStringNotContainsString('virtualGet', $serialized);
$this->assertStringNotContainsString('virtualSet', $serialized);

// Ensure attributes and protected normal attributes are also serialized.
$this->assertStringContainsString('foo', $serialized);
$this->assertStringContainsString('bar', $serialized);
$this->assertStringContainsString('isVisible', $serialized);
$this->assertStringContainsString('yes', $serialized);
}
}

if (version_compare(PHP_VERSION, '8.4.0-dev', '>=')) {
eval(<<<'PHP'
namespace Illuminate\Tests\Database;

use Illuminate\Database\Eloquent\Model;

class EloquentModelWithVirtualPropertiesStub extends Model
{
public $virtualGet {
get => $this->foo;
}

public $virtualSet {
get => $this->foo;
set {
//
}
}

protected $isVisible = 'yes';
}

PHP
);
}
Loading