Lines
100.00%
7 / 7
Functions and Methods
100.00%
3 / 3
Classes and Traits
100.00%
1 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| DefaultValueCodec | 100.00% | 7 / 7 | 100.00% | 3 / 3 | 4 | 100.00% | 1 / 1 | |||
| __construct | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| encode | 100.00% | 5 / 5 | 100.00% | 1 / 1 | 2 | |||||
| decode | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace BlueprintAU\Radiant\Database\ValueCodecs; | |
| 6 | ||
| 7 | use Override; | |
| 8 | ||
| 9 | /** | |
| 10 | * The default value codec — passes scalar values through untouched and | |
| 11 | * formats `DateTimeInterface` values to a dialect datetime string. | |
| 12 | * | |
| 13 | * Subclasses override {@see encode()} and {@see decode()} for | |
| 14 | * dialect-specific adaptation (e.g. Postgres' microsecond datetimes). | |
| 15 | */ | |
| 16 | class DefaultValueCodec implements ValueCodecInterface | |
| 17 | { | |
| 18 | /** | |
| 19 | * @param string $datetimeFormat | |
| 20 | * @param string $timezone | |
| 21 | */ | |
| 22 | public function __construct( | |
| 23 | private string $datetimeFormat = 'Y-m-d H:i:s', | |
| 24 | private string $timezone = 'UTC', | |
| 25 | ) {} | |
| 26 | ||
| 27 | /** | |
| 28 | * PHP value → driver value (write/bind path). | |
| 29 | * | |
| 30 | * @param string|int|float|bool|null|\DateTimeInterface $value | |
| 31 | * @return string|int|float|bool|null | |
| 32 | */ | |
| 33 | #[Override] | |
| 34 | public function encode(string|int|float|bool|null|\DateTimeInterface $value): string|int|float|bool|null | |
| 35 | { | |
| 36 | // Raw-path bindings may carry a DateTimeInterface (e.g. a Carbon in a | |
| 37 | // where clause); normalize to the codec's timezone and format it | |
| 38 | // explicitly rather than relying on PDO's implicit stringification. | |
| 39 | // createFromInterface() yields a fresh instance, so the caller's | |
| 40 | // object is never mutated. | |
| 41 | if ($value instanceof \DateTimeInterface) { | |
| 42 | return \DateTimeImmutable::createFromInterface($value) | |
| 43 | ->setTimezone(new \DateTimeZone($this->timezone)) | |
| 44 | ->format($this->datetimeFormat); | |
| 45 | } | |
| 46 | ||
| 47 | return $value; | |
| 48 | } | |
| 49 | ||
| 50 | /** | |
| 51 | * Driver value → PHP value (read path). | |
| 52 | * | |
| 53 | * @param string|int|float|bool|null $value | |
| 54 | * @return string|int|float|bool|null | |
| 55 | */ | |
| 56 | #[Override] | |
| 57 | public function decode(string|int|float|bool|null $value): string|int|float|bool|null | |
| 58 | { | |
| 59 | return $value; | |
| 60 | } | |
| 61 | } |