didix16/php-datatransformer

一个简单的库,允许将任何类型的数据转换为原生PHP数据或其他类型。

1.0.1 2021-08-11 08:54 UTC

This package is auto-updated.

Last update: 2024-09-11 15:22:07 UTC


README

一个简单的库,允许将任何类型的数据转换为原生PHP数据或其他类型。

内容

什么是DataTransformer

它只是一个抽象层,用于在两种数据类型之间转换数据。非常适合那些在您的系统和接收到的数据之间进行API桥梁数据转换的场景。

它可以处理json接收到的数据,并将其转换为类或其他类型。

安装

composer require didix16/php-datatransformer

使用

如何使用它的示例。这是一个转换器,它获取一个字符串数据值并将其转换为PHP DateTime。

use didix16\DataTransformer\DataTransformer;

class DateTransformer extends DataTransformer {

    const FORMATS = [
        DateTimeInterface::ATOM,
        DateTimeInterface::COOKIE,
        DateTimeInterface::ISO8601,
        DateTimeInterface::RFC822,
        DateTimeInterface::RFC850,
        DateTimeInterface::RFC1036,
        DateTimeInterface::RFC1123,
        DateTimeInterface::RFC2822,
        DateTimeInterface::RFC3339,
        DateTimeInterface::RFC3339_EXTENDED,
        DateTimeInterface::RSS,
        DateTimeInterface::W3C
    ];

    /**
     * @var string
     */
    protected $fromFormat;

    /**
     * @var DateTimeZone
     */
    protected $toTimezone;

    public function __construct($fromFormat='Y-m-d', $toTimezone= 'Europe/Madrid')
    {
        $this->fromFormat = $fromFormat;
        $this->toTimezone = new DateTimeZone($toTimezone);
    }

    protected function transform(&$value)
    {
        if(empty($value)){
            $value = null;
            return;
        }

        $date = $this->convertToDate($value);
        if($this->assertClass($date, DateTime::class)){

            $this->dateToTimezone($date);
            $value = $date;
        } else {
            throw new Exception(
                sprintf("An error was ocurred while transforming the value '%s' into date:\n
                Expected to be an instance of '%s', founded '%s'", $value, DateTime::class, gettype($date))
            );
        }
    }

    /**
     * Tries to convert the passed value to a date by checking all possible DateTimeInterface formats first.
     * If no one satisfies then try using the specified format at constructor
     */
    private function convertToDate(&$value){

        foreach(self::FORMATS as $format){

            $t = DateTime::createFromFormat($format, $value);
            if($t) return $t;
        }

        try {
            return new DateTime($value);
        } catch(Exception $e){
            return DateTime::createFromFormat($this->fromFormat, $value);
        }
    }

    private function dateToTimezone(DateTime &$value){

        $currentTimezone = $value->getTimezone()->getName();
        $toTimezone = $this->toTimezone->getName();

        if($currentTimezone !== $toTimezone){
            $value->setTimezone($this->toTimezone);
        }
    }

}