DateTimeType.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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 Cake\Database\TypeInterface;
  19. use DateTimeInterface;
  20. use Exception;
  21. use PDO;
  22. use RuntimeException;
  23. /**
  24. * Datetime type converter.
  25. *
  26. * Use to convert datetime instances to strings & back.
  27. */
  28. class DateTimeType extends Type implements TypeInterface
  29. {
  30. /**
  31. * Identifier name for this type.
  32. *
  33. * (This property is declared here again so that the inheritance from
  34. * Cake\Database\Type can be removed in the future.)
  35. *
  36. * @var string|null
  37. */
  38. protected $_name = null;
  39. /**
  40. * The class to use for representing date objects
  41. *
  42. * This property can only be used before an instance of this type
  43. * class is constructed. After that use `useMutable()` or `useImmutable()` instead.
  44. *
  45. * @var string
  46. * @deprecated Use DateTimeType::useMutable() or DateTimeType::useImmutable() instead.
  47. */
  48. public static $dateTimeClass = 'Cake\I18n\Time';
  49. /**
  50. * String format to use for DateTime parsing
  51. *
  52. * @var string
  53. */
  54. protected $_format = 'Y-m-d H:i:s';
  55. /**
  56. * Whether dates should be parsed using a locale aware parser
  57. * when marshalling string inputs.
  58. *
  59. * @var bool
  60. */
  61. protected $_useLocaleParser = false;
  62. /**
  63. * The date format to use for parsing incoming dates for marshalling.
  64. *
  65. * @var string|array|int
  66. */
  67. protected $_localeFormat;
  68. /**
  69. * An instance of the configured dateTimeClass, used to quickly generate
  70. * new instances without calling the constructor.
  71. *
  72. * @var \DateTime
  73. */
  74. protected $_datetimeInstance;
  75. /**
  76. * The classname to use when creating objects.
  77. *
  78. * @var string
  79. */
  80. protected $_className;
  81. /**
  82. * {@inheritDoc}
  83. */
  84. public function __construct($name = null)
  85. {
  86. $this->_name = $name;
  87. $this->_setClassName(static::$dateTimeClass, 'DateTime');
  88. }
  89. /**
  90. * Convert DateTime instance into strings.
  91. *
  92. * @param string|int|\DateTime $value The value to convert.
  93. * @param \Cake\Database\Driver $driver The driver instance to convert with.
  94. * @return string
  95. */
  96. public function toDatabase($value, Driver $driver)
  97. {
  98. if ($value === null || is_string($value)) {
  99. return $value;
  100. }
  101. if (is_int($value)) {
  102. $class = $this->_className;
  103. $value = new $class('@' . $value);
  104. }
  105. return $value->format($this->_format);
  106. }
  107. /**
  108. * Convert strings into DateTime instances.
  109. *
  110. * @param string $value The value to convert.
  111. * @param \Cake\Database\Driver $driver The driver instance to convert with.
  112. * @return \Cake\I18n\Time|\DateTime
  113. */
  114. public function toPHP($value, Driver $driver)
  115. {
  116. if ($value === null || strpos($value, '0000-00-00') === 0) {
  117. return null;
  118. }
  119. if (strpos($value, '.') !== false) {
  120. list($value) = explode('.', $value);
  121. }
  122. $instance = clone $this->_datetimeInstance;
  123. return $instance->modify($value);
  124. }
  125. /**
  126. * Convert request data into a datetime object.
  127. *
  128. * @param mixed $value Request data
  129. * @return \Cake\I18n\Time|\DateTime
  130. */
  131. public function marshal($value)
  132. {
  133. if ($value instanceof DateTimeInterface) {
  134. return $value;
  135. }
  136. $class = $this->_className;
  137. try {
  138. $compare = $date = false;
  139. if ($value === '' || $value === null || $value === false || $value === true) {
  140. return null;
  141. } elseif (is_numeric($value)) {
  142. $date = new $class('@' . $value);
  143. } elseif (is_string($value) && $this->_useLocaleParser) {
  144. return $this->_parseValue($value);
  145. } elseif (is_string($value)) {
  146. $date = new $class($value);
  147. $compare = true;
  148. }
  149. if ($compare && $date && $date->format($this->_format) !== $value) {
  150. return $value;
  151. }
  152. if ($date) {
  153. return $date;
  154. }
  155. } catch (Exception $e) {
  156. return $value;
  157. }
  158. if (is_array($value) && implode('', $value) === '') {
  159. return null;
  160. }
  161. $value += ['hour' => 0, 'minute' => 0, 'second' => 0];
  162. $format = '';
  163. if (isset($value['year'], $value['month'], $value['day']) &&
  164. (is_numeric($value['year']) && is_numeric($value['month']) && is_numeric($value['day']))
  165. ) {
  166. $format .= sprintf('%d-%02d-%02d', $value['year'], $value['month'], $value['day']);
  167. }
  168. if (isset($value['meridian']) && (int)$value['hour'] === 12) {
  169. $value['hour'] = 0;
  170. }
  171. if (isset($value['meridian'])) {
  172. $value['hour'] = strtolower($value['meridian']) === 'am' ? $value['hour'] : $value['hour'] + 12;
  173. }
  174. $format .= sprintf(
  175. '%s%02d:%02d:%02d',
  176. empty($format) ? '' : ' ',
  177. $value['hour'],
  178. $value['minute'],
  179. $value['second']
  180. );
  181. $tz = isset($value['timezone']) ? $value['timezone'] : null;
  182. return new $class($format, $tz);
  183. }
  184. /**
  185. * Sets whether or not to parse dates passed to the marshal() function
  186. * by using a locale aware parser.
  187. *
  188. * @param bool $enable Whether or not to enable
  189. * @return self
  190. */
  191. public function useLocaleParser($enable = true)
  192. {
  193. if ($enable === false) {
  194. $this->_useLocaleParser = $enable;
  195. return $this;
  196. }
  197. if (method_exists($this->_className, 'parseDateTime')) {
  198. $this->_useLocaleParser = $enable;
  199. return $this;
  200. }
  201. throw new RuntimeException(
  202. sprintf('Cannot use locale parsing with the %s class', $this->_className)
  203. );
  204. }
  205. /**
  206. * Sets the format string to use for parsing dates in this class. The formats
  207. * that are accepted are documented in the `Cake\I18n\Time::parseDateTime()`
  208. * function.
  209. *
  210. * @param string|array $format The format in which the string are passed.
  211. * @see \Cake\I18n\Time::parseDateTime()
  212. * @return self
  213. */
  214. public function setLocaleFormat($format)
  215. {
  216. $this->_localeFormat = $format;
  217. return $this;
  218. }
  219. /**
  220. * Change the preferred class name to the FrozenTime implementation.
  221. *
  222. * @return self
  223. */
  224. public function useImmutable()
  225. {
  226. $this->_setClassName('Cake\I18n\FrozenTime', 'DateTimeImmutable');
  227. return $this;
  228. }
  229. /**
  230. * Set the classname to use when building objects.
  231. *
  232. * @param string $class The classname to use.
  233. * @param string $fallback The classname to use when the preferred class does not exist.
  234. * @return void
  235. */
  236. protected function _setClassName($class, $fallback)
  237. {
  238. if (!class_exists($class)) {
  239. $class = $fallback;
  240. }
  241. $this->_className = $class;
  242. $this->_datetimeInstance = new $this->_className;
  243. }
  244. /**
  245. * Change the preferred class name to the mutable Time implementation.
  246. *
  247. * @return self
  248. */
  249. public function useMutable()
  250. {
  251. $this->_setClassName('Cake\I18n\Time', 'DateTime');
  252. return $this;
  253. }
  254. /**
  255. * Converts a string into a DateTime object after parsing it using the locale
  256. * aware parser with the specified format.
  257. *
  258. * @param string $value The value to parse and convert to an object.
  259. * @return \Cake\I18n\Time|null
  260. */
  261. protected function _parseValue($value)
  262. {
  263. /* @var \Cake\I18n\Time $class */
  264. $class = $this->_className;
  265. return $class::parseDateTime($value, $this->_localeFormat);
  266. }
  267. /**
  268. * Casts given value to Statement equivalent
  269. *
  270. * @param mixed $value value to be converted to PDO statement
  271. * @param \Cake\Database\Driver $driver object from which database preferences and configuration will be extracted
  272. *
  273. * @return mixed
  274. */
  275. public function toStatement($value, Driver $driver)
  276. {
  277. return PDO::PARAM_STR;
  278. }
  279. }