PageRenderTime 27ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToStringTransformer.php

https://gitlab.com/Snizer/PI-DEV-TUNISIAMALL3A6-WEB
PHP | 232 lines | 119 code | 25 blank | 88 comment | 18 complexity | d290a16e801bdd47a91fbd2ed331ae48 MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Form\Extension\Core\DataTransformer;
  11. use Symfony\Component\Form\Exception\TransformationFailedException;
  12. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  13. /**
  14. * Transforms between a date string and a DateTime object.
  15. *
  16. * @author Bernhard Schussek <bschussek@gmail.com>
  17. * @author Florian Eckerstorfer <florian@eckerstorfer.org>
  18. */
  19. class DateTimeToStringTransformer extends BaseDateTimeTransformer
  20. {
  21. /**
  22. * Format used for generating strings.
  23. *
  24. * @var string
  25. */
  26. private $generateFormat;
  27. /**
  28. * Format used for parsing strings.
  29. *
  30. * Different than the {@link $generateFormat} because formats for parsing
  31. * support additional characters in PHP that are not supported for
  32. * generating strings.
  33. *
  34. * @var string
  35. */
  36. private $parseFormat;
  37. /**
  38. * Whether to parse by appending a pipe "|" to the parse format.
  39. *
  40. * This only works as of PHP 5.3.7.
  41. *
  42. * @var bool
  43. */
  44. private $parseUsingPipe;
  45. /**
  46. * Transforms a \DateTime instance to a string.
  47. *
  48. * @see \DateTime::format() for supported formats
  49. *
  50. * @param string $inputTimezone The name of the input timezone
  51. * @param string $outputTimezone The name of the output timezone
  52. * @param string $format The date format
  53. * @param bool $parseUsingPipe Whether to parse by appending a pipe "|" to the parse format
  54. *
  55. * @throws UnexpectedTypeException if a timezone is not a string
  56. */
  57. public function __construct($inputTimezone = null, $outputTimezone = null, $format = 'Y-m-d H:i:s', $parseUsingPipe = null)
  58. {
  59. parent::__construct($inputTimezone, $outputTimezone);
  60. $this->generateFormat = $this->parseFormat = $format;
  61. // The pipe in the parser pattern only works as of PHP 5.3.7
  62. // See http://bugs.php.net/54316
  63. $this->parseUsingPipe = null === $parseUsingPipe
  64. ? PHP_VERSION_ID >= 50307
  65. : $parseUsingPipe;
  66. // See http://php.net/manual/en/datetime.createfromformat.php
  67. // The character "|" in the format makes sure that the parts of a date
  68. // that are *not* specified in the format are reset to the corresponding
  69. // values from 1970-01-01 00:00:00 instead of the current time.
  70. // Without "|" and "Y-m-d", "2010-02-03" becomes "2010-02-03 12:32:47",
  71. // where the time corresponds to the current server time.
  72. // With "|" and "Y-m-d", "2010-02-03" becomes "2010-02-03 00:00:00",
  73. // which is at least deterministic and thus used here.
  74. if ($this->parseUsingPipe && false === strpos($this->parseFormat, '|')) {
  75. $this->parseFormat .= '|';
  76. }
  77. }
  78. /**
  79. * Transforms a DateTime object into a date string with the configured format
  80. * and timezone.
  81. *
  82. * @param \DateTime $value A DateTime object
  83. *
  84. * @return string A value as produced by PHP's date() function
  85. *
  86. * @throws TransformationFailedException If the given value is not a \DateTime
  87. * instance or if the output timezone
  88. * is not supported.
  89. */
  90. public function transform($value)
  91. {
  92. if (null === $value) {
  93. return '';
  94. }
  95. if (!$value instanceof \DateTime) {
  96. throw new TransformationFailedException('Expected a \DateTime.');
  97. }
  98. $value = clone $value;
  99. try {
  100. $value->setTimezone(new \DateTimeZone($this->outputTimezone));
  101. } catch (\Exception $e) {
  102. throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e);
  103. }
  104. return $value->format($this->generateFormat);
  105. }
  106. /**
  107. * Transforms a date string in the configured timezone into a DateTime object.
  108. *
  109. * @param string $value A value as produced by PHP's date() function
  110. *
  111. * @return \DateTime An instance of \DateTime
  112. *
  113. * @throws TransformationFailedException If the given value is not a string,
  114. * if the date could not be parsed or
  115. * if the input timezone is not supported.
  116. */
  117. public function reverseTransform($value)
  118. {
  119. if (empty($value)) {
  120. return;
  121. }
  122. if (!is_string($value)) {
  123. throw new TransformationFailedException('Expected a string.');
  124. }
  125. try {
  126. $outputTz = new \DateTimeZone($this->outputTimezone);
  127. $dateTime = \DateTime::createFromFormat($this->parseFormat, $value, $outputTz);
  128. $lastErrors = \DateTime::getLastErrors();
  129. if (0 < $lastErrors['warning_count'] || 0 < $lastErrors['error_count']) {
  130. throw new TransformationFailedException(
  131. implode(', ', array_merge(
  132. array_values($lastErrors['warnings']),
  133. array_values($lastErrors['errors'])
  134. ))
  135. );
  136. }
  137. // On PHP versions < 5.3.7 we need to emulate the pipe operator
  138. // and reset parts not given in the format to their equivalent
  139. // of the UNIX base timestamp.
  140. if (!$this->parseUsingPipe) {
  141. list($year, $month, $day, $hour, $minute, $second) = explode('-', $dateTime->format('Y-m-d-H-i-s'));
  142. // Check which of the date parts are present in the pattern
  143. preg_match(
  144. '/('.
  145. '(?P<day>[djDl])|'.
  146. '(?P<month>[FMmn])|'.
  147. '(?P<year>[Yy])|'.
  148. '(?P<hour>[ghGH])|'.
  149. '(?P<minute>i)|'.
  150. '(?P<second>s)|'.
  151. '(?P<dayofyear>z)|'.
  152. '(?P<timestamp>U)|'.
  153. '[^djDlFMmnYyghGHiszU]'.
  154. ')*/',
  155. $this->parseFormat,
  156. $matches
  157. );
  158. // preg_match() does not guarantee to set all indices, so
  159. // set them unless given
  160. $matches = array_merge(array(
  161. 'day' => false,
  162. 'month' => false,
  163. 'year' => false,
  164. 'hour' => false,
  165. 'minute' => false,
  166. 'second' => false,
  167. 'dayofyear' => false,
  168. 'timestamp' => false,
  169. ), $matches);
  170. // Reset all parts that don't exist in the format to the
  171. // corresponding part of the UNIX base timestamp
  172. if (!$matches['timestamp']) {
  173. if (!$matches['dayofyear']) {
  174. if (!$matches['day']) {
  175. $day = 1;
  176. }
  177. if (!$matches['month']) {
  178. $month = 1;
  179. }
  180. }
  181. if (!$matches['year']) {
  182. $year = 1970;
  183. }
  184. if (!$matches['hour']) {
  185. $hour = 0;
  186. }
  187. if (!$matches['minute']) {
  188. $minute = 0;
  189. }
  190. if (!$matches['second']) {
  191. $second = 0;
  192. }
  193. $dateTime->setDate($year, $month, $day);
  194. $dateTime->setTime($hour, $minute, $second);
  195. }
  196. }
  197. if ($this->inputTimezone !== $this->outputTimezone) {
  198. $dateTime->setTimeZone(new \DateTimeZone($this->inputTimezone));
  199. }
  200. } catch (TransformationFailedException $e) {
  201. throw $e;
  202. } catch (\Exception $e) {
  203. throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e);
  204. }
  205. return $dateTime;
  206. }
  207. }