Skip to content

Instantly share code, notes, and snippets.

@samdark
Created April 8, 2020 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samdark/408dcf707a8b1792065bfbbf8a66bf26 to your computer and use it in GitHub Desktop.
Save samdark/408dcf707a8b1792065bfbbf8a66bf26 to your computer and use it in GitHub Desktop.
Timsetamp case refactoring
<?php
// see https://gist.github.com/Nex-Otaku/622ce7f2f336f27b4953e85efffa7c45
class Timestamp
{
private int $intTimestamp;
private function __construct(int $intTimestamp)
{
$this->intTimestamp = $intTimestamp;
}
public static function current(): self
{
return new self(time());
}
public static function fromInt(int $intTimestamp): self
{
return new self($intTimestamp);
}
public function toInt(): int
{
return $this->intTimestamp;
}
public function toString(?TimestampFormatterInterface $formatter): string
{
if ($formatter === null) {
$formatter = new DefaultTimestampFormatter();
}
return $formatter->format($this->intTimestamp);
}
}
interface TimestampFormatterInterface
{
public function format(int $timestamp): string;
}
class DefaultTimestampFormatter implements TimestampFormatterInterface
{
public function format(int $timestamp): string
{
try {
return (new \DateTime("@{$timestamp}"))
->setTimezone(new \DateTimeZone('Europe/Moscow'))
->format('Y-m-d H:i:s');
} catch (\Exception $exception) {
throw new \LogicException("Не удалось сконвертировать время, Timestamp: {$timestamp}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment