Database
2 years ago
Database.php
2 years ago
DateTimeAdapter.php
4 years ago
Directory.php
2 years ago
Maintenance.php
4 years ago
PhpAdapter.php
4 years ago
SourceDatabase.php
2 years ago
WpAdapter.php
3 years ago
DateTimeAdapter.php
101 lines
| 1 | <?php |
| 2 | |
| 3 | //TODO PHP7.x; declare(strict_types=1); |
| 4 | //TODO PHP7.x; type hinting & return types |
| 5 | |
| 6 | namespace WPStaging\Framework\Adapter; |
| 7 | |
| 8 | use DateTime; |
| 9 | |
| 10 | class DateTimeAdapter |
| 11 | { |
| 12 | const DEFAULT_TIME_FORMAT = 'H:i:s'; |
| 13 | |
| 14 | /** @var string */ |
| 15 | private $dateFormat; |
| 16 | |
| 17 | /** @var string */ |
| 18 | private $timeFormat; |
| 19 | |
| 20 | // TODO PHP5.6 constant |
| 21 | private $genericDateFormats = [ |
| 22 | // WP Suggested formats |
| 23 | 'F j, Y', |
| 24 | 'Y-m-d', |
| 25 | 'm/d/Y', |
| 26 | 'd/m/Y', |
| 27 | // Commonly used formats |
| 28 | 'd-m-Y', |
| 29 | 'm-d-Y', |
| 30 | 'Y-m-d', |
| 31 | 'Y/m/d', |
| 32 | ]; |
| 33 | |
| 34 | public function __construct() |
| 35 | { |
| 36 | $this->dateFormat = get_option('date_format'); |
| 37 | $this->timeFormat = get_option('time_format'); |
| 38 | } |
| 39 | |
| 40 | public function getWPDateTimeFormat() |
| 41 | { |
| 42 | return $this->dateFormat . ' ' . $this->timeFormat; |
| 43 | } |
| 44 | |
| 45 | public function getDateTimeFormat() |
| 46 | { |
| 47 | $dateFormat = $this->dateFormat; |
| 48 | $timeFormat = self::DEFAULT_TIME_FORMAT; |
| 49 | |
| 50 | if (!$dateFormat) { |
| 51 | $dateFormat = 'Y/m/d'; |
| 52 | } |
| 53 | |
| 54 | $dateFormat = str_replace('F', 'M', $dateFormat); |
| 55 | |
| 56 | return $dateFormat . ' ' . $timeFormat; |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * @param DateTime $dateTime |
| 61 | * @return string |
| 62 | */ |
| 63 | public function transformToWpFormat(DateTime $dateTime) |
| 64 | { |
| 65 | return get_date_from_gmt($dateTime->format('Y-m-d H:i:s'), $this->getDateTimeFormat()); |
| 66 | } |
| 67 | |
| 68 | /** |
| 69 | * @param string $value |
| 70 | * @return DateTime|null |
| 71 | */ |
| 72 | public function getDateTime($value) |
| 73 | { |
| 74 | $date = null; |
| 75 | foreach ($this->generateDefaultDateFormats() as $format) { |
| 76 | $date = DateTime::createFromFormat($format, $value); |
| 77 | if ($date) { |
| 78 | break; |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | return $date ?: null; |
| 83 | } |
| 84 | |
| 85 | // TODO |
| 86 | private function generateDefaultDateFormats() |
| 87 | { |
| 88 | $formats = [ |
| 89 | 'U', // Timestamp |
| 90 | $this->getDateTimeFormat(), |
| 91 | $this->getWPDateTimeFormat(), |
| 92 | ]; |
| 93 | |
| 94 | foreach ($this->genericDateFormats as $format) { |
| 95 | $formats[] = $format . ' ' . self::DEFAULT_TIME_FORMAT; |
| 96 | } |
| 97 | |
| 98 | return $formats; |
| 99 | } |
| 100 | } |
| 101 |