Skip to content

Commit

Permalink
Add Builder On Clone callback support (#54477)
Browse files Browse the repository at this point in the history
* Add onClone callbacks

* Update DatabaseEloquentBuilderTest.php

* Style

* Update Builder.php

* Style
  • Loading branch information
ralphjsmit authored Feb 6, 2025
1 parent 1eaf24b commit a254dbd
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/Illuminate/Database/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,13 @@ class Builder implements BuilderContract
*/
protected $afterQueryCallbacks = [];

/**
* The callbacks that should be invoked on clone.
*
* @var array
*/
protected $onCloneCallbacks = [];

/**
* Create a new Eloquent query builder instance.
*
Expand Down Expand Up @@ -2170,6 +2177,19 @@ public function clone()
return clone $this;
}

/**
* Register a closure to be invoked on a clone.
*
* @param \Closure $callback
* @return $this
*/
public function onClone(Closure $callback)
{
$this->onCloneCallbacks[] = $callback;

return $this;
}

/**
* Force a clone of the underlying query builder when cloning.
*
Expand All @@ -2178,5 +2198,9 @@ public function clone()
public function __clone()
{
$this->query = clone $this->query;

foreach ($this->onCloneCallbacks as $onCloneCallback) {
$onCloneCallback($this);
}
}
}
26 changes: 26 additions & 0 deletions tests/Database/DatabaseEloquentBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2485,6 +2485,32 @@ public function testClone()
$this->assertSame('select * from "users" where "email" = ?', $clone->toSql());
}

public function testCloneModelMakesAFreshCopyOfTheModel()
{
$query = new BaseBuilder(m::mock(ConnectionInterface::class), new Grammar, m::mock(Processor::class));
$builder = (new Builder($query))->setModel(new EloquentBuilderTestStub);
$builder->select('*')->from('users');

$onCloneCallbackCalledCount = 0;

$onCloneQuery = null;

$builder->onClone(function (Builder $query) use (&$onCloneCallbackCalledCount, &$onCloneQuery) {
$onCloneCallbackCalledCount++;

$onCloneQuery = $query;
});

$clone = $builder->clone()->where('email', 'foo');

$this->assertNotSame($builder, $clone);
$this->assertSame('select * from "users"', $builder->toSql());
$this->assertSame('select * from "users" where "email" = ?', $clone->toSql());

$this->assertSame(1, $onCloneCallbackCalledCount);
$this->assertSame($onCloneQuery, $clone);
}

public function testToRawSql()
{
$query = m::mock(BaseBuilder::class);
Expand Down

0 comments on commit a254dbd

Please sign in to comment.