Skip to content

Commit d6bc9c6

Browse files
committed
fix: Carbon was being altered by google/cloud-spanner (#264)
1 parent 4529a9f commit d6bc9c6

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

src/Connection.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
use Colopl\Spanner\Query\Processor as QueryProcessor;
2525
use Colopl\Spanner\Schema\Builder as SchemaBuilder;
2626
use Colopl\Spanner\Schema\Grammar as SchemaGrammar;
27+
use DateTimeImmutable;
2728
use DateTimeInterface;
2829
use Exception;
2930
use Generator;
@@ -425,7 +426,11 @@ protected function prepareBinding(BaseQueryGrammar $grammar, mixed $value): mixe
425426
// date string. Each query grammar maintains its own date string format
426427
// so we'll just ask the grammar for the format to get from the date.
427428
if ($value instanceof DateTimeInterface) {
428-
return new Timestamp($value);
429+
// Since Timestamp::__toString calls setTimezone() on the DateTime object,
430+
// we need to clone the DateTime object to avoid changing the original object.
431+
return ($value instanceof DateTimeImmutable)
432+
? new Timestamp($value)
433+
: new Timestamp(DateTimeImmutable::createFromInterface($value));
429434
}
430435

431436
if (is_array($value)) {

tests/ConnectionTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -601,4 +601,12 @@ public function test_getSchemaGrammar(): void
601601
$conn->useDefaultSchemaGrammar();
602602
$this->assertSame('test_', $conn->getSchemaGrammar()->getTablePrefix());
603603
}
604+
605+
public function test_binding_mutable_carbon_doesnt_change_timezone(): void
606+
{
607+
$conn = $this->getDefaultConnection();
608+
$now = now()->setTimezone('Asia/Tokyo');
609+
$conn->select('SELECT ?', [$now]);
610+
$this->assertSame('Asia/Tokyo', $now->getTimezone()->getName());
611+
}
604612
}

0 commit comments

Comments
 (0)