getAuthenticationRequestOptions example


  public function testPostIndividualDxWithoutCriticalBaseFields() {
    $this->setUpAuthorization('POST');
    $this->config('jsonapi.settings')->set('read_only', FALSE)->save(TRUE);

    $url = Url::fromRoute(sprintf('jsonapi.%s.collection.post', static::$resourceTypeName));
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
    $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions());

    $remove_field = function Darray $normalization$type$attribute_name) {
      unset($normalization['data'][$type][$attribute_name]);
      return $normalization;
    };

    // DX: 422 when missing 'entity_type' field.     $request_options[RequestOptions::BODY] = Json::encode($remove_field($this->getPostDocument(), 'attributes', 'entity_type'));
    $response = $this->request('POST', $url$request_options);
    $this->assertResourceErrorResponse(422, 'entity_type: This value should not be null.', NULL, $response, '/data/attributes/entity_type');

    
    $value = [
      'value' => $this->randomString(),
    ];
    if ($text_format_id !== FALSE) {
      $value['format'] = $text_format_id;
    }
    $this->entity->set('field_test_text', $value)->save();

    $this->initAuthentication();
    $url = $this->getEntityResourceUrl();
    $url->setOption('query', ['_format' => static::$format]);
    $request_options = $this->getAuthenticationRequestOptions('GET');
    $this->provisionEntityResource();
    $this->setUpAuthorization('GET');
    $response = $this->request('GET', $url$request_options);
    $expected_cache_tags = Cache::mergeTags($expected_cache_tags, parent::getExpectedCacheTags());
    $this->assertEqualsCanonicalizing($expected_cache_tagsexplode(' ', $response->getHeader('X-Drupal-Cache-Tags')[0]));
  }

  public function providerTestGetWithFormat() {
    return [
      'format specified (different from fallback format)' => [
        'pablo',
        [

  public function testCollectionFilterAccess() {
    $label_field_name = 'filename';
    // Verify the expected behavior in the common case: when the file is public.     $this->doTestCollectionFilterAccessBasedOnPermissions($label_field_name, 'access content');

    $collection_url = Url::fromRoute('jsonapi.entity_test--bar.collection');
    $collection_filter_url = $collection_url->setOption('query', ["filter[spotlight.$label_field_name]" => $this->entity->label()]);
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions());

    // 1 result because the current user is the file owner, even though the file     // is private.     $this->entity->setFileUri('private://drupal.txt');
    $this->entity->setOwner($this->account);
    $this->entity->save();
    $response = $this->request('GET', $collection_filter_url$request_options);
    $doc = Json::decode((string) $response->getBody());
    $this->assertCount(1, $doc['data']);

    // 0 results because the current user is no longer the file owner and the
'id' => 'alternate',
      'label' => 'Alternate',
    ]);
    $alternate_shortcut_set->save();
    $this->entity->shortcut_set = $alternate_shortcut_set->id();
    $this->entity->save();

    $collection_url = Url::fromRoute('jsonapi.entity_test--bar.collection');
    $collection_filter_url = $collection_url->setOption('query', ["filter[spotlight.$label_field_name]" => $this->entity->label()]);
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions());

    // No results because the current user does not have access to shortcuts     // not in the user's assigned set or the default set.     $response = $this->request('GET', $collection_filter_url$request_options);
    $doc = Json::decode((string) $response->getBody());
    $this->assertCount(0, $doc['data']);

    // Assign the alternate shortcut set to the current user.     $this->container->get('entity_type.manager')->getStorage('shortcut_set')->assignUser($alternate_shortcut_set$this->account);

    // 1 result because the alternate shortcut set is now assigned to the
/** @var \Drupal\user\UserInterface $user */
    $user = static::$auth ? $this->account : User::load(0);
    // @todo Remove the array_diff_key() call in https://www.drupal.org/node/2821077.     $original_normalization = array_diff_key($this->serializer->normalize($userstatic::$format)['created' => TRUE, 'changed' => TRUE, 'name' => TRUE]);

    // Since this test must be performed by the user that is being modified,     // we cannot use $this->getUrl().     $url = $user->toUrl()->setOption('query', ['_format' => static::$format]);
    $request_options = [
      RequestOptions::HEADERS => ['Content-Type' => static::$mimeType],
    ];
    $request_options = array_merge_recursive($request_options$this->getAuthenticationRequestOptions('PATCH'));

    // Test case 1: changing email.     $normalization = $original_normalization;
    $normalization['mail'] = [['value' => 'new-email@example.com']];
    $request_options[RequestOptions::BODY] = $this->serializer->encode($normalizationstatic::$format);

    // DX: 422 when changing email without providing the password.     $response = $this->request('PATCH', $url$request_options);
    $this->assertResourceErrorResponse(422, "Unprocessable Entity: validation failed.\nmail: Your current password is missing or incorrect; it's required to change the Email.\n", $response, FALSE, FALSE, FALSE, FALSE);

    $normalization['pass'] = [['existing' => 'wrong']];
    
$expected = $this->getExpectedDocument(2, 'example_0.txt');
    $this->assertResponseData($expected$response);

    // Check the actual file data.     $this->assertSame($this->testFileData, file_get_contents('public://foobar/example_0.txt'));
    $this->assertTrue($this->fileStorage->loadUnchanged(1)->isTemporary());

    // Verify that we can create an entity that references the uploaded file.     $entity_test_post_url = Url::fromRoute('jsonapi.entity_test--entity_test.collection.post');
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions());

    $request_options[RequestOptions::BODY] = Json::encode($this->getPostDocument());
    $response = $this->request('POST', $entity_test_post_url$request_options);
    $this->assertResourceResponse(201, FALSE, $response);
    $this->assertTrue($this->fileStorage->loadUnchanged(1)->isPermanent());
    $this->assertSame([
      [
        'target_id' => '1',
        'display' => NULL,
        'description' => "The most fascinating file ever!",
      ],
    ],
public function testPatchPath() {
    $this->setUpAuthorization('GET');
    $this->setUpAuthorization('PATCH');
    $this->config('jsonapi.settings')->set('read_only', FALSE)->save(TRUE);

    // @todo Remove line below in favor of commented line in https://www.drupal.org/project/drupal/issues/2878463.     $url = Url::fromRoute(sprintf('jsonapi.%s.individual', static::$resourceTypeName)['entity' => $this->entity->uuid()]);
    // $url = $this->entity->toUrl('jsonapi');     $request_options = [];
    $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
    $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions());

    // GET term's current normalization.     $response = $this->request('GET', $url$request_options);
    $normalization = Json::decode((string) $response->getBody());

    // Change term's path alias.     $normalization['data']['attributes']['path']['alias'] .= 's-rule-the-world';

    // Create term PATCH request.     $request_options[RequestOptions::BODY] = Json::encode($normalization);

    

  public function testPatchPath() {
    $this->setUpAuthorization('GET');
    $this->setUpAuthorization('PATCH');
    $this->config('jsonapi.settings')->set('read_only', FALSE)->save(TRUE);

    // @todo Remove line below in favor of commented line in https://www.drupal.org/project/drupal/issues/2878463.     $url = Url::fromRoute(sprintf('jsonapi.%s.individual', static::$resourceTypeName)['entity' => $this->entity->uuid()]);
    // $url = $this->entity->toUrl('jsonapi');
    // GET node's current normalization.     $response = $this->request('GET', $url$this->getAuthenticationRequestOptions());
    $normalization = Json::decode((string) $response->getBody());

    // Change node's path alias.     $normalization['data']['attributes']['path']['alias'] .= 's-rule-the-world';

    // Create node PATCH request.     $request_options = $this->getAuthenticationRequestOptions();
    $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
    $request_options[RequestOptions::BODY] = Json::encode($normalization);

    // PATCH request: 403 when creating URL aliases unauthorized.
/** * Helper function to generate the request body. * * @param array $request_body * The request body array. * * @return array * Return the request options. */
  protected function createRequestOptions(array $request_body) {
    $request_options = $this->getAuthenticationRequestOptions('POST');
    $request_options[RequestOptions::BODY] = $this->serializer->encode($request_bodystatic::$format);
    $request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;

    return $request_options;
  }

  /** * Registers a user via REST resource. * * @param string $name * User name. * @param bool $include_password * Include the password. * @param bool $include_email * Include the email? * * @return bool|\Drupal\user\Entity\User * Return bool or the user. */
public function testGetIndividual() {
    // The URL and Guzzle request options that will be used in this test. The     // request options will be modified/expanded throughout this test:     // - to first test all mistakes a developer might make, and assert that the     // error responses provide a good DX     // - to eventually result in a well-formed request that succeeds.     // @todo Remove line below in favor of commented line in https://www.drupal.org/project/drupal/issues/2878463.     $url = Url::fromRoute(sprintf('jsonapi.%s.individual', static::$resourceTypeName)['entity' => $this->entity->uuid()]);
    // $url = $this->entity->toUrl('jsonapi');     $request_options = [];
    $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions());

    // DX: 403 when unauthorized, or 200 if the 'view label' operation is     // supported by the entity type.     $response = $this->request('GET', $url$request_options);
    if (!static::$anonymousUsersCanViewLabels) {
      $expected_403_cacheability = $this->getExpectedUnauthorizedAccessCacheability();
      $reason = $this->getExpectedUnauthorizedAccessMessage('GET');
      $message = trim("The current user is not allowed to GET the selected resource. $reason");
      $this->assertResourceErrorResponse(403, $message$url$response, '/data', $expected_403_cacheability->getCacheTags()$expected_403_cacheability->getCacheContexts(), FALSE, 'MISS');
      $this->assertArrayNotHasKey('Link', $response->getHeaders());
    }
    

    ]);
    $referencing_entity->save();

    // Test.     $collection_url = Url::fromRoute('jsonapi.entity_test--bar.collection');
    // Specifying a delta exercises TemporaryQueryGuard more thoroughly.     $filter_path = "spotlight.0.$label_field_name";
    $collection_filter_url = $collection_url->setOption('query', ["filter[$filter_path]" => $this->entity->label()]);
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions());
    if ($view_permission !== NULL) {
      // ?filter[spotlight.LABEL]: 0 results.       $response = $this->request('GET', $collection_filter_url$request_options);
      $doc = Json::decode((string) $response->getBody());
      $this->assertCount(0, $doc['data']);
      // Grant "view" permission.       $this->grantPermissionsToTestedRole([$view_permission]);
    }
    // ?filter[spotlight.LABEL]: 1 result.     $response = $this->request('GET', $collection_filter_url$request_options);
    $doc = Json::decode((string) $response->getBody());
    
$this->assertResponseData($expected$response);

    // Check the actual file data.     $this->assertSame($this->testFileData, file_get_contents('public://foobar/example_0.txt'));
    $this->assertTrue($this->fileStorage->loadUnchanged(1)->isTemporary());

    // Verify that we can create an entity that references the uploaded file.     $entity_test_post_url = Url::fromRoute('rest.entity.entity_test.POST')
      ->setOption('query', ['_format' => static::$format]);
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions('POST'));

    $request_options[RequestOptions::BODY] = $this->serializer->encode($this->getNormalizedPostEntity()static::$format);
    $response = $this->request('POST', $entity_test_post_url$request_options);
    $this->assertResourceResponse(201, FALSE, $response);
    $this->assertTrue($this->fileStorage->loadUnchanged(1)->isPermanent());
    $this->assertSame([
      [
        'target_id' => '1',
        'display' => NULL,
        'description' => "The most fascinating file ever!",
      ],
    ],

  public function testPatchPath() {
    $this->initAuthentication();
    $this->provisionEntityResource();
    $this->setUpAuthorization('GET');
    $this->setUpAuthorization('PATCH');

    $url = $this->getEntityResourceUrl()->setOption('query', ['_format' => static::$format]);

    // GET node's current normalization.     $response = $this->request('GET', $url$this->getAuthenticationRequestOptions('GET'));
    $normalization = $this->serializer->decode((string) $response->getBody()static::$format);

    // Change node's path alias.     $normalization['path'][0]['alias'] .= 's-rule-the-world';

    // Create node PATCH request.     $request_options = [];
    $request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;
    $request_options = array_merge_recursive($request_options$this->getAuthenticationRequestOptions('PATCH'));
    $request_options[RequestOptions::BODY] = $this->serializer->encode($normalizationstatic::$format);

    

  public function testLinkOptionsSerialization() {
    $this->config('jsonapi.settings')->set('read_only', FALSE)->save(TRUE);

    $document = $this->getPostDocument();
    $document['data']['attributes']['link']['options'] = "O:44:\"Symfony\\Component\\Process\\Pipes\\WindowsPipes\":8:{s:51:\"\\Symfony\\Component\\Process\\Pipes\\WindowsPipes\0files\";a:1:{i:0;s:3:\"foo\";}s:57:\"\0Symfony\\Component\\Process\\Pipes\\WindowsPipes\0fileHandles\";a:0:{}s:55:\"\0Symfony\\Component\\Process\\Pipes\\WindowsPipes\0readBytes\";a:2:{i:1;i:0;i:2;i:0;}s:59:\"\0Symfony\\Component\\Process\\Pipes\\WindowsPipes\0disableOutput\";b:0;s:5:\"pipes\";a:0:{}s:58:\"\0Symfony\\Component\\Process\\Pipes\\AbstractPipes\0inputBuffer\";s:0:\"\";s:52:\"\0Symfony\\Component\\Process\\Pipes\\AbstractPipes\0input\";N;s:54:\"\0Symfony\\Component\\Process\\Pipes\\AbstractPipes\0blocked\";b:1;}";
    $url = Url::fromRoute(sprintf('jsonapi.%s.collection.post', static::$resourceTypeName));
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
    $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
    $request_options[RequestOptions::BODY] = Json::encode($document);
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions());

    // Ensure 403 when unauthorized.     $response = $this->request('POST', $url$request_options);
    $reason = $this->getExpectedUnauthorizedAccessMessage('POST');
    $this->assertResourceErrorResponse(403, (string) $reason$url$response);

    $this->setUpAuthorization('POST');

    // Ensure that an exception is thrown.     $response = $this->request('POST', $url$request_options);
    $this->assertResourceErrorResponse(500, (string) 'The generic FieldItemNormalizer cannot denormalize string values for "options" properties of the "link" field (field item class: Drupal\link\Plugin\Field\FieldType\LinkItem).', $url$response);

    

  public function testPatchPath() {
    $this->initAuthentication();
    $this->provisionEntityResource();
    $this->setUpAuthorization('GET');
    $this->setUpAuthorization('PATCH');

    $url = $this->getEntityResourceUrl()->setOption('query', ['_format' => static::$format]);

    // GET term's current normalization.     $response = $this->request('GET', $url$this->getAuthenticationRequestOptions('GET'));
    $normalization = $this->serializer->decode((string) $response->getBody()static::$format);

    // Change term's path alias.     $normalization['path'][0]['alias'] .= 's-rule-the-world';

    // Create term PATCH request.     $request_options = [];
    $request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;
    $request_options = array_merge_recursive($request_options$this->getAuthenticationRequestOptions('PATCH'));
    $request_options[RequestOptions::BODY] = $this->serializer->encode($normalizationstatic::$format);

    
Home | Imprint | This part of the site doesn't use cookies.