Skip to content

Commit

Permalink
Merge pull request #28 from okazy/fix/datetime-field
Browse files Browse the repository at this point in the history
日付を取得できるようにした
  • Loading branch information
Kiyotaka Oku committed Jul 17, 2020
2 parents 92d682e + 9968e59 commit b07a2c9
Show file tree
Hide file tree
Showing 2 changed files with 90 additions and 1 deletion.
88 changes: 88 additions & 0 deletions GraphQL/Type/Definition/DateTimeType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

/*
* This file is part of EC-CUBE
*
* Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
*
* http://www.ec-cube.co.jp/
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Plugin\Api\GraphQL\Type\Definition;

use DateTime;
use DateTimeInterface;
use GraphQL\Error\InvariantViolation;
use GraphQL\Language\AST\Node;
use GraphQL\Language\AST\StringValueNode;
use GraphQL\Type\Definition\ScalarType;
use GraphQL\Utils\Utils;

class DateTimeType extends ScalarType
{
private static $DateTimeType;

/**
* @var string
*/
public $name = 'DateTime';

/**
* @var string
*/
public $description = 'The `DateTime` scalar type represents time data, represented as an ISO-8601 encoded UTC date string.';

/**
* @param mixed $value
*
* @return string
*/
public function serialize($value)
{
if (!$value instanceof DateTimeInterface) {
throw new InvariantViolation('DateTime is not an instance of DateTimeInterface: '.Utils::printSafe($value));
}

return $value->format(DateTime::ATOM);
}

/**
* @param mixed $value
*
* @return DateTime|false|null
*/
public function parseValue($value)
{
return DateTime::createFromFormat(DateTime::ATOM, $value) ?: null;
}

/**
* @param Node $valueNode
* @param array|null $variables
*
* @return string|null
*/
public function parseLiteral($valueNode, ?array $variables = null)
{
if ($valueNode instanceof StringValueNode) {
return $valueNode->value;
}

return null;
}

/**
* @api
*/
public static function DateTime(): ScalarType
{
if (static::$DateTimeType === null) {
static::$DateTimeType = new DateTimeType();
}

return static::$DateTimeType;
}
}
3 changes: 2 additions & 1 deletion GraphQL/Types.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Doctrine\ORM\Mapping\ClassMetadata;
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use Plugin\Api\GraphQL\Type\Definition\DateTimeType;

/**
* DoctrineのEntityからGraphQLのObjectTypeを変換するクラス.
Expand Down Expand Up @@ -108,7 +109,7 @@ private function convertFieldMappingToType($fieldMapping)
'text' => Type::string(),
'integer' => Type::int(),
'decimal' => Type::float(),
'datetimetz' => Type::int(),
'datetimetz' => DateTimeType::DateTime(),
'smallint' => Type::int(),
'boolean' => Type::boolean(),
][$fieldMapping['type']];
Expand Down

0 comments on commit b07a2c9

Please sign in to comment.