<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Doctrine\Type;

use Chill\MainBundle\Doctrine\Model\Point;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;

/**
 * A Type for Doctrine to implement the Geography Point type
 * implemented by Postgis on postgis+postgresql databases.
 */
class PointType extends Type
{
    final public const POINT = 'point';

    public function canRequireSQLConversion()
    {
        return true;
    }

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

        return $value->toWKT();
    }

    public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform)
    {
        return $sqlExpr;
    }

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

        return Point::fromGeoJson($value);
    }

    public function convertToPHPValueSQL($sqlExpr, $platform)
    {
        return 'ST_AsGeoJSON('.$sqlExpr.') ';
    }

    public function getName()
    {
        return self::POINT;
    }

    /**
     * @return string
     */
    public function getSQLDeclaration(array $column, AbstractPlatform $platform)
    {
        return 'geometry(POINT,'.Point::$SRID.')';
    }
}
