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