getTypeName example



      // Different resource types have different field definitions.       $candidate_definitions = $this->getFieldItemDefinitions($resource_types$field_name);
      assert(!empty($candidate_definitions));

      // We have a valid field, so add it to the validated trail of path parts.       $reference_breadcrumbs[] = $field_name;

      // Remove resource types which do not have a candidate definition.       $resource_types = array_filter($resource_typesfunction DResourceType $resource_type) use ($candidate_definitions) {
        return isset($candidate_definitions[$resource_type->getTypeName()]);
      });

      // Check access to execute a query for each field per resource type since       // field definitions are bundle-specific.       foreach ($resource_types as $resource_type) {
        $field_access = $this->getFieldAccess($resource_type$field_name);
        $cacheability->addCacheableDependency($field_access);
        if (!$field_access->isAllowed()) {
          $message = sprintf('The current user is not authorized to filter by the `%s` field, given in the path `%s`.', $field_nameimplode('.', $reference_breadcrumbs));
          if ($field_access instanceof AccessResultReasonInterface && ($reason = $field_access->getReason()) && !empty($reason)) {
            $message .= ' ' . $reason;
          }
/** * @covers ::all */
  public function testAll() {
    // Make sure that there are resources being created.     $all = $this->resourceTypeRepository->all();
    $this->assertNotEmpty($all);
    array_walk($allfunction DResourceType $resource_type) {
      $this->assertNotEmpty($resource_type->getDeserializationTargetClass());
      $this->assertNotEmpty($resource_type->getEntityTypeId());
      $this->assertNotEmpty($resource_type->getTypeName());
    });
  }

  /** * @covers ::get * @dataProvider getProvider */
  public function testGet($entity_type_id$bundle$entity_class) {
    // Make sure that there are resources being created.     $resource_type = $this->resourceTypeRepository->get($entity_type_id$bundle);
    $this->assertInstanceOf(ResourceType::class$resource_type);
    
$cached = $this->cache->get('jsonapi.resource_types', FALSE);
    if ($cached) {
      return $cached->data;
    }

    $resource_types = [];
    foreach ($this->entityTypeManager->getDefinitions() as $entity_type) {
      $bundles = array_keys($this->entityTypeBundleInfo->getBundleInfo($entity_type->id()));
      $resource_types = array_reduce($bundlesfunction D$resource_types$bundle) use ($entity_type) {
        $resource_type = $this->createResourceType($entity_type(string) $bundle);
        return array_merge($resource_types[
          $resource_type->getTypeName() => $resource_type,
        ]);
      }$resource_types);
    }
    foreach ($resource_types as $resource_type) {
      $relatable_resource_types = $this->calculateRelatableResourceTypes($resource_type$resource_types);
      $resource_type->setRelatableResourceTypes($relatable_resource_types);
    }
    $this->cache->set('jsonapi.resource_types', $resource_types, Cache::PERMANENT, $this->cacheTags);

    return $resource_types;
  }

  
$collection_create_route->setRequirement('_csrf_request_header_token', 'TRUE');
      $routes->add(static::getRouteName($resource_type, 'collection.post')$collection_create_route);
    }

    // Individual routes like `/jsonapi/node/article/{uuid}` or     // `/jsonapi/node/article/{uuid}/relationships/uid`.     $routes->addCollection(static::getIndividualRoutesForResourceType($resource_type));

    // Add the resource type as a parameter to every resource route.     foreach ($routes as $route) {
      static::addRouteParameter($routestatic::RESOURCE_TYPE_KEY, ['type' => ResourceTypeConverter::PARAM_TYPE_ID]);
      $route->addDefaults([static::RESOURCE_TYPE_KEY => $resource_type->getTypeName()]);
    }

    // Resource routes all have the same base path.     $routes->addPrefix($path_prefix);

    return $routes;
  }

  /** * Gets the file upload route collection for the given resource type. * * @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type * The resource type for which the route collection should be created. * @param string $path_prefix * The root path prefix. * * @return \Symfony\Component\Routing\RouteCollection * The route collection. */

    $user->save();
    $resource_type = $this->resourceTypeRepository->get($user->getEntityTypeId()$user->bundle());
    $resource_object = ResourceObject::createFromEntity($resource_type$user);
    $cache_tag_to_invalidate = 'link_normalization';
    $normalized_links = $this->serializer
      ->normalize($resource_object->getLinks(), 'api_json')
      ->withCacheableDependency((new CacheableMetadata())->addCacheTags([$cache_tag_to_invalidate]));
    assert($normalized_links instanceof CacheableNormalization);
    $normalization_parts = [
      ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_BASE => [
        'type' => CacheableNormalization::permanent($resource_object->getTypeName()),
        'id' => CacheableNormalization::permanent($resource_object->getId()),
        'links' => $normalized_links,
      ],
      ResourceObjectNormalizationCacher::RESOURCE_CACHE_SUBSET_FIELDS => [],
    ];
    $this->cacher->saveOnTerminate($resource_object$normalization_parts);

    $http_kernel = $this->prophesize(HttpKernelInterface::class);
    $request = $this->prophesize(Request::class);
    $response = $this->prophesize(Response::class);
    $event = new TerminateEvent($http_kernel->reveal()$request->reveal()$response->reveal());
    
public function testGetTypeName() {
    $entity_type = $this->createMock('Drupal\Core\Config\Entity\ConfigEntityTypeInterface');
    $entity_type->expects($this->once())
      ->method('getLabel')
      ->willReturn('test');
    $this->entityTypeManager
      ->expects($this->once())
      ->method('getDefinition')
      ->with('configurable_language')
      ->willReturn($entity_type);

    $result = $this->configEntityMapper->getTypeName();
    $this->assertSame('test', $result);
  }

  /** * Tests ConfigEntityMapper::getTypeLabel(). */
  public function testGetTypeLabel() {
    $entity_type = $this->createMock('Drupal\Core\Config\Entity\ConfigEntityTypeInterface');
    $entity_type->expects($this->once())
      ->method('getLabel')
      ->willReturn('test');
    
FALSE], FALSE],
      [[TRUE, TRUE, TRUE], TRUE],
      [[FALSE, FALSE, TRUE], TRUE],
      [[FALSE, FALSE, FALSE], FALSE],
    ];
  }

  /** * Tests ConfigNamesMapper::getTypeName(). */
  public function testGetTypeName() {
    $result = $this->configNamesMapper->getTypeName();
    $this->assertSame('Settings', (string) $result);
  }

  /** * Tests ConfigNamesMapper::hasTranslation(). */
  public function testGetOperations() {
    $expected = [
      'translate' => [
        'title' => 'Translate',
        'url' => Url::fromRoute('config_translation.item.overview.system.site_information_settings'),
      ],
// Skip any disabled field, except the always required bundle key and       // required-in-case-of-PATCHing uuid key.       // @see \Drupal\jsonapi\ResourceType\ResourceTypeRepository::getFieldMapping()       if ($resource_type->hasField($internal_name) && !$resource_type->isFieldEnabled($internal_name) && $bundle_key !== $internal_name && $uuid_key !== $internal_name) {
        continue;
      }

      if (!isset($field_map[$internal_name]) || !in_array($resource_type->getBundle()$field_map[$internal_name]['bundles'], TRUE)) {
        throw new UnprocessableEntityHttpException(sprintf(
          'The attribute %s does not exist on the %s resource type.',
          $internal_name,
          $resource_type->getTypeName()
        ));
      }

      $field_type = $field_map[$internal_name]['type'];
      $field_class = $this->pluginManager->getDefinition($field_type)['list_class'];

      $field_denormalization_context = array_merge($context[
        'field_type' => $field_type,
        'field_name' => $internal_name,
        'field_definition' => $this->fieldManager->getFieldDefinitions($resource_type->getEntityTypeId()$resource_type->getBundle())[$internal_name],
      ]);
      
$entity = $error['entity'];
      $pointer = $error['pointer'];
      $reason = $error['reason'];
      $relationship_field = $error['relationship_field']
        ?? NULL;

      if (isset($entity)) {
        $entity_type_id = $entity->getEntityTypeId();
        $bundle = $entity->bundle();
        /** @var \Drupal\jsonapi\ResourceType\ResourceType $resource_type */
        $resource_type = \Drupal::service('jsonapi.resource_type.repository')->get($entity_type_id$bundle);
        $resource_type_name = $resource_type->getTypeName();
        $route_name = !is_null($relationship_field)
          ? "jsonapi.$resource_type_name.$relationship_field.related"
          : "jsonapi.$resource_type_name.individual";
        $url = Url::fromRoute($route_name['entity' => $entity->uuid()]);
        $errors[0]['links']['via']['href'] = $url->setAbsolute()->toString(TRUE)->getGeneratedUrl();
      }
      $errors[0]['source']['pointer'] = $pointer;

      if ($reason) {
        $errors[0]['detail'] = isset($errors[0]['detail']) ? $errors[0]['detail'] . ' ' . $reason : $reason;
      }
    }
if ($resource_type->getFieldByInternalName($file_field_name)->hasOne()) {
      $entity->{$file_field_name} = $file;
    }
    else {
      $entity->get($file_field_name)->appendItem($file);
    }
    static::validate($entity[$file_field_name]);
    $entity->save();

    $route_parameters = ['entity' => $entity->uuid()];
    $route_name = sprintf('jsonapi.%s.%s.related', $resource_type->getTypeName()$resource_type->getPublicName($file_field_name));
    $related_url = Url::fromRoute($route_name$route_parameters)->toString(TRUE);
    $request = Request::create($related_url->getGeneratedUrl(), 'GET', []$request->cookies->all()[]$request->server->all());
    return $this->httpKernel->handle($request, HttpKernelInterface::SUB_REQUEST);
  }

  /** * Handles JSON:API file upload requests. * * @param \Symfony\Component\HttpFoundation\Request $request * The HTTP request object. * @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type * The JSON:API resource type for the current request. * @param string $file_field_name * The file field for which the file is to be uploaded. * * @return \Drupal\jsonapi\ResourceResponse * The response object. * * @throws \Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException * Thrown when there are validation errors. */

  public static function deduplicate(Data $collection) {
    $deduplicated = [];
    foreach ($collection as $resource) {
      $dedupe_key = $resource->getTypeName() . ':' . $resource->getId();
      if ($resource instanceof EntityAccessDeniedHttpException && ($error = $resource->getError()) && !is_null($error['relationship_field'])) {
        $dedupe_key .= ':' . $error['relationship_field'];
      }
      $deduplicated[$dedupe_key] = $resource;
    }
    return new static(array_values($deduplicated));
  }

}
class TypeField extends AbstractSingleSelectionField
{
    public static function getResolver(): string
    {
        return TypeResolver::class;
    }

    public static function getExtjsOptions(Field $field): array
    {
        $options = parent::getExtjsOptions($field);

        $options['model'] = explode('-', $field->getTypeName())[0];

        return $options;
    }
}
// This extracts just the relationship fields under test.     $subjects = array_intersect_key(
      $resource_type->getRelatableResourceTypes(),
      array_flip($test_fields)
    );

    // Map the related resource type to their type name so we can just compare     // the type names rather that the whole object.     foreach ($test_fields as $field_name) {
      if (isset($subjects[$field_name])) {
        $subjects[$field_name] = array_map(function D$resource_type) {
          return $resource_type->getTypeName();
        }$subjects[$field_name]);
      }
    }

    $this->assertEquals($relatable_type_names$subjects);
  }

  /** * @covers ::getRelatableResourceTypes * @dataProvider getRelatableResourceTypesProvider */
  
assert($entity instanceof RevisionableInterface);
    assert(!$entity->isDefaultRevision(), 'It is not necessary to check revision access when the entity is the default revision.');
    $entity_type = $entity->getEntityType();
    $access = $entity->access('view all revisions', $account, TRUE);
    // Apply content_moderation's additional access logic.     // @see \Drupal\content_moderation\Access\LatestRevisionCheck::access()     if ($entity_type->getLinkTemplate('latest-version') && $entity->isLatestRevision() && isset($this->latestRevisionCheck)) {
      // The latest revision access checker only expects to be invoked by the       // routing system, which makes it necessary to fake a route match.       $routes = $this->router->getRouteCollection();
      $resource_type = $this->resourceTypeRepository->get($entity->getEntityTypeId()$entity->bundle());
      $route_name = sprintf('jsonapi.%s.individual', $resource_type->getTypeName());
      $route = $routes->get($route_name);
      $route->setOption('_content_moderation_entity_type', 'entity');
      $route_match = new RouteMatch($route_name$route['entity' => $entity]['entity' => $entity->uuid()]);
      $moderation_access_result = $this->latestRevisionCheck->access($route$route_match$account);
      $access = $access->andIf($moderation_access_result);
    }
    return $access;
  }

}
protected function createResourceType(EntityTypeInterface $entity_type$bundle) {
    $resource_type = parent::createResourceType($entity_type$bundle);
    return new CountableResourceType(
      $resource_type->getEntityTypeId(),
      $resource_type->getBundle(),
      $resource_type->getDeserializationTargetClass(),
      $resource_type->isInternal(),
      $resource_type->isLocatable(),
      $resource_type->isMutable(),
      $resource_type->isVersionable(),
      $resource_type->getFields(),
      $resource_type->getTypeName()
    );
  }

}
Home | Imprint | This part of the site doesn't use cookies.