vendor/overblog/graphql-bundle/src/Definition/Type/CustomScalarType.php line 48

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