You are here

protected function DataProviderEntity::getEntityIdByFieldId in RESTful 7.2

Get the entity ID based on the ID provided in the request.

As any field may be used as the ID, we convert it to the numeric internal ID of the entity

Parameters

mixed $id: The provided ID.

Return value

int The entity ID.

Throws

BadRequestException

UnprocessableEntityException

4 calls to DataProviderEntity::getEntityIdByFieldId()
DataProviderEntity::getCacheFragments in src/Plugin/resource/DataProvider/DataProviderEntity.php
Gets the entity context.
DataProviderEntity::initDataInterpreter in src/Plugin/resource/DataProvider/DataProviderEntity.php
Get the data interpreter.
DataProviderEntity::update in src/Plugin/resource/DataProvider/DataProviderEntity.php
Update operation.
DataProviderEntity::view in src/Plugin/resource/DataProvider/DataProviderEntity.php
Read operation.

File

src/Plugin/resource/DataProvider/DataProviderEntity.php, line 429
Contains \Drupal\restful\Plugin\resource\DataProvider\DataProviderEntity.

Class

DataProviderEntity
Class DataProviderEntity.

Namespace

Drupal\restful\Plugin\resource\DataProvider

Code

protected function getEntityIdByFieldId($id) {
  $request = $this
    ->getRequest();
  $input = $request
    ->getParsedInput();
  $public_property_name = empty($input['loadByFieldName']) ? NULL : $input['loadByFieldName'];
  $public_property_name = $public_property_name ?: (empty($this->options['idField']) ? NULL : $this->options['idField']);
  if (!$public_property_name) {

    // The regular entity ID was provided.
    return $id;
  }

  // We need to get the internal field/property from the public name.
  if (!($public_field_info = $this->fieldDefinitions
    ->get($public_property_name)) || !$public_field_info
    ->getProperty()) {
    throw new BadRequestException(format_string('Cannot load an entity using the field "@name"', array(
      '@name' => $public_property_name,
    )));
  }
  $query = $this
    ->getEntityFieldQuery();
  $query
    ->range(0, 1);

  // Find out if the provided ID is a Drupal field or an entity property.
  $property = $public_field_info
    ->getProperty();

  /* @var ResourceFieldEntity $public_field_info */
  if (ResourceFieldEntity::propertyIsField($property)) {
    $query
      ->fieldCondition($property, $public_field_info
      ->getColumn(), $id);
  }
  else {
    $query
      ->propertyCondition($property, $id);
  }

  // Execute the query and gather the results.
  $result = $query
    ->execute();
  if (empty($result[$this->entityType])) {
    throw new UnprocessableEntityException(format_string('The entity ID @id by @name cannot be loaded.', array(
      '@id' => $id,
      '@name' => $public_property_name,
    )));
  }

  // There is nothing that guarantees that there is only one result, since
  // this is user input data. Return the first ID.
  $entity_id = key($result[$this->entityType]);
  return $entity_id;
}