DateType.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Database\Type;
  17. use Cake\I18n\Date;
  18. use Cake\I18n\I18nDateTimeInterface;
  19. use DateTimeImmutable;
  20. use DateTimeInterface;
  21. /**
  22. * Class DateType
  23. */
  24. class DateType extends DateTimeType
  25. {
  26. /**
  27. * @inheritDoc
  28. */
  29. protected string $_format = 'Y-m-d';
  30. /**
  31. * {@inheritDoc}
  32. *
  33. * @var array<string>
  34. */
  35. protected array $_marshalFormats = [
  36. 'Y-m-d',
  37. ];
  38. /**
  39. * In this class we want Date objects to have their time
  40. * set to the beginning of the day.
  41. *
  42. * @var bool
  43. */
  44. protected bool $setToDateStart = true;
  45. /**
  46. * @inheritDoc
  47. */
  48. public function __construct(?string $name = null)
  49. {
  50. parent::__construct($name);
  51. $this->_className = class_exists(Date::class) ? Date::class : DateTimeImmutable::class;
  52. }
  53. /**
  54. * Convert request data into a datetime object.
  55. *
  56. * @param mixed $value Request data
  57. * @return \DateTimeInterface|null
  58. */
  59. public function marshal(mixed $value): ?DateTimeInterface
  60. {
  61. $date = parent::marshal($value);
  62. if ($date && !$date instanceof I18nDateTimeInterface) {
  63. // Clear time manually when I18n types aren't available and raw DateTime used
  64. /** @psalm-var \DateTime|\DateTimeImmutable $date */
  65. $date->setTime(0, 0, 0);
  66. }
  67. return $date;
  68. }
  69. /**
  70. * @inheritDoc
  71. */
  72. protected function _parseLocaleValue(string $value): ?I18nDateTimeInterface
  73. {
  74. /** @psalm-var class-string<\Cake\I18n\I18nDateTimeInterface> $class */
  75. $class = $this->_className;
  76. return $class::parseDate($value, $this->_localeMarshalFormat);
  77. }
  78. }