Skip to content

Add support for PointType #331

@seb-jean

Description

@seb-jean

Hello,

Do you think it would be worth adding PointType to your repository? :)

Here it is in one of my projects:

// src/Doctrine/Types/PointType.php

<?php

namespace App\Doctrine\Types;

use App\ValueObject\Point;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Exception\InvalidType;
use Doctrine\DBAL\Types\Exception\ValueNotConvertible;
use Doctrine\DBAL\Types\Type;

class PointType extends Type
{
    public const NAME = 'point';

    public function getName(): string
    {
        return self::NAME;
    }

    public function getSQLDeclaration(array $column, AbstractPlatform $platform): string
    {
        return 'POINT';
    }

    public function convertToPHPValue(mixed $value, AbstractPlatform $platform): ?Point
    {
        if (null === $value) {
            return null;
        }

        if (!\is_string($value)) {
            throw ValueNotConvertible::new($value, 'point');
        }

        sscanf($value, '(%f,%f)', $longitude, $latitude);

        return new Point((float) $latitude, (float) $longitude);
    }

    public function convertToDatabaseValue(mixed $value, AbstractPlatform $platform): ?string
    {
        if (null === $value) {
            return null;
        }

        if ($value instanceof Point) {
            return \sprintf('(%F, %F)', $value->getLongitude(), $value->getLatitude());
        }

        throw InvalidType::new($value, static::class, ['null', Point::class]);
    }
}
// src/ValueObject/Point.php

<?php

namespace App\ValueObject;

final readonly class Point
{
    public function __construct(
        private float $latitude,
        private float $longitude,
    ) {
    }

    public function getLatitude(): float
    {
        return $this->latitude;
    }

    public function getLongitude(): float
    {
        return $this->longitude;
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions