Created
April 8, 2020 13:00
-
-
Save samdark/408dcf707a8b1792065bfbbf8a66bf26 to your computer and use it in GitHub Desktop.
Timsetamp case refactoring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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