You are here

public function AnnotationNormalizer::normalize in JSON-RPC 2.x

Same name and namespace in other branches
  1. 8 modules/jsonrpc_discovery/src/Normalizer/AnnotationNormalizer.php \Drupal\jsonrpc_discovery\Normalizer\AnnotationNormalizer::normalize()

File

modules/jsonrpc_discovery/src/Normalizer/AnnotationNormalizer.php, line 42

Class

AnnotationNormalizer
The normalizer class for annotated objects.

Namespace

Drupal\jsonrpc_discovery\Normalizer

Code

public function normalize($object, $format = NULL, array $context = []) {
  $attributes = [];
  foreach ($object as $key => $value) {
    switch ($key) {
      case 'id':
      case 'call':
      case 'access':
        break;
      default:
        $child = $value instanceof AnnotationInterface ? $value
          ->get() : $value;
        if (isset($context[static::DEPTH_KEY]) && $child instanceof AnnotationInterface || is_array($child) && Inspector::assertAllObjects($child, AnnotationInterface::class)) {
          if ($context[static::DEPTH_KEY] === 0) {
            break;
          }
          $context[static::DEPTH_KEY] -= 1;
        }
        $attributes[$key] = $this->serializer
          ->normalize($child, $format, $context);
    }
  }
  $normalized = [
    'type' => static::getAnnotationType($object),
    'id' => $object
      ->getId(),
    'attributes' => array_filter($attributes),
  ];
  if ($object instanceof JsonRpcMethod) {
    $self = Url::fromRoute('jsonrpc.method_resource', [
      'method_id' => $object
        ->id(),
    ])
      ->setAbsolute()
      ->toString(TRUE);
    $collection = Url::fromRoute('jsonrpc.method_collection')
      ->setAbsolute()
      ->toString(TRUE);
    $this
      ->addCacheableDependency($context, $self);
    $this
      ->addCacheableDependency($context, $collection);
    $normalized['links'] = [
      'self' => $self
        ->getGeneratedUrl(),
      'collection' => $collection
        ->getGeneratedUrl(),
    ];
  }
  if ($object instanceof JsonRpcParameterDefinition) {
    $normalized['schema'] = $object
      ->getSchema();
  }
  return $normalized;
}