You are here

public function DataProviderDbQuery::create in RESTful 7.2

Create operation.

Parameters

mixed $object: The thing to be created.

Return value

array An array of structured data for the thing that was created.

Overrides CrudInterface::create

File

src/Plugin/resource/DataProvider/DataProviderDbQuery.php, line 159
Contains \Drupal\restful\Plugin\resource\DataProvider\DataProviderDbQuery.

Class

DataProviderDbQuery

Namespace

Drupal\restful\Plugin\resource\DataProvider

Code

public function create($object) {
  $save = FALSE;
  $original_object = $object;
  $id_columns = $this
    ->getIdColumn();
  $record = array();
  foreach ($this->fieldDefinitions as $public_field_name => $resource_field) {

    /* @var ResourceFieldDbColumnInterface $resource_field */
    if (!$this
      ->methodAccess($resource_field)) {

      // Allow passing the value in the request.
      unset($original_object[$public_field_name]);
      continue;
    }
    $property_name = $resource_field
      ->getProperty();

    // If this is the primary field, skip.
    if ($this
      ->isPrimaryField($property_name)) {
      unset($original_object[$public_field_name]);
      continue;
    }
    if (isset($object[$public_field_name])) {
      $record[$property_name] = $object[$public_field_name];
    }
    unset($original_object[$public_field_name]);
    $save = TRUE;
  }

  // No request was sent.
  if (!$save) {
    throw new BadRequestException('No values were sent with the request.');
  }

  // If the original request is not empty, then illegal values are present.
  if (!empty($original_object)) {
    $error_message = format_plural(count($original_object), 'Property @names is invalid.', 'Property @names are invalid.', array(
      '@names' => implode(', ', array_keys($original_object)),
    ));
    throw new BadRequestException($error_message);
  }

  // Once the record is built, write it and view it.
  if (drupal_write_record($this
    ->getTableName(), $record)) {

    // Handle multiple id columns.
    $id_values = array();
    foreach ($id_columns as $id_column) {
      $id_values[$id_column] = $record[$id_column];
    }
    $new_id = implode(self::COLUMN_IDS_SEPARATOR, $id_values);
    return array(
      $this
        ->view($new_id),
    );
  }
  return NULL;
}