Skip to content

Commit 00a9d22

Browse files
committed
fix: Carbon was being altered by google/cloud-spanner (#264)
1 parent de49b9c commit 00a9d22

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
@@ -25,6 +25,7 @@
2525
use Colopl\Spanner\Query\Processor as QueryProcessor;
2626
use Colopl\Spanner\Schema\Builder as SchemaBuilder;
2727
use Colopl\Spanner\Schema\Grammar as SchemaGrammar;
28+
use DateTimeImmutable;
2829
use DateTimeInterface;
2930
use Exception;
3031
use Generator;
@@ -461,7 +462,11 @@ protected function prepareBinding(BaseQueryGrammar $grammar, mixed $value): mixe
461462
// date string. Each query grammar maintains its own date string format
462463
// so we'll just ask the grammar for the format to get from the date.
463464
if ($value instanceof DateTimeInterface) {
464-
return new Timestamp($value);
465+
// Since Timestamp::__toString calls setTimezone() on the DateTime object,
466+
// we need to clone the DateTime object to avoid changing the original object.
467+
return ($value instanceof DateTimeImmutable)
468+
? new Timestamp($value)
469+
: new Timestamp(DateTimeImmutable::createFromInterface($value));
465470
}
466471

467472
if (is_array($value)) {

tests/ConnectionTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -631,4 +631,12 @@ public function test_getSchemaGrammar(): void
631631
$conn->useDefaultSchemaGrammar();
632632
$this->assertSame('test_', $conn->getSchemaGrammar()->getTablePrefix());
633633
}
634+
635+
public function test_binding_mutable_carbon_doesnt_change_timezone(): void
636+
{
637+
$conn = $this->getDefaultConnection();
638+
$now = now()->setTimezone('Asia/Tokyo');
639+
$conn->select('SELECT ?', [$now]);
640+
$this->assertSame('Asia/Tokyo', $now->getTimezone()->getName());
641+
}
634642
}

0 commit comments

Comments
 (0)