Datasets:

Modalities:
Text
Formats:
parquet
Languages:
English
ArXiv:
Libraries:
Datasets
pandas
License:
Dataset Viewer
Auto-converted to Parquet
id
int64
0
886
original_context
stringlengths
648
56.6k
modified_context
stringlengths
587
47.6k
omitted_context
sequencelengths
0
19
omitted_index
sequencelengths
0
19
metadata
dict
0
diff --git a/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php b/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php index 09fbf4829e7..25549425b7c 100644 --- a/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php +++ b/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php @@ -107,7 +107,7 @@ public function restoreModel($value) { return $this->getQueryForModelRestoration( (new $value->class)->setConnection($value->connection), $value->id - )->useWritePdo()->firstOrFail()->load($value->relations ?? []); + )->useWritePdo()->firstOrFail()->loadMissing($value->relations ?? []); } /** diff --git a/tests/Integration/Queue/ModelSerializationTest.php b/tests/Integration/Queue/ModelSerializationTest.php index bd3b401c657..e13cbb4ec29 100644 --- a/tests/Integration/Queue/ModelSerializationTest.php +++ b/tests/Integration/Queue/ModelSerializationTest.php @@ -31,6 +31,8 @@ protected function setUp(): void { parent::setUp(); + Model::preventLazyLoading(false); + Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('email'); @@ -161,6 +163,28 @@ public function testItReloadsRelationships() $this->assertEquals($unSerialized->order->getRelations(), $order->getRelations()); } + public function testItReloadsRelationshipsOnlyOnce() + { + $order = tap(ModelSerializationTestCustomOrder::create(), function (ModelSerializationTestCustomOrder $order) { + $order->wasRecentlyCreated = false; + }); + + $product1 = Product::create(); + $product2 = Product::create(); + + Line::create(['order_id' => $order->id, 'product_id' => $product1->id]); + Line::create(['order_id' => $order->id, 'product_id' => $product2->id]); + + $order->load('line', 'lines', 'products'); + + $this->expectsDatabaseQueryCount(4); + + $serialized = serialize(new ModelRelationSerializationTestClass($order)); + $unSerialized = unserialize($serialized); + + $this->assertEquals($unSerialized->order->getRelations(), $order->getRelations()); + } + public function testItReloadsNestedRelationships() { $order = tap(Order::create(), function (Order $order) { @@ -433,6 +457,29 @@ public function newCollection(array $models = []) } } +class ModelSerializationTestCustomOrder extends Model +{ + public $table = 'orders'; + public $guarded = []; + public $timestamps = false; + public $with = ['line', 'lines', 'products']; + + public function line() + { + return $this->hasOne(Line::class, 'order_id'); + } + + public function lines() + { + return $this->hasMany(Line::class, 'order_id'); + } + + public function products() + { + return $this->belongsToMany(Product::class, 'lines', 'order_id'); + } +} + class Order extends Model { public $guarded = [];
diff --git a/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php b/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php index 09fbf4829e7..25549425b7c 100644 --- a/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php +++ b/src/Illuminate/Queue/SerializesAndRestoresModelIdentifiers.php @@ -107,7 +107,7 @@ public function restoreModel($value) return $this->getQueryForModelRestoration( (new $value->class)->setConnection($value->connection), $value->id - )->useWritePdo()->firstOrFail()->load($value->relations ?? []); + )->useWritePdo()->firstOrFail()->loadMissing($value->relations ?? []); /** diff --git a/tests/Integration/Queue/ModelSerializationTest.php b/tests/Integration/Queue/ModelSerializationTest.php index bd3b401c657..e13cbb4ec29 100644 --- a/tests/Integration/Queue/ModelSerializationTest.php +++ b/tests/Integration/Queue/ModelSerializationTest.php @@ -31,6 +31,8 @@ protected function setUp(): void parent::setUp(); + Model::preventLazyLoading(false); Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('email'); @@ -161,6 +163,28 @@ public function testItReloadsRelationships() $this->assertEquals($unSerialized->order->getRelations(), $order->getRelations()); + public function testItReloadsRelationshipsOnlyOnce() + $order = tap(ModelSerializationTestCustomOrder::create(), function (ModelSerializationTestCustomOrder $order) { + $order->wasRecentlyCreated = false; + }); + $product1 = Product::create(); + $product2 = Product::create(); + Line::create(['order_id' => $order->id, 'product_id' => $product1->id]); + $order->load('line', 'lines', 'products'); + $this->expectsDatabaseQueryCount(4); + $unSerialized = unserialize($serialized); + $this->assertEquals($unSerialized->order->getRelations(), $order->getRelations()); public function testItReloadsNestedRelationships() $order = tap(Order::create(), function (Order $order) { @@ -433,6 +457,29 @@ public function newCollection(array $models = []) } +class ModelSerializationTestCustomOrder extends Model +{ + public $table = 'orders'; + public $guarded = []; + public $with = ['line', 'lines', 'products']; + public function line() + return $this->hasOne(Line::class, 'order_id'); + public function lines() + return $this->hasMany(Line::class, 'order_id'); + public function products() + return $this->belongsToMany(Product::class, 'lines', 'order_id'); +} class Order extends Model { public $guarded = [];
[ "+ Line::create(['order_id' => $order->id, 'product_id' => $product2->id]);", "+ $serialized = serialize(new ModelRelationSerializationTestClass($order));", "+ public $timestamps = false;" ]
[ 40, 46, 63 ]
{ "additions": 48, "author": "AndrewMast", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55547", "issue_id": 55547, "merged_at": "2025-04-25T15:21:17Z", "omission_probability": 0.1, "pr_number": 55547, "repo": "laravel/framework", "title": "[12.x] Fix double query in model relation serialization", "total_changes": 49 }
1
diff --git a/src/Illuminate/Database/Eloquent/Collection.php b/src/Illuminate/Database/Eloquent/Collection.php index 05ec0d345a1..1c9dad35263 100755 --- a/src/Illuminate/Database/Eloquent/Collection.php +++ b/src/Illuminate/Database/Eloquent/Collection.php @@ -761,7 +761,7 @@ public function withRelationshipAutoloading() foreach ($this as $model) { if (! $model->hasRelationAutoloadCallback()) { - $model->autoloadRelationsUsing($callback); + $model->autoloadRelationsUsing($callback, $this); } } diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index fc211e179a5..4b193d8d87a 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -46,6 +46,13 @@ trait HasRelationships */ protected $relationAutoloadCallback = null; + /** + * The relationship autoloader callback context. + * + * @var mixed + */ + protected $relationAutoloadContext = null; + /** * The many to many relationship methods. * @@ -118,10 +125,16 @@ public function hasRelationAutoloadCallback() */ public function autoloadRelationsUsing(Closure $callback, $context = null) { + // Prevent circular relation autoloading... + if ($context && $this->relationAutoloadContext === $context) { + return $this; + } + $this->relationAutoloadCallback = $callback; + $this->relationAutoloadContext = $context; foreach ($this->relations as $key => $value) { - $this->propagateRelationAutoloadCallbackToRelation($key, $value, $context); + $this->propagateRelationAutoloadCallbackToRelation($key, $value); } return $this; @@ -163,10 +176,9 @@ protected function invokeRelationAutoloadCallbackFor($key, $tuples) * * @param string $key * @param mixed $models - * @param mixed $context * @return void */ - protected function propagateRelationAutoloadCallbackToRelation($key, $models, $context = null) + protected function propagateRelationAutoloadCallbackToRelation($key, $models) { if (! $this->hasRelationAutoloadCallback() || ! $models) { return; @@ -183,10 +195,7 @@ protected function propagateRelationAutoloadCallbackToRelation($key, $models, $c $callback = fn (array $tuples) => $this->invokeRelationAutoloadCallbackFor($key, $tuples); foreach ($models as $model) { - // Check if relation autoload contexts are different to avoid circular relation autoload... - if ((is_null($context) || $context !== $model) && is_object($model) && method_exists($model, 'autoloadRelationsUsing')) { - $model->autoloadRelationsUsing($callback, $context); - } + $model->autoloadRelationsUsing($callback, $this->relationAutoloadContext); } } @@ -1111,7 +1120,7 @@ public function setRelation($relation, $value) { $this->relations[$relation] = $value; - $this->propagateRelationAutoloadCallbackToRelation($relation, $value, $this); + $this->propagateRelationAutoloadCallbackToRelation($relation, $value); return $this; } diff --git a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php index a3f8a5f882f..03f1d7ca611 100644 --- a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php +++ b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php @@ -61,6 +61,8 @@ public function testRelationAutoloadForCollection() $this->assertCount(2, DB::getQueryLog()); $this->assertCount(3, $likes); $this->assertTrue($posts[0]->comments[0]->relationLoaded('likes')); + + DB::disableQueryLog(); } public function testRelationAutoloadForSingleModel() @@ -84,6 +86,8 @@ public function testRelationAutoloadForSingleModel() $this->assertCount(2, DB::getQueryLog()); $this->assertCount(2, $likes); $this->assertTrue($post->comments[0]->relationLoaded('likes')); + + DB::disableQueryLog(); } public function testRelationAutoloadWithSerialization() @@ -109,6 +113,50 @@ public function testRelationAutoloadWithSerialization() $this->assertCount(2, DB::getQueryLog()); Model::automaticallyEagerLoadRelationships(false); + + DB::disableQueryLog(); + } + + public function testRelationAutoloadWithCircularRelations() + { + $post = Post::create(); + $comment1 = $post->comments()->create(['parent_id' => null]); + $comment2 = $post->comments()->create(['parent_id' => $comment1->id]); + $post->likes()->create(); + + DB::enableQueryLog(); + + $post->withRelationshipAutoloading(); + $comment = $post->comments->first(); + $comment->setRelation('post', $post); + + $this->assertCount(1, $post->likes); + + $this->assertCount(2, DB::getQueryLog()); + + DB::disableQueryLog(); + } + + public function testRelationAutoloadWithChaperoneRelations() + { + Model::automaticallyEagerLoadRelationships(); + + $post = Post::create(); + $comment1 = $post->comments()->create(['parent_id' => null]); + $comment2 = $post->comments()->create(['parent_id' => $comment1->id]); + $post->likes()->create(); + + DB::enableQueryLog(); + + $post->load('commentsWithChaperone'); + + $this->assertCount(1, $post->likes); + + $this->assertCount(2, DB::getQueryLog()); + + Model::automaticallyEagerLoadRelationships(false); + + DB::disableQueryLog(); } public function testRelationAutoloadVariousNestedMorphRelations() @@ -163,6 +211,8 @@ public function testRelationAutoloadVariousNestedMorphRelations() $this->assertCount(2, $videos); $this->assertTrue($videoLike->relationLoaded('likeable')); $this->assertTrue($videoLike->likeable->relationLoaded('commentable')); + + DB::disableQueryLog(); } } @@ -197,6 +247,11 @@ public function comments() return $this->morphMany(Comment::class, 'commentable'); } + public function commentsWithChaperone() + { + return $this->morphMany(Comment::class, 'commentable')->chaperone(); + } + public function likes() { return $this->morphMany(Like::class, 'likeable');
diff --git a/src/Illuminate/Database/Eloquent/Collection.php b/src/Illuminate/Database/Eloquent/Collection.php index 05ec0d345a1..1c9dad35263 100755 --- a/src/Illuminate/Database/Eloquent/Collection.php +++ b/src/Illuminate/Database/Eloquent/Collection.php @@ -761,7 +761,7 @@ public function withRelationshipAutoloading() foreach ($this as $model) { if (! $model->hasRelationAutoloadCallback()) { } diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index fc211e179a5..4b193d8d87a 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -46,6 +46,13 @@ trait HasRelationships protected $relationAutoloadCallback = null; + /** + * The relationship autoloader callback context. + * + * @var mixed + */ + protected $relationAutoloadContext = null; /** * The many to many relationship methods. @@ -118,10 +125,16 @@ public function hasRelationAutoloadCallback() public function autoloadRelationsUsing(Closure $callback, $context = null) + // Prevent circular relation autoloading... + if ($context && $this->relationAutoloadContext === $context) { + return $this; $this->relationAutoloadCallback = $callback; + $this->relationAutoloadContext = $context; foreach ($this->relations as $key => $value) { - $this->propagateRelationAutoloadCallbackToRelation($key, $value, $context); + $this->propagateRelationAutoloadCallbackToRelation($key, $value); @@ -163,10 +176,9 @@ protected function invokeRelationAutoloadCallbackFor($key, $tuples) * @param string $key * @param mixed $models - * @param mixed $context * @return void - protected function propagateRelationAutoloadCallbackToRelation($key, $models, $context = null) + protected function propagateRelationAutoloadCallbackToRelation($key, $models) if (! $this->hasRelationAutoloadCallback() || ! $models) { return; @@ -183,10 +195,7 @@ protected function propagateRelationAutoloadCallbackToRelation($key, $models, $c $callback = fn (array $tuples) => $this->invokeRelationAutoloadCallbackFor($key, $tuples); foreach ($models as $model) { - // Check if relation autoload contexts are different to avoid circular relation autoload... - if ((is_null($context) || $context !== $model) && is_object($model) && method_exists($model, 'autoloadRelationsUsing')) { - $model->autoloadRelationsUsing($callback, $context); - } + $model->autoloadRelationsUsing($callback, $this->relationAutoloadContext); @@ -1111,7 +1120,7 @@ public function setRelation($relation, $value) $this->relations[$relation] = $value; - $this->propagateRelationAutoloadCallbackToRelation($relation, $value, $this); + $this->propagateRelationAutoloadCallbackToRelation($relation, $value); diff --git a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php index a3f8a5f882f..03f1d7ca611 100644 --- a/tests/Integration/Database/EloquentModelRelationAutoloadTest.php +++ b/tests/Integration/Database/EloquentModelRelationAutoloadTest.php @@ -61,6 +61,8 @@ public function testRelationAutoloadForCollection() $this->assertCount(3, $likes); $this->assertTrue($posts[0]->comments[0]->relationLoaded('likes')); public function testRelationAutoloadForSingleModel() @@ -84,6 +86,8 @@ public function testRelationAutoloadForSingleModel() $this->assertCount(2, $likes); $this->assertTrue($post->comments[0]->relationLoaded('likes')); public function testRelationAutoloadWithSerialization() @@ -109,6 +113,50 @@ public function testRelationAutoloadWithSerialization() Model::automaticallyEagerLoadRelationships(false); + public function testRelationAutoloadWithCircularRelations() + $post->withRelationshipAutoloading(); + $comment = $post->comments->first(); + $comment->setRelation('post', $post); + public function testRelationAutoloadWithChaperoneRelations() + Model::automaticallyEagerLoadRelationships(); + $post->load('commentsWithChaperone'); + Model::automaticallyEagerLoadRelationships(false); public function testRelationAutoloadVariousNestedMorphRelations() @@ -163,6 +211,8 @@ public function testRelationAutoloadVariousNestedMorphRelations() $this->assertCount(2, $videos); $this->assertTrue($videoLike->relationLoaded('likeable')); $this->assertTrue($videoLike->likeable->relationLoaded('commentable')); } @@ -197,6 +247,11 @@ public function comments() return $this->morphMany(Comment::class, 'commentable'); + public function commentsWithChaperone() + return $this->morphMany(Comment::class, 'commentable')->chaperone(); public function likes() return $this->morphMany(Like::class, 'likeable');
[ "- $model->autoloadRelationsUsing($callback);", "+ $model->autoloadRelationsUsing($callback, $this);", "+ }" ]
[ 8, 9, 38 ]
{ "additions": 73, "author": "litvinchuk", "deletions": 9, "html_url": "https://github.com/laravel/framework/pull/55542", "issue_id": 55542, "merged_at": "2025-04-25T15:59:34Z", "omission_probability": 0.1, "pr_number": 55542, "repo": "laravel/framework", "title": "[12.x] Improve circular relation check in Automatic Relation Loading", "total_changes": 82 }
2
diff --git a/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php b/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php index da004c83bc74..fd350e6fce6c 100644 --- a/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php +++ b/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php @@ -50,7 +50,9 @@ public function __construct($factory, $pivot, $relationship) */ public function createFor(Model $model) { - Collection::wrap($this->factory instanceof Factory ? $this->factory->create([], $model) : $this->factory)->each(function ($attachable) use ($model) { + $relationship = $model->{$this->relationship}(); + + Collection::wrap($this->factory instanceof Factory ? $this->factory->prependState($relationship->getQuery()->pendingAttributes)->create([], $model) : $this->factory)->each(function ($attachable) use ($model) { $model->{$this->relationship}()->attach( $attachable, is_callable($this->pivot) ? call_user_func($this->pivot, $model) : $this->pivot diff --git a/src/Illuminate/Database/Eloquent/Factories/Factory.php b/src/Illuminate/Database/Eloquent/Factories/Factory.php index ffe9018e67f0..a52d840f421e 100644 --- a/src/Illuminate/Database/Eloquent/Factories/Factory.php +++ b/src/Illuminate/Database/Eloquent/Factories/Factory.php @@ -530,6 +530,21 @@ public function state($state) ]); } + /** + * Prepend a new state transformation to the model definition. + * + * @param (callable(array<string, mixed>, TModel|null): array<string, mixed>)|array<string, mixed> $state + * @return static + */ + public function prependState($state) + { + return $this->newInstance([ + 'states' => $this->states->prepend( + is_callable($state) ? $state : fn () => $state, + ), + ]); + } + /** * Set a single model attribute. * diff --git a/src/Illuminate/Database/Eloquent/Factories/Relationship.php b/src/Illuminate/Database/Eloquent/Factories/Relationship.php index 4024f1c929c0..e23bc99d78b0 100644 --- a/src/Illuminate/Database/Eloquent/Factories/Relationship.php +++ b/src/Illuminate/Database/Eloquent/Factories/Relationship.php @@ -49,13 +49,15 @@ public function createFor(Model $parent) $this->factory->state([ $relationship->getMorphType() => $relationship->getMorphClass(), $relationship->getForeignKeyName() => $relationship->getParentKey(), - ])->create([], $parent); + ])->prependState($relationship->getQuery()->pendingAttributes)->create([], $parent); } elseif ($relationship instanceof HasOneOrMany) { $this->factory->state([ $relationship->getForeignKeyName() => $relationship->getParentKey(), - ])->create([], $parent); + ])->prependState($relationship->getQuery()->pendingAttributes)->create([], $parent); } elseif ($relationship instanceof BelongsToMany) { - $relationship->attach($this->factory->create([], $parent)); + $relationship->attach( + $this->factory->prependState($relationship->getQuery()->pendingAttributes)->create([], $parent) + ); } } diff --git a/tests/Database/DatabaseEloquentFactoryTest.php b/tests/Database/DatabaseEloquentFactoryTest.php index b0860d236b03..da5467794d77 100644 --- a/tests/Database/DatabaseEloquentFactoryTest.php +++ b/tests/Database/DatabaseEloquentFactoryTest.php @@ -850,6 +850,62 @@ public function test_factory_global_model_resolver() $this->assertEquals(FactoryTestGuessModelFactory::new()->modelName(), FactoryTestGuessModel::class); } + public function test_factory_model_has_many_relationship_has_pending_attributes() + { + FactoryTestUser::factory()->has(new FactoryTestPostFactory(), 'postsWithFooBarBazAsTitle')->create(); + + $this->assertEquals('foo bar baz', FactoryTestPost::first()->title); + } + + public function test_factory_model_has_many_relationship_has_pending_attributes_override() + { + FactoryTestUser::factory()->has((new FactoryTestPostFactory())->state(['title' => 'other title']), 'postsWithFooBarBazAsTitle')->create(); + + $this->assertEquals('other title', FactoryTestPost::first()->title); + } + + public function test_factory_model_has_one_relationship_has_pending_attributes() + { + FactoryTestUser::factory()->has(new FactoryTestPostFactory(), 'postWithFooBarBazAsTitle')->create(); + + $this->assertEquals('foo bar baz', FactoryTestPost::first()->title); + } + + public function test_factory_model_has_one_relationship_has_pending_attributes_override() + { + FactoryTestUser::factory()->has((new FactoryTestPostFactory())->state(['title' => 'other title']), 'postWithFooBarBazAsTitle')->create(); + + $this->assertEquals('other title', FactoryTestPost::first()->title); + } + + public function test_factory_model_belongs_to_many_relationship_has_pending_attributes() + { + FactoryTestUser::factory()->has(new FactoryTestRoleFactory(), 'rolesWithFooBarBazAsName')->create(); + + $this->assertEquals('foo bar baz', FactoryTestRole::first()->name); + } + + public function test_factory_model_belongs_to_many_relationship_has_pending_attributes_override() + { + FactoryTestUser::factory()->has((new FactoryTestRoleFactory())->state(['name' => 'other name']), 'rolesWithFooBarBazAsName')->create(); + + $this->assertEquals('other name', FactoryTestRole::first()->name); + } + + public function test_factory_model_morph_many_relationship_has_pending_attributes() + { + (new FactoryTestPostFactory())->has(new FactoryTestCommentFactory(), 'commentsWithFooBarBazAsBody')->create(); + + $this->assertEquals('foo bar baz', FactoryTestComment::first()->body); + } + + public function test_factory_model_morph_many_relationship_has_pending_attributes_override() + { + (new FactoryTestPostFactory())->has((new FactoryTestCommentFactory())->state(['body' => 'other body']), 'commentsWithFooBarBazAsBody')->create(); + + $this->assertEquals('other body', FactoryTestComment::first()->body); + } + /** * Get a database connection instance. * @@ -895,11 +951,26 @@ public function posts() return $this->hasMany(FactoryTestPost::class, 'user_id'); } + public function postsWithFooBarBazAsTitle() + { + return $this->hasMany(FactoryTestPost::class, 'user_id')->withAttributes(['title' => 'foo bar baz']); + } + + public function postWithFooBarBazAsTitle() + { + return $this->hasOne(FactoryTestPost::class, 'user_id')->withAttributes(['title' => 'foo bar baz']); + } + public function roles() { return $this->belongsToMany(FactoryTestRole::class, 'role_user', 'user_id', 'role_id')->withPivot('admin'); } + public function rolesWithFooBarBazAsName() + { + return $this->belongsToMany(FactoryTestRole::class, 'role_user', 'user_id', 'role_id')->withPivot('admin')->withAttributes(['name' => 'foo bar baz']); + } + public function factoryTestRoles() { return $this->belongsToMany(FactoryTestRole::class, 'role_user', 'user_id', 'role_id')->withPivot('admin'); @@ -944,6 +1015,11 @@ public function comments() { return $this->morphMany(FactoryTestComment::class, 'commentable'); } + + public function commentsWithFooBarBazAsBody() + { + return $this->morphMany(FactoryTestComment::class, 'commentable')->withAttributes(['body' => 'foo bar baz']); + } } class FactoryTestCommentFactory extends Factory
diff --git a/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php b/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php index da004c83bc74..fd350e6fce6c 100644 --- a/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php +++ b/src/Illuminate/Database/Eloquent/Factories/BelongsToManyRelationship.php @@ -50,7 +50,9 @@ public function __construct($factory, $pivot, $relationship) */ public function createFor(Model $model) - Collection::wrap($this->factory instanceof Factory ? $this->factory->create([], $model) : $this->factory)->each(function ($attachable) use ($model) { + $relationship = $model->{$this->relationship}(); + Collection::wrap($this->factory instanceof Factory ? $this->factory->prependState($relationship->getQuery()->pendingAttributes)->create([], $model) : $this->factory)->each(function ($attachable) use ($model) { $model->{$this->relationship}()->attach( $attachable, is_callable($this->pivot) ? call_user_func($this->pivot, $model) : $this->pivot diff --git a/src/Illuminate/Database/Eloquent/Factories/Factory.php b/src/Illuminate/Database/Eloquent/Factories/Factory.php index ffe9018e67f0..a52d840f421e 100644 --- a/src/Illuminate/Database/Eloquent/Factories/Factory.php +++ b/src/Illuminate/Database/Eloquent/Factories/Factory.php @@ -530,6 +530,21 @@ public function state($state) ]); + /** + * Prepend a new state transformation to the model definition. + * + * @param (callable(array<string, mixed>, TModel|null): array<string, mixed>)|array<string, mixed> $state + * @return static + */ + public function prependState($state) + return $this->newInstance([ + is_callable($state) ? $state : fn () => $state, + ), + ]); * Set a single model attribute. diff --git a/src/Illuminate/Database/Eloquent/Factories/Relationship.php b/src/Illuminate/Database/Eloquent/Factories/Relationship.php index 4024f1c929c0..e23bc99d78b0 100644 --- a/src/Illuminate/Database/Eloquent/Factories/Relationship.php +++ b/src/Illuminate/Database/Eloquent/Factories/Relationship.php @@ -49,13 +49,15 @@ public function createFor(Model $parent) $relationship->getMorphType() => $relationship->getMorphClass(), } elseif ($relationship instanceof HasOneOrMany) { } elseif ($relationship instanceof BelongsToMany) { - $relationship->attach($this->factory->create([], $parent)); + $relationship->attach( + $this->factory->prependState($relationship->getQuery()->pendingAttributes)->create([], $parent) + ); } diff --git a/tests/Database/DatabaseEloquentFactoryTest.php b/tests/Database/DatabaseEloquentFactoryTest.php index b0860d236b03..da5467794d77 100644 --- a/tests/Database/DatabaseEloquentFactoryTest.php +++ b/tests/Database/DatabaseEloquentFactoryTest.php @@ -850,6 +850,62 @@ public function test_factory_global_model_resolver() $this->assertEquals(FactoryTestGuessModelFactory::new()->modelName(), FactoryTestGuessModel::class); + public function test_factory_model_has_many_relationship_has_pending_attributes() + FactoryTestUser::factory()->has(new FactoryTestPostFactory(), 'postsWithFooBarBazAsTitle')->create(); + public function test_factory_model_has_many_relationship_has_pending_attributes_override() + FactoryTestUser::factory()->has((new FactoryTestPostFactory())->state(['title' => 'other title']), 'postsWithFooBarBazAsTitle')->create(); + public function test_factory_model_has_one_relationship_has_pending_attributes() + FactoryTestUser::factory()->has(new FactoryTestPostFactory(), 'postWithFooBarBazAsTitle')->create(); + FactoryTestUser::factory()->has((new FactoryTestPostFactory())->state(['title' => 'other title']), 'postWithFooBarBazAsTitle')->create(); + public function test_factory_model_belongs_to_many_relationship_has_pending_attributes() + FactoryTestUser::factory()->has(new FactoryTestRoleFactory(), 'rolesWithFooBarBazAsName')->create(); + $this->assertEquals('foo bar baz', FactoryTestRole::first()->name); + public function test_factory_model_belongs_to_many_relationship_has_pending_attributes_override() + FactoryTestUser::factory()->has((new FactoryTestRoleFactory())->state(['name' => 'other name']), 'rolesWithFooBarBazAsName')->create(); + $this->assertEquals('other name', FactoryTestRole::first()->name); + public function test_factory_model_morph_many_relationship_has_pending_attributes() + $this->assertEquals('foo bar baz', FactoryTestComment::first()->body); + public function test_factory_model_morph_many_relationship_has_pending_attributes_override() + $this->assertEquals('other body', FactoryTestComment::first()->body); * Get a database connection instance. @@ -895,11 +951,26 @@ public function posts() return $this->hasMany(FactoryTestPost::class, 'user_id'); + public function postsWithFooBarBazAsTitle() + return $this->hasMany(FactoryTestPost::class, 'user_id')->withAttributes(['title' => 'foo bar baz']); + public function postWithFooBarBazAsTitle() public function roles() + public function rolesWithFooBarBazAsName() + return $this->belongsToMany(FactoryTestRole::class, 'role_user', 'user_id', 'role_id')->withPivot('admin')->withAttributes(['name' => 'foo bar baz']); public function factoryTestRoles() @@ -944,6 +1015,11 @@ public function comments() return $this->morphMany(FactoryTestComment::class, 'commentable'); + public function commentsWithFooBarBazAsBody() + return $this->morphMany(FactoryTestComment::class, 'commentable')->withAttributes(['body' => 'foo bar baz']); } class FactoryTestCommentFactory extends Factory
[ "+ 'states' => $this->states->prepend(", "+ public function test_factory_model_has_one_relationship_has_pending_attributes_override()", "+ (new FactoryTestPostFactory())->has(new FactoryTestCommentFactory(), 'commentsWithFooBarBazAsBody')->create();", "+ (new FactoryTestPostFactory())->has((new FactoryTestCommentFactory())->state(['body' => 'other body']), 'commentsWithFooBarBazAsBody')->create();", "+ return $this->hasOne(FactoryTestPost::class, 'user_id')->withAttributes(['title' => 'foo bar baz']);" ]
[ 32, 93, 116, 123, 142 ]
{ "additions": 99, "author": "gdebrauwer", "deletions": 4, "html_url": "https://github.com/laravel/framework/pull/55558", "issue_id": 55558, "merged_at": "2025-04-25T15:08:46Z", "omission_probability": 0.1, "pr_number": 55558, "repo": "laravel/framework", "title": "[12.x] Use pendingAttributes of relationships when creating relationship models via model factories", "total_changes": 103 }
3
diff --git a/src/Illuminate/Mail/resources/views/html/panel.blade.php b/src/Illuminate/Mail/resources/views/html/panel.blade.php index 812db7c08e77..2975a60a021e 100644 --- a/src/Illuminate/Mail/resources/views/html/panel.blade.php +++ b/src/Illuminate/Mail/resources/views/html/panel.blade.php @@ -4,7 +4,7 @@ <table width="100%" cellpadding="0" cellspacing="0" role="presentation"> <tr> <td class="panel-item"> -{!! Illuminate\Mail\Markdown::parse($slot) !!} +{{ Illuminate\Mail\Markdown::parse($slot) }} </td> </tr> </table> diff --git a/src/Illuminate/Support/EncodedHtmlString.php b/src/Illuminate/Support/EncodedHtmlString.php index 18928e75b633..a25115740277 100644 --- a/src/Illuminate/Support/EncodedHtmlString.php +++ b/src/Illuminate/Support/EncodedHtmlString.php @@ -2,8 +2,19 @@ namespace Illuminate\Support; +use BackedEnum; +use Illuminate\Contracts\Support\DeferringDisplayableValue; +use Illuminate\Contracts\Support\Htmlable; + class EncodedHtmlString extends HtmlString { + /** + * The HTML string. + * + * @var \Illuminate\Contracts\Support\DeferringDisplayableValue|\Illuminate\Contracts\Support\Htmlable|\BackedEnum|string|int|float|null + */ + protected $html; + /** * The callback that should be used to encode the HTML strings. * @@ -14,7 +25,7 @@ class EncodedHtmlString extends HtmlString /** * Create a new encoded HTML string instance. * - * @param string $html + * @param \Illuminate\Contracts\Support\DeferringDisplayableValue|\Illuminate\Contracts\Support\Htmlable|\BackedEnum|string|int|float|null $html * @param bool $doubleEncode * @return void */ @@ -48,9 +59,23 @@ public static function convert($value, bool $withQuote = true, bool $doubleEncod #[\Override] public function toHtml() { + $value = $this->html; + + if ($value instanceof DeferringDisplayableValue) { + $value = $value->resolveDisplayableValue(); + } + + if ($value instanceof Htmlable) { + return $value->toHtml(); + } + + if ($value instanceof BackedEnum) { + $value = $value->value; + } + return (static::$encodeUsingFactory ?? function ($value, $doubleEncode) { return static::convert($value, doubleEncode: $doubleEncode); - })($this->html, $this->doubleEncode); + })($value, $this->doubleEncode); } /** diff --git a/tests/Integration/Mail/Fixtures/table-with-template.blade.php b/tests/Integration/Mail/Fixtures/table-with-template.blade.php new file mode 100644 index 000000000000..3a4ec4c6260e --- /dev/null +++ b/tests/Integration/Mail/Fixtures/table-with-template.blade.php @@ -0,0 +1,12 @@ +<x-mail::message subcopy="This is a subcopy"> + +<x-mail::table> +*Hi* {{ $user->name }} + +| Laravel | Table | Example | +| ------------- | :-----------: | ------------: | +| Col 2 is | Centered | $10 | +| Col 3 is | Right-Aligned | $20 | +</x-mail::table> + +</x-mail::message> diff --git a/tests/Integration/Mail/MailableWithSecuredEncodingTest.php b/tests/Integration/Mail/MailableWithSecuredEncodingTest.php index a84fd487c20d..9feb03886335 100644 --- a/tests/Integration/Mail/MailableWithSecuredEncodingTest.php +++ b/tests/Integration/Mail/MailableWithSecuredEncodingTest.php @@ -116,6 +116,56 @@ public function build() $mailable->assertSeeInHtml($expected, false); } + #[WithMigration] + #[DataProvider('markdownEncodedTemplateDataProvider')] + public function testItCanAssertMarkdownEncodedStringUsingTemplateWithTable($given, $expected) + { + $user = UserFactory::new()->create([ + 'name' => $given, + ]); + + $mailable = new class($user) extends Mailable + { + public $theme = 'taylor'; + + public function __construct(public User $user) + { + // + } + + public function build() + { + return $this->markdown('table-with-template'); + } + }; + + $mailable->assertSeeInHtml($expected, false); + $mailable->assertSeeInHtml('<p>This is a subcopy</p>', false); + $mailable->assertSeeInHtml(<<<'TABLE' +<table> +<thead> +<tr> +<th>Laravel</th> +<th align="center">Table</th> +<th align="right">Example</th> +</tr> +</thead> +<tbody> +<tr> +<td>Col 2 is</td> +<td align="center">Centered</td> +<td align="right">$10</td> +</tr> +<tr> +<td>Col 3 is</td> +<td align="center">Right-Aligned</td> +<td align="right">$20</td> +</tr> +</tbody> +</table> +TABLE, false); + } + public static function markdownEncodedTemplateDataProvider() { yield ['[Laravel](https://laravel.com)', '<em>Hi</em> [Laravel](https://laravel.com)']; diff --git a/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php b/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php index 52db775cefae..aea392c520ca 100644 --- a/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php +++ b/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php @@ -116,6 +116,56 @@ public function build() $mailable->assertSeeInHtml($expected, false); } + #[WithMigration] + #[DataProvider('markdownEncodedTemplateDataProvider')] + public function testItCanAssertMarkdownEncodedStringUsingTemplateWithTable($given, $expected) + { + $user = UserFactory::new()->create([ + 'name' => $given, + ]); + + $mailable = new class($user) extends Mailable + { + public $theme = 'taylor'; + + public function __construct(public User $user) + { + // + } + + public function build() + { + return $this->markdown('table-with-template'); + } + }; + + $mailable->assertSeeInHtml($expected, false); + $mailable->assertSeeInHtml('<p>This is a subcopy</p>', false); + $mailable->assertSeeInHtml(<<<'TABLE' +<table> +<thead> +<tr> +<th>Laravel</th> +<th align="center">Table</th> +<th align="right">Example</th> +</tr> +</thead> +<tbody> +<tr> +<td>Col 2 is</td> +<td align="center">Centered</td> +<td align="right">$10</td> +</tr> +<tr> +<td>Col 3 is</td> +<td align="center">Right-Aligned</td> +<td align="right">$20</td> +</tr> +</tbody> +</table> +TABLE, false); + } + public static function markdownEncodedTemplateDataProvider() { yield ['[Laravel](https://laravel.com)', '<p><em>Hi</em> <a href="https://laravel.com">Laravel</a></p>']; diff --git a/tests/Integration/Mail/MarkdownParserTest.php b/tests/Integration/Mail/MarkdownParserTest.php index 7ff74ae21eb3..16910e79fd18 100644 --- a/tests/Integration/Mail/MarkdownParserTest.php +++ b/tests/Integration/Mail/MarkdownParserTest.php @@ -76,6 +76,11 @@ public static function markdownEncodedDataProvider() '<p>Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation</p>', ]; + yield [ + new EncodedHtmlString(new HtmlString('Visit <span>https://laravel.com/docs</span> to browse the documentation')), + '<p>Visit <span>https://laravel.com/docs</span> to browse the documentation</p>', + ]; + yield [ '![Welcome to Laravel](https://laravel.com/assets/img/welcome/background.svg)<br />'.new EncodedHtmlString('Visit <span>https://laravel.com/docs</span> to browse the documentation'), '<p><img src="https://laravel.com/assets/img/welcome/background.svg" alt="Welcome to Laravel" /><br />Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation</p>',
diff --git a/src/Illuminate/Mail/resources/views/html/panel.blade.php b/src/Illuminate/Mail/resources/views/html/panel.blade.php index 812db7c08e77..2975a60a021e 100644 --- a/src/Illuminate/Mail/resources/views/html/panel.blade.php +++ b/src/Illuminate/Mail/resources/views/html/panel.blade.php @@ -4,7 +4,7 @@ <table width="100%" cellpadding="0" cellspacing="0" role="presentation"> <tr> <td class="panel-item"> -{!! Illuminate\Mail\Markdown::parse($slot) !!} +{{ Illuminate\Mail\Markdown::parse($slot) }} </td> </tr> </table> diff --git a/src/Illuminate/Support/EncodedHtmlString.php b/src/Illuminate/Support/EncodedHtmlString.php index 18928e75b633..a25115740277 100644 --- a/src/Illuminate/Support/EncodedHtmlString.php +++ b/src/Illuminate/Support/EncodedHtmlString.php @@ -2,8 +2,19 @@ namespace Illuminate\Support; +use BackedEnum; +use Illuminate\Contracts\Support\DeferringDisplayableValue; +use Illuminate\Contracts\Support\Htmlable; class EncodedHtmlString extends HtmlString { + /** + * The HTML string. + * + * @var \Illuminate\Contracts\Support\DeferringDisplayableValue|\Illuminate\Contracts\Support\Htmlable|\BackedEnum|string|int|float|null + */ * The callback that should be used to encode the HTML strings. @@ -14,7 +25,7 @@ class EncodedHtmlString extends HtmlString * Create a new encoded HTML string instance. - * @param string $html + * @param \Illuminate\Contracts\Support\DeferringDisplayableValue|\Illuminate\Contracts\Support\Htmlable|\BackedEnum|string|int|float|null $html * @param bool $doubleEncode * @return void */ @@ -48,9 +59,23 @@ public static function convert($value, bool $withQuote = true, bool $doubleEncod #[\Override] public function toHtml() + $value = $this->html; + if ($value instanceof DeferringDisplayableValue) { + $value = $value->resolveDisplayableValue(); + if ($value instanceof Htmlable) { + return $value->toHtml(); + if ($value instanceof BackedEnum) { + $value = $value->value; return (static::$encodeUsingFactory ?? function ($value, $doubleEncode) { return static::convert($value, doubleEncode: $doubleEncode); - })($this->html, $this->doubleEncode); + })($value, $this->doubleEncode); diff --git a/tests/Integration/Mail/Fixtures/table-with-template.blade.php b/tests/Integration/Mail/Fixtures/table-with-template.blade.php new file mode 100644 index 000000000000..3a4ec4c6260e --- /dev/null +++ b/tests/Integration/Mail/Fixtures/table-with-template.blade.php @@ -0,0 +1,12 @@ +<x-mail::message subcopy="This is a subcopy"> +<x-mail::table> +*Hi* {{ $user->name }} +| ------------- | :-----------: | ------------: | +| Col 2 is | Centered | $10 | +| Col 3 is | Right-Aligned | $20 | +</x-mail::table> +</x-mail::message> diff --git a/tests/Integration/Mail/MailableWithSecuredEncodingTest.php b/tests/Integration/Mail/MailableWithSecuredEncodingTest.php index a84fd487c20d..9feb03886335 100644 --- a/tests/Integration/Mail/MailableWithSecuredEncodingTest.php +++ b/tests/Integration/Mail/MailableWithSecuredEncodingTest.php yield ['[Laravel](https://laravel.com)', '<em>Hi</em> [Laravel](https://laravel.com)']; diff --git a/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php b/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php index 52db775cefae..aea392c520ca 100644 --- a/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php +++ b/tests/Integration/Mail/MailableWithoutSecuredEncodingTest.php yield ['[Laravel](https://laravel.com)', '<p><em>Hi</em> <a href="https://laravel.com">Laravel</a></p>']; diff --git a/tests/Integration/Mail/MarkdownParserTest.php b/tests/Integration/Mail/MarkdownParserTest.php index 7ff74ae21eb3..16910e79fd18 100644 --- a/tests/Integration/Mail/MarkdownParserTest.php +++ b/tests/Integration/Mail/MarkdownParserTest.php @@ -76,6 +76,11 @@ public static function markdownEncodedDataProvider() '<p>Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation</p>', ]; + yield [ + new EncodedHtmlString(new HtmlString('Visit <span>https://laravel.com/docs</span> to browse the documentation')), + '<p>Visit <span>https://laravel.com/docs</span> to browse the documentation</p>', + ]; yield [ '![Welcome to Laravel](https://laravel.com/assets/img/welcome/background.svg)<br />'.new EncodedHtmlString('Visit <span>https://laravel.com/docs</span> to browse the documentation'), '<p><img src="https://laravel.com/assets/img/welcome/background.svg" alt="Welcome to Laravel" /><br />Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation</p>',
[ "+ protected $html;", "+| Laravel | Table | Example |" ]
[ 32, 82 ]
{ "additions": 145, "author": "jbraband", "deletions": 3, "html_url": "https://github.com/laravel/framework/pull/55543", "issue_id": 55543, "merged_at": "2025-04-25T08:31:51Z", "omission_probability": 0.1, "pr_number": 55543, "repo": "laravel/framework", "title": "[11.x] Fix `EncodedHtmlString` to ignore instance of `HtmlString`", "total_changes": 148 }
4
diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index fc211e179a5..b27b7110909 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -1088,7 +1088,11 @@ public function relationLoaded($key) if ($nestedRelation !== null) { $relatedModels = is_iterable($relatedModels = $this->$relation) ? $relatedModels - : [$relatedModels]; + : array_filter([$relatedModels]); + + if (count($relatedModels) === 0) { + return false; + } foreach ($relatedModels as $related) { if (! $related->relationLoaded($nestedRelation)) { diff --git a/tests/Integration/Database/EloquentModelRelationLoadedTest.php b/tests/Integration/Database/EloquentModelRelationLoadedTest.php index 548a50d1195..265926d9cd4 100644 --- a/tests/Integration/Database/EloquentModelRelationLoadedTest.php +++ b/tests/Integration/Database/EloquentModelRelationLoadedTest.php @@ -135,6 +135,21 @@ public function testWhenParentRelationIsASingleInstance() $this->assertTrue($model->relationLoaded('two.one')); $this->assertTrue($model->two->one->is($one)); } + + public function testWhenRelationIsNull() + { + $one = One::query()->create(); + $two = $one->twos()->create(); + $three = $two->threes()->create(); + + $model = Three::query() + ->with('one.twos') + ->find($three->id); + + $this->assertTrue($model->relationLoaded('one')); + $this->assertNull($model->one); + $this->assertFalse($model->relationLoaded('one.twos')); + } } class One extends Model
diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index fc211e179a5..b27b7110909 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -1088,7 +1088,11 @@ public function relationLoaded($key) if ($nestedRelation !== null) { $relatedModels = is_iterable($relatedModels = $this->$relation) ? $relatedModels - : [$relatedModels]; + : array_filter([$relatedModels]); + if (count($relatedModels) === 0) { + return false; + } foreach ($relatedModels as $related) { if (! $related->relationLoaded($nestedRelation)) { diff --git a/tests/Integration/Database/EloquentModelRelationLoadedTest.php b/tests/Integration/Database/EloquentModelRelationLoadedTest.php index 548a50d1195..265926d9cd4 100644 --- a/tests/Integration/Database/EloquentModelRelationLoadedTest.php +++ b/tests/Integration/Database/EloquentModelRelationLoadedTest.php @@ -135,6 +135,21 @@ public function testWhenParentRelationIsASingleInstance() $this->assertTrue($model->relationLoaded('two.one')); $this->assertTrue($model->two->one->is($one)); } + { + $one = One::query()->create(); + $two = $one->twos()->create(); + $three = $two->threes()->create(); + $model = Three::query() + ->with('one.twos') + ->find($three->id); + $this->assertTrue($model->relationLoaded('one')); + $this->assertNull($model->one); + $this->assertFalse($model->relationLoaded('one.twos')); + } } class One extends Model
[ "+ public function testWhenRelationIsNull()" ]
[ 26 ]
{ "additions": 20, "author": "rodrigopedra", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55531", "issue_id": 55531, "merged_at": "2025-04-24T14:05:39Z", "omission_probability": 0.1, "pr_number": 55531, "repo": "laravel/framework", "title": "[12.x] Address Model@relationLoaded when relation is null", "total_changes": 21 }
5
diff --git a/src/Illuminate/Mail/Markdown.php b/src/Illuminate/Mail/Markdown.php index e8ec2defc4c4..54c9c2ece372 100644 --- a/src/Illuminate/Mail/Markdown.php +++ b/src/Illuminate/Mail/Markdown.php @@ -69,9 +69,25 @@ public function render($view, array $data = [], $inliner = null) $contents = $bladeCompiler->usingEchoFormat( 'new \Illuminate\Support\EncodedHtmlString(%s)', function () use ($view, $data) { - return $this->view->replaceNamespace( - 'mail', $this->htmlComponentPaths() - )->make($view, $data)->render(); + EncodedHtmlString::encodeUsing(function ($value) { + $replacements = [ + '[' => '\[', + '<' => '&lt;', + '>' => '&gt;', + ]; + + return str_replace(array_keys($replacements), array_values($replacements), $value); + }); + + try { + $contents = $this->view->replaceNamespace( + 'mail', $this->htmlComponentPaths() + )->make($view, $data)->render(); + } finally { + EncodedHtmlString::flushState(); + } + + return $contents; } ); @@ -84,7 +100,7 @@ function () use ($view, $data) { } return new HtmlString(($inliner ?: new CssToInlineStyles)->convert( - $contents, $this->view->make($theme, $data)->render() + str_replace('\[', '[', $contents), $this->view->make($theme, $data)->render() )); } @@ -112,10 +128,15 @@ public function renderText($view, array $data = []) * Parse the given Markdown text into HTML. * * @param string $text + * @param bool $encoded * @return \Illuminate\Support\HtmlString */ - public static function parse($text) + public static function parse($text, bool $encoded = false) { + if ($encoded === false) { + return new HtmlString(static::converter()->convert($text)->getContent()); + } + EncodedHtmlString::encodeUsing(function ($value) { $replacements = [ '[' => '\[', diff --git a/src/Illuminate/Mail/resources/views/html/button.blade.php b/src/Illuminate/Mail/resources/views/html/button.blade.php index 4a9bf7d00495..050e969d2130 100644 --- a/src/Illuminate/Mail/resources/views/html/button.blade.php +++ b/src/Illuminate/Mail/resources/views/html/button.blade.php @@ -12,7 +12,7 @@ <table border="0" cellpadding="0" cellspacing="0" role="presentation"> <tr> <td> -<a href="{{ $url }}" class="button button-{{ $color }}" target="_blank" rel="noopener">{{ $slot }}</a> +<a href="{{ $url }}" class="button button-{{ $color }}" target="_blank" rel="noopener">{!! $slot !!}</a> </td> </tr> </table> diff --git a/src/Illuminate/Mail/resources/views/html/header.blade.php b/src/Illuminate/Mail/resources/views/html/header.blade.php index 56197f8d23f3..c47a260c56b2 100644 --- a/src/Illuminate/Mail/resources/views/html/header.blade.php +++ b/src/Illuminate/Mail/resources/views/html/header.blade.php @@ -5,7 +5,7 @@ @if (trim($slot) === 'Laravel') <img src="https://laravel.com/img/notification-logo.png" class="logo" alt="Laravel Logo"> @else -{{ $slot }} +{!! $slot !!} @endif </a> </td> diff --git a/src/Illuminate/Mail/resources/views/html/layout.blade.php b/src/Illuminate/Mail/resources/views/html/layout.blade.php index d31a01de8630..0fa6b82f72b2 100644 --- a/src/Illuminate/Mail/resources/views/html/layout.blade.php +++ b/src/Illuminate/Mail/resources/views/html/layout.blade.php @@ -23,7 +23,7 @@ } } </style> -{{ $head ?? '' }} +{!! $head ?? '' !!} </head> <body> @@ -31,7 +31,7 @@ <tr> <td align="center"> <table class="content" width="100%" cellpadding="0" cellspacing="0" role="presentation"> -{{ $header ?? '' }} +{!! $header ?? '' !!} <!-- Email Body --> <tr> @@ -40,16 +40,16 @@ <!-- Body content --> <tr> <td class="content-cell"> -{{ Illuminate\Mail\Markdown::parse($slot) }} +{!! Illuminate\Mail\Markdown::parse($slot) !!} -{{ $subcopy ?? '' }} +{!! $subcopy ?? '' !!} </td> </tr> </table> </td> </tr> -{{ $footer ?? '' }} +{!! $footer ?? '' !!} </table> </td> </tr> diff --git a/src/Illuminate/Mail/resources/views/html/message.blade.php b/src/Illuminate/Mail/resources/views/html/message.blade.php index 1a874fc26de5..f1e815f32a41 100644 --- a/src/Illuminate/Mail/resources/views/html/message.blade.php +++ b/src/Illuminate/Mail/resources/views/html/message.blade.php @@ -7,13 +7,13 @@ </x-slot:header> {{-- Body --}} -{{ $slot }} +{!! $slot !!} {{-- Subcopy --}} @isset($subcopy) <x-slot:subcopy> <x-mail::subcopy> -{{ $subcopy }} +{!! $subcopy !!}} </x-mail::subcopy> </x-slot:subcopy> @endisset diff --git a/src/Illuminate/Mail/resources/views/html/panel.blade.php b/src/Illuminate/Mail/resources/views/html/panel.blade.php index 2975a60a021e..812db7c08e77 100644 --- a/src/Illuminate/Mail/resources/views/html/panel.blade.php +++ b/src/Illuminate/Mail/resources/views/html/panel.blade.php @@ -4,7 +4,7 @@ <table width="100%" cellpadding="0" cellspacing="0" role="presentation"> <tr> <td class="panel-item"> -{{ Illuminate\Mail\Markdown::parse($slot) }} +{!! Illuminate\Mail\Markdown::parse($slot) !!} </td> </tr> </table> diff --git a/tests/Integration/Mail/Fixtures/message-with-template.blade.php b/tests/Integration/Mail/Fixtures/message-with-template.blade.php new file mode 100644 index 000000000000..9c53cef7e1bb --- /dev/null +++ b/tests/Integration/Mail/Fixtures/message-with-template.blade.php @@ -0,0 +1,4 @@ +@component('mail::message') +*Hi* {{ $user->name }} + +@endcomponent diff --git a/tests/Integration/Mail/MailableTest.php b/tests/Integration/Mail/MailableTest.php index 339ebb2422d7..4ff0f539b6ad 100644 --- a/tests/Integration/Mail/MailableTest.php +++ b/tests/Integration/Mail/MailableTest.php @@ -2,14 +2,20 @@ namespace Illuminate\Tests\Integration\Mail; +use Illuminate\Foundation\Auth\User; +use Illuminate\Foundation\Testing\LazilyRefreshDatabase; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Content; use Illuminate\Mail\Mailables\Envelope; +use Orchestra\Testbench\Attributes\WithMigration; +use Orchestra\Testbench\Factories\UserFactory; use Orchestra\Testbench\TestCase; use PHPUnit\Framework\Attributes\DataProvider; class MailableTest extends TestCase { + use LazilyRefreshDatabase; + /** {@inheritdoc} */ #[\Override] protected function defineEnvironment($app) @@ -69,4 +75,55 @@ public static function markdownEncodedDataProvider() 'My message is: Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation', ]; } + + #[WithMigration] + #[DataProvider('markdownEncodedTemplateDataProvider')] + public function testItCanAssertMarkdownEncodedStringUsingTemplate($given, $expected) + { + $user = UserFactory::new()->create([ + 'name' => $given, + ]); + + $mailable = new class($user) extends Mailable + { + public $theme = 'taylor'; + + public function __construct(public User $user) + { + // + } + + public function build() + { + return $this->markdown('message-with-template'); + } + }; + + $mailable->assertSeeInHtml($expected, false); + } + + public static function markdownEncodedTemplateDataProvider() + { + yield ['[Laravel](https://laravel.com)', '<em>Hi</em> [Laravel](https://laravel.com)']; + + yield [ + '![Welcome to Laravel](https://laravel.com/assets/img/welcome/background.svg)', + '<em>Hi</em> ![Welcome to Laravel](https://laravel.com/assets/img/welcome/background.svg)', + ]; + + yield [ + 'Visit https://laravel.com/docs to browse the documentation', + '<em>Hi</em> Visit https://laravel.com/docs to browse the documentation', + ]; + + yield [ + 'Visit <https://laravel.com/docs> to browse the documentation', + '<em>Hi</em> Visit &lt;https://laravel.com/docs&gt; to browse the documentation', + ]; + + yield [ + 'Visit <span>https://laravel.com/docs</span> to browse the documentation', + '<em>Hi</em> Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation', + ]; + } } diff --git a/tests/Integration/Mail/MarkdownParserTest.php b/tests/Integration/Mail/MarkdownParserTest.php index d21602c9ad00..6669fe038ba3 100644 --- a/tests/Integration/Mail/MarkdownParserTest.php +++ b/tests/Integration/Mail/MarkdownParserTest.php @@ -24,7 +24,7 @@ public function testItCanParseMarkdownString($given, $expected) #[DataProvider('markdownEncodedDataProvider')] public function testItCanParseMarkdownEncodedString($given, $expected) { - tap(Markdown::parse($given), function ($html) use ($expected) { + tap(Markdown::parse($given, encoded: true), function ($html) use ($expected) { $this->assertInstanceOf(HtmlString::class, $html); $this->assertStringEqualsStringIgnoringLineEndings($expected.PHP_EOL, (string) $html);
diff --git a/src/Illuminate/Mail/Markdown.php b/src/Illuminate/Mail/Markdown.php index e8ec2defc4c4..54c9c2ece372 100644 --- a/src/Illuminate/Mail/Markdown.php +++ b/src/Illuminate/Mail/Markdown.php @@ -69,9 +69,25 @@ public function render($view, array $data = [], $inliner = null) $contents = $bladeCompiler->usingEchoFormat( 'new \Illuminate\Support\EncodedHtmlString(%s)', function () use ($view, $data) { - return $this->view->replaceNamespace( - 'mail', $this->htmlComponentPaths() - )->make($view, $data)->render(); + EncodedHtmlString::encodeUsing(function ($value) { + $replacements = [ + '[' => '\[', + '<' => '&lt;', + '>' => '&gt;', + ]; + return str_replace(array_keys($replacements), array_values($replacements), $value); + }); + try { + 'mail', $this->htmlComponentPaths() + )->make($view, $data)->render(); + } finally { + EncodedHtmlString::flushState(); } ); @@ -84,7 +100,7 @@ function () use ($view, $data) { } return new HtmlString(($inliner ?: new CssToInlineStyles)->convert( - $contents, $this->view->make($theme, $data)->render() )); @@ -112,10 +128,15 @@ public function renderText($view, array $data = []) * Parse the given Markdown text into HTML. * * @param string $text + * @param bool $encoded * @return \Illuminate\Support\HtmlString */ - public static function parse($text) + public static function parse($text, bool $encoded = false) + if ($encoded === false) { + return new HtmlString(static::converter()->convert($text)->getContent()); EncodedHtmlString::encodeUsing(function ($value) { $replacements = [ '[' => '\[', diff --git a/src/Illuminate/Mail/resources/views/html/button.blade.php b/src/Illuminate/Mail/resources/views/html/button.blade.php index 4a9bf7d00495..050e969d2130 100644 --- a/src/Illuminate/Mail/resources/views/html/button.blade.php +++ b/src/Illuminate/Mail/resources/views/html/button.blade.php @@ -12,7 +12,7 @@ <table border="0" cellpadding="0" cellspacing="0" role="presentation"> <td> -<a href="{{ $url }}" class="button button-{{ $color }}" target="_blank" rel="noopener">{{ $slot }}</a> +<a href="{{ $url }}" class="button button-{{ $color }}" target="_blank" rel="noopener">{!! $slot !!}</a> diff --git a/src/Illuminate/Mail/resources/views/html/header.blade.php b/src/Illuminate/Mail/resources/views/html/header.blade.php index 56197f8d23f3..c47a260c56b2 100644 --- a/src/Illuminate/Mail/resources/views/html/header.blade.php +++ b/src/Illuminate/Mail/resources/views/html/header.blade.php @@ -5,7 +5,7 @@ @if (trim($slot) === 'Laravel') <img src="https://laravel.com/img/notification-logo.png" class="logo" alt="Laravel Logo"> @else @endif </a> diff --git a/src/Illuminate/Mail/resources/views/html/layout.blade.php b/src/Illuminate/Mail/resources/views/html/layout.blade.php index d31a01de8630..0fa6b82f72b2 100644 --- a/src/Illuminate/Mail/resources/views/html/layout.blade.php +++ b/src/Illuminate/Mail/resources/views/html/layout.blade.php @@ -23,7 +23,7 @@ </style> -{{ $head ?? '' }} +{!! $head ?? '' !!} </head> <body> @@ -31,7 +31,7 @@ <td align="center"> <table class="content" width="100%" cellpadding="0" cellspacing="0" role="presentation"> -{{ $header ?? '' }} +{!! $header ?? '' !!} <!-- Email Body --> @@ -40,16 +40,16 @@ <!-- Body content --> <td class="content-cell"> -{{ $subcopy ?? '' }} +{!! $subcopy ?? '' !!} -{{ $footer ?? '' }} +{!! $footer ?? '' !!} diff --git a/src/Illuminate/Mail/resources/views/html/message.blade.php b/src/Illuminate/Mail/resources/views/html/message.blade.php index 1a874fc26de5..f1e815f32a41 100644 --- a/src/Illuminate/Mail/resources/views/html/message.blade.php +++ b/src/Illuminate/Mail/resources/views/html/message.blade.php @@ -7,13 +7,13 @@ </x-slot:header> {{-- Body --}} {{-- Subcopy --}} @isset($subcopy) <x-slot:subcopy> <x-mail::subcopy> -{{ $subcopy }} +{!! $subcopy !!}} </x-mail::subcopy> </x-slot:subcopy> @endisset diff --git a/src/Illuminate/Mail/resources/views/html/panel.blade.php b/src/Illuminate/Mail/resources/views/html/panel.blade.php index 2975a60a021e..812db7c08e77 100644 --- a/src/Illuminate/Mail/resources/views/html/panel.blade.php +++ b/src/Illuminate/Mail/resources/views/html/panel.blade.php @@ -4,7 +4,7 @@ <table width="100%" cellpadding="0" cellspacing="0" role="presentation"> <td class="panel-item"> diff --git a/tests/Integration/Mail/Fixtures/message-with-template.blade.php b/tests/Integration/Mail/Fixtures/message-with-template.blade.php new file mode 100644 index 000000000000..9c53cef7e1bb --- /dev/null +++ b/tests/Integration/Mail/Fixtures/message-with-template.blade.php @@ -0,0 +1,4 @@ +@component('mail::message') +*Hi* {{ $user->name }} +@endcomponent diff --git a/tests/Integration/Mail/MailableTest.php b/tests/Integration/Mail/MailableTest.php index 339ebb2422d7..4ff0f539b6ad 100644 --- a/tests/Integration/Mail/MailableTest.php +++ b/tests/Integration/Mail/MailableTest.php @@ -2,14 +2,20 @@ namespace Illuminate\Tests\Integration\Mail; +use Illuminate\Foundation\Auth\User; +use Illuminate\Foundation\Testing\LazilyRefreshDatabase; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Content; use Illuminate\Mail\Mailables\Envelope; +use Orchestra\Testbench\Attributes\WithMigration; +use Orchestra\Testbench\Factories\UserFactory; use Orchestra\Testbench\TestCase; use PHPUnit\Framework\Attributes\DataProvider; class MailableTest extends TestCase { + use LazilyRefreshDatabase; /** {@inheritdoc} */ #[\Override] protected function defineEnvironment($app) @@ -69,4 +75,55 @@ public static function markdownEncodedDataProvider() 'My message is: Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation', ]; + #[WithMigration] + #[DataProvider('markdownEncodedTemplateDataProvider')] + public function testItCanAssertMarkdownEncodedStringUsingTemplate($given, $expected) + $user = UserFactory::new()->create([ + 'name' => $given, + ]); + $mailable = new class($user) extends Mailable + { + public $theme = 'taylor'; + public function __construct(public User $user) + // + return $this->markdown('message-with-template'); + }; + $mailable->assertSeeInHtml($expected, false); + public static function markdownEncodedTemplateDataProvider() + yield ['[Laravel](https://laravel.com)', '<em>Hi</em> [Laravel](https://laravel.com)']; + '![Welcome to Laravel](https://laravel.com/assets/img/welcome/background.svg)', + '<em>Hi</em> ![Welcome to Laravel](https://laravel.com/assets/img/welcome/background.svg)', + 'Visit https://laravel.com/docs to browse the documentation', + '<em>Hi</em> Visit https://laravel.com/docs to browse the documentation', + 'Visit <https://laravel.com/docs> to browse the documentation', + '<em>Hi</em> Visit &lt;https://laravel.com/docs&gt; to browse the documentation', + 'Visit <span>https://laravel.com/docs</span> to browse the documentation', + '<em>Hi</em> Visit &lt;span&gt;https://laravel.com/docs&lt;/span&gt; to browse the documentation', diff --git a/tests/Integration/Mail/MarkdownParserTest.php b/tests/Integration/Mail/MarkdownParserTest.php index d21602c9ad00..6669fe038ba3 100644 --- a/tests/Integration/Mail/MarkdownParserTest.php +++ b/tests/Integration/Mail/MarkdownParserTest.php @@ -24,7 +24,7 @@ public function testItCanParseMarkdownString($given, $expected) #[DataProvider('markdownEncodedDataProvider')] public function testItCanParseMarkdownEncodedString($given, $expected) - tap(Markdown::parse($given), function ($html) use ($expected) { + tap(Markdown::parse($given, encoded: true), function ($html) use ($expected) { $this->assertInstanceOf(HtmlString::class, $html); $this->assertStringEqualsStringIgnoringLineEndings($expected.PHP_EOL, (string) $html);
[ "+ $contents = $this->view->replaceNamespace(", "+ }", "+ return $contents;", "+ str_replace('\\[', '[', $contents), $this->view->make($theme, $data)->render()", "+ }", "+ public function build()" ]
[ 22, 27, 29, 38, 54, 217 ]
{ "additions": 98, "author": "crynobone", "deletions": 16, "html_url": "https://github.com/laravel/framework/pull/55149", "issue_id": 55149, "merged_at": "2025-03-24T14:53:50Z", "omission_probability": 0.1, "pr_number": 55149, "repo": "laravel/framework", "title": "[11.x] Fix `Illuminate\\Support\\EncodedHtmlString` from causing breaking change", "total_changes": 114 }
6
diff --git a/src/Illuminate/Bus/Dispatcher.php b/src/Illuminate/Bus/Dispatcher.php index 32f917d796a6..0107b9e5acd4 100644 --- a/src/Illuminate/Bus/Dispatcher.php +++ b/src/Illuminate/Bus/Dispatcher.php @@ -51,6 +51,13 @@ class Dispatcher implements QueueingDispatcher */ protected $queueResolver; + /** + * Indicates if dispatching after response is disabled. + * + * @var bool + */ + protected $allowsDispatchingAfterResponses = true; + /** * Create a new command dispatcher instance. * @@ -252,6 +259,12 @@ protected function pushCommandToQueue($queue, $command) */ public function dispatchAfterResponse($command, $handler = null) { + if (! $this->allowsDispatchingAfterResponses) { + $this->dispatchSync($command); + + return; + } + $this->container->terminating(function () use ($command, $handler) { $this->dispatchSync($command, $handler); }); @@ -282,4 +295,28 @@ public function map(array $map) return $this; } + + /** + * Allow dispatching after responses. + * + * @return $this + */ + public function withDispatchingAfterResponses() + { + $this->allowsDispatchingAfterResponses = true; + + return $this; + } + + /** + * Disable dispatching after responses. + * + * @return $this + */ + public function withoutDispatchingAfterResponses() + { + $this->allowsDispatchingAfterResponses = false; + + return $this; + } } diff --git a/tests/Integration/Queue/JobDispatchingTest.php b/tests/Integration/Queue/JobDispatchingTest.php index ebef0f344318..eddfd83c23c1 100644 --- a/tests/Integration/Queue/JobDispatchingTest.php +++ b/tests/Integration/Queue/JobDispatchingTest.php @@ -10,6 +10,7 @@ use Illuminate\Queue\Events\JobQueued; use Illuminate\Queue\Events\JobQueueing; use Illuminate\Queue\InteractsWithQueue; +use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Config; use Orchestra\Testbench\Attributes\WithMigration; @@ -165,6 +166,37 @@ public function testQueueMayBeNullForJobQueueingAndJobQueuedEvent() $this->assertNull($events[3]->queue); } + public function testCanDisableDispatchingAfterResponse() + { + Job::dispatchAfterResponse('test'); + + $this->assertFalse(Job::$ran); + + $this->app->terminate(); + + $this->assertTrue(Job::$ran); + + Bus::withoutDispatchingAfterResponses(); + + Job::$ran = false; + Job::dispatchAfterResponse('test'); + + $this->assertTrue(Job::$ran); + + $this->app->terminate(); + + Bus::withDispatchingAfterResponses(); + + Job::$ran = false; + Job::dispatchAfterResponse('test'); + + $this->assertFalse(Job::$ran); + + $this->app->terminate(); + + $this->assertTrue(Job::$ran); + } + /** * Helpers. */
diff --git a/src/Illuminate/Bus/Dispatcher.php b/src/Illuminate/Bus/Dispatcher.php index 32f917d796a6..0107b9e5acd4 100644 --- a/src/Illuminate/Bus/Dispatcher.php +++ b/src/Illuminate/Bus/Dispatcher.php @@ -51,6 +51,13 @@ class Dispatcher implements QueueingDispatcher protected $queueResolver; + * Indicates if dispatching after response is disabled. + * @var bool + protected $allowsDispatchingAfterResponses = true; * Create a new command dispatcher instance. * @@ -252,6 +259,12 @@ protected function pushCommandToQueue($queue, $command) public function dispatchAfterResponse($command, $handler = null) { + if (! $this->allowsDispatchingAfterResponses) { + $this->dispatchSync($command); + return; + } $this->container->terminating(function () use ($command, $handler) { $this->dispatchSync($command, $handler); }); @@ -282,4 +295,28 @@ public function map(array $map) return $this; + * Allow dispatching after responses. + public function withDispatchingAfterResponses() + $this->allowsDispatchingAfterResponses = true; + * Disable dispatching after responses. + public function withoutDispatchingAfterResponses() + $this->allowsDispatchingAfterResponses = false; } diff --git a/tests/Integration/Queue/JobDispatchingTest.php b/tests/Integration/Queue/JobDispatchingTest.php index ebef0f344318..eddfd83c23c1 100644 --- a/tests/Integration/Queue/JobDispatchingTest.php +++ b/tests/Integration/Queue/JobDispatchingTest.php @@ -10,6 +10,7 @@ use Illuminate\Queue\Events\JobQueued; use Illuminate\Queue\Events\JobQueueing; use Illuminate\Queue\InteractsWithQueue; +use Illuminate\Support\Facades\Bus; use Illuminate\Support\Facades\Config; use Orchestra\Testbench\Attributes\WithMigration; @@ -165,6 +166,37 @@ public function testQueueMayBeNullForJobQueueingAndJobQueuedEvent() $this->assertNull($events[3]->queue); + public function testCanDisableDispatchingAfterResponse() + Bus::withoutDispatchingAfterResponses(); + Bus::withDispatchingAfterResponses(); * Helpers.
[]
[]
{ "additions": 69, "author": "gdebrauwer", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55456", "issue_id": 55456, "merged_at": "2025-04-24T19:45:06Z", "omission_probability": 0.1, "pr_number": 55456, "repo": "laravel/framework", "title": "[12.x] Option to disable dispatchAfterResponse in a test", "total_changes": 69 }
7
diff --git a/src/Illuminate/Notifications/NotificationSender.php b/src/Illuminate/Notifications/NotificationSender.php index c7e75fd851b2..46ef9e88cf15 100644 --- a/src/Illuminate/Notifications/NotificationSender.php +++ b/src/Illuminate/Notifications/NotificationSender.php @@ -6,11 +6,13 @@ use Illuminate\Contracts\Translation\HasLocalePreference; use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Illuminate\Database\Eloquent\Model; +use Illuminate\Notifications\Events\NotificationFailed; use Illuminate\Notifications\Events\NotificationSending; use Illuminate\Notifications\Events\NotificationSent; use Illuminate\Support\Collection; use Illuminate\Support\Str; use Illuminate\Support\Traits\Localizable; +use Throwable; class NotificationSender { @@ -44,6 +46,13 @@ class NotificationSender */ protected $locale; + /** + * Indicates whether a NotificationFailed event has been dispatched. + * + * @var bool + */ + protected $failedEventWasDispatched = false; + /** * Create a new notification sender instance. * @@ -58,6 +67,8 @@ public function __construct($manager, $bus, $events, $locale = null) $this->events = $events; $this->locale = $locale; $this->manager = $manager; + + $this->events->listen(NotificationFailed::class, fn () => $this->failedEventWasDispatched = true); } /** @@ -144,7 +155,19 @@ protected function sendToNotifiable($notifiable, $id, $notification, $channel) return; } - $response = $this->manager->driver($channel)->send($notifiable, $notification); + try { + $response = $this->manager->driver($channel)->send($notifiable, $notification); + } catch (Throwable $exception) { + if (! $this->failedEventWasDispatched) { + $this->events->dispatch( + new NotificationFailed($notifiable, $notification, $channel, ['exception' => $exception]) + ); + } + + $this->failedEventWasDispatched = false; + + throw $exception; + } $this->events->dispatch( new NotificationSent($notifiable, $notification, $channel, $response) diff --git a/tests/Notifications/NotificationChannelManagerTest.php b/tests/Notifications/NotificationChannelManagerTest.php index efcce081aeee..4b272db8399f 100644 --- a/tests/Notifications/NotificationChannelManagerTest.php +++ b/tests/Notifications/NotificationChannelManagerTest.php @@ -2,17 +2,20 @@ namespace Illuminate\Tests\Notifications; +use Exception; use Illuminate\Bus\Queueable; use Illuminate\Container\Container; use Illuminate\Contracts\Bus\Dispatcher as Bus; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\ChannelManager; +use Illuminate\Notifications\Events\NotificationFailed; use Illuminate\Notifications\Events\NotificationSending; use Illuminate\Notifications\Events\NotificationSent; use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notification; use Illuminate\Notifications\SendQueuedNotifications; +use Illuminate\Support\Collection; use Mockery as m; use PHPUnit\Framework\TestCase; @@ -34,6 +37,7 @@ public function testNotificationCanBeDispatchedToDriver() Container::setInstance($container); $manager = m::mock(ChannelManager::class.'[driver]', [$container]); $manager->shouldReceive('driver')->andReturn($driver = m::mock()); + $events->shouldReceive('listen')->once(); $events->shouldReceive('until')->with(m::type(NotificationSending::class))->andReturn(true); $driver->shouldReceive('send')->once(); $events->shouldReceive('dispatch')->with(m::type(NotificationSent::class)); @@ -49,6 +53,7 @@ public function testNotificationNotSentOnHalt() $container->instance(Dispatcher::class, $events = m::mock()); Container::setInstance($container); $manager = m::mock(ChannelManager::class.'[driver]', [$container]); + $events->shouldReceive('listen')->once(); $events->shouldReceive('until')->once()->with(m::type(NotificationSending::class))->andReturn(false); $events->shouldReceive('until')->with(m::type(NotificationSending::class))->andReturn(true); $manager->shouldReceive('driver')->once()->andReturn($driver = m::mock()); @@ -66,6 +71,7 @@ public function testNotificationNotSentWhenCancelled() $container->instance(Dispatcher::class, $events = m::mock()); Container::setInstance($container); $manager = m::mock(ChannelManager::class.'[driver]', [$container]); + $events->shouldReceive('listen')->once(); $events->shouldReceive('until')->with(m::type(NotificationSending::class))->andReturn(true); $manager->shouldNotReceive('driver'); $events->shouldNotReceive('dispatch'); @@ -81,6 +87,7 @@ public function testNotificationSentWhenNotCancelled() $container->instance(Dispatcher::class, $events = m::mock()); Container::setInstance($container); $manager = m::mock(ChannelManager::class.'[driver]', [$container]); + $events->shouldReceive('listen')->once(); $events->shouldReceive('until')->with(m::type(NotificationSending::class))->andReturn(true); $manager->shouldReceive('driver')->once()->andReturn($driver = m::mock()); $driver->shouldReceive('send')->once(); @@ -89,6 +96,56 @@ public function testNotificationSentWhenNotCancelled() $manager->send([new NotificationChannelManagerTestNotifiable], new NotificationChannelManagerTestNotCancelledNotification); } + public function testNotificationNotSentWhenFailed() + { + $this->expectException(Exception::class); + + $container = new Container; + $container->instance('config', ['app.name' => 'Name', 'app.logo' => 'Logo']); + $container->instance(Bus::class, $bus = m::mock()); + $container->instance(Dispatcher::class, $events = m::mock()); + Container::setInstance($container); + $manager = m::mock(ChannelManager::class.'[driver]', [$container]); + $manager->shouldReceive('driver')->andReturn($driver = m::mock()); + $driver->shouldReceive('send')->andThrow(new Exception()); + $events->shouldReceive('listen')->once(); + $events->shouldReceive('until')->with(m::type(NotificationSending::class))->andReturn(true); + $events->shouldReceive('dispatch')->once()->with(m::type(NotificationFailed::class)); + $events->shouldReceive('dispatch')->never()->with(m::type(NotificationSent::class)); + + $manager->send(new NotificationChannelManagerTestNotifiable, new NotificationChannelManagerTestNotification); + } + + public function testNotificationFailedDispatchedOnlyOnceWhenFailed() + { + $this->expectException(Exception::class); + + $container = new Container; + $container->instance('config', ['app.name' => 'Name', 'app.logo' => 'Logo']); + $container->instance(Bus::class, $bus = m::mock()); + $container->instance(Dispatcher::class, $events = m::mock(Dispatcher::class)); + Container::setInstance($container); + $manager = m::mock(ChannelManager::class.'[driver]', [$container]); + $manager->shouldReceive('driver')->andReturn($driver = m::mock()); + $driver->shouldReceive('send')->andReturnUsing(function ($notifiable, $notification) use ($events) { + $events->dispatch(new NotificationFailed($notifiable, $notification, 'test')); + throw new Exception(); + }); + $listeners = new Collection(); + $events->shouldReceive('until')->with(m::type(NotificationSending::class))->andReturn(true); + $events->shouldReceive('listen')->once()->andReturnUsing(function ($event, $callback) use ($listeners) { + $listeners->push($callback); + }); + $events->shouldReceive('dispatch')->once()->with(m::type(NotificationFailed::class))->andReturnUsing(function ($event) use ($listeners) { + foreach ($listeners as $listener) { + $listener($event); + } + }); + $events->shouldReceive('dispatch')->never()->with(m::type(NotificationSent::class)); + + $manager->send(new NotificationChannelManagerTestNotifiable, new NotificationChannelManagerTestNotification); + } + public function testNotificationCanBeQueued() { $container = new Container; @@ -98,6 +155,7 @@ public function testNotificationCanBeQueued() $bus->shouldReceive('dispatch')->with(m::type(SendQueuedNotifications::class)); Container::setInstance($container); $manager = m::mock(ChannelManager::class.'[driver]', [$container]); + $events->shouldReceive('listen')->once(); $manager->send([new NotificationChannelManagerTestNotifiable], new NotificationChannelManagerTestQueuedNotification); } diff --git a/tests/Notifications/NotificationSenderTest.php b/tests/Notifications/NotificationSenderTest.php index 4770fc96cd17..6e3a9954938c 100644 --- a/tests/Notifications/NotificationSenderTest.php +++ b/tests/Notifications/NotificationSenderTest.php @@ -30,6 +30,7 @@ public function testItCanSendQueuedNotificationsWithAStringVia() $bus = m::mock(BusDispatcher::class); $bus->shouldReceive('dispatch'); $events = m::mock(EventDispatcher::class); + $events->shouldReceive('listen')->once(); $sender = new NotificationSender($manager, $bus, $events); @@ -43,6 +44,7 @@ public function testItCanSendNotificationsWithAnEmptyStringVia() $bus = m::mock(BusDispatcher::class); $bus->shouldNotReceive('dispatch'); $events = m::mock(EventDispatcher::class); + $events->shouldReceive('listen')->once(); $sender = new NotificationSender($manager, $bus, $events); @@ -56,6 +58,7 @@ public function testItCannotSendNotificationsViaDatabaseForAnonymousNotifiables( $bus = m::mock(BusDispatcher::class); $bus->shouldNotReceive('dispatch'); $events = m::mock(EventDispatcher::class); + $events->shouldReceive('listen')->once(); $sender = new NotificationSender($manager, $bus, $events); @@ -72,6 +75,7 @@ public function testItCanSendQueuedNotificationsThroughMiddleware() return $job->middleware[0] instanceof TestNotificationMiddleware; }); $events = m::mock(EventDispatcher::class); + $events->shouldReceive('listen')->once(); $sender = new NotificationSender($manager, $bus, $events); @@ -99,6 +103,7 @@ public function testItCanSendQueuedMultiChannelNotificationsThroughDifferentMidd return empty($job->middleware); }); $events = m::mock(EventDispatcher::class); + $events->shouldReceive('listen')->once(); $sender = new NotificationSender($manager, $bus, $events); @@ -122,6 +127,7 @@ public function testItCanSendQueuedWithViaConnectionsNotifications() }); $events = m::mock(EventDispatcher::class); + $events->shouldReceive('listen')->once(); $sender = new NotificationSender($manager, $bus, $events);
diff --git a/src/Illuminate/Notifications/NotificationSender.php b/src/Illuminate/Notifications/NotificationSender.php index c7e75fd851b2..46ef9e88cf15 100644 --- a/src/Illuminate/Notifications/NotificationSender.php +++ b/src/Illuminate/Notifications/NotificationSender.php @@ -6,11 +6,13 @@ use Illuminate\Contracts\Translation\HasLocalePreference; use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Collection; use Illuminate\Support\Str; use Illuminate\Support\Traits\Localizable; +use Throwable; class NotificationSender { @@ -44,6 +46,13 @@ class NotificationSender */ protected $locale; + /** + * Indicates whether a NotificationFailed event has been dispatched. + * + * @var bool + */ + protected $failedEventWasDispatched = false; * Create a new notification sender instance. * @@ -58,6 +67,8 @@ public function __construct($manager, $bus, $events, $locale = null) $this->events = $events; $this->locale = $locale; $this->manager = $manager; + $this->events->listen(NotificationFailed::class, fn () => $this->failedEventWasDispatched = true); @@ -144,7 +155,19 @@ protected function sendToNotifiable($notifiable, $id, $notification, $channel) return; } - $response = $this->manager->driver($channel)->send($notifiable, $notification); + try { + $response = $this->manager->driver($channel)->send($notifiable, $notification); + } catch (Throwable $exception) { + if (! $this->failedEventWasDispatched) { + $this->events->dispatch( + new NotificationFailed($notifiable, $notification, $channel, ['exception' => $exception]) + ); + $this->failedEventWasDispatched = false; + throw $exception; + } $this->events->dispatch( new NotificationSent($notifiable, $notification, $channel, $response) diff --git a/tests/Notifications/NotificationChannelManagerTest.php b/tests/Notifications/NotificationChannelManagerTest.php index efcce081aeee..4b272db8399f 100644 --- a/tests/Notifications/NotificationChannelManagerTest.php +++ b/tests/Notifications/NotificationChannelManagerTest.php @@ -2,17 +2,20 @@ namespace Illuminate\Tests\Notifications; +use Exception; use Illuminate\Bus\Queueable; use Illuminate\Container\Container; use Illuminate\Contracts\Bus\Dispatcher as Bus; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\ChannelManager; use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notification; use Illuminate\Notifications\SendQueuedNotifications; +use Illuminate\Support\Collection; use Mockery as m; use PHPUnit\Framework\TestCase; @@ -34,6 +37,7 @@ public function testNotificationCanBeDispatchedToDriver() $manager->shouldReceive('driver')->andReturn($driver = m::mock()); $events->shouldReceive('dispatch')->with(m::type(NotificationSent::class)); @@ -49,6 +53,7 @@ public function testNotificationNotSentOnHalt() $events->shouldReceive('until')->once()->with(m::type(NotificationSending::class))->andReturn(false); @@ -66,6 +71,7 @@ public function testNotificationNotSentWhenCancelled() $manager->shouldNotReceive('driver'); $events->shouldNotReceive('dispatch'); @@ -81,6 +87,7 @@ public function testNotificationSentWhenNotCancelled() @@ -89,6 +96,56 @@ public function testNotificationSentWhenNotCancelled() $manager->send([new NotificationChannelManagerTestNotifiable], new NotificationChannelManagerTestNotCancelledNotification); + $container->instance(Dispatcher::class, $events = m::mock()); + $driver->shouldReceive('send')->andThrow(new Exception()); + $events->shouldReceive('dispatch')->once()->with(m::type(NotificationFailed::class)); + public function testNotificationFailedDispatchedOnlyOnceWhenFailed() + $driver->shouldReceive('send')->andReturnUsing(function ($notifiable, $notification) use ($events) { + $events->dispatch(new NotificationFailed($notifiable, $notification, 'test')); + throw new Exception(); + $listeners = new Collection(); + $events->shouldReceive('listen')->once()->andReturnUsing(function ($event, $callback) use ($listeners) { + $listeners->push($callback); + $events->shouldReceive('dispatch')->once()->with(m::type(NotificationFailed::class))->andReturnUsing(function ($event) use ($listeners) { + $listener($event); public function testNotificationCanBeQueued() { $container = new Container; @@ -98,6 +155,7 @@ public function testNotificationCanBeQueued() $bus->shouldReceive('dispatch')->with(m::type(SendQueuedNotifications::class)); $manager->send([new NotificationChannelManagerTestNotifiable], new NotificationChannelManagerTestQueuedNotification); diff --git a/tests/Notifications/NotificationSenderTest.php b/tests/Notifications/NotificationSenderTest.php index 4770fc96cd17..6e3a9954938c 100644 --- a/tests/Notifications/NotificationSenderTest.php +++ b/tests/Notifications/NotificationSenderTest.php @@ -30,6 +30,7 @@ public function testItCanSendQueuedNotificationsWithAStringVia() $bus->shouldReceive('dispatch'); @@ -43,6 +44,7 @@ public function testItCanSendNotificationsWithAnEmptyStringVia() @@ -56,6 +58,7 @@ public function testItCannotSendNotificationsViaDatabaseForAnonymousNotifiables( @@ -72,6 +75,7 @@ public function testItCanSendQueuedNotificationsThroughMiddleware() return $job->middleware[0] instanceof TestNotificationMiddleware; @@ -99,6 +103,7 @@ public function testItCanSendQueuedMultiChannelNotificationsThroughDifferentMidd return empty($job->middleware); @@ -122,6 +127,7 @@ public function testItCanSendQueuedWithViaConnectionsNotifications()
[ "+ public function testNotificationNotSentWhenFailed()", "+ $container->instance(Dispatcher::class, $events = m::mock(Dispatcher::class));", "+ foreach ($listeners as $listener) {" ]
[ 123, 150, 164 ]
{ "additions": 88, "author": "rodrigopedra", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55507", "issue_id": 55507, "merged_at": "2025-04-24T19:24:00Z", "omission_probability": 0.1, "pr_number": 55507, "repo": "laravel/framework", "title": "[12.x] Dispatch NotificationFailed when sending fails", "total_changes": 89 }
8
diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index 79a2f5d98cd..6893c1284e3 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -1072,7 +1072,28 @@ public function getRelation($relation) */ public function relationLoaded($key) { - return array_key_exists($key, $this->relations); + if (array_key_exists($key, $this->relations)) { + return true; + } + + [$relation, $nestedRelation] = array_replace( + [null, null], + explode('.', $key, 2), + ); + + if (! array_key_exists($relation, $this->relations)) { + return false; + } + + if ($nestedRelation !== null) { + foreach ($this->$relation as $related) { + if (! $related->relationLoaded($nestedRelation)) { + return false; + } + } + } + + return true; } /** diff --git a/tests/Integration/Database/EloquentModelRelationLoadedTest.php b/tests/Integration/Database/EloquentModelRelationLoadedTest.php new file mode 100644 index 00000000000..06a0a740d3b --- /dev/null +++ b/tests/Integration/Database/EloquentModelRelationLoadedTest.php @@ -0,0 +1,168 @@ +<?php + +namespace Illuminate\Tests\Integration\Database\EloquentModelRelationLoadedTest; + +use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; +use Illuminate\Tests\Integration\Database\DatabaseTestCase; + +class EloquentModelRelationLoadedTest extends DatabaseTestCase +{ + protected function afterRefreshingDatabase() + { + Schema::create('ones', function (Blueprint $table) { + $table->increments('id'); + }); + + Schema::create('twos', function (Blueprint $table) { + $table->increments('id'); + $table->integer('one_id'); + }); + + Schema::create('threes', function (Blueprint $table) { + $table->increments('id'); + $table->integer('two_id'); + $table->integer('one_id')->nullable(); + }); + } + + public function testWhenRelationIsInvalid() + { + $one = One::query()->create(); + $one->twos()->create(); + + $model = One::query() + ->with('twos') + ->find($one->id); + + $this->assertFalse($model->relationLoaded('.')); + $this->assertFalse($model->relationLoaded('invalid')); + } + + public function testWhenNestedRelationIsInvalid() + { + $one = One::query()->create(); + $one->twos()->create(); + + $model = One::query() + ->with('twos') + ->find($one->id); + + $this->assertFalse($model->relationLoaded('twos.')); + $this->assertFalse($model->relationLoaded('twos.invalid')); + } + + public function testWhenRelationNotLoaded() + { + $one = One::query()->create(); + $one->twos()->create(); + + $model = One::query()->find($one->id); + + $this->assertFalse($model->relationLoaded('twos')); + } + + public function testWhenRelationLoaded() + { + $one = One::query()->create(); + $one->twos()->create(); + + $model = One::query() + ->with('twos') + ->find($one->id); + + $this->assertTrue($model->relationLoaded('twos')); + } + + public function testWhenChildRelationIsNotLoaded() + { + $one = One::query()->create(); + $two = $one->twos()->create(); + $two->threes()->create(); + + $model = One::query() + ->with('twos') + ->find($one->id); + + $this->assertTrue($model->relationLoaded('twos')); + $this->assertFalse($model->relationLoaded('twos.threes')); + } + + public function testWhenChildRelationIsLoaded() + { + $one = One::query()->create(); + $two = $one->twos()->create(); + $two->threes()->create(); + + $model = One::query() + ->with('twos.threes') + ->find($one->id); + + $this->assertTrue($model->relationLoaded('twos')); + $this->assertTrue($model->relationLoaded('twos.threes')); + } + + public function testWhenChildRecursiveRelationIsLoaded() + { + $one = One::query()->create(); + $two = $one->twos()->create(); + $two->threes()->create(['one_id' => $one->id]); + + $model = One::query() + ->with('twos.threes.one') + ->find($one->id); + + $this->assertTrue($model->relationLoaded('twos')); + $this->assertTrue($model->relationLoaded('twos.threes')); + $this->assertTrue($model->relationLoaded('twos.threes.one')); + } +} + +class One extends Model +{ + public $table = 'ones'; + public $timestamps = false; + protected $guarded = []; + + public function twos(): HasMany + { + return $this->hasMany(Two::class, 'one_id'); + } +} + +class Two extends Model +{ + public $table = 'twos'; + public $timestamps = false; + protected $guarded = []; + + public function one(): BelongsTo + { + return $this->belongsTo(One::class, 'one_id'); + } + + public function threes(): HasMany + { + return $this->hasMany(Three::class, 'two_id'); + } +} + +class Three extends Model +{ + public $table = 'threes'; + public $timestamps = false; + protected $guarded = []; + + public function one(): BelongsTo + { + return $this->belongsTo(One::class, 'one_id'); + } + + public function two(): BelongsTo + { + return $this->belongsTo(Two::class, 'two_id'); + } +}
diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index 79a2f5d98cd..6893c1284e3 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -1072,7 +1072,28 @@ public function getRelation($relation) */ public function relationLoaded($key) { - return array_key_exists($key, $this->relations); + if (array_key_exists($key, $this->relations)) { + return true; + [$relation, $nestedRelation] = array_replace( + [null, null], + explode('.', $key, 2), + ); + return false; + if ($nestedRelation !== null) { + foreach ($this->$relation as $related) { + if (! $related->relationLoaded($nestedRelation)) { + } + return true; } /** diff --git a/tests/Integration/Database/EloquentModelRelationLoadedTest.php b/tests/Integration/Database/EloquentModelRelationLoadedTest.php new file mode 100644 index 00000000000..06a0a740d3b --- /dev/null +++ b/tests/Integration/Database/EloquentModelRelationLoadedTest.php @@ -0,0 +1,168 @@ +<?php +namespace Illuminate\Tests\Integration\Database\EloquentModelRelationLoadedTest; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Tests\Integration\Database\DatabaseTestCase; +class EloquentModelRelationLoadedTest extends DatabaseTestCase + protected function afterRefreshingDatabase() + Schema::create('ones', function (Blueprint $table) { + Schema::create('twos', function (Blueprint $table) { + $table->integer('one_id'); + Schema::create('threes', function (Blueprint $table) { + $table->integer('two_id'); + $table->integer('one_id')->nullable(); + public function testWhenRelationIsInvalid() + $this->assertFalse($model->relationLoaded('.')); + public function testWhenNestedRelationIsInvalid() + $this->assertFalse($model->relationLoaded('twos.')); + public function testWhenRelationNotLoaded() + $model = One::query()->find($one->id); + $this->assertFalse($model->relationLoaded('twos')); + public function testWhenRelationLoaded() + public function testWhenChildRelationIsNotLoaded() + $this->assertFalse($model->relationLoaded('twos.threes')); + public function testWhenChildRelationIsLoaded() + ->with('twos.threes') + public function testWhenChildRecursiveRelationIsLoaded() + $two->threes()->create(['one_id' => $one->id]); + ->with('twos.threes.one') + $this->assertTrue($model->relationLoaded('twos.threes.one')); +class One extends Model + public $table = 'ones'; + public function twos(): HasMany + return $this->hasMany(Two::class, 'one_id'); +class Two extends Model + public $table = 'twos'; + public function threes(): HasMany + return $this->hasMany(Three::class, 'two_id'); +class Three extends Model + public $table = 'threes'; + public function two(): BelongsTo + return $this->belongsTo(Two::class, 'two_id');
[ "+ if (! array_key_exists($relation, $this->relations)) {", "+ return false;", "+ }", "+use Illuminate\\Support\\Facades\\Schema;", "+ $this->assertFalse($model->relationLoaded('invalid'));", "+ $this->assertFalse($model->relationLoaded('twos.invalid'));" ]
[ 18, 25, 26, 48, 81, 94 ]
{ "additions": 190, "author": "tmsperera", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55471", "issue_id": 55471, "merged_at": "2025-04-21T14:32:31Z", "omission_probability": 0.1, "pr_number": 55471, "repo": "laravel/framework", "title": "[12.x] Support nested relations on `relationLoaded` method", "total_changes": 191 }
9
diff --git a/src/Illuminate/View/Compilers/Compiler.php b/src/Illuminate/View/Compilers/Compiler.php index dbd349e69e2..1e61eae9593 100755 --- a/src/Illuminate/View/Compilers/Compiler.php +++ b/src/Illuminate/View/Compilers/Compiler.php @@ -44,6 +44,13 @@ abstract class Compiler */ protected $compiledExtension = 'php'; + /** + * Indicates if view cache timestamps should be checked. + * + * @var bool + */ + protected $shouldCheckTimestamps; + /** * Create a new compiler instance. * @@ -51,6 +58,7 @@ abstract class Compiler * @param string $cachePath * @param string $basePath * @param bool $shouldCache + * @param bool $shouldCheckTimestamps * @param string $compiledExtension * * @throws \InvalidArgumentException @@ -61,6 +69,7 @@ public function __construct( $basePath = '', $shouldCache = true, $compiledExtension = 'php', + $shouldCheckTimestamps = true, ) { if (! $cachePath) { throw new InvalidArgumentException('Please provide a valid cache path.'); @@ -71,6 +80,7 @@ public function __construct( $this->basePath = $basePath; $this->shouldCache = $shouldCache; $this->compiledExtension = $compiledExtension; + $this->shouldCheckTimestamps = $shouldCheckTimestamps; } /** @@ -107,6 +117,10 @@ public function isExpired($path) return true; } + if (! $this->shouldCheckTimestamps) { + return false; + } + try { return $this->files->lastModified($path) >= $this->files->lastModified($compiled); diff --git a/src/Illuminate/View/ViewServiceProvider.php b/src/Illuminate/View/ViewServiceProvider.php index 41cd8b93c9a..2ef3d31177b 100755 --- a/src/Illuminate/View/ViewServiceProvider.php +++ b/src/Illuminate/View/ViewServiceProvider.php @@ -100,6 +100,7 @@ public function registerBladeCompiler() $app['config']->get('view.relative_hash', false) ? $app->basePath() : '', $app['config']->get('view.cache', true), $app['config']->get('view.compiled_extension', 'php'), + $app['config']->get('view.check_cache_timestamps', true), ), function ($blade) { $blade->component('dynamic-component', DynamicComponent::class); }); diff --git a/tests/View/ViewBladeCompilerTest.php b/tests/View/ViewBladeCompilerTest.php index ed59a62fbbe..b26693489c8 100644 --- a/tests/View/ViewBladeCompilerTest.php +++ b/tests/View/ViewBladeCompilerTest.php @@ -51,10 +51,17 @@ public function testIsExpiredReturnsFalseWhenUseCacheIsTrueAndNoFileModification public function testIsExpiredReturnsTrueWhenUseCacheIsFalse() { - $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__, $basePath = '', $useCache = false); + $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__, shouldCache: false); $this->assertTrue($compiler->isExpired('foo')); } + public function testIsExpiredReturnsFalseWhenIgnoreCacheTimestampsIsTrue() + { + $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__, shouldCheckTimestamps: false); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php')->andReturn(true); + $this->assertFalse($compiler->isExpired('foo')); + } + public function testCompilePathIsProperlyCreated() { $compiler = new BladeCompiler($this->getFiles(), __DIR__);
diff --git a/src/Illuminate/View/Compilers/Compiler.php b/src/Illuminate/View/Compilers/Compiler.php index dbd349e69e2..1e61eae9593 100755 --- a/src/Illuminate/View/Compilers/Compiler.php +++ b/src/Illuminate/View/Compilers/Compiler.php @@ -44,6 +44,13 @@ abstract class Compiler */ protected $compiledExtension = 'php'; + /** + * Indicates if view cache timestamps should be checked. + * @var bool + */ + protected $shouldCheckTimestamps; * Create a new compiler instance. @@ -51,6 +58,7 @@ abstract class Compiler * @param string $cachePath * @param string $basePath * @param bool $shouldCache + * @param bool $shouldCheckTimestamps * @param string $compiledExtension * @throws \InvalidArgumentException @@ -61,6 +69,7 @@ public function __construct( $basePath = '', $shouldCache = true, $compiledExtension = 'php', + $shouldCheckTimestamps = true, ) { if (! $cachePath) { throw new InvalidArgumentException('Please provide a valid cache path.'); @@ -71,6 +80,7 @@ public function __construct( $this->basePath = $basePath; $this->shouldCache = $shouldCache; $this->compiledExtension = $compiledExtension; @@ -107,6 +117,10 @@ public function isExpired($path) return true; } + if (! $this->shouldCheckTimestamps) { try { return $this->files->lastModified($path) >= $this->files->lastModified($compiled); diff --git a/src/Illuminate/View/ViewServiceProvider.php b/src/Illuminate/View/ViewServiceProvider.php index 41cd8b93c9a..2ef3d31177b 100755 --- a/src/Illuminate/View/ViewServiceProvider.php +++ b/src/Illuminate/View/ViewServiceProvider.php @@ -100,6 +100,7 @@ public function registerBladeCompiler() $app['config']->get('view.relative_hash', false) ? $app->basePath() : '', $app['config']->get('view.cache', true), $app['config']->get('view.compiled_extension', 'php'), + $app['config']->get('view.check_cache_timestamps', true), ), function ($blade) { $blade->component('dynamic-component', DynamicComponent::class); }); diff --git a/tests/View/ViewBladeCompilerTest.php b/tests/View/ViewBladeCompilerTest.php index ed59a62fbbe..b26693489c8 100644 --- a/tests/View/ViewBladeCompilerTest.php +++ b/tests/View/ViewBladeCompilerTest.php @@ -51,10 +51,17 @@ public function testIsExpiredReturnsFalseWhenUseCacheIsTrueAndNoFileModification public function testIsExpiredReturnsTrueWhenUseCacheIsFalse() - $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__, $basePath = '', $useCache = false); + $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__, shouldCache: false); $this->assertTrue($compiler->isExpired('foo')); + public function testIsExpiredReturnsFalseWhenIgnoreCacheTimestampsIsTrue() + { + $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__, shouldCheckTimestamps: false); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php')->andReturn(true); + $this->assertFalse($compiler->isExpired('foo')); public function testCompilePathIsProperlyCreated() $compiler = new BladeCompiler($this->getFiles(), __DIR__);
[ "+ *", "+ $this->shouldCheckTimestamps = $shouldCheckTimestamps;", "+ return false;", "+ }", "+ }" ]
[ 10, 38, 47, 48, 83 ]
{ "additions": 23, "author": "pizkaz", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55536", "issue_id": 55536, "merged_at": "2025-04-24T14:29:34Z", "omission_probability": 0.1, "pr_number": 55536, "repo": "laravel/framework", "title": "Add config option to ignore view cache timestamps", "total_changes": 24 }
10
diff --git a/src/Illuminate/Queue/BeanstalkdQueue.php b/src/Illuminate/Queue/BeanstalkdQueue.php index d1f64e98249..56e9c4e0664 100755 --- a/src/Illuminate/Queue/BeanstalkdQueue.php +++ b/src/Illuminate/Queue/BeanstalkdQueue.php @@ -125,7 +125,7 @@ public function later($delay, $job, $data = '', $queue = null) { return $this->enqueueUsing( $job, - $this->createPayload($job, $this->getQueue($queue), $data), + $this->createPayload($job, $this->getQueue($queue), $data, $delay), $queue, $delay, function ($payload, $queue, $delay) { diff --git a/src/Illuminate/Queue/DatabaseQueue.php b/src/Illuminate/Queue/DatabaseQueue.php index 0e6163a2c26..41d04e2b001 100644 --- a/src/Illuminate/Queue/DatabaseQueue.php +++ b/src/Illuminate/Queue/DatabaseQueue.php @@ -126,7 +126,7 @@ public function later($delay, $job, $data = '', $queue = null) { return $this->enqueueUsing( $job, - $this->createPayload($job, $this->getQueue($queue), $data), + $this->createPayload($job, $this->getQueue($queue), $data, $delay), $queue, $delay, function ($payload, $queue, $delay) { diff --git a/src/Illuminate/Queue/Queue.php b/src/Illuminate/Queue/Queue.php index a5f831957b0..49b3cdda6f2 100755 --- a/src/Illuminate/Queue/Queue.php +++ b/src/Illuminate/Queue/Queue.php @@ -2,6 +2,7 @@ namespace Illuminate\Queue; +use Carbon\Carbon; use Closure; use DateTimeInterface; use Illuminate\Bus\UniqueLock; @@ -97,17 +98,24 @@ public function bulk($jobs, $data = '', $queue = null) * @param \Closure|string|object $job * @param string $queue * @param mixed $data + * @param \DateTimeInterface|\DateInterval|int|null $delay * @return string * * @throws \Illuminate\Queue\InvalidPayloadException */ - protected function createPayload($job, $queue, $data = '') + protected function createPayload($job, $queue, $data = '', $delay = null) { if ($job instanceof Closure) { $job = CallQueuedClosure::create($job); } - $payload = json_encode($value = $this->createPayloadArray($job, $queue, $data), \JSON_UNESCAPED_UNICODE); + $value = $this->createPayloadArray($job, $queue, $data); + + $value['delay'] = isset($delay) + ? $this->secondsUntil($delay) + : null; + + $payload = json_encode($value, \JSON_UNESCAPED_UNICODE); if (json_last_error() !== JSON_ERROR_NONE) { throw new InvalidPayloadException( @@ -156,6 +164,7 @@ protected function createObjectPayload($job, $queue) 'commandName' => $job, 'command' => $job, ], + 'createdAt' => Carbon::now()->getTimestamp(), ]); $command = $this->jobShouldBeEncrypted($job) && $this->container->bound(Encrypter::class) @@ -277,6 +286,7 @@ protected function createStringPayload($job, $queue, $data) 'backoff' => null, 'timeout' => null, 'data' => $data, + 'createdAt' => Carbon::now()->getTimestamp(), ]); } diff --git a/src/Illuminate/Queue/RedisQueue.php b/src/Illuminate/Queue/RedisQueue.php index e8d6d77c7a5..84cfbde358c 100644 --- a/src/Illuminate/Queue/RedisQueue.php +++ b/src/Illuminate/Queue/RedisQueue.php @@ -192,7 +192,7 @@ public function later($delay, $job, $data = '', $queue = null) { return $this->enqueueUsing( $job, - $this->createPayload($job, $this->getQueue($queue), $data), + $this->createPayload($job, $this->getQueue($queue), $data, $delay), $queue, $delay, function ($payload, $queue, $delay) { diff --git a/src/Illuminate/Queue/SqsQueue.php b/src/Illuminate/Queue/SqsQueue.php index 0d74b8dda43..a128be81109 100755 --- a/src/Illuminate/Queue/SqsQueue.php +++ b/src/Illuminate/Queue/SqsQueue.php @@ -128,7 +128,7 @@ public function later($delay, $job, $data = '', $queue = null) { return $this->enqueueUsing( $job, - $this->createPayload($job, $queue ?: $this->default, $data), + $this->createPayload($job, $queue ?: $this->default, $data, $delay), $queue, $delay, function ($payload, $queue, $delay) { diff --git a/tests/Queue/QueueBeanstalkdQueueTest.php b/tests/Queue/QueueBeanstalkdQueueTest.php index ba34a706930..dfa4eace4a1 100755 --- a/tests/Queue/QueueBeanstalkdQueueTest.php +++ b/tests/Queue/QueueBeanstalkdQueueTest.php @@ -2,6 +2,7 @@ namespace Illuminate\Tests\Queue; +use Carbon\Carbon; use Illuminate\Container\Container; use Illuminate\Queue\BeanstalkdQueue; use Illuminate\Queue\Jobs\BeanstalkdJob; @@ -38,6 +39,9 @@ public function testPushProperlyPushesJobOntoBeanstalkd() { $uuid = Str::uuid(); + $time = Carbon::now(); + Carbon::setTestNow($time); + Str::createUuidsUsing(function () use ($uuid) { return $uuid; }); @@ -46,13 +50,14 @@ public function testPushProperlyPushesJobOntoBeanstalkd() $pheanstalk = $this->queue->getPheanstalk(); $pheanstalk->shouldReceive('useTube')->once()->with(m::type(TubeName::class)); $pheanstalk->shouldReceive('useTube')->once()->with(m::type(TubeName::class)); - $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), 1024, 0, 60); + $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => null]), 1024, 0, 60); $this->queue->push('foo', ['data'], 'stack'); $this->queue->push('foo', ['data']); $this->container->shouldHaveReceived('bound')->with('events')->times(4); + Carbon::setTestNow(); Str::createUuidsNormally(); } @@ -64,17 +69,21 @@ public function testDelayedPushProperlyPushesJobOntoBeanstalkd() return $uuid; }); + $time = Carbon::now(); + Carbon::setTestNow($time); + $this->setQueue('default', 60); $pheanstalk = $this->queue->getPheanstalk(); $pheanstalk->shouldReceive('useTube')->once()->with(m::type(TubeName::class)); $pheanstalk->shouldReceive('useTube')->once()->with(m::type(TubeName::class)); - $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), Pheanstalk::DEFAULT_PRIORITY, 5, Pheanstalk::DEFAULT_TTR); + $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => 5]), Pheanstalk::DEFAULT_PRIORITY, 5, Pheanstalk::DEFAULT_TTR); $this->queue->later(5, 'foo', ['data'], 'stack'); $this->queue->later(5, 'foo', ['data']); $this->container->shouldHaveReceived('bound')->with('events')->times(4); + Carbon::setTestNow(); Str::createUuidsNormally(); } diff --git a/tests/Queue/QueueDatabaseQueueUnitTest.php b/tests/Queue/QueueDatabaseQueueUnitTest.php index 3714b99a80b..9702a4d6695 100644 --- a/tests/Queue/QueueDatabaseQueueUnitTest.php +++ b/tests/Queue/QueueDatabaseQueueUnitTest.php @@ -2,6 +2,7 @@ namespace Illuminate\Tests\Queue; +use Carbon\Carbon; use Illuminate\Container\Container; use Illuminate\Database\Connection; use Illuminate\Queue\DatabaseQueue; @@ -69,6 +70,9 @@ public function testDelayedPushProperlyPushesJobOntoDatabase() return $uuid; }); + $time = Carbon::now(); + Carbon::setTestNow($time); + $queue = $this->getMockBuilder(DatabaseQueue::class) ->onlyMethods(['currentTime']) ->setConstructorArgs([$database = m::mock(Connection::class), 'table', 'default']) @@ -76,9 +80,9 @@ public function testDelayedPushProperlyPushesJobOntoDatabase() $queue->expects($this->any())->method('currentTime')->willReturn('time'); $queue->setContainer($container = m::spy(Container::class)); $database->shouldReceive('table')->with('table')->andReturn($query = m::mock(stdClass::class)); - $query->shouldReceive('insertGetId')->once()->andReturnUsing(function ($array) use ($uuid) { + $query->shouldReceive('insertGetId')->once()->andReturnUsing(function ($array) use ($uuid, $time) { $this->assertSame('default', $array['queue']); - $this->assertSame(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), $array['payload']); + $this->assertSame(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => 10]), $array['payload']); $this->assertEquals(0, $array['attempts']); $this->assertNull($array['reserved_at']); $this->assertIsInt($array['available_at']); @@ -88,6 +92,7 @@ public function testDelayedPushProperlyPushesJobOntoDatabase() $container->shouldHaveReceived('bound')->with('events')->twice(); + Carbon::setTestNow(); Str::createUuidsNormally(); } @@ -130,22 +135,25 @@ public function testBulkBatchPushesOntoDatabase() return $uuid; }); + $time = Carbon::now(); + Carbon::setTestNow($time); + $database = m::mock(Connection::class); $queue = $this->getMockBuilder(DatabaseQueue::class)->onlyMethods(['currentTime', 'availableAt'])->setConstructorArgs([$database, 'table', 'default'])->getMock(); $queue->expects($this->any())->method('currentTime')->willReturn('created'); $queue->expects($this->any())->method('availableAt')->willReturn('available'); $database->shouldReceive('table')->with('table')->andReturn($query = m::mock(stdClass::class)); - $query->shouldReceive('insert')->once()->andReturnUsing(function ($records) use ($uuid) { + $query->shouldReceive('insert')->once()->andReturnUsing(function ($records) use ($uuid, $time) { $this->assertEquals([[ 'queue' => 'queue', - 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), + 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => null]), 'attempts' => 0, 'reserved_at' => null, 'available_at' => 'available', 'created_at' => 'created', ], [ 'queue' => 'queue', - 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'bar', 'job' => 'bar', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), + 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'bar', 'job' => 'bar', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => null]), 'attempts' => 0, 'reserved_at' => null, 'available_at' => 'available', @@ -155,6 +163,7 @@ public function testBulkBatchPushesOntoDatabase() $queue->bulk(['foo', 'bar'], ['data'], 'queue'); + Carbon::setTestNow(); Str::createUuidsNormally(); } diff --git a/tests/Queue/QueueRedisQueueTest.php b/tests/Queue/QueueRedisQueueTest.php index 007f743653d..7ea0bfdbe07 100644 --- a/tests/Queue/QueueRedisQueueTest.php +++ b/tests/Queue/QueueRedisQueueTest.php @@ -27,16 +27,20 @@ public function testPushProperlyPushesJobOntoRedis() return $uuid; }); + $time = Carbon::now(); + Carbon::setTestNow($time); + $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = m::mock(Factory::class), 'default'])->getMock(); $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); $queue->setContainer($container = m::spy(Container::class)); $redis->shouldReceive('connection')->once()->andReturn($redis); - $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'id' => 'foo', 'attempts' => 0])); + $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'id' => 'foo', 'attempts' => 0, 'delay' => null])); $id = $queue->push('foo', ['data']); $this->assertSame('foo', $id); $container->shouldHaveReceived('bound')->with('events')->twice(); + Carbon::setTestNow(); Str::createUuidsNormally(); } @@ -48,11 +52,14 @@ public function testPushProperlyPushesJobOntoRedisWithCustomPayloadHook() return $uuid; }); + $time = Carbon::now(); + Carbon::setTestNow($time); + $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = m::mock(Factory::class), 'default'])->getMock(); $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); $queue->setContainer($container = m::spy(Container::class)); $redis->shouldReceive('connection')->once()->andReturn($redis); - $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'custom' => 'taylor', 'id' => 'foo', 'attempts' => 0])); + $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'custom' => 'taylor', 'id' => 'foo', 'attempts' => 0, 'delay' => null])); Queue::createPayloadUsing(function ($connection, $queue, $payload) { return ['custom' => 'taylor']; @@ -64,6 +71,7 @@ public function testPushProperlyPushesJobOntoRedisWithCustomPayloadHook() Queue::createPayloadUsing(null); + Carbon::setTestNow(); Str::createUuidsNormally(); } @@ -75,11 +83,14 @@ public function testPushProperlyPushesJobOntoRedisWithTwoCustomPayloadHook() return $uuid; }); + $time = Carbon::now(); + Carbon::setTestNow($time); + $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['getRandomId'])->setConstructorArgs([$redis = m::mock(Factory::class), 'default'])->getMock(); $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); $queue->setContainer($container = m::spy(Container::class)); $redis->shouldReceive('connection')->once()->andReturn($redis); - $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'custom' => 'taylor', 'bar' => 'foo', 'id' => 'foo', 'attempts' => 0])); + $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'custom' => 'taylor', 'bar' => 'foo', 'id' => 'foo', 'attempts' => 0, 'delay' => null])); Queue::createPayloadUsing(function ($connection, $queue, $payload) { return ['custom' => 'taylor']; @@ -95,6 +106,7 @@ public function testPushProperlyPushesJobOntoRedisWithTwoCustomPayloadHook() Queue::createPayloadUsing(null); + Carbon::setTestNow(); Str::createUuidsNormally(); } @@ -106,6 +118,9 @@ public function testDelayedPushProperlyPushesJobOntoRedis() return $uuid; }); + $time = Carbon::now(); + Carbon::setTestNow($time); + $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['availableAt', 'getRandomId'])->setConstructorArgs([$redis = m::mock(Factory::class), 'default'])->getMock(); $queue->setContainer($container = m::spy(Container::class)); $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); @@ -115,13 +130,14 @@ public function testDelayedPushProperlyPushesJobOntoRedis() $redis->shouldReceive('zadd')->once()->with( 'queues:default:delayed', 2, - json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'id' => 'foo', 'attempts' => 0]) + json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'id' => 'foo', 'attempts' => 0, 'delay' => 1]) ); $id = $queue->later(1, 'foo', ['data']); $this->assertSame('foo', $id); $container->shouldHaveReceived('bound')->with('events')->twice(); + Carbon::setTestNow(); Str::createUuidsNormally(); } @@ -133,22 +149,24 @@ public function testDelayedPushWithDateTimeProperlyPushesJobOntoRedis() return $uuid; }); - $date = Carbon::now(); + $time = $date = Carbon::now(); + Carbon::setTestNow($time); $queue = $this->getMockBuilder(RedisQueue::class)->onlyMethods(['availableAt', 'getRandomId'])->setConstructorArgs([$redis = m::mock(Factory::class), 'default'])->getMock(); $queue->setContainer($container = m::spy(Container::class)); $queue->expects($this->once())->method('getRandomId')->willReturn('foo'); - $queue->expects($this->once())->method('availableAt')->with($date)->willReturn(2); + $queue->expects($this->once())->method('availableAt')->with($date)->willReturn(5); $redis->shouldReceive('connection')->once()->andReturn($redis); $redis->shouldReceive('zadd')->once()->with( 'queues:default:delayed', - 2, - json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'id' => 'foo', 'attempts' => 0]) + 5, + json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'id' => 'foo', 'attempts' => 0, 'delay' => 5]) ); - $queue->later($date, 'foo', ['data']); + $queue->later($date->addSeconds(5), 'foo', ['data']); $container->shouldHaveReceived('bound')->with('events')->twice(); + Carbon::setTestNow(); Str::createUuidsNormally(); } }
diff --git a/src/Illuminate/Queue/BeanstalkdQueue.php b/src/Illuminate/Queue/BeanstalkdQueue.php index d1f64e98249..56e9c4e0664 100755 --- a/src/Illuminate/Queue/BeanstalkdQueue.php +++ b/src/Illuminate/Queue/BeanstalkdQueue.php @@ -125,7 +125,7 @@ public function later($delay, $job, $data = '', $queue = null) diff --git a/src/Illuminate/Queue/DatabaseQueue.php b/src/Illuminate/Queue/DatabaseQueue.php index 0e6163a2c26..41d04e2b001 100644 --- a/src/Illuminate/Queue/DatabaseQueue.php +++ b/src/Illuminate/Queue/DatabaseQueue.php @@ -126,7 +126,7 @@ public function later($delay, $job, $data = '', $queue = null) diff --git a/src/Illuminate/Queue/Queue.php b/src/Illuminate/Queue/Queue.php index a5f831957b0..49b3cdda6f2 100755 --- a/src/Illuminate/Queue/Queue.php +++ b/src/Illuminate/Queue/Queue.php namespace Illuminate\Queue; use Closure; use DateTimeInterface; use Illuminate\Bus\UniqueLock; @@ -97,17 +98,24 @@ public function bulk($jobs, $data = '', $queue = null) * @param \Closure|string|object $job * @param string $queue * @param mixed $data + * @param \DateTimeInterface|\DateInterval|int|null $delay * @return string * * @throws \Illuminate\Queue\InvalidPayloadException */ - protected function createPayload($job, $queue, $data = '') + protected function createPayload($job, $queue, $data = '', $delay = null) if ($job instanceof Closure) { $job = CallQueuedClosure::create($job); } - $payload = json_encode($value = $this->createPayloadArray($job, $queue, $data), \JSON_UNESCAPED_UNICODE); + $value = $this->createPayloadArray($job, $queue, $data); + $value['delay'] = isset($delay) + ? $this->secondsUntil($delay) + : null; + $payload = json_encode($value, \JSON_UNESCAPED_UNICODE); if (json_last_error() !== JSON_ERROR_NONE) { throw new InvalidPayloadException( @@ -156,6 +164,7 @@ protected function createObjectPayload($job, $queue) 'commandName' => $job, 'command' => $job, ], $command = $this->jobShouldBeEncrypted($job) && $this->container->bound(Encrypter::class) @@ -277,6 +286,7 @@ protected function createStringPayload($job, $queue, $data) 'backoff' => null, 'timeout' => null, 'data' => $data, diff --git a/src/Illuminate/Queue/RedisQueue.php b/src/Illuminate/Queue/RedisQueue.php index e8d6d77c7a5..84cfbde358c 100644 --- a/src/Illuminate/Queue/RedisQueue.php +++ b/src/Illuminate/Queue/RedisQueue.php @@ -192,7 +192,7 @@ public function later($delay, $job, $data = '', $queue = null) diff --git a/src/Illuminate/Queue/SqsQueue.php b/src/Illuminate/Queue/SqsQueue.php index 0d74b8dda43..a128be81109 100755 --- a/src/Illuminate/Queue/SqsQueue.php +++ b/src/Illuminate/Queue/SqsQueue.php @@ -128,7 +128,7 @@ public function later($delay, $job, $data = '', $queue = null) - $this->createPayload($job, $queue ?: $this->default, $data), diff --git a/tests/Queue/QueueBeanstalkdQueueTest.php b/tests/Queue/QueueBeanstalkdQueueTest.php index ba34a706930..dfa4eace4a1 100755 --- a/tests/Queue/QueueBeanstalkdQueueTest.php +++ b/tests/Queue/QueueBeanstalkdQueueTest.php use Illuminate\Queue\BeanstalkdQueue; use Illuminate\Queue\Jobs\BeanstalkdJob; @@ -38,6 +39,9 @@ public function testPushProperlyPushesJobOntoBeanstalkd() $uuid = Str::uuid(); Str::createUuidsUsing(function () use ($uuid) { @@ -46,13 +50,14 @@ public function testPushProperlyPushesJobOntoBeanstalkd() - $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), 1024, 0, 60); + $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => null]), 1024, 0, 60); $this->queue->push('foo', ['data'], 'stack'); $this->queue->push('foo', ['data']); @@ -64,17 +69,21 @@ public function testDelayedPushProperlyPushesJobOntoBeanstalkd() $this->setQueue('default', 60); - $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), Pheanstalk::DEFAULT_PRIORITY, 5, Pheanstalk::DEFAULT_TTR); + $pheanstalk->shouldReceive('put')->twice()->with(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => 5]), Pheanstalk::DEFAULT_PRIORITY, 5, Pheanstalk::DEFAULT_TTR); $this->queue->later(5, 'foo', ['data'], 'stack'); $this->queue->later(5, 'foo', ['data']); diff --git a/tests/Queue/QueueDatabaseQueueUnitTest.php b/tests/Queue/QueueDatabaseQueueUnitTest.php index 3714b99a80b..9702a4d6695 100644 --- a/tests/Queue/QueueDatabaseQueueUnitTest.php +++ b/tests/Queue/QueueDatabaseQueueUnitTest.php use Illuminate\Database\Connection; use Illuminate\Queue\DatabaseQueue; @@ -69,6 +70,9 @@ public function testDelayedPushProperlyPushesJobOntoDatabase() $queue = $this->getMockBuilder(DatabaseQueue::class) ->onlyMethods(['currentTime']) ->setConstructorArgs([$database = m::mock(Connection::class), 'table', 'default']) @@ -76,9 +80,9 @@ public function testDelayedPushProperlyPushesJobOntoDatabase() $queue->expects($this->any())->method('currentTime')->willReturn('time'); - $query->shouldReceive('insertGetId')->once()->andReturnUsing(function ($array) use ($uuid) { $this->assertSame('default', $array['queue']); - $this->assertSame(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), $array['payload']); + $this->assertSame(json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => 10]), $array['payload']); $this->assertEquals(0, $array['attempts']); $this->assertNull($array['reserved_at']); $this->assertIsInt($array['available_at']); @@ -88,6 +92,7 @@ public function testDelayedPushProperlyPushesJobOntoDatabase() @@ -130,22 +135,25 @@ public function testBulkBatchPushesOntoDatabase() $database = m::mock(Connection::class); $queue = $this->getMockBuilder(DatabaseQueue::class)->onlyMethods(['currentTime', 'availableAt'])->setConstructorArgs([$database, 'table', 'default'])->getMock(); $queue->expects($this->any())->method('currentTime')->willReturn('created'); $queue->expects($this->any())->method('availableAt')->willReturn('available'); - $query->shouldReceive('insert')->once()->andReturnUsing(function ($records) use ($uuid) { + $query->shouldReceive('insert')->once()->andReturnUsing(function ($records) use ($uuid, $time) { $this->assertEquals([[ - 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), 'created_at' => 'created', ], [ - 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'bar', 'job' => 'bar', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data']]), + 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'bar', 'job' => 'bar', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => null]), @@ -155,6 +163,7 @@ public function testBulkBatchPushesOntoDatabase() $queue->bulk(['foo', 'bar'], ['data'], 'queue'); diff --git a/tests/Queue/QueueRedisQueueTest.php b/tests/Queue/QueueRedisQueueTest.php index 007f743653d..7ea0bfdbe07 100644 --- a/tests/Queue/QueueRedisQueueTest.php +++ b/tests/Queue/QueueRedisQueueTest.php @@ -27,16 +27,20 @@ public function testPushProperlyPushesJobOntoRedis() - $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'id' => 'foo', 'attempts' => 0])); + $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'id' => 'foo', 'attempts' => 0, 'delay' => null])); $id = $queue->push('foo', ['data']); @@ -48,11 +52,14 @@ public function testPushProperlyPushesJobOntoRedisWithCustomPayloadHook() - $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'custom' => 'taylor', 'id' => 'foo', 'attempts' => 0])); + $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'custom' => 'taylor', 'id' => 'foo', 'attempts' => 0, 'delay' => null])); @@ -64,6 +71,7 @@ public function testPushProperlyPushesJobOntoRedisWithCustomPayloadHook() @@ -75,11 +83,14 @@ public function testPushProperlyPushesJobOntoRedisWithTwoCustomPayloadHook() - $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'custom' => 'taylor', 'bar' => 'foo', 'id' => 'foo', 'attempts' => 0])); + $redis->shouldReceive('eval')->once()->with(LuaScripts::push(), 2, 'queues:default', 'queues:default:notify', json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'custom' => 'taylor', 'bar' => 'foo', 'id' => 'foo', 'attempts' => 0, 'delay' => null])); @@ -95,6 +106,7 @@ public function testPushProperlyPushesJobOntoRedisWithTwoCustomPayloadHook() @@ -106,6 +118,9 @@ public function testDelayedPushProperlyPushesJobOntoRedis() @@ -115,13 +130,14 @@ public function testDelayedPushProperlyPushesJobOntoRedis() 2, + json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'id' => 'foo', 'attempts' => 0, 'delay' => 1]) $id = $queue->later(1, 'foo', ['data']); @@ -133,22 +149,24 @@ public function testDelayedPushWithDateTimeProperlyPushesJobOntoRedis() - $date = Carbon::now(); + $time = $date = Carbon::now(); - $queue->expects($this->once())->method('availableAt')->with($date)->willReturn(2); + $queue->expects($this->once())->method('availableAt')->with($date)->willReturn(5); - 2, + 5, + $queue->later($date->addSeconds(5), 'foo', ['data']); }
[ "+ $this->createPayload($job, $queue ?: $this->default, $data, $delay),", "+ $query->shouldReceive('insertGetId')->once()->andReturnUsing(function ($array) use ($uuid, $time) {", "+ 'payload' => json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'delay' => null]),", "+ json_encode(['uuid' => $uuid, 'displayName' => 'foo', 'job' => 'foo', 'maxTries' => null, 'maxExceptions' => null, 'failOnTimeout' => false, 'backoff' => null, 'timeout' => null, 'data' => ['data'], 'createdAt' => $time->getTimestamp(), 'id' => 'foo', 'attempts' => 0, 'delay' => 5])", "- $queue->later($date, 'foo', ['data']);" ]
[ 103, 195, 227, 366, 369 ]
{ "additions": 68, "author": "taylorotwell", "deletions": 22, "html_url": "https://github.com/laravel/framework/pull/55529", "issue_id": 55529, "merged_at": "2025-04-24T14:15:22Z", "omission_probability": 0.1, "pr_number": 55529, "repo": "laravel/framework", "title": "Add payload creation and original delay info to job payload", "total_changes": 90 }
11
diff --git a/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php b/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php index 4142572207af..7451491cbaf9 100755 --- a/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php +++ b/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php @@ -436,6 +436,34 @@ public function createManyQuietly(iterable $records) return Model::withoutEvents(fn () => $this->createMany($records)); } + /** + * Create a Collection of new instances of the related model, allowing mass-assignment. + * + * @param iterable $records + * @return \Illuminate\Database\Eloquent\Collection<int, TRelatedModel> + */ + public function forceCreateMany(iterable $records) + { + $instances = $this->related->newCollection(); + + foreach ($records as $record) { + $instances->push($this->forceCreate($record)); + } + + return $instances; + } + + /** + * Create a Collection of new instances of the related model, allowing mass-assignment and without raising any events to the parent model. + * + * @param iterable $records + * @return \Illuminate\Database\Eloquent\Collection<int, TRelatedModel> + */ + public function forceCreateManyQuietly(iterable $records) + { + return Model::withoutEvents(fn () => $this->forceCreateMany($records)); + } + /** * Set the foreign ID for creating a related model. *
diff --git a/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php b/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php index 4142572207af..7451491cbaf9 100755 --- a/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php +++ b/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php @@ -436,6 +436,34 @@ public function createManyQuietly(iterable $records) return Model::withoutEvents(fn () => $this->createMany($records)); } + * Create a Collection of new instances of the related model, allowing mass-assignment. + public function forceCreateMany(iterable $records) + $instances = $this->related->newCollection(); + foreach ($records as $record) { + $instances->push($this->forceCreate($record)); + } + * Create a Collection of new instances of the related model, allowing mass-assignment and without raising any events to the parent model. + public function forceCreateManyQuietly(iterable $records) + return Model::withoutEvents(fn () => $this->forceCreateMany($records)); /** * Set the foreign ID for creating a related model. *
[ "+ return $instances;" ]
[ 22 ]
{ "additions": 28, "author": "onlime", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55262", "issue_id": 55262, "merged_at": "2025-04-04T16:27:04Z", "omission_probability": 0.1, "pr_number": 55262, "repo": "laravel/framework", "title": "[12.x] Add createMany mass-assignment variants to `HasOneOrMany` relation", "total_changes": 28 }
12
diff --git a/src/Illuminate/View/Compilers/BladeCompiler.php b/src/Illuminate/View/Compilers/BladeCompiler.php index 48e5d734d90f..b17bde52bce7 100644 --- a/src/Illuminate/View/Compilers/BladeCompiler.php +++ b/src/Illuminate/View/Compilers/BladeCompiler.php @@ -193,7 +193,17 @@ public function compile($path = null) $compiledPath = $this->getCompiledPath($this->getPath()) ); - $this->files->put($compiledPath, $contents); + if (! $this->files->exists($compiledPath)) { + $this->files->put($compiledPath, $contents); + + return; + } + + $compiledHash = $this->files->hash($compiledPath, 'sha256'); + + if ($compiledHash !== hash('sha256', $contents)) { + $this->files->put($compiledPath, $contents); + } } } diff --git a/tests/View/ViewBladeCompilerTest.php b/tests/View/ViewBladeCompilerTest.php index c3955945e8ff..e69de4a3f46d 100644 --- a/tests/View/ViewBladeCompilerTest.php +++ b/tests/View/ViewBladeCompilerTest.php @@ -66,17 +66,42 @@ public function testCompileCompilesFileAndReturnsContents() $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php')->andReturn(false); $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); $compiler->compile('foo'); } public function testCompileCompilesFileAndReturnsContentsCreatingDirectory() { + $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); + $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); + $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php')->andReturn(false); + $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); + $compiler->compile('foo'); + } + + public function testCompileUpdatesCacheIfChanged() + { + $compiledPath = __DIR__.'/'.hash('xxh128', 'v2foo').'.php'; + $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); + $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); + $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with($compiledPath)->andReturn(true); + $files->shouldReceive('hash')->once()->with($compiledPath, 'sha256')->andReturn(hash('sha256', 'outdated content')); + $files->shouldReceive('put')->once()->with($compiledPath, 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); + $compiler->compile('foo'); + } + + public function testCompileKeepsCacheIfUnchanged() + { + $compiledPath = __DIR__.'/'.hash('xxh128', 'v2foo').'.php'; $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(false); $files->shouldReceive('makeDirectory')->once()->with(__DIR__, 0777, true, true); - $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); + $files->shouldReceive('exists')->once()->with($compiledPath)->andReturn(true); + $files->shouldReceive('hash')->once()->with($compiledPath, 'sha256')->andReturn(hash('sha256', 'Hello World<?php /**PATH foo ENDPATH**/ ?>')); $compiler->compile('foo'); } @@ -85,6 +110,7 @@ public function testCompileCompilesAndGetThePath() $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php')->andReturn(false); $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); $compiler->compile('foo'); $this->assertSame('foo', $compiler->getPath()); @@ -102,6 +128,7 @@ public function testCompileWithPathSetBefore() $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with('foo')->andReturn('Hello World'); $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php')->andReturn(false); $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); // set path before compilation $compiler->setPath('foo'); @@ -132,6 +159,7 @@ public function testIncludePathToTemplate($content, $compiled) $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with('foo')->andReturn($content); $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php')->andReturn(false); $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', $compiled); $compiler->compile('foo'); @@ -187,6 +215,7 @@ public function testDontIncludeEmptyPath() $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with('')->andReturn('Hello World'); $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2').'.php')->andReturn(false); $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2').'.php', 'Hello World'); $compiler->setPath(''); $compiler->compile(); @@ -197,6 +226,7 @@ public function testDontIncludeNullPath() $compiler = new BladeCompiler($files = $this->getFiles(), __DIR__); $files->shouldReceive('get')->once()->with(null)->andReturn('Hello World'); $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(true); + $files->shouldReceive('exists')->once()->with(__DIR__.'/'.hash('xxh128', 'v2').'.php')->andReturn(false); $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2').'.php', 'Hello World'); $compiler->setPath(null); $compiler->compile();
diff --git a/src/Illuminate/View/Compilers/BladeCompiler.php b/src/Illuminate/View/Compilers/BladeCompiler.php index 48e5d734d90f..b17bde52bce7 100644 --- a/src/Illuminate/View/Compilers/BladeCompiler.php +++ b/src/Illuminate/View/Compilers/BladeCompiler.php @@ -193,7 +193,17 @@ public function compile($path = null) $compiledPath = $this->getCompiledPath($this->getPath()) ); - $this->files->put($compiledPath, $contents); + if (! $this->files->exists($compiledPath)) { + return; + if ($compiledHash !== hash('sha256', $contents)) { } diff --git a/tests/View/ViewBladeCompilerTest.php b/tests/View/ViewBladeCompilerTest.php index c3955945e8ff..e69de4a3f46d 100644 --- a/tests/View/ViewBladeCompilerTest.php +++ b/tests/View/ViewBladeCompilerTest.php @@ -66,17 +66,42 @@ public function testCompileCompilesFileAndReturnsContents() public function testCompileCompilesFileAndReturnsContentsCreatingDirectory() { + $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); + public function testCompileUpdatesCacheIfChanged() + $files->shouldReceive('hash')->once()->with($compiledPath, 'sha256')->andReturn(hash('sha256', 'outdated content')); + $files->shouldReceive('put')->once()->with($compiledPath, 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); + public function testCompileKeepsCacheIfUnchanged() $files->shouldReceive('exists')->once()->with(__DIR__)->andReturn(false); $files->shouldReceive('makeDirectory')->once()->with(__DIR__, 0777, true, true); - $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', 'Hello World<?php /**PATH foo ENDPATH**/ ?>'); + $files->shouldReceive('hash')->once()->with($compiledPath, 'sha256')->andReturn(hash('sha256', 'Hello World<?php /**PATH foo ENDPATH**/ ?>')); @@ -85,6 +110,7 @@ public function testCompileCompilesAndGetThePath() $this->assertSame('foo', $compiler->getPath()); @@ -102,6 +128,7 @@ public function testCompileWithPathSetBefore() // set path before compilation $compiler->setPath('foo'); @@ -132,6 +159,7 @@ public function testIncludePathToTemplate($content, $compiled) $files->shouldReceive('get')->once()->with('foo')->andReturn($content); $files->shouldReceive('put')->once()->with(__DIR__.'/'.hash('xxh128', 'v2foo').'.php', $compiled); @@ -187,6 +215,7 @@ public function testDontIncludeEmptyPath() $files->shouldReceive('get')->once()->with('')->andReturn('Hello World'); $compiler->setPath(''); @@ -197,6 +226,7 @@ public function testDontIncludeNullPath() $files->shouldReceive('get')->once()->with(null)->andReturn('Hello World'); $compiler->setPath(null);
[ "+ $compiledHash = $this->files->hash($compiledPath, 'sha256');" ]
[ 15 ]
{ "additions": 42, "author": "pizkaz", "deletions": 2, "html_url": "https://github.com/laravel/framework/pull/55450", "issue_id": 55450, "merged_at": "2025-04-21T14:13:20Z", "omission_probability": 0.1, "pr_number": 55450, "repo": "laravel/framework", "title": "Update compiled views only if they actually changed", "total_changes": 44 }
13
diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index 6893c1284e3..fc211e179a5 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -1086,7 +1086,11 @@ public function relationLoaded($key) } if ($nestedRelation !== null) { - foreach ($this->$relation as $related) { + $relatedModels = is_iterable($relatedModels = $this->$relation) + ? $relatedModels + : [$relatedModels]; + + foreach ($relatedModels as $related) { if (! $related->relationLoaded($nestedRelation)) { return false; } diff --git a/tests/Integration/Database/EloquentModelRelationLoadedTest.php b/tests/Integration/Database/EloquentModelRelationLoadedTest.php index 06a0a740d3b..548a50d1195 100644 --- a/tests/Integration/Database/EloquentModelRelationLoadedTest.php +++ b/tests/Integration/Database/EloquentModelRelationLoadedTest.php @@ -119,6 +119,22 @@ public function testWhenChildRecursiveRelationIsLoaded() $this->assertTrue($model->relationLoaded('twos.threes')); $this->assertTrue($model->relationLoaded('twos.threes.one')); } + + public function testWhenParentRelationIsASingleInstance() + { + $one = One::query()->create(); + $two = $one->twos()->create(); + $three = $two->threes()->create(); + + $model = Three::query() + ->with('two.one') + ->find($three->id); + + $this->assertTrue($model->relationLoaded('two')); + $this->assertTrue($model->two->is($two)); + $this->assertTrue($model->relationLoaded('two.one')); + $this->assertTrue($model->two->one->is($one)); + } } class One extends Model
diff --git a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php index 6893c1284e3..fc211e179a5 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php +++ b/src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php @@ -1086,7 +1086,11 @@ public function relationLoaded($key) } if ($nestedRelation !== null) { - foreach ($this->$relation as $related) { + ? $relatedModels + : [$relatedModels]; + foreach ($relatedModels as $related) { if (! $related->relationLoaded($nestedRelation)) { return false; } diff --git a/tests/Integration/Database/EloquentModelRelationLoadedTest.php b/tests/Integration/Database/EloquentModelRelationLoadedTest.php index 06a0a740d3b..548a50d1195 100644 --- a/tests/Integration/Database/EloquentModelRelationLoadedTest.php +++ b/tests/Integration/Database/EloquentModelRelationLoadedTest.php @@ -119,6 +119,22 @@ public function testWhenChildRecursiveRelationIsLoaded() $this->assertTrue($model->relationLoaded('twos.threes')); $this->assertTrue($model->relationLoaded('twos.threes.one')); } + public function testWhenParentRelationIsASingleInstance() + $one = One::query()->create(); + $two = $one->twos()->create(); + $three = $two->threes()->create(); + $model = Three::query() + ->with('two.one') + ->find($three->id); + $this->assertTrue($model->relationLoaded('two.one')); + $this->assertTrue($model->two->one->is($one)); + } } class One extends Model
[ "+ $relatedModels = is_iterable($relatedModels = $this->$relation)", "+ {", "+ $this->assertTrue($model->relationLoaded('two'));", "+ $this->assertTrue($model->two->is($two));" ]
[ 9, 27, 36, 37 ]
{ "additions": 21, "author": "rodrigopedra", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55519", "issue_id": 55519, "merged_at": "2025-04-23T13:13:45Z", "omission_probability": 0.1, "pr_number": 55519, "repo": "laravel/framework", "title": "[12.x] Ensure related models is iterable on `HasRelationships@relationLoaded()`", "total_changes": 22 }
14
diff --git a/src/Illuminate/Testing/AssertableJsonString.php b/src/Illuminate/Testing/AssertableJsonString.php index 0bf221bea0da..d089ab071dc3 100644 --- a/src/Illuminate/Testing/AssertableJsonString.php +++ b/src/Illuminate/Testing/AssertableJsonString.php @@ -12,6 +12,8 @@ use Illuminate\Testing\Assert as PHPUnit; use JsonSerializable; +use function Illuminate\Support\enum_value; + class AssertableJsonString implements ArrayAccess, Countable { /** @@ -238,7 +240,7 @@ public function assertPath($path, $expect) if ($expect instanceof Closure) { PHPUnit::assertTrue($expect($this->json($path))); } else { - PHPUnit::assertSame($expect, $this->json($path)); + PHPUnit::assertSame(enum_value($expect), $this->json($path)); } return $this; diff --git a/tests/Testing/TestResponseTest.php b/tests/Testing/TestResponseTest.php index 9de88ddff3f3..cae497bdd133 100644 --- a/tests/Testing/TestResponseTest.php +++ b/tests/Testing/TestResponseTest.php @@ -1437,6 +1437,27 @@ public function testAssertJsonPathWithClosureCanFail() $response->assertJsonPath('data.foo', fn ($value) => $value === null); } + public function testAssertJsonPathWithEnum() + { + $response = TestResponse::fromBaseResponse(new Response([ + 'data' => ['status' => 'booked'], + ])); + + $response->assertJsonPath('data.status', TestStatus::Booked); + } + + public function testAssertJsonPathWithEnumCanFail() + { + $response = TestResponse::fromBaseResponse(new Response([ + 'data' => ['status' => 'failed'], + ])); + + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('Failed asserting that two strings are identical.'); + + $response->assertJsonPath('data.status', TestStatus::Booked); + } + public function testAssertJsonPathCanonicalizing() { $response = TestResponse::fromBaseResponse(new Response(new JsonSerializableSingleResourceStub)); @@ -2954,3 +2975,8 @@ class AnotherTestModel extends Model { protected $guarded = []; } + +enum TestStatus: string +{ + case Booked = 'booked'; +}
diff --git a/src/Illuminate/Testing/AssertableJsonString.php b/src/Illuminate/Testing/AssertableJsonString.php index 0bf221bea0da..d089ab071dc3 100644 --- a/src/Illuminate/Testing/AssertableJsonString.php +++ b/src/Illuminate/Testing/AssertableJsonString.php @@ -12,6 +12,8 @@ use Illuminate\Testing\Assert as PHPUnit; use JsonSerializable; class AssertableJsonString implements ArrayAccess, Countable /** @@ -238,7 +240,7 @@ public function assertPath($path, $expect) if ($expect instanceof Closure) { PHPUnit::assertTrue($expect($this->json($path))); } else { - PHPUnit::assertSame($expect, $this->json($path)); + PHPUnit::assertSame(enum_value($expect), $this->json($path)); } return $this; diff --git a/tests/Testing/TestResponseTest.php b/tests/Testing/TestResponseTest.php index 9de88ddff3f3..cae497bdd133 100644 --- a/tests/Testing/TestResponseTest.php +++ b/tests/Testing/TestResponseTest.php @@ -1437,6 +1437,27 @@ public function testAssertJsonPathWithClosureCanFail() $response->assertJsonPath('data.foo', fn ($value) => $value === null); } + public function testAssertJsonPathWithEnum() + public function testAssertJsonPathWithEnumCanFail() + 'data' => ['status' => 'failed'], + $this->expectException(AssertionFailedError::class); + $this->expectExceptionMessage('Failed asserting that two strings are identical.'); public function testAssertJsonPathCanonicalizing() { $response = TestResponse::fromBaseResponse(new Response(new JsonSerializableSingleResourceStub)); @@ -2954,3 +2975,8 @@ class AnotherTestModel extends Model protected $guarded = []; } +enum TestStatus: string +{ + case Booked = 'booked'; +}
[ "+use function Illuminate\\Support\\enum_value;", "+ 'data' => ['status' => 'booked']," ]
[ 8, 33 ]
{ "additions": 29, "author": "azim-kordpour", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55516", "issue_id": 55516, "merged_at": "2025-04-23T13:17:11Z", "omission_probability": 0.1, "pr_number": 55516, "repo": "laravel/framework", "title": "[12.x] Add Enum support for assertJsonPath in AssertableJsonString.php", "total_changes": 30 }
15
diff --git a/src/Illuminate/Database/MigrationServiceProvider.php b/src/Illuminate/Database/MigrationServiceProvider.php index cab266bb2f9..037106c7357 100755 --- a/src/Illuminate/Database/MigrationServiceProvider.php +++ b/src/Illuminate/Database/MigrationServiceProvider.php @@ -82,6 +82,8 @@ protected function registerMigrator() return new Migrator($repository, $app['db'], $app['files'], $app['events']); }); + + $this->app->bind(Migrator::class, fn ($app) => $app['migrator']); } /** @@ -220,7 +222,7 @@ protected function registerMigrateStatusCommand() public function provides() { return array_merge([ - 'migrator', 'migration.repository', 'migration.creator', + 'migrator', 'migration.repository', 'migration.creator', Migrator::class, ], array_values($this->commands)); } } diff --git a/tests/Integration/Database/MigrationServiceProviderTest.php b/tests/Integration/Database/MigrationServiceProviderTest.php new file mode 100644 index 00000000000..6da602074f3 --- /dev/null +++ b/tests/Integration/Database/MigrationServiceProviderTest.php @@ -0,0 +1,16 @@ +<?php + +namespace Illuminate\Tests\Integration\Database; + +use Illuminate\Database\Migrations\Migrator; + +class MigrationServiceProviderTest extends DatabaseTestCase +{ + public function testContainerCanBuildMigrator() + { + $fromString = $this->app->make('migrator'); + $fromClass = $this->app->make(Migrator::class); + + $this->assertSame($fromString, $fromClass); + } +}
diff --git a/src/Illuminate/Database/MigrationServiceProvider.php b/src/Illuminate/Database/MigrationServiceProvider.php index cab266bb2f9..037106c7357 100755 --- a/src/Illuminate/Database/MigrationServiceProvider.php +++ b/src/Illuminate/Database/MigrationServiceProvider.php @@ -82,6 +82,8 @@ protected function registerMigrator() return new Migrator($repository, $app['db'], $app['files'], $app['events']); }); + $this->app->bind(Migrator::class, fn ($app) => $app['migrator']); /** @@ -220,7 +222,7 @@ protected function registerMigrateStatusCommand() public function provides() { return array_merge([ - 'migrator', 'migration.repository', 'migration.creator', + 'migrator', 'migration.repository', 'migration.creator', Migrator::class, ], array_values($this->commands)); } diff --git a/tests/Integration/Database/MigrationServiceProviderTest.php b/tests/Integration/Database/MigrationServiceProviderTest.php new file mode 100644 index 00000000000..6da602074f3 --- /dev/null +++ b/tests/Integration/Database/MigrationServiceProviderTest.php @@ -0,0 +1,16 @@ +<?php +namespace Illuminate\Tests\Integration\Database; +use Illuminate\Database\Migrations\Migrator; +class MigrationServiceProviderTest extends DatabaseTestCase +{ + public function testContainerCanBuildMigrator() + $fromString = $this->app->make('migrator'); + $fromClass = $this->app->make(Migrator::class); + $this->assertSame($fromString, $fromClass); + } +}
[ "+ {" ]
[ 37 ]
{ "additions": 19, "author": "cosmastech", "deletions": 1, "html_url": "https://github.com/laravel/framework/pull/55501", "issue_id": 55501, "merged_at": "2025-04-22T13:50:14Z", "omission_probability": 0.1, "pr_number": 55501, "repo": "laravel/framework", "title": "[12.x] Allow Container to build `Migrator` from class name", "total_changes": 20 }
16
diff --git a/src/Illuminate/Cache/MemoizedStore.php b/src/Illuminate/Cache/MemoizedStore.php index 9888810de6d7..d899ef09d609 100644 --- a/src/Illuminate/Cache/MemoizedStore.php +++ b/src/Illuminate/Cache/MemoizedStore.php @@ -75,12 +75,17 @@ public function many(array $keys) }); } - $result = [ - ...$memoized, - ...$retrieved, - ]; + $result = []; - return array_replace(array_flip($keys), $result); + foreach ($keys as $key) { + if (array_key_exists($key, $memoized)) { + $result[$key] = $memoized[$key]; + } else { + $result[$key] = $retrieved[$key]; + } + } + + return $result; } /** diff --git a/tests/Integration/Cache/MemoizedStoreTest.php b/tests/Integration/Cache/MemoizedStoreTest.php index e599f83225d0..028688b262e2 100644 --- a/tests/Integration/Cache/MemoizedStoreTest.php +++ b/tests/Integration/Cache/MemoizedStoreTest.php @@ -89,6 +89,33 @@ public function test_it_can_memoize_when_retrieving_mulitple_values() $this->assertSame(['name.0' => 'Tim', 'name.1' => 'Taylor'], $memoized); } + public function test_it_uses_correct_keys_for_getMultiple() + { + $data = [ + 'a' => 'string-value', + '1.1' => 'float-value', + '1' => 'integer-value-as-string', + 2 => 'integer-value', + ]; + Cache::putMany($data); + + $memoValue = Cache::memo()->many(['a', '1.1', '1', 2]); + $cacheValue = Cache::many(['a', '1.1', '1', 2]); + + $this->assertSame([ + 'a' => 'string-value', + '1.1' => 'float-value', + '1' => 'integer-value-as-string', + 2 => 'integer-value', + ], $cacheValue); + $this->assertSame($cacheValue, $memoValue); + + // ensure correct on the second memoized retrieval + $memoValue = Cache::memo()->many(['a', '1.1', '1', 2]); + + $this->assertSame($cacheValue, $memoValue); + } + public function test_null_values_are_memoized_when_retrieving_mulitple_values() { $live = Cache::getMultiple(['name.0', 'name.1']);
diff --git a/src/Illuminate/Cache/MemoizedStore.php b/src/Illuminate/Cache/MemoizedStore.php index 9888810de6d7..d899ef09d609 100644 --- a/src/Illuminate/Cache/MemoizedStore.php +++ b/src/Illuminate/Cache/MemoizedStore.php @@ -75,12 +75,17 @@ public function many(array $keys) }); } - $result = [ - ...$memoized, - ...$retrieved, - ]; + $result = []; - return array_replace(array_flip($keys), $result); + foreach ($keys as $key) { + if (array_key_exists($key, $memoized)) { + $result[$key] = $memoized[$key]; + } else { + $result[$key] = $retrieved[$key]; + } + } + return $result; /** diff --git a/tests/Integration/Cache/MemoizedStoreTest.php b/tests/Integration/Cache/MemoizedStoreTest.php index e599f83225d0..028688b262e2 100644 --- a/tests/Integration/Cache/MemoizedStoreTest.php +++ b/tests/Integration/Cache/MemoizedStoreTest.php @@ -89,6 +89,33 @@ public function test_it_can_memoize_when_retrieving_mulitple_values() $this->assertSame(['name.0' => 'Tim', 'name.1' => 'Taylor'], $memoized); + public function test_it_uses_correct_keys_for_getMultiple() + { + $data = [ + ]; + Cache::putMany($data); + $cacheValue = Cache::many(['a', '1.1', '1', 2]); + ], $cacheValue); + // ensure correct on the second memoized retrieval + } public function test_null_values_are_memoized_when_retrieving_mulitple_values() { $live = Cache::getMultiple(['name.0', 'name.1']);
[ "+ $this->assertSame([" ]
[ 48 ]
{ "additions": 37, "author": "bmckay959", "deletions": 5, "html_url": "https://github.com/laravel/framework/pull/55503", "issue_id": 55503, "merged_at": "2025-04-22T13:45:35Z", "omission_probability": 0.1, "pr_number": 55503, "repo": "laravel/framework", "title": "Bugfix for Cache::memo()->many() returning the wrong value with an integer key type", "total_changes": 42 }
17
diff --git a/src/Illuminate/Broadcasting/BroadcastEvent.php b/src/Illuminate/Broadcasting/BroadcastEvent.php index c4da0faab220..7c03641ace53 100644 --- a/src/Illuminate/Broadcasting/BroadcastEvent.php +++ b/src/Illuminate/Broadcasting/BroadcastEvent.php @@ -50,6 +50,13 @@ class BroadcastEvent implements ShouldQueue */ public $maxExceptions; + /** + * Indicates if the job should be deleted when models are missing. + * + * @var bool + */ + public $deleteWhenMissingModels; + /** * Create a new job handler instance. * @@ -63,6 +70,7 @@ public function __construct($event) $this->backoff = property_exists($event, 'backoff') ? $event->backoff : null; $this->afterCommit = property_exists($event, 'afterCommit') ? $event->afterCommit : null; $this->maxExceptions = property_exists($event, 'maxExceptions') ? $event->maxExceptions : null; + $this->deleteWhenMissingModels = property_exists($event, 'deleteWhenMissingModels') ? $event->deleteWhenMissingModels : null; } /** diff --git a/src/Illuminate/Events/CallQueuedListener.php b/src/Illuminate/Events/CallQueuedListener.php index e78a4c4e2c5f..13f33e338304 100644 --- a/src/Illuminate/Events/CallQueuedListener.php +++ b/src/Illuminate/Events/CallQueuedListener.php @@ -82,6 +82,13 @@ class CallQueuedListener implements ShouldQueue */ public $shouldBeEncrypted = false; + /** + * Indicates if the job should be deleted when models are missing. + * + * @var bool + */ + public $deleteWhenMissingModels; + /** * Create a new job instance. * diff --git a/src/Illuminate/Events/Dispatcher.php b/src/Illuminate/Events/Dispatcher.php index ee409586efc8..bfea9a47e353 100755 --- a/src/Illuminate/Events/Dispatcher.php +++ b/src/Illuminate/Events/Dispatcher.php @@ -677,6 +677,7 @@ protected function propagateListenerOptions($listener, $job) $job->timeout = $listener->timeout ?? null; $job->failOnTimeout = $listener->failOnTimeout ?? false; $job->tries = $listener->tries ?? null; + $job->deleteWhenMissingModels = $listener->deleteWhenMissingModels ?? false; $job->through(array_merge( method_exists($listener, 'middleware') ? $listener->middleware(...$data) : [],
diff --git a/src/Illuminate/Broadcasting/BroadcastEvent.php b/src/Illuminate/Broadcasting/BroadcastEvent.php index c4da0faab220..7c03641ace53 100644 --- a/src/Illuminate/Broadcasting/BroadcastEvent.php +++ b/src/Illuminate/Broadcasting/BroadcastEvent.php @@ -50,6 +50,13 @@ class BroadcastEvent implements ShouldQueue public $maxExceptions; * Create a new job handler instance. @@ -63,6 +70,7 @@ public function __construct($event) $this->backoff = property_exists($event, 'backoff') ? $event->backoff : null; $this->afterCommit = property_exists($event, 'afterCommit') ? $event->afterCommit : null; $this->maxExceptions = property_exists($event, 'maxExceptions') ? $event->maxExceptions : null; + $this->deleteWhenMissingModels = property_exists($event, 'deleteWhenMissingModels') ? $event->deleteWhenMissingModels : null; } diff --git a/src/Illuminate/Events/CallQueuedListener.php b/src/Illuminate/Events/CallQueuedListener.php index e78a4c4e2c5f..13f33e338304 100644 --- a/src/Illuminate/Events/CallQueuedListener.php +++ b/src/Illuminate/Events/CallQueuedListener.php @@ -82,6 +82,13 @@ class CallQueuedListener implements ShouldQueue public $shouldBeEncrypted = false; * Create a new job instance. diff --git a/src/Illuminate/Events/Dispatcher.php b/src/Illuminate/Events/Dispatcher.php index ee409586efc8..bfea9a47e353 100755 --- a/src/Illuminate/Events/Dispatcher.php +++ b/src/Illuminate/Events/Dispatcher.php @@ -677,6 +677,7 @@ protected function propagateListenerOptions($listener, $job) $job->timeout = $listener->timeout ?? null; $job->failOnTimeout = $listener->failOnTimeout ?? false; $job->tries = $listener->tries ?? null; + $job->deleteWhenMissingModels = $listener->deleteWhenMissingModels ?? false; $job->through(array_merge( method_exists($listener, 'middleware') ? $listener->middleware(...$data) : [],
[]
[]
{ "additions": 16, "author": "L3o-pold", "deletions": 0, "html_url": "https://github.com/laravel/framework/pull/55508", "issue_id": 55508, "merged_at": "2025-04-22T13:44:53Z", "omission_probability": 0.1, "pr_number": 55508, "repo": "laravel/framework", "title": "Allow Listeners to dynamically specify deleteWhenMissingModels", "total_changes": 16 }
18
diff --git a/src/Illuminate/Contracts/Validation/InvokableRule.php b/src/Illuminate/Contracts/Validation/InvokableRule.php index bed9ed567fb4..17c296446945 100644 --- a/src/Illuminate/Contracts/Validation/InvokableRule.php +++ b/src/Illuminate/Contracts/Validation/InvokableRule.php @@ -14,7 +14,7 @@ interface InvokableRule * * @param string $attribute * @param mixed $value - * @param \Closure(string, ?string = null): \Illuminate\Translation\PotentiallyTranslatedString $fail + * @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail * @return void */ public function __invoke(string $attribute, mixed $value, Closure $fail); diff --git a/src/Illuminate/Contracts/Validation/ValidationRule.php b/src/Illuminate/Contracts/Validation/ValidationRule.php index c687b26a2d98..6829372b3714 100644 --- a/src/Illuminate/Contracts/Validation/ValidationRule.php +++ b/src/Illuminate/Contracts/Validation/ValidationRule.php @@ -11,7 +11,7 @@ interface ValidationRule * * @param string $attribute * @param mixed $value - * @param \Closure(string, ?string = null): \Illuminate\Translation\PotentiallyTranslatedString $fail + * @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail * @return void */ public function validate(string $attribute, mixed $value, Closure $fail): void; diff --git a/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub b/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub index e04915bf5852..fa23cdfc2139 100644 --- a/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub +++ b/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub @@ -17,7 +17,7 @@ class {{ class }} implements ValidationRule /** * Run the validation rule. * - * @param \Closure(string, ?string = null): \Illuminate\Translation\PotentiallyTranslatedString $fail + * @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { diff --git a/src/Illuminate/Foundation/Console/stubs/rule.stub b/src/Illuminate/Foundation/Console/stubs/rule.stub index 7b54420895b4..bc1d35139247 100644 --- a/src/Illuminate/Foundation/Console/stubs/rule.stub +++ b/src/Illuminate/Foundation/Console/stubs/rule.stub @@ -10,7 +10,7 @@ class {{ class }} implements ValidationRule /** * Run the validation rule. * - * @param \Closure(string, ?string = null): \Illuminate\Translation\PotentiallyTranslatedString $fail + * @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail */ public function validate(string $attribute, mixed $value, Closure $fail): void { diff --git a/types/Contracts/Validation/ValidationRule.php b/types/Contracts/Validation/ValidationRule.php new file mode 100644 index 000000000000..565a7d972340 --- /dev/null +++ b/types/Contracts/Validation/ValidationRule.php @@ -0,0 +1,13 @@ +<?php + +use Illuminate\Contracts\Validation\ValidationRule; + +use function PHPStan\Testing\assertType; + +new class implements ValidationRule +{ + public function validate(string $attribute, mixed $value, Closure $fail): void + { + assertType('Closure(string, string|null=): Illuminate\Translation\PotentiallyTranslatedString', $fail); + } +};
diff --git a/src/Illuminate/Contracts/Validation/InvokableRule.php b/src/Illuminate/Contracts/Validation/InvokableRule.php index bed9ed567fb4..17c296446945 100644 --- a/src/Illuminate/Contracts/Validation/InvokableRule.php +++ b/src/Illuminate/Contracts/Validation/InvokableRule.php @@ -14,7 +14,7 @@ interface InvokableRule public function __invoke(string $attribute, mixed $value, Closure $fail); diff --git a/src/Illuminate/Contracts/Validation/ValidationRule.php b/src/Illuminate/Contracts/Validation/ValidationRule.php index c687b26a2d98..6829372b3714 100644 --- a/src/Illuminate/Contracts/Validation/ValidationRule.php +++ b/src/Illuminate/Contracts/Validation/ValidationRule.php @@ -11,7 +11,7 @@ interface ValidationRule public function validate(string $attribute, mixed $value, Closure $fail): void; diff --git a/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub b/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub index e04915bf5852..fa23cdfc2139 100644 --- a/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub +++ b/src/Illuminate/Foundation/Console/stubs/rule.implicit.stub @@ -17,7 +17,7 @@ class {{ class }} implements ValidationRule diff --git a/src/Illuminate/Foundation/Console/stubs/rule.stub b/src/Illuminate/Foundation/Console/stubs/rule.stub index 7b54420895b4..bc1d35139247 100644 --- a/src/Illuminate/Foundation/Console/stubs/rule.stub +++ b/src/Illuminate/Foundation/Console/stubs/rule.stub @@ -10,7 +10,7 @@ class {{ class }} implements ValidationRule diff --git a/types/Contracts/Validation/ValidationRule.php b/types/Contracts/Validation/ValidationRule.php new file mode 100644 index 000000000000..565a7d972340 --- /dev/null +++ b/types/Contracts/Validation/ValidationRule.php @@ -0,0 +1,13 @@ +<?php +use Illuminate\Contracts\Validation\ValidationRule; +new class implements ValidationRule +{ + public function validate(string $attribute, mixed $value, Closure $fail): void + { + assertType('Closure(string, string|null=): Illuminate\Translation\PotentiallyTranslatedString', $fail); + }
[ "+use function PHPStan\\Testing\\assertType;", "+};" ]
[ 62, 70 ]
{ "additions": 17, "author": "axlon", "deletions": 4, "html_url": "https://github.com/laravel/framework/pull/52870", "issue_id": 52870, "merged_at": "2024-09-22T15:08:08Z", "omission_probability": 0.1, "pr_number": 52870, "repo": "laravel/framework", "title": "[11.x] Fix validation rule type hints", "total_changes": 21 }
End of preview. Expand in Data Studio

AbsenceBench: Language Models Can't Tell What's Missing

[paper] [code]

Dataset Card for AbsenceBench

AbsenceBench covers three distinct domains:

  • Poetry (realistic)
  • Numerical sequences (synthetic)
  • GitHub pull requests (realistic)

There are 4302 instances in total, with an average context length of 5K tokens.

Data Structure

Each domain contains the following features:

  • original_context: string
  • modified_context: string
  • omitted_context: List[string]
  • omitted_index: List[int]
  • metadata: Dict Extra information regarding the dataset generation

Data Split

Currently we provide only the validation split. Since all instances of AbsenceBench natually come up with labeled answers according to the task setting, we will not be able to provide an unlabeled test split.

Dataset Construction

We provide the source data for generating the poetry domain, originally from the Gutenberg Poetry Corpus in the poetry_raw subset. Please refer to this repo for scripts and more information.

Citation

If you find this work useful, please cite our paper:

@misc{fu2025absencebenchlanguagemodelscant,
      title={AbsenceBench: Language Models Can't Tell What's Missing}, 
      author={Harvey Yiyun Fu and Aryan Shrivastava and Jared Moore and Peter West and Chenhao Tan and Ari Holtzman},
      year={2025},
      eprint={2506.11440},
      archivePrefix={arXiv},
      primaryClass={cs.CL},
      url={https://arxiv.org/abs/2506.11440}, 
}
Downloads last month
159