DateTimeType.php 7.0 KB

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