<?php
namespace Incoviba\Common\Implement\Repository\Mapper;

use DateTimeImmutable;
use DateMalformedStringException;
use Incoviba\Common\Implement\Repository\Mapper;

class DateTime extends Mapper
{
    public function __construct(string $column, ?string $property = null)
    {
        $this->setFunction(function($data) use ($column) {
            if (!isset($data[$column])) {
                return null;
            }
            if (is_a($data[$column], DateTimeImmutable::class)) {
                return $data[$column];
            }
            try {
                return new DateTimeImmutable($data[$column] ?? '');
            } catch (DateMalformedStringException) {
                return new DateTimeImmutable();
            }
        });
        if ($property !== null) {
            $this->setProperty($property);
        }
    }
}
