You are here

protected function RestfulCreateEntityTestCase::fileResource in RESTful 7.2

Uploads a file issuing a POST HTTP request.

Return value

\Drupal\restful\Plugin\resource\ResourceInterface The file resource.

Throws

\Drupal\restful\Exception\BadRequestException

\Drupal\restful\Exception\ServiceUnavailableException

1 call to RestfulCreateEntityTestCase::fileResource()
RestfulCreateEntityTestCase::testFileUploadAccess in tests/RestfulCreateEntityTestCase.test
Test access for file upload.

File

tests/RestfulCreateEntityTestCase.test, line 262
Contains RestfulCreateEntityTestCase

Class

RestfulCreateEntityTestCase
Class RestfulCreateEntityTestCase.

Code

protected function fileResource() {

  // We are setting the $_FILES array directly on tests, so we need to
  // override the is_uploaded_file PHP method by setting a custom variable.
  // Otherwise the manually set file will not be detected.
  variable_set('restful_insecure_uploaded_flag', TRUE);

  // Clear the plugin definition cache to regenerate authenticationOptional
  // based on the variable value.
  $resource_manager = restful()
    ->getResourceManager();
  $resource_manager
    ->clearPluginCache('files_upload_test:1.0');
  if (!($handler = $resource_manager
    ->getPlugin('files_upload_test:1.0'))) {
    throw new \Drupal\restful\Exception\ServiceUnavailableException();
  }
  $plugin_definition = $handler
    ->getPluginDefinition();
  $plugin_definition['authenticationOptional'] = variable_get('restful_file_upload_allow_anonymous_user', FALSE);
  $handler
    ->setPluginDefinition($plugin_definition);
  $account = $this->account;
  if (!$this->loggedInUser) {
    $account = drupal_anonymous_user();
  }
  $handler
    ->setAccount($account);

  // Due to entity_metadata_file_access we need to set the global user to the
  // user for the test.
  $GLOBALS['user'] = $account;
  $value = '@' . $this->imagePath;

  // PHP 5.5 introduced a CurlFile object that deprecates the old @filename
  // syntax. See: https://wiki.php.net/rfc/curl-file-upload
  if (function_exists('curl_file_create')) {
    $value = curl_file_create($this->imagePath);
  }
  $tmp_name = drupal_tempnam('/tmp', 'restful_test_');
  file_put_contents($tmp_name, file_get_contents($this->imagePath));
  $headers = new \Drupal\restful\Http\HttpHeaderBag(array(
    'Content-Type' => 'multipart/form-data',
  ));

  // Mock the $_FILES global variable.
  $files = array(
    'my-filename' => array(
      'error' => 0,
      'name' => basename($this->imagePath),
      'size' => filesize($this->imagePath),
      'tmp_name' => $tmp_name,
      'type' => 'image/png',
    ),
  );
  $handler
    ->setRequest(Request::create('api/file-upload', array(), RequestInterface::METHOD_POST, $headers, FALSE, NULL, array(), $files, array(), array(
    'filename' => $value,
  )));
  $handler
    ->setPath('');
  return $handler;
}