Skip to content
Snippets Groups Projects

CreatedTrait

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Thomas Flori

    A trait I'm using for tflori/orm models

    CreatedTrait.php 1.05 KiB
    <?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;
        }
    }
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment