|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Overblog\GraphQLBundle\Definition\Type; |
| 4 | + |
| 5 | +use GraphQL\Type\Definition\CustomScalarType as BaseCustomScalarType; |
| 6 | +use GraphQL\Type\Definition\ScalarType; |
| 7 | +use GraphQL\Utils\Utils; |
| 8 | + |
| 9 | +class CustomScalarType extends BaseCustomScalarType |
| 10 | +{ |
| 11 | + public function __construct(array $config = []) |
| 12 | + { |
| 13 | + $config['name'] = isset($config['name']) ? $config['name'] : uniqid('CustomScalar'); |
| 14 | + parent::__construct($config); |
| 15 | + |
| 16 | + $this->config['scalarType'] = isset($this->config['scalarType']) ? $this->config['scalarType'] : null; |
| 17 | + $this->initOptionalFunctions(); |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * {@inheritdoc} |
| 22 | + */ |
| 23 | + public function serialize($value) |
| 24 | + { |
| 25 | + return $this->call('serialize', $value); |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * {@inheritdoc} |
| 30 | + */ |
| 31 | + public function parseValue($value) |
| 32 | + { |
| 33 | + return $this->call('parseValue', $value); |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * {@inheritdoc} |
| 38 | + */ |
| 39 | + public function parseLiteral(/* GraphQL\Language\AST\ValueNode */ $valueNode) |
| 40 | + { |
| 41 | + return $this->call('parseLiteral', $valueNode); |
| 42 | + } |
| 43 | + |
| 44 | + private function call($type, $value) |
| 45 | + { |
| 46 | + if (isset($this->config['scalarType'])) { |
| 47 | + $scalarType = $this->config['scalarType']; |
| 48 | + $scalarType = is_callable($scalarType) ? $scalarType() : $scalarType; |
| 49 | + |
| 50 | + return call_user_func([$scalarType, $type], $value); |
| 51 | + } else { |
| 52 | + return parent::$type($value); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + private function initOptionalFunctions() |
| 57 | + { |
| 58 | + foreach (['parseLiteral', 'parseValue'] as $field) { |
| 59 | + if (!isset($this->config[$field])) { |
| 60 | + $this->config[$field] = static function () { |
| 61 | + return null; |
| 62 | + }; |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + public function assertValid() |
| 68 | + { |
| 69 | + if (isset($this->config['scalarType'])) { |
| 70 | + $scalarType = $this->config['scalarType']; |
| 71 | + if (is_callable($scalarType)) { |
| 72 | + $scalarType = $scalarType(); |
| 73 | + } |
| 74 | + |
| 75 | + Utils::invariant( |
| 76 | + $scalarType instanceof ScalarType, |
| 77 | + sprintf( |
| 78 | + '%s must provide a valid "scalarType" instance of %s but got: %s', |
| 79 | + $this->name, |
| 80 | + ScalarType::class, |
| 81 | + Utils::printSafe($scalarType) |
| 82 | + ) |
| 83 | + ); |
| 84 | + } else { |
| 85 | + parent::assertValid(); |
| 86 | + } |
| 87 | + } |
| 88 | +} |
0 commit comments