You are here

public function DataProviderFile::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 DataProviderEntity::create

File

src/Plugin/resource/DataProvider/DataProviderFile.php, line 44
Contains \Drupal\restful\Plugin\resource\DataProvider\DataProviderFile.

Class

DataProviderFile
Class DataProviderFile.

Namespace

Drupal\restful\Plugin\resource\DataProvider

Code

public function create($object) {
  $files = $this
    ->getRequest()
    ->getFiles();
  if (!$files) {
    throw new BadRequestException('No files sent with the request.');
  }
  $ids = array();
  foreach ($files as $file_info) {

    // Populate the $_FILES the way file_save_upload() expects.
    $name = $file_info['name'];
    foreach ($file_info as $key => $value) {
      $files['files'][$key][$name] = $value;
    }
    if (!($file = $this
      ->fileSaveUpload($name, $files))) {
      throw new BadRequestException('Unacceptable file sent with the request.');
    }

    // Required to be able to reference this file.
    file_usage_add($file, 'restful', 'files', $file->fid);
    $ids[] = $file->fid;
  }
  $return = array();
  foreach ($ids as $id) {

    // The access calls use the request method. Fake the view to be a GET.
    $old_request = $this
      ->getRequest();
    $this
      ->getRequest()
      ->setMethod(RequestInterface::METHOD_GET);
    try {
      $return[] = array(
        $this
          ->view($id),
      );
    } catch (ForbiddenException $e) {

      // A forbidden element should not forbid access to the whole list.
    }

    // Put the original request back to a POST.
    $this->request = $old_request;
  }
  return $return;
}