<?php<liu21st@gmail.com>declare (strict_types = 1);
namespace think\model\concern;
use DateTime;
trait TimeStamp
{
protected $autoWriteTimestamp;
protected $createTime = 'create_time';
protected $updateTime = 'update_time';
protected $dateFormat;
public function isAutoWriteTimestamp($auto)
{
$this->autoWriteTimestamp = $this->checkTimeFieldType($auto);
return $this;
}
protected function checkTimeFieldType($type)
{
if (true === $type) {
if (isset($this->type[$this->createTime])) {
$type = $this->type[$this->createTime];
} elseif (isset($this->schema[$this->createTime]) && in_array($this->schema[$this->createTime], ['datetime', 'date', 'timestamp', 'int'])) {
$type = $this->schema[$this->createTime];
} else {
$type = $this->getFieldType($this->createTime);
}
}
return $type;
}
public function getAutoWriteTimestamp()
{
return $this->autoWriteTimestamp;
}
public function setDateFormat($format)
{
$this->dateFormat = $format;
return $this;
}
public function getDateFormat()
{
return $this->dateFormat;
}
protected function autoWriteTimestamp()
{
$type = $this->checkTimeFieldType($this->autoWriteTimestamp);
return is_string($type) ? $this->getTimeTypeValue($type) : time();
}
protected function getTimeTypeValue(string $type)
{
$value = time();
switch ($type) {
case 'datetime':
case 'date':
case 'timestamp':
$value = $this->formatDateTime('Y-m-d H:i:s.u');
break;
default:
if (false !== strpos($type, '\\')) {
$obj = new $type();
if (method_exists($obj, '__toString')) {
$value = $obj->__toString();
}
}
}
return $value;
}
protected function formatDateTime($format, $time = 'now', bool $timestamp = false)
{
if (empty($time)) {
return;
}
if (false === $format) {
return $time;
} elseif (false !== strpos($format, '\\')) {
return new $format($time);
}
if ($time instanceof DateTime) {
$dateTime = $time;
} elseif ($timestamp) {
$dateTime = new DateTime();
$dateTime->setTimestamp((int) $time);
} else {
$dateTime = new DateTime($time);
}
return $dateTime->format($format);
}
protected function getTimestampValue($value)
{
$type = $this->checkTimeFieldType($this->autoWriteTimestamp);
if (is_string($type) && in_array(strtolower($type), [
'datetime', 'date', 'timestamp',
])) {
$value = $this->formatDateTime($this->dateFormat, $value);
} else {
$value = $this->formatDateTime($this->dateFormat, $value, true);
}
return $value;
}
}