eesyphp/src/Db/AttrTimestamp.php
Benjamin Renard 347de8eeaf
Add DbObject
2024-02-18 18:27:58 +01:00

75 lines
2 KiB
PHP

<?php
namespace EesyPHP\Db;
use EesyPHP\Date;
use function EesyPHP\get_system_timezone;
class AttrTimestamp extends Attr {
/**
* The timezone of the date
* @var \DateTimeZone|string|null
*/
protected $timezone = 'system';
/**
* The export format
* @var string
*/
protected $export_format = 'Y/m/d H:i:s';
/**
* Compute attribute value from DB
* @param int|null $value The value as retrieved from debug
* @return \DateTime|null The attribute value
*/
public function from_db($value) {
$value = parent::from_db($value);
if (is_null($value)) return null;
return Date :: from_timestamp($value, $this -> timezone);
}
/**
* Compute attribute value for DB
* @param \DateTime|int|null $value The value as handled in PHP
* @return int|null The attribute value as stored in DB
*/
public function to_db($value) {
$value = parent::from_db($value);
if (is_null($value)) return null;
$value = $value instanceof \DateTime?$value:Date :: from_timestamp($value);
return $value->getTimestamp();
}
/**
* Compute attribute value from string
* @param string $value The input value
* @return \DateTime|null The attribute value as handled in PHP
*/
public function from_string($value) {
if (!$value) return null;
$timestamp = Date :: parse($value, $this -> export_format, null, true);
if ($timestamp === false)
throw new DbException(
"Error parsing date '%s' from export using format '%s'",
$value, $this -> export_format
);
return $timestamp;
}
/**
* Compute attribute value to string
* @param \DateTime|int|null $value The input value as handled in PHP
* @return string The attribute value as string
*/
public function to_string($value) {
$value = parent::from_db($value);
if (is_null($value)) return '';
$value = $value instanceof \DateTime?$value:Date :: from_timestamp($value);
return Date :: format($value->getTimestamp(), $this -> export_format);
}
}