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