You are here

protected function RestfulEntityBase::getEntityIdByFieldId in RESTful 7

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

RestfulBadRequestException

RestfulUnprocessableEntityException

2 calls to RestfulEntityBase::getEntityIdByFieldId()
RestfulEntityBase::updateEntity in plugins/restful/RestfulEntityBase.php
Update an entity.
RestfulEntityBase::viewEntity in plugins/restful/RestfulEntityBase.php
View an entity.

File

plugins/restful/RestfulEntityBase.php, line 1538
Contains RestfulEntityBase.

Class

RestfulEntityBase
An abstract implementation of RestfulEntityInterface.

Code

protected function getEntityIdByFieldId($id) {
  $request = $this
    ->getRequest();
  if (empty($request['loadByFieldName'])) {

    // The regular entity ID was provided.
    return $id;
  }
  $public_property_name = $request['loadByFieldName'];

  // We need to get the internal field/property from the public name.
  $public_fields = $this
    ->getPublicFields();
  if (!($public_field_info = $public_fields[$public_property_name]) || empty($public_field_info['property'])) {
    throw new \RestfulBadRequestException(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.
  if (static::propertyIsField($public_field_info['property'])) {
    $query
      ->fieldCondition($public_field_info['property'], $public_field_info['column'], $id);
  }
  else {
    $query
      ->propertyCondition($public_field_info['property'], $id);
  }

  // Execute the query and gather the results.
  $result = $query
    ->execute();
  if (empty($result[$this
    ->getEntityType()])) {
    throw new RestfulUnprocessableEntityException(format_string('The entity ID @id by @name for @resource cannot be loaded.', array(
      '@id' => $id,
      '@resource' => $this
        ->getPluginKey('label'),
      '@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
    ->getEntityType()]);

  // REST requires a canonical URL for every resource.
  $this
    ->addHttpHeaders('Link', $this
    ->versionedUrl($entity_id, array(), FALSE) . '; rel="canonical"');
  return $entity_id;
}