Ключ DateTime в проекте Symfony / Doctrine - PullRequest
0 голосов
/ 28 октября 2019

Как прочитано в этом ответе Я пытался применить решение к моему проекту Symfony. Это файлы

Приложение \ Тип \ DateTimeKey


    namespace App\Type;

    /**
     * Description of DateKey
     *
     */
    class DateTimeKey extends \DateTime{

        function __toString() {
            return $this->format('c');
        }

        /**
         * @param \DateTime $dateTime
         *
         * @return static
         * @throws \Exception
         */
        public static function fromDateTime(\DateTime $dateTime) {
            return new static($dateTime->format('c'));
        }
    }

Приложение \ Тип \ DateKeyType


namespace App\Type;

use DateTime;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateTimeType;

/**
 * Description of DataKeyType
 *
 */
class DateTimeKeyType extends DateTimeType{

    /**
     * @param $value
     * @param AbstractPlatform $platform
     *
     * @return bool|DateTime|false|DateTimeKey|mixed
     * @throws ConversionException
     * @throws \Exception
     */
    public function convertToPHPValue($value, AbstractPlatform $platform) {

        $value = parent::convertToPHPValue($value, $platform);

        if ($value !== null) {
            $value = DateTimeKey::fromDateTime($value);
        }

        return $value;

    }

    /**
     * 
     * @return string
     */
    public function getName()
    {
        return 'DateTimeKey';
    }
}

config / package / doctrine

doctrine:
    dbal:
        types:
            datetime_key: App\Type\DateTimeKeyType
        # configure these for your database server
        driver: 'pdo_mysql'
        server_version: '5.7'
        charset: utf8mb4
        default_table_options:
            charset: utf8mb4
            collate: utf8mb4_unicode_ci

        url: '%env(resolve:DATABASE_URL)%'
    orm:
        auto_generate_proxy_classes: true
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true
        mappings:
            App:
                is_bundle: false
                type: annotation
                dir: '%kernel.project_dir%/src/Entity'
                prefix: 'App\Entity'
                alias: App

App \ Entity \ Contabilita \ PrezzoUsoMacchina

<?php

namespace App\Entity\Contabilita;

use App\Entity\Hardware\Macchina;
use \DateTimeInterface;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

/**
 * @ORM\Entity(repositoryClass="App\Repository\Contabilita\PrezzoUsoMacchinaRepository")
 */
class PrezzoUsoMacchina
{

    /**
     * @var float
     *
     * @ORM\Column(type="decimal", precision=5, scale=2)
     * @Assert\NotBlank(message="Beh, immagino non lavino gratis i clienti...", groups={"new"})
     * @Assert\PositiveOrZero(message="Il prezzo deve essere un numero positivo", groups={"Default","new"})
     */
    private $prezzo;

    /**
     * @var Macchina
     *
     * @ORM\Id
     * @ORM\ManyToOne(targetEntity="App\Entity\Hardware\Macchina", inversedBy="prezziUsoMacchina")
     * @ORM\JoinColumn(nullable=false)
     */
    private $macchina;

    /**
     * @var \DateTime
     *
     * @ORM\Id
     * @ORM\Column(type="datetime_key")
     *
     * @Assert\NotBlank(message="È un campo obbligatorio", groups={"new"})
     * @Assert\NotNull(message="È un campo obbligatorio", groups={"new"})
     * @Assert\Date(message="Data inizio non valida", groups={"Default", "new"})
     */
    private $dataValiditaInizio;

    /**
     * @return float
     */
    public function getPrezzo(): ?float
    {
        return $this->prezzo;
    }

    /**
     * @param float $prezzo
     * @return $this
     */
    public function setPrezzo(float $prezzo): self
    {
        $this->prezzo = $prezzo;

        return $this;
    }

    /**
     * @return Macchina
     */
    public function getMacchina(): Macchina
    {
        return $this->macchina;
    }

    /**
     * @param Macchina|null $macchina
     *
     * @return $this
     */
    public function setMacchina(?Macchina $macchina): self
    {
        $this->macchina = $macchina;

        return $this;
    }

    /**
     * @return DateTimeInterface|null
     */
    public function getDataValiditaInizio(): ?DateTimeInterface
    {
        return $this->dataValiditaInizio;
    }

    /**
     * @param DateTimeInterface|null $dataValiditaInizio
     *
     * @return $this
     */
    public function setDataValiditaInizio(?DateTimeInterface $dataValiditaInizio): self
    {
        $this->dataValiditaInizio = $dataValiditaInizio;

        return $this;
    }
}

Когда я пытаюсь сохранить new PrezzoUsoMacchina(), я получаю этоошибка

Catchable Fatal Ошибка: объект класса DateTime не может быть преобразован в строку

Может кто-нибудь помочь? Спасибо

...