Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Introduce freezing Model #53472

Draft
wants to merge 7 commits into
base: 11.x
Choose a base branch
from
Draft
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
9 changes: 8 additions & 1 deletion src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
use Illuminate\Database\Eloquent\Casts\AsEnumCollection;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Casts\Json;
use Illuminate\Database\Eloquent\FrozenModelException;
use Illuminate\Database\Eloquent\InvalidCastException;
use Illuminate\Database\Eloquent\JsonEncodingException;
use Illuminate\Database\Eloquent\MissingAttributeException;
Expand Down Expand Up @@ -1006,10 +1007,16 @@ protected function isDecimalCast($cast)
* @param string $key
* @param mixed $value
* @return mixed
*
* @throws \Illuminate\Database\Eloquent\FrozenModelException
*/
public function setAttribute($key, $value)
{
// First we will check for the presence of a mutator for the set operation
if ($this->frozen) {
throw FrozenModelException::forSetAttribute($this, $key);
}

// Next we will check for the presence of a mutator for the set operation
// which simply lets the developers tweak the attribute as it is set on
// this model, such as "json_encoding" a listing of data for storage.
if ($this->hasSetMutator($key)) {
Expand Down
46 changes: 46 additions & 0 deletions src/Illuminate/Database/Eloquent/FrozenModelException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

namespace Illuminate\Database\Eloquent;

use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use PhpParser\Node\Expr\AssignOp\Mod;

class FrozenModelException extends \RuntimeException
{
/**
* @param Model $model
* @return self
*/
public static function forFill(Model $model)
{
return new self(sprintf("Cannot fill properties on Model [%s] because it is frozen.", $model::class));
}

/**
* @param Model $model
* @param string $attribute
* @return self
*/
public static function forSetAttribute(Model $model, string $attribute)
{
return new self(sprintf("Cannot set property [%s] on Model [%s] because it is frozen.", $attribute,
$model::class));
}

public static function forRelations(Model $model, array $relations)
{
return new self(
sprintf(
"Cannot load relation(s) [%s] on Model [%s] because it is frozen.",
Arr::join($relations, ', '),
$model::class
)
);
}

public static function forUnset(Model $model)
{
return new self(sprintf("Cannot unset properties or relations on Model [%s] because it is frozen.", $model::class));
}
}
40 changes: 40 additions & 0 deletions src/Illuminate/Database/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ abstract class Model implements Arrayable, ArrayAccess, CanBeEscapedWhenCastToSt
Concerns\GuardsAttributes,
Concerns\PreventsCircularRecursion,
ForwardsCalls;

/** @use HasCollection<\Illuminate\Database\Eloquent\Collection<array-key, static>> */
use HasCollection;

Expand Down Expand Up @@ -124,6 +125,13 @@ abstract class Model implements Arrayable, ArrayAccess, CanBeEscapedWhenCastToSt
*/
protected $escapeWhenCastingToString = false;

/**
* Indicates that the model is frozen and cannot modify properties or load relations.
*
* @var bool
*/
protected $frozen = false;

/**
* The connection resolver instance.
*
Expand Down Expand Up @@ -526,6 +534,10 @@ public static function withoutBroadcasting(callable $callback)
*/
public function fill(array $attributes)
{
if ($this->frozen) {
throw FrozenModelException::forFill($this);
}

$totallyGuarded = $this->totallyGuarded();

$fillable = $this->fillableFromArray($attributes);
Expand Down Expand Up @@ -716,6 +728,10 @@ public static function with($relations)
*/
public function load($relations)
{
if ($this->frozen) {
throw FrozenModelException::forRelations($this, Arr::wrap($relations));
}

$query = $this->newQueryWithoutRelationships()->with(
is_string($relations) ? func_get_args() : $relations
);
Expand Down Expand Up @@ -2117,6 +2133,25 @@ public function resolveSoftDeletableChildRouteBinding($childType, $value, $field
return $this->resolveChildRouteBindingQuery($childType, $value, $field)->withTrashed()->first();
}

/**
* @param bool $frozen
* @return $this
*/
public function freeze($frozen = true)
{
$this->frozen = $frozen;

return $this;
}

/**
* @return bool
*/
public function isFrozen()
{
return $this->frozen;
}

/**
* Retrieve the child model query for a bound value.
*
Expand Down Expand Up @@ -2314,9 +2349,14 @@ public function offsetSet($offset, $value): void
*
* @param mixed $offset
* @return void
* @throws FrozenModelException
*/
public function offsetUnset($offset): void
{
if ($this->frozen) {
throw FrozenModelException::forUnset($this);
}

unset($this->attributes[$offset], $this->relations[$offset]);
}

Expand Down
107 changes: 107 additions & 0 deletions tests/Database/DatabaseEloquentModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\FrozenModelException;
use Illuminate\Database\Eloquent\JsonEncodingException;
use Illuminate\Database\Eloquent\MassAssignmentException;
use Illuminate\Database\Eloquent\MissingAttributeException;
Expand All @@ -48,6 +49,7 @@
use InvalidArgumentException;
use LogicException;
use Mockery as m;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use stdClass;
Expand Down Expand Up @@ -3178,6 +3180,111 @@ public function testCollectedByAttribute()

$this->assertInstanceOf(CustomEloquentCollection::class, $collection);
}

public function testCanFreezeModel()
{
$model = new EloquentModelStub();
$this->assertFalse($model->isFrozen());
$model->freeze();
$this->assertTrue($model->isFrozen());
$model->freeze(false);
$this->assertFalse($model->isFrozen());
}

public function testCannotSetAttributeOnFrozenModel()
{
$model = new EloquentModelStub();
$model->freeze();

try {
$model->castedFloat = 199.2;
$this->fail("No FrozenModelException thrown");
} catch (FrozenModelException $exception) {
$this->assertEquals("Cannot set property [castedFloat] on Model [Illuminate\Tests\Database\EloquentModelStub] because it is frozen.", $exception->getMessage());
}
}

public function testCannotOffsetSetAttributeOnFrozenModel()
{
$model = new EloquentModelStub();
$model->freeze();

try {
$model['castedFloat'] = 199.2;
$this->fail("No FrozenModelException thrown");
} catch (FrozenModelException $exception) {
$this->assertEquals("Cannot set property [castedFloat] on Model [Illuminate\Tests\Database\EloquentModelStub] because it is frozen.", $exception->getMessage());
}
}

#[DataProvider('cannotLoadRelationsDataProvider')]
public function testCannotLoadRelationOnFrozenModel($relations, $relationsAsString)
{
$model = new EloquentModelStub();
$model->freeze();

try {
$model->load($relations);
$this->fail("No exception thrown");
} catch (FrozenModelException $exception) {
$this->assertEquals("Cannot load relation(s) [$relationsAsString] on Model [Illuminate\Tests\Database\EloquentModelStub] because it is frozen.", $exception->getMessage());
}
}

public static function cannotLoadRelationsDataProvider()
{
return [
'single relation as string' => ['morphToStub', 'morphToStub'],
'single relation in array' => [['morphToStub'], 'morphToStub'],
'multiple relations in array' => [['belongsToStub', 'morphsToStub'], 'belongsToStub, morphsToStub']
];
}

public function testCannotFillOnFrozenModel()
{
$model = new EloquentModelStub();
$model->freeze();

try {
$model->fill([
'castedFloat' => 2001.3
]);
$this->fail("No FrozenModelException thrown.");
} catch (FrozenModelException $exception) {
$this->assertEquals(
'Cannot fill properties on Model [Illuminate\Tests\Database\EloquentModelStub] because it is frozen.',
$exception->getMessage()
);
}
}

public function testCannotUnsetAttributeOnFrozenModel()
{
$model = new EloquentModelStub();
$model->freeze();

try {
unset($model['castedFloat']);
$this->fail("No exception was thrown");
} catch (FrozenModelException $exception) {
$this->assertEquals("Cannot unset properties or relations on Model [Illuminate\Tests\Database\EloquentModelStub] because it is frozen.", $exception->getMessage());
}
}

public function testCannotOffsetUnsetAttributeOnFrozenModel()
{
$model = new EloquentModelStub();
$model->freeze();

try {
$model->offsetUnset('castedFloat');
$this->fail("No exception was thrown");
} catch (FrozenModelException $exception) {
$this->assertEquals("Cannot unset properties or relations on Model [Illuminate\Tests\Database\EloquentModelStub] because it is frozen.", $exception->getMessage());
}
}


}

class EloquentTestObserverStub
Expand Down