<?php

namespace App\Model;

use ORM\Entity;

trait CreatedTrait
{
    /**
     * Get a DateTime object from created
     *
     * @return \DateTime|null
     */
    public function getCreated()
    {
        if (!$this instanceof Entity) {
            return null;
        }

        $col = static::getColumnName('created');

        if (!isset($this->data[$col])) {
            return null;
        }

        return new \DateTime($this->data[$col]);
    }

    /**
     * Set created to $dt or 'now'
     *
     * @param \DateTime|null $dt
     * @return $this
     */
    public function setCreated(\DateTime $dt = null)
    {
        if (!$this instanceof Entity) {
            return $this;
        }

        $col = static::getColumnName('created');

        if (isset($this->data[$col])) {
            return $this;
        }

        $dt = $dt ?? \DateTime::createFromFormat('U.u', microtime(true))
                              ->setTimezone(new \DateTimeZone('UTC'));
        $this->data[$col] = $dt->format('Y-m-d\TH:i:s.u\Z');

        return $this;
    }
}