]> git.immae.eu Git - github/wallabag/wallabag.git/blob - vendor/symfony/form/Symfony/Component/Form/Extension/Core/DataTransformer/DateTimeToTimestampTransformer.php
d2ca6604db8c60326160d469ab5f5d2cedfcc35f
[github/wallabag/wallabag.git] / vendor / symfony / form / Symfony / Component / Form / Extension / Core / DataTransformer / DateTimeToTimestampTransformer.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
16 /**
17 * Transforms between a timestamp and a DateTime object
18 *
19 * @author Bernhard Schussek <bschussek@gmail.com>
20 * @author Florian Eckerstorfer <florian@eckerstorfer.org>
21 */
22 class DateTimeToTimestampTransformer extends BaseDateTimeTransformer
23 {
24 /**
25 * Transforms a DateTime object into a timestamp in the configured timezone.
26 *
27 * @param \DateTime $value A \DateTime object
28 *
29 * @return integer A timestamp
30 *
31 * @throws TransformationFailedException If the given value is not an instance
32 * of \DateTime or if the output
33 * timezone is not supported.
34 */
35 public function transform($value)
36 {
37 if (null === $value) {
38 return null;
39 }
40
41 if (!$value instanceof \DateTime) {
42 throw new TransformationFailedException('Expected a \DateTime.');
43 }
44
45 $value = clone $value;
46 try {
47 $value->setTimezone(new \DateTimeZone($this->outputTimezone));
48 } catch (\Exception $e) {
49 throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e);
50 }
51
52 return (int) $value->format('U');
53 }
54
55 /**
56 * Transforms a timestamp in the configured timezone into a DateTime object
57 *
58 * @param string $value A timestamp
59 *
60 * @return \DateTime A \DateTime object
61 *
62 * @throws TransformationFailedException If the given value is not a timestamp
63 * or if the given timestamp is invalid.
64 */
65 public function reverseTransform($value)
66 {
67 if (null === $value) {
68 return null;
69 }
70
71 if (!is_numeric($value)) {
72 throw new TransformationFailedException('Expected a numeric.');
73 }
74
75 try {
76 $dateTime = new \DateTime();
77 $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone));
78 $dateTime->setTimestamp($value);
79
80 if ($this->inputTimezone !== $this->outputTimezone) {
81 $dateTime->setTimezone(new \DateTimeZone($this->inputTimezone));
82 }
83 } catch (\Exception $e) {
84 throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e);
85 }
86
87 return $dateTime;
88 }
89 }