Skip to content

Instantly share code, notes, and snippets.

@vaclavvanik
Created November 30, 2018 14:58
Show Gist options
  • Save vaclavvanik/10dacd816dc6c690b07e71e84060b7fb to your computer and use it in GitHub Desktop.
Save vaclavvanik/10dacd816dc6c690b07e71e84060b7fb to your computer and use it in GitHub Desktop.
DateTimeImmutableFormatterStrategy
<?php
/**
* @see https://github.com/zendframework/zend-hydrator for the canonical source repository
* @copyright Copyright (c) 2010-2018 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-hydrator/blob/master/LICENSE.md New BSD License
*/
declare(strict_types=1);
namespace Zend\Hydrator\Strategy;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
final class DateTimeImmutableFormatterStrategy implements StrategyInterface
{
/**
* @var DateTimeFormatterStrategy
*/
private $dateTimeStrategy;
/**
* DateTimeImmutableFormatterStrategy constructor.
* @param DateTimeFormatterStrategy $dateTimeStrategy
*/
public function __construct(DateTimeFormatterStrategy $dateTimeStrategy)
{
$this->dateTimeStrategy = $dateTimeStrategy;
}
/**
* {@inheritDoc}
*
* Converts to date time string
*
* @param mixed|DateTimeInterface $value
* @return mixed|string If a non-DateTimeInterface $value is provided, it
* will be returned unmodified; otherwise, it will be extracted to a
* string.
*/
public function extract($value, ?object $object = null)
{
return $this->dateTimeStrategy->extract($value, $object);
}
/**
* Converts date time string to DateTimeImmutable instance for injecting to object
*
* {@inheritDoc}
*
* @param mixed|string $value
* @return mixed|DateTimeInterface
* @throws Exception\InvalidArgumentException if $value is not null, not a
* string, nor a DateTimeInterface.
*/
public function hydrate($value, ?array $data = null)
{
if ($value instanceof DateTimeImmutable) {
return $value;
}
$hydrated = $this->dateTimeStrategy->hydrate($value, $data);
if ($hydrated instanceof DateTime) {
return DateTimeImmutable::createFromMutable($hydrated);
}
if ($hydrated instanceof DateTimeInterface) {
return DateTimeImmutable::createFromFormat(
DateTimeInterface::RFC3339_EXTENDED,
$hydrated->format(DateTimeInterface::RFC3339_EXTENDED)
);
}
return $hydrated ?: $value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment