PageRenderTime 38ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/symfony/src/Symfony/Component/Intl/DateFormatter/DateFormat/FullTransformer.php

https://gitlab.com/TouirMohamedMarwen/Symfony2
PHP | 355 lines | 329 code | 6 blank | 20 comment | 1 complexity | 7f46e5e227555a31543e950de000f288 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\Intl\DateFormatter\DateFormat;
  11. use Symfony\Component\Intl\Exception\NotImplementedException;
  12. use Symfony\Component\Intl\Globals\IntlGlobals;
  13. /**
  14. * Parser and formatter for date formats
  15. *
  16. * @author Igor Wiedler <igor@wiedler.ch>
  17. */
  18. class FullTransformer
  19. {
  20. private $quoteMatch = "'(?:[^']+|'')*'";
  21. private $implementedChars = 'MLydQqhDEaHkKmsz';
  22. private $notImplementedChars = 'GYuwWFgecSAZvVW';
  23. private $regExp;
  24. /**
  25. * @var Transformer[]
  26. */
  27. private $transformers;
  28. private $pattern;
  29. private $timezone;
  30. /**
  31. * Constructor
  32. *
  33. * @param string $pattern The pattern to be used to format and/or parse values
  34. * @param string $timezone The timezone to perform the date/time calculations
  35. */
  36. public function __construct($pattern, $timezone)
  37. {
  38. $this->pattern = $pattern;
  39. $this->timezone = $timezone;
  40. $implementedCharsMatch = $this->buildCharsMatch($this->implementedChars);
  41. $notImplementedCharsMatch = $this->buildCharsMatch($this->notImplementedChars);
  42. $this->regExp = "/($this->quoteMatch|$implementedCharsMatch|$notImplementedCharsMatch)/";
  43. $this->transformers = array(
  44. 'M' => new MonthTransformer(),
  45. 'L' => new MonthTransformer(),
  46. 'y' => new YearTransformer(),
  47. 'd' => new DayTransformer(),
  48. 'q' => new QuarterTransformer(),
  49. 'Q' => new QuarterTransformer(),
  50. 'h' => new Hour1201Transformer(),
  51. 'D' => new DayOfYearTransformer(),
  52. 'E' => new DayOfWeekTransformer(),
  53. 'a' => new AmPmTransformer(),
  54. 'H' => new Hour2400Transformer(),
  55. 'K' => new Hour1200Transformer(),
  56. 'k' => new Hour2401Transformer(),
  57. 'm' => new MinuteTransformer(),
  58. 's' => new SecondTransformer(),
  59. 'z' => new TimeZoneTransformer(),
  60. );
  61. }
  62. /**
  63. * Return the array of Transformer objects
  64. *
  65. * @return Transformer[] Associative array of Transformer objects (format char => Transformer)
  66. */
  67. public function getTransformers()
  68. {
  69. return $this->transformers;
  70. }
  71. /**
  72. * Format a DateTime using ICU dateformat pattern
  73. *
  74. * @param \DateTime $dateTime A DateTime object to be used to generate the formatted value
  75. *
  76. * @return string The formatted value
  77. */
  78. public function format(\DateTime $dateTime)
  79. {
  80. $that = $this;
  81. $formatted = preg_replace_callback($this->regExp, function ($matches) use ($that, $dateTime) {
  82. return $that->formatReplace($matches[0], $dateTime);
  83. }, $this->pattern);
  84. return $formatted;
  85. }
  86. /**
  87. * Return the formatted ICU value for the matched date characters
  88. *
  89. * @param string $dateChars The date characters to be replaced with a formatted ICU value
  90. * @param \DateTime $dateTime A DateTime object to be used to generate the formatted value
  91. *
  92. * @return string The formatted value
  93. *
  94. * @throws NotImplementedException When it encounters a not implemented date character
  95. */
  96. public function formatReplace($dateChars, $dateTime)
  97. {
  98. $length = strlen($dateChars);
  99. if ($this->isQuoteMatch($dateChars)) {
  100. return $this->replaceQuoteMatch($dateChars);
  101. }
  102. if (isset($this->transformers[$dateChars[0]])) {
  103. $transformer = $this->transformers[$dateChars[0]];
  104. return $transformer->format($dateTime, $length);
  105. }
  106. // handle unimplemented characters
  107. if (false !== strpos($this->notImplementedChars, $dateChars[0])) {
  108. throw new NotImplementedException(sprintf("Unimplemented date character '%s' in format '%s'", $dateChars[0], $this->pattern));
  109. }
  110. }
  111. /**
  112. * Parse a pattern based string to a timestamp value
  113. *
  114. * @param \DateTime $dateTime A configured DateTime object to use to perform the date calculation
  115. * @param string $value String to convert to a time value
  116. *
  117. * @return int The corresponding Unix timestamp
  118. *
  119. * @throws \InvalidArgumentException When the value can not be matched with pattern
  120. */
  121. public function parse(\DateTime $dateTime, $value)
  122. {
  123. $reverseMatchingRegExp = $this->getReverseMatchingRegExp($this->pattern);
  124. $reverseMatchingRegExp = '/^'.$reverseMatchingRegExp.'$/';
  125. $options = array();
  126. if (preg_match($reverseMatchingRegExp, $value, $matches)) {
  127. $matches = $this->normalizeArray($matches);
  128. foreach ($this->transformers as $char => $transformer) {
  129. if (isset($matches[$char])) {
  130. $length = strlen($matches[$char]['pattern']);
  131. $options = array_merge($options, $transformer->extractDateOptions($matches[$char]['value'], $length));
  132. }
  133. }
  134. // reset error code and message
  135. IntlGlobals::setError(IntlGlobals::U_ZERO_ERROR);
  136. return $this->calculateUnixTimestamp($dateTime, $options);
  137. }
  138. // behave like the intl extension
  139. IntlGlobals::setError(IntlGlobals::U_PARSE_ERROR, 'Date parsing failed');
  140. return false;
  141. }
  142. /**
  143. * Retrieve a regular expression to match with a formatted value.
  144. *
  145. * @param string $pattern The pattern to create the reverse matching regular expression
  146. *
  147. * @return string The reverse matching regular expression with named captures being formed by the
  148. * transformer index in the $transformer array
  149. */
  150. public function getReverseMatchingRegExp($pattern)
  151. {
  152. $that = $this;
  153. $escapedPattern = preg_quote($pattern, '/');
  154. // ICU 4.8 recognizes slash ("/") in a value to be parsed as a dash ("-") and vice-versa
  155. // when parsing a date/time value
  156. $escapedPattern = preg_replace('/\\\[\-|\/]/', '[\/\-]', $escapedPattern);
  157. $reverseMatchingRegExp = preg_replace_callback($this->regExp, function ($matches) use ($that) {
  158. $length = strlen($matches[0]);
  159. $transformerIndex = $matches[0][0];
  160. $dateChars = $matches[0];
  161. if ($that->isQuoteMatch($dateChars)) {
  162. return $that->replaceQuoteMatch($dateChars);
  163. }
  164. $transformers = $that->getTransformers();
  165. if (isset($transformers[$transformerIndex])) {
  166. $transformer = $transformers[$transformerIndex];
  167. $captureName = str_repeat($transformerIndex, $length);
  168. return "(?P<$captureName>".$transformer->getReverseMatchingRegExp($length).')';
  169. }
  170. }, $escapedPattern);
  171. return $reverseMatchingRegExp;
  172. }
  173. /**
  174. * Check if the first char of a string is a single quote
  175. *
  176. * @param string $quoteMatch The string to check
  177. *
  178. * @return bool true if matches, false otherwise
  179. */
  180. public function isQuoteMatch($quoteMatch)
  181. {
  182. return ("'" === $quoteMatch[0]);
  183. }
  184. /**
  185. * Replaces single quotes at the start or end of a string with two single quotes
  186. *
  187. * @param string $quoteMatch The string to replace the quotes
  188. *
  189. * @return string A string with the single quotes replaced
  190. */
  191. public function replaceQuoteMatch($quoteMatch)
  192. {
  193. if (preg_match("/^'+$/", $quoteMatch)) {
  194. return str_replace("''", "'", $quoteMatch);
  195. }
  196. return str_replace("''", "'", substr($quoteMatch, 1, -1));
  197. }
  198. /**
  199. * Builds a chars match regular expression
  200. *
  201. * @param string $specialChars A string of chars to build the regular expression
  202. *
  203. * @return string The chars match regular expression
  204. */
  205. protected function buildCharsMatch($specialChars)
  206. {
  207. $specialCharsArray = str_split($specialChars);
  208. $specialCharsMatch = implode('|', array_map(function ($char) {
  209. return $char.'+';
  210. }, $specialCharsArray));
  211. return $specialCharsMatch;
  212. }
  213. /**
  214. * Normalize a preg_replace match array, removing the numeric keys and returning an associative array
  215. * with the value and pattern values for the matched Transformer
  216. *
  217. * @param array $data
  218. *
  219. * @return array
  220. */
  221. protected function normalizeArray(array $data)
  222. {
  223. $ret = array();
  224. foreach ($data as $key => $value) {
  225. if (!is_string($key)) {
  226. continue;
  227. }
  228. $ret[$key[0]] = array(
  229. 'value' => $value,
  230. 'pattern' => $key,
  231. );
  232. }
  233. return $ret;
  234. }
  235. /**
  236. * Calculates the Unix timestamp based on the matched values by the reverse matching regular
  237. * expression of parse()
  238. *
  239. * @param \DateTime $dateTime The DateTime object to be used to calculate the timestamp
  240. * @param array $options An array with the matched values to be used to calculate the timestamp
  241. *
  242. * @return bool|int The calculated timestamp or false if matched date is invalid
  243. */
  244. protected function calculateUnixTimestamp(\DateTime $dateTime, array $options)
  245. {
  246. $options = $this->getDefaultValueForOptions($options);
  247. $year = $options['year'];
  248. $month = $options['month'];
  249. $day = $options['day'];
  250. $hour = $options['hour'];
  251. $hourInstance = $options['hourInstance'];
  252. $minute = $options['minute'];
  253. $second = $options['second'];
  254. $marker = $options['marker'];
  255. $timezone = $options['timezone'];
  256. // If month is false, return immediately (intl behavior)
  257. if (false === $month) {
  258. IntlGlobals::setError(IntlGlobals::U_PARSE_ERROR, 'Date parsing failed');
  259. return false;
  260. }
  261. // Normalize hour
  262. if ($hourInstance instanceof HourTransformer) {
  263. $hour = $hourInstance->normalizeHour($hour, $marker);
  264. }
  265. // Set the timezone if different from the default one
  266. if (null !== $timezone && $timezone !== $this->timezone) {
  267. $dateTime->setTimezone(new \DateTimeZone($timezone));
  268. }
  269. // Normalize yy year
  270. preg_match_all($this->regExp, $this->pattern, $matches);
  271. if (in_array('yy', $matches[0])) {
  272. $dateTime->setTimestamp(time());
  273. $year = $year > $dateTime->format('y') + 20 ? 1900 + $year : 2000 + $year;
  274. }
  275. $dateTime->setDate($year, $month, $day);
  276. $dateTime->setTime($hour, $minute, $second);
  277. return $dateTime->getTimestamp();
  278. }
  279. /**
  280. * Add sensible default values for missing items in the extracted date/time options array. The values
  281. * are base in the beginning of the Unix era
  282. *
  283. * @param array $options
  284. *
  285. * @return array
  286. */
  287. private function getDefaultValueForOptions(array $options)
  288. {
  289. return array(
  290. 'year' => isset($options['year']) ? $options['year'] : 1970,
  291. 'month' => isset($options['month']) ? $options['month'] : 1,
  292. 'day' => isset($options['day']) ? $options['day'] : 1,
  293. 'hour' => isset($options['hour']) ? $options['hour'] : 0,
  294. 'hourInstance' => isset($options['hourInstance']) ? $options['hourInstance'] : null,
  295. 'minute' => isset($options['minute']) ? $options['minute'] : 0,
  296. 'second' => isset($options['second']) ? $options['second'] : 0,
  297. 'marker' => isset($options['marker']) ? $options['marker'] : null,
  298. 'timezone' => isset($options['timezone']) ? $options['timezone'] : null,
  299. );
  300. }
  301. }