You are here

public function RestGenerator::getDefinitions in OpenAPI 8

Get model definitions for Drupal entities and bundles.

Return value

array The model definitions.

Overrides OpenApiGeneratorBase::getDefinitions

File

src/Plugin/openapi/OpenApiGenerator/RestGenerator.php, line 65

Class

RestGenerator
Defines an OpenApi Schema Generator for the Rest module.

Namespace

Drupal\openapi\Plugin\openapi\OpenApiGenerator

Code

public function getDefinitions() {
  $bundle_name = isset($this
    ->getOptions()['bundle_name']) ? $this
    ->getOptions()['bundle_name'] : NULL;
  $entity_type_id = isset($this
    ->getOptions()['entity_type_id']) ? $this
    ->getOptions()['entity_type_id'] : NULL;
  static $definitions = [];
  if (!$definitions) {
    $entity_types = $this
      ->getRestEnabledEntityTypes($entity_type_id);
    $definitions = [];
    foreach ($entity_types as $entity_id => $entity_type) {
      $entity_schema = $this
        ->getJsonSchema('json', $entity_id);
      $definitions[$entity_id] = $entity_schema;
      if ($bundle_type = $entity_type
        ->getBundleEntityType()) {
        $bundle_storage = $this->entityTypeManager
          ->getStorage($bundle_type);
        if ($bundle_name) {
          $bundles[$bundle_name] = $bundle_storage
            ->load($bundle_name);
        }
        else {
          $bundles = $bundle_storage
            ->loadMultiple();
        }
        foreach ($bundles as $bundle => $bundle_data) {
          $bundle_schema = $this
            ->getJsonSchema('json', $entity_id, $bundle);
          foreach ($entity_schema['properties'] as $property_id => $property) {
            if (isset($bundle_schema['properties'][$property_id]) && $bundle_schema['properties'][$property_id] === $property) {

              // Remove any bundle schema property that is the same as the
              // entity schema property.
              unset($bundle_schema['properties'][$property_id]);
            }
          }

          // Use Open API polymorphism support to show that bundles extend
          // entity type.
          // @todo Should base fields be removed from bundle schema?
          // @todo Can base fields could be different from entity type base fields?
          // @see hook_entity_bundle_field_info().
          // @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#models-with-polymorphism-support
          $definitions[$this
            ->getEntityDefinitionKey($entity_type
            ->id(), $bundle)] = [
            'allOf' => [
              [
                '$ref' => "#/definitions/{$entity_id}",
              ],
              $bundle_schema,
            ],
          ];
        }
      }
    }
  }
  return $definitions;
}