|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace MartinGeorgiev\Doctrine\DBAL\Types; |
| 6 | + |
| 7 | +use MartinGeorgiev\Doctrine\DBAL\Types\Exceptions\InvalidPointArrayItemForDatabaseException; |
| 8 | +use MartinGeorgiev\Doctrine\DBAL\Types\Exceptions\InvalidPointArrayItemForPHPException; |
| 9 | +use MartinGeorgiev\Doctrine\DBAL\Types\ValueObject\Point as PointValueObject; |
| 10 | + |
| 11 | +/** |
| 12 | + * Implementation of PostgreSQL POINT[] data type. |
| 13 | + * |
| 14 | + * @see https://www.postgresql.org/docs/17/datatype-geometric.html#DATATYPE-GEOMETRIC-POINTS |
| 15 | + * @since 3.1 |
| 16 | + * |
| 17 | + * @author Sébastien Jean <sebastien.jean76@gmail.com> |
| 18 | + */ |
| 19 | +class PointArray extends BaseArray |
| 20 | +{ |
| 21 | + protected const TYPE_NAME = 'point[]'; |
| 22 | + |
| 23 | + protected function transformArrayItemForPostgres(mixed $item): string |
| 24 | + { |
| 25 | + if (!$item instanceof PointValueObject) { |
| 26 | + throw InvalidPointArrayItemForDatabaseException::isNotAPoint($item); |
| 27 | + } |
| 28 | + |
| 29 | + return '"'.$item.'"'; |
| 30 | + } |
| 31 | + |
| 32 | + protected function transformPostgresArrayToPHPArray(string $postgresArray): array |
| 33 | + { |
| 34 | + if (!\str_starts_with($postgresArray, '{"') || !\str_ends_with($postgresArray, '"}')) { |
| 35 | + return []; |
| 36 | + } |
| 37 | + |
| 38 | + $trimmedPostgresArray = \mb_substr($postgresArray, 2, -2); |
| 39 | + if ($trimmedPostgresArray === '') { |
| 40 | + return []; |
| 41 | + } |
| 42 | + |
| 43 | + return \explode('","', $trimmedPostgresArray); |
| 44 | + } |
| 45 | + |
| 46 | + public function transformArrayItemForPHP(mixed $item): ?PointValueObject |
| 47 | + { |
| 48 | + if ($item === null) { |
| 49 | + return null; |
| 50 | + } |
| 51 | + |
| 52 | + if (!\is_string($item)) { |
| 53 | + $this->throwInvalidTypeException($item); |
| 54 | + } |
| 55 | + |
| 56 | + try { |
| 57 | + return PointValueObject::fromString($item); |
| 58 | + } catch (\InvalidArgumentException) { |
| 59 | + $this->throwInvalidFormatException($item); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + public function isValidArrayItemForDatabase(mixed $item): bool |
| 64 | + { |
| 65 | + return $item instanceof PointValueObject; |
| 66 | + } |
| 67 | + |
| 68 | + protected function throwInvalidTypeException(mixed $value): never |
| 69 | + { |
| 70 | + throw InvalidPointArrayItemForPHPException::forInvalidType($value); |
| 71 | + } |
| 72 | + |
| 73 | + protected function throwInvalidFormatException(mixed $value): never |
| 74 | + { |
| 75 | + throw InvalidPointArrayItemForPHPException::forInvalidFormat($value); |
| 76 | + } |
| 77 | + |
| 78 | + protected function throwInvalidItemException(): never |
| 79 | + { |
| 80 | + throw InvalidPointArrayItemForPHPException::forInvalidFormat('Array contains invalid point items'); |
| 81 | + } |
| 82 | +} |
0 commit comments