Datetime.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Eav\Model\Entity\Attribute\Backend;
  7. /**
  8. * @api
  9. * @since 100.0.2
  10. */
  11. class Datetime extends \Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend
  12. {
  13. /**
  14. * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
  15. */
  16. protected $_localeDate;
  17. /**
  18. * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate
  19. * @codeCoverageIgnore
  20. */
  21. public function __construct(\Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate)
  22. {
  23. $this->_localeDate = $localeDate;
  24. }
  25. /**
  26. * Formatting date value before save
  27. *
  28. * Should set (bool, string) correct type for empty value from html form,
  29. * necessary for further process, else date string
  30. *
  31. * @param \Magento\Framework\DataObject $object
  32. * @throws \Magento\Framework\Exception\LocalizedException
  33. * @return $this
  34. */
  35. public function beforeSave($object)
  36. {
  37. $attributeName = $this->getAttribute()->getName();
  38. $_formated = $object->getData($attributeName . '_is_formated');
  39. if (!$_formated && $object->hasData($attributeName)) {
  40. try {
  41. $value = $this->formatDate($object->getData($attributeName));
  42. } catch (\Exception $e) {
  43. throw new \Magento\Framework\Exception\LocalizedException(__('Invalid date'));
  44. }
  45. if ($value === null) {
  46. $value = $object->getData($attributeName);
  47. }
  48. $object->setData($attributeName, $value);
  49. $object->setData($attributeName . '_is_formated', true);
  50. }
  51. return $this;
  52. }
  53. /**
  54. * Prepare date for save in DB
  55. *
  56. * string format used from input fields (all date input fields need apply locale settings)
  57. * int value can be declared in code (this meen whot we use valid date)
  58. *
  59. * @param string|int|\DateTimeInterface $date
  60. * @return string
  61. */
  62. public function formatDate($date)
  63. {
  64. if (empty($date)) {
  65. return null;
  66. }
  67. // unix timestamp given - simply instantiate date object
  68. if (is_scalar($date) && preg_match('/^[0-9]+$/', $date)) {
  69. $date = (new \DateTime())->setTimestamp($date);
  70. } elseif (!($date instanceof \DateTimeInterface)) {
  71. // normalized format expecting Y-m-d[ H:i:s] - time is optional
  72. $date = new \DateTime($date);
  73. }
  74. return $date->format('Y-m-d H:i:s');
  75. }
  76. }