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
12namespace Symfony\Component\Form\Extension\Core\DataTransformer;
13
14use 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 */
22class DateTimeToTimestampTransformer extends BaseDateTimeTransformer
23{
24    /**
25     * Transforms a DateTime object into a timestamp in the configured timezone.
26     *
27     * @param \DateTime|\DateTimeInterface $dateTime A DateTime object
28     *
29     * @return int 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;
39        }
40
41        if (!$value instanceof \DateTime && !$value instanceof \DateTimeInterface) {
42            throw new TransformationFailedException('Expected a \DateTime or \DateTimeInterface.');
43        }
44
45        return $value->getTimestamp();
46    }
47
48    /**
49     * Transforms a timestamp in the configured timezone into a DateTime object.
50     *
51     * @param string $value A timestamp
52     *
53     * @return \DateTime A \DateTime object
54     *
55     * @throws TransformationFailedException If the given value is not a timestamp
56     *                                       or if the given timestamp is invalid.
57     */
58    public function reverseTransform($value)
59    {
60        if (null === $value) {
61            return;
62        }
63
64        if (!is_numeric($value)) {
65            throw new TransformationFailedException('Expected a numeric.');
66        }
67
68        try {
69            $dateTime = new \DateTime();
70            $dateTime->setTimezone(new \DateTimeZone($this->outputTimezone));
71            $dateTime->setTimestamp($value);
72
73            if ($this->inputTimezone !== $this->outputTimezone) {
74                $dateTime->setTimezone(new \DateTimeZone($this->inputTimezone));
75            }
76        } catch (\Exception $e) {
77            throw new TransformationFailedException($e->getMessage(), $e->getCode(), $e);
78        }
79
80        return $dateTime;
81    }
82}
83