Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[10.x] Add timestamps casting and mutation support to Eloquent #47945

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions src/Illuminate/Database/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -1079,9 +1079,9 @@ public function upsert(array $values, $uniqueBy, $update = null)
*/
public function touch($column = null)
{
$time = $this->model->freshTimestamp();

if ($column) {
$time = $this->model->freshTimestampForAttribute($column);

return $this->toBase()->update([$column => $time]);
}

Expand All @@ -1091,6 +1091,8 @@ public function touch($column = null)
return false;
}

$time = $this->model->freshTimestampForAttribute($column);

return $this->toBase()->update([$column => $time]);
}

Expand Down Expand Up @@ -1140,7 +1142,7 @@ protected function addUpdatedAtColumn(array $values)
$column = $this->model->getUpdatedAtColumn();

$values = array_merge(
[$column => $this->model->freshTimestampString()],
[$column => $this->model->freshTimestampForAttribute($column)],
$values
);

Expand Down Expand Up @@ -1190,16 +1192,19 @@ protected function addTimestampsToUpsertValues(array $values)
return $values;
}

$timestamp = $this->model->freshTimestampString();

$timestamps = [];
$columns = array_filter([
$this->model->getCreatedAtColumn(),
$this->model->getUpdatedAtColumn(),
]);

foreach ($columns as $column) {
$timestamps[$column] = $this->model->freshTimestampForAttribute($column);
}

if (! empty($timestamps)) {
foreach ($values as &$row) {
$row = array_merge([$column => $timestamp], $row);
$row = array_merge($timestamps, $row);
}
}

Expand Down
19 changes: 19 additions & 0 deletions src/Illuminate/Database/Eloquent/Concerns/HasTimestamps.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,25 @@ public function freshTimestampString()
return $this->fromDateTime($this->freshTimestamp());
}

/**
* Get a fresh timestamp for the model attribute considering casting or mutation.
*
* @param string $key
* @return mixed
*/
public function freshTimestampForAttribute(string $key): mixed
{
$value = $this->freshTimestamp();

if ($this->hasGetMutator($key) || $this->hasCast($key)) {
$value =
(clone $this)->forceFill([$key => $value])->getAttributes()[$key] ??
$value;
}

return $value;
}

/**
* Determine if the model uses timestamps.
*
Expand Down
194 changes: 194 additions & 0 deletions tests/Database/DatabaseEloquentBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use BadMethodCallException;
use Closure;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\ConnectionResolverInterface;
use Illuminate\Database\Eloquent\Builder;
Expand Down Expand Up @@ -2068,6 +2069,42 @@ public function testUpdateWithQualifiedTimestampValue()
$this->assertEquals(1, $result);
}

public function testUpdateWithCustomTimestampCasts()
{
$now = Carbon::parse('2017-10-10 10:10:10');
Carbon::setTestNow($now);
$now = $now->timestamp;

$query = new BaseBuilder(m::mock(ConnectionInterface::class), new Grammar, m::mock(Processor::class));
$builder = new Builder($query);
$model = new EloquentBuilderTestStubWithTimestampCasts;
$this->mockConnectionForModel($model, '');
$builder->setModel($model);
$builder->getConnection()->shouldReceive('update')->once()
->with('update "table" set "foo" = ?, "table"."updated_at" = ?', ['bar', $now])->andReturn(1);

$result = $builder->update(['foo' => 'bar']);
$this->assertEquals(1, $result);
}

public function testUpdateWithCustomTimestampMutators()
{
$now = Carbon::parse('2017-10-10 10:10:10');
Carbon::setTestNow($now);
$now = $now->timestamp;

$query = new BaseBuilder(m::mock(ConnectionInterface::class), new Grammar, m::mock(Processor::class));
$builder = new Builder($query);
$model = new EloquentBuilderTestStubWithTimestampMutators();
$this->mockConnectionForModel($model, '');
$builder->setModel($model);
$builder->getConnection()->shouldReceive('update')->once()
->with('update "table" set "foo" = ?, "table"."updated_at" = ?', ['bar', $now])->andReturn(1);

$result = $builder->update(['foo' => 'bar']);
$this->assertEquals(1, $result);
}

public function testUpdateWithoutTimestamp()
{
$query = new BaseBuilder(m::mock(ConnectionInterface::class), new Grammar, m::mock(Processor::class));
Expand Down Expand Up @@ -2139,6 +2176,58 @@ public function testUpsert()
$this->assertEquals(2, $result);
}

public function testUpsertWithCustomTimestampCasts()
{
$now = Carbon::parse('2017-10-10 10:10:10');
Carbon::setTestNow($now);
$now = $now->timestamp;

$query = m::mock(BaseBuilder::class);
$query->shouldReceive('from')->with('table')->andReturn('table');
$query->from = 'table';

$builder = new Builder($query);
$model = new EloquentBuilderTestStubWithTimestampCasts;
$model->setDateFormat('Y-m-d H:i:s');
$builder->setModel($model);

$query->shouldReceive('upsert')->once()
->with([
['email' => 'foo', 'name' => 'bar', 'updated_at' => $now, 'created_at' => $now],
['name' => 'bar2', 'email' => 'foo2', 'updated_at' => $now, 'created_at' => $now],
], ['email'], ['email', 'name', 'updated_at'])->andReturn(2);

$result = $builder->upsert([['email' => 'foo', 'name' => 'bar'], ['name' => 'bar2', 'email' => 'foo2']], ['email']);

$this->assertEquals(2, $result);
}

public function testUpsertWithCustomTimestampMutators()
{
$now = Carbon::parse('2017-10-10 10:10:10');
Carbon::setTestNow($now);
$now = $now->timestamp;

$query = m::mock(BaseBuilder::class);
$query->shouldReceive('from')->with('table')->andReturn('table');
$query->from = 'table';

$builder = new Builder($query);
$model = new EloquentBuilderTestStubWithTimestampMutators;
$model->setDateFormat('Y-m-d H:i:s');
$builder->setModel($model);

$query->shouldReceive('upsert')->once()
->with([
['email' => 'foo', 'name' => 'bar', 'updated_at' => $now, 'created_at' => $now],
['name' => 'bar2', 'email' => 'foo2', 'updated_at' => $now, 'created_at' => $now],
], ['email'], ['email', 'name', 'updated_at'])->andReturn(2);

$result = $builder->upsert([['email' => 'foo', 'name' => 'bar'], ['name' => 'bar2', 'email' => 'foo2']], ['email']);

$this->assertEquals(2, $result);
}

public function testTouch()
{
Carbon::setTestNow($now = '2017-10-10 10:10:10');
Expand Down Expand Up @@ -2194,6 +2283,62 @@ public function testTouchWithoutUpdatedAtColumn()
$this->assertFalse($result);
}

public function testTouchWithCustomTimestampCasts()
{
$now = Carbon::parse('2017-10-10 10:10:10');
Carbon::setTestNow($now);
$now = $now->timestamp;

$query = m::mock(BaseBuilder::class);
$query->shouldReceive('from')->with('table')->andReturn('table');
$query->from = 'table';

$builder = new Builder($query);
$model = new EloquentBuilderTestStubWithTimestampCasts;
$model->setDateFormat('Y-m-d H:i:s');
$builder->setModel($model);

$query->shouldReceive('update')->once()->with(['updated_at' => $now])->andReturn(2);

$result = $builder->touch();

$this->assertEquals(2, $result);

$query->shouldReceive('update')->once()->with(['created_at' => $now])->andReturn(3);

$result = $builder->touch('created_at');

$this->assertEquals(3, $result);
}

public function testTouchWithCustomTimestampMutators()
{
$now = Carbon::parse('2017-10-10 10:10:10');
Carbon::setTestNow($now);
$now = $now->timestamp;

$query = m::mock(BaseBuilder::class);
$query->shouldReceive('from')->with('table')->andReturn('table');
$query->from = 'table';

$builder = new Builder($query);
$model = new EloquentBuilderTestStubWithTimestampMutators;
$model->setDateFormat('Y-m-d H:i:s');
$builder->setModel($model);

$query->shouldReceive('update')->once()->with(['updated_at' => $now])->andReturn(2);

$result = $builder->touch();

$this->assertEquals(2, $result);

$query->shouldReceive('update')->once()->with(['created_at' => $now])->andReturn(3);

$result = $builder->touch('created_at');

$this->assertEquals(3, $result);
}

public function testWithCastsMethod()
{
$builder = new Builder($this->getMockQueryBuilder());
Expand Down Expand Up @@ -2468,3 +2613,52 @@ public function parent()
return $this->belongsTo(self::class, 'parent_id', 'id', 'parent');
}
}

class UnixTimeStampCast implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes)
{
return $value ? Carbon::createFromTimestampUTC($value) : null;
}

public function set($model, string $key, $value, array $attributes)
{
$value = Carbon::parse($value);
return $value ? $value->timestamp : null;
}
}

class EloquentBuilderTestStubWithTimestampCasts extends Model
{
protected $table = 'table';

protected $casts = [
'created_at' => UnixTimeStampCast::class,
'updated_at' => UnixTimeStampCast::class,
];
}

class EloquentBuilderTestStubWithTimestampMutators extends Model
{
protected $table = 'table';

public function getCreatedAtAttribute($value)
{
return $value ? Carbon::createFromTimestampUTC($value) : null;
}

public function setCreatedAtAttribute($value)
{
return $this->attributes['created_at'] = Carbon::parse($value)->timestamp ?? null;
}

public function getUpdatedAtAttribute($value)
{
return $value ? Carbon::createFromTimestampUTC($value) : null;
}

public function setUpdatedAtAttribute($value)
{
return $this->attributes['updated_at'] = Carbon::parse($value)->timestamp ?? null;
}
}