DateTimeType.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Database\Type;
  16. use Cake\Database\Driver;
  17. use Cake\Database\Type;
  18. use DateTimeInterface;
  19. use DateTimeImmutable;
  20. use Exception;
  21. use RuntimeException;
  22. /**
  23. * Datetime type converter.
  24. *
  25. * Use to convert datetime instances to strings & back.
  26. */
  27. class DateTimeType extends Type
  28. {
  29. /**
  30. * The class to use for representing date objects
  31. *
  32. * @var string
  33. */
  34. public static $dateTimeClass = 'Cake\I18n\Time';
  35. /**
  36. * String format to use for DateTime parsing
  37. *
  38. * @var string
  39. */
  40. protected $_format = 'Y-m-d H:i:s';
  41. /**
  42. * Whether dates should be parsed using a locale aware parser
  43. * when marshalling string inputs.
  44. *
  45. * @var bool
  46. */
  47. protected $_useLocaleParser = false;
  48. /**
  49. * The date format to use for parsing incoming dates for marshalling.
  50. *
  51. * @var string|array|int
  52. */
  53. protected $_localeFormat;
  54. /**
  55. * An instance of the configured dateTimeClass, used to quickly generate
  56. * new instances without calling the constructor.
  57. *
  58. * @var \DateTime
  59. */
  60. protected $_datetimeInstance;
  61. /**
  62. * {@inheritDoc}
  63. */
  64. public function __construct($name = null)
  65. {
  66. parent::__construct($name);
  67. if (!class_exists(static::$dateTimeClass)) {
  68. static::$dateTimeClass = 'DateTime';
  69. }
  70. $this->_datetimeInstance = new static::$dateTimeClass;
  71. }
  72. /**
  73. * Convert DateTime instance into strings.
  74. *
  75. * @param string|int|\DateTime $value The value to convert.
  76. * @param Driver $driver The driver instance to convert with.
  77. * @return string
  78. */
  79. public function toDatabase($value, Driver $driver)
  80. {
  81. if ($value === null || is_string($value)) {
  82. return $value;
  83. }
  84. if (is_int($value)) {
  85. $value = new static::$dateTimeClass('@' . $value);
  86. }
  87. return $value->format($this->_format);
  88. }
  89. /**
  90. * Convert strings into DateTime instances.
  91. *
  92. * @param string $value The value to convert.
  93. * @param Driver $driver The driver instance to convert with.
  94. * @return \Cake\I18n\Time|\DateTime
  95. */
  96. public function toPHP($value, Driver $driver)
  97. {
  98. if ($value === null || strpos($value, '0000-00-00') === 0) {
  99. return null;
  100. }
  101. if (strpos($value, '.') !== false) {
  102. list($value) = explode('.', $value);
  103. }
  104. $instance = clone $this->_datetimeInstance;
  105. return $instance->modify($value);
  106. }
  107. /**
  108. * Convert request data into a datetime object.
  109. *
  110. * @param mixed $value Request data
  111. * @return \Cake\I18n\Time|\DateTime
  112. */
  113. public function marshal($value)
  114. {
  115. if ($value instanceof DateTime || $value instanceof DateTimeImmutable) {
  116. return $value;
  117. }
  118. $class = static::$dateTimeClass;
  119. try {
  120. $compare = $date = false;
  121. if ($value === '' || $value === null || $value === false || $value === true) {
  122. return null;
  123. } elseif (is_numeric($value)) {
  124. $date = new $class('@' . $value);
  125. } elseif (is_string($value) && $this->_useLocaleParser) {
  126. return $this->_parseValue($value);
  127. } elseif (is_string($value)) {
  128. $date = new $class($value);
  129. $compare = true;
  130. }
  131. if ($compare && $date && $date->format($this->_format) !== $value) {
  132. return $value;
  133. }
  134. if ($date) {
  135. return $date;
  136. }
  137. } catch (Exception $e) {
  138. return $value;
  139. }
  140. if (is_array($value) && implode('', $value) === '') {
  141. return null;
  142. }
  143. $value += ['hour' => 0, 'minute' => 0, 'second' => 0];
  144. $format = '';
  145. if (isset($value['year'], $value['month'], $value['day']) &&
  146. (is_numeric($value['year']) && is_numeric($value['month']) && is_numeric($value['day']))
  147. ) {
  148. $format .= sprintf('%d-%02d-%02d', $value['year'], $value['month'], $value['day']);
  149. }
  150. if (isset($value['meridian']) && (int)$value['hour'] === 12) {
  151. $value['hour'] = 0;
  152. }
  153. if (isset($value['meridian'])) {
  154. $value['hour'] = strtolower($value['meridian']) === 'am' ? $value['hour'] : $value['hour'] + 12;
  155. }
  156. $format .= sprintf(
  157. '%s%02d:%02d:%02d',
  158. empty($format) ? '' : ' ',
  159. $value['hour'],
  160. $value['minute'],
  161. $value['second']
  162. );
  163. $tz = isset($value['timezone']) ? $value['timezone'] : null;
  164. return new $class($format, $tz);
  165. }
  166. /**
  167. * Sets whether or not to parse dates passed to the marshal() function
  168. * by using a locale aware parser.
  169. *
  170. * @param bool $enable Whether or not to enable
  171. * @return $this
  172. */
  173. public function useLocaleParser($enable = true)
  174. {
  175. if ($enable === false) {
  176. $this->_useLocaleParser = $enable;
  177. return $this;
  178. }
  179. if (method_exists(static::$dateTimeClass, 'parseDateTime')) {
  180. $this->_useLocaleParser = $enable;
  181. return $this;
  182. }
  183. throw new RuntimeException(
  184. sprintf('Cannot use locale parsing with the %s class', static::$dateTimeClass)
  185. );
  186. }
  187. /**
  188. * Sets the format string to use for parsing dates in this class. The formats
  189. * that are accepted are documented in the `Cake\I18n\Time::parseDateTime()`
  190. * function.
  191. *
  192. * @param string|array $format The format in which the string are passed.
  193. * @see \Cake\I18n\Time::parseDateTime()
  194. * @return $this
  195. */
  196. public function setLocaleFormat($format)
  197. {
  198. $this->_localeFormat = $format;
  199. return $this;
  200. }
  201. /**
  202. * Converts a string into a DateTime object after parseing it using the locale
  203. * aware parser with the specified format.
  204. *
  205. * @param string $value The value to parse and convert to an object.
  206. * @return \Cake\I18n\Time|null
  207. */
  208. protected function _parseValue($value)
  209. {
  210. $class = static::$dateTimeClass;
  211. return $class::parseDateTime($value, $this->_localeFormat);
  212. }
  213. }