Chris@18: "The 'administer comments' permission is required.", Chris@18: 'name' => "The 'administer comments' permission is required.", Chris@18: 'homepage' => "The 'administer comments' permission is required.", Chris@18: 'created' => "The 'administer comments' permission is required.", Chris@18: 'changed' => NULL, Chris@18: 'thread' => NULL, Chris@18: 'entity_type' => NULL, Chris@18: 'field_name' => NULL, Chris@18: // @todo Uncomment this after https://www.drupal.org/project/drupal/issues/1847608 lands. Until then, it's impossible to test this. Chris@18: // 'pid' => NULL, Chris@18: 'uid' => "The 'administer comments' permission is required.", Chris@18: 'entity_id' => NULL, Chris@18: ]; Chris@18: Chris@18: /** Chris@18: * {@inheritdoc} Chris@18: * Chris@18: * @var \Drupal\comment\CommentInterface Chris@18: */ Chris@18: protected $entity; Chris@18: Chris@18: /** Chris@18: * {@inheritdoc} Chris@18: */ Chris@18: protected function setUpAuthorization($method) { Chris@18: switch ($method) { Chris@18: case 'GET': Chris@18: $this->grantPermissionsToTestedRole(['access comments', 'view test entity']); Chris@18: break; Chris@18: Chris@18: case 'POST': Chris@18: $this->grantPermissionsToTestedRole(['post comments']); Chris@18: break; Chris@18: Chris@18: case 'PATCH': Chris@18: $this->grantPermissionsToTestedRole(['edit own comments']); Chris@18: break; Chris@18: Chris@18: case 'DELETE': Chris@18: $this->grantPermissionsToTestedRole(['administer comments']); Chris@18: break; Chris@18: } Chris@18: } Chris@18: Chris@18: /** Chris@18: * {@inheritdoc} Chris@18: */ Chris@18: protected function createEntity() { Chris@18: // Create a "bar" bundle for the "entity_test" entity type and create. Chris@18: $bundle = 'bar'; Chris@18: entity_test_create_bundle($bundle, NULL, 'entity_test'); Chris@18: Chris@18: // Create a comment field on this bundle. Chris@18: $this->addDefaultCommentField('entity_test', 'bar', 'comment'); Chris@18: Chris@18: // Create a "Camelids" test entity that the comment will be assigned to. Chris@18: $commented_entity = EntityTest::create([ Chris@18: 'name' => 'Camelids', Chris@18: 'type' => 'bar', Chris@18: ]); Chris@18: $commented_entity->save(); Chris@18: Chris@18: // Create a "Llama" comment. Chris@18: $comment = Comment::create([ Chris@18: 'comment_body' => [ Chris@18: 'value' => 'The name "llama" was adopted by European settlers from native Peruvians.', Chris@18: 'format' => 'plain_text', Chris@18: ], Chris@18: 'entity_id' => $commented_entity->id(), Chris@18: 'entity_type' => 'entity_test', Chris@18: 'field_name' => 'comment', Chris@18: ]); Chris@18: $comment->setSubject('Llama') Chris@18: ->setOwnerId($this->account->id()) Chris@18: ->setPublished() Chris@18: ->setCreatedTime(123456789) Chris@18: ->setChangedTime(123456789); Chris@18: $comment->save(); Chris@18: Chris@18: return $comment; Chris@18: } Chris@18: Chris@18: /** Chris@18: * {@inheritdoc} Chris@18: */ Chris@18: protected function getExpectedDocument() { Chris@18: $self_url = Url::fromUri('base:/jsonapi/comment/comment/' . $this->entity->uuid())->setAbsolute()->toString(TRUE)->getGeneratedUrl(); Chris@18: $author = User::load($this->entity->getOwnerId()); Chris@18: return [ Chris@18: 'jsonapi' => [ Chris@18: 'meta' => [ Chris@18: 'links' => [ Chris@18: 'self' => ['href' => 'http://jsonapi.org/format/1.0/'], Chris@18: ], Chris@18: ], Chris@18: 'version' => '1.0', Chris@18: ], Chris@18: 'links' => [ Chris@18: 'self' => ['href' => $self_url], Chris@18: ], Chris@18: 'data' => [ Chris@18: 'id' => $this->entity->uuid(), Chris@18: 'type' => 'comment--comment', Chris@18: 'links' => [ Chris@18: 'self' => ['href' => $self_url], Chris@18: ], Chris@18: 'attributes' => [ Chris@18: 'created' => '1973-11-29T21:33:09+00:00', Chris@18: 'changed' => (new \DateTime())->setTimestamp($this->entity->getChangedTime())->setTimezone(new \DateTimeZone('UTC'))->format(\DateTime::RFC3339), Chris@18: 'comment_body' => [ Chris@18: 'value' => 'The name "llama" was adopted by European settlers from native Peruvians.', Chris@18: 'format' => 'plain_text', Chris@18: 'processed' => "

The name "llama" was adopted by European settlers from native Peruvians.

\n", Chris@18: ], Chris@18: 'default_langcode' => TRUE, Chris@18: 'entity_type' => 'entity_test', Chris@18: 'field_name' => 'comment', Chris@18: 'homepage' => NULL, Chris@18: 'langcode' => 'en', Chris@18: 'name' => NULL, Chris@18: 'status' => TRUE, Chris@18: 'subject' => 'Llama', Chris@18: 'thread' => '01/', Chris@18: 'drupal_internal__cid' => 1, Chris@18: ], Chris@18: 'relationships' => [ Chris@18: 'uid' => [ Chris@18: 'data' => [ Chris@18: 'id' => $author->uuid(), Chris@18: 'type' => 'user--user', Chris@18: ], Chris@18: 'links' => [ Chris@18: 'related' => ['href' => $self_url . '/uid'], Chris@18: 'self' => ['href' => $self_url . '/relationships/uid'], Chris@18: ], Chris@18: ], Chris@18: 'comment_type' => [ Chris@18: 'data' => [ Chris@18: 'id' => CommentType::load('comment')->uuid(), Chris@18: 'type' => 'comment_type--comment_type', Chris@18: ], Chris@18: 'links' => [ Chris@18: 'related' => ['href' => $self_url . '/comment_type'], Chris@18: 'self' => ['href' => $self_url . '/relationships/comment_type'], Chris@18: ], Chris@18: ], Chris@18: 'entity_id' => [ Chris@18: 'data' => [ Chris@18: 'id' => EntityTest::load(1)->uuid(), Chris@18: 'type' => 'entity_test--bar', Chris@18: ], Chris@18: 'links' => [ Chris@18: 'related' => ['href' => $self_url . '/entity_id'], Chris@18: 'self' => ['href' => $self_url . '/relationships/entity_id'], Chris@18: ], Chris@18: ], Chris@18: 'pid' => [ Chris@18: 'data' => NULL, Chris@18: 'links' => [ Chris@18: 'related' => ['href' => $self_url . '/pid'], Chris@18: 'self' => ['href' => $self_url . '/relationships/pid'], Chris@18: ], Chris@18: ], Chris@18: ], Chris@18: ], Chris@18: ]; Chris@18: } Chris@18: Chris@18: /** Chris@18: * {@inheritdoc} Chris@18: */ Chris@18: protected function getPostDocument() { Chris@18: return [ Chris@18: 'data' => [ Chris@18: 'type' => 'comment--comment', Chris@18: 'attributes' => [ Chris@18: 'entity_type' => 'entity_test', Chris@18: 'field_name' => 'comment', Chris@18: 'subject' => 'Dramallama', Chris@18: 'comment_body' => [ Chris@18: 'value' => 'Llamas are awesome.', Chris@18: 'format' => 'plain_text', Chris@18: ], Chris@18: ], Chris@18: 'relationships' => [ Chris@18: 'entity_id' => [ Chris@18: 'data' => [ Chris@18: 'type' => 'entity_test--bar', Chris@18: 'id' => EntityTest::load(1)->uuid(), Chris@18: ], Chris@18: ], Chris@18: ], Chris@18: ], Chris@18: ]; Chris@18: } Chris@18: Chris@18: /** Chris@18: * {@inheritdoc} Chris@18: */ Chris@18: protected function getExpectedCacheTags(array $sparse_fieldset = NULL) { Chris@18: $tags = parent::getExpectedCacheTags($sparse_fieldset); Chris@18: if ($sparse_fieldset === NULL || in_array('comment_body', $sparse_fieldset)) { Chris@18: $tags = Cache::mergeTags($tags, ['config:filter.format.plain_text']); Chris@18: } Chris@18: return $tags; Chris@18: } Chris@18: Chris@18: /** Chris@18: * {@inheritdoc} Chris@18: */ Chris@18: protected function getExpectedCacheContexts(array $sparse_fieldset = NULL) { Chris@18: $contexts = parent::getExpectedCacheContexts($sparse_fieldset); Chris@18: if ($sparse_fieldset === NULL || in_array('comment_body', $sparse_fieldset)) { Chris@18: $contexts = Cache::mergeContexts($contexts, ['languages:language_interface', 'theme']); Chris@18: } Chris@18: return $contexts; Chris@18: } Chris@18: Chris@18: /** Chris@18: * {@inheritdoc} Chris@18: */ Chris@18: protected function getExpectedUnauthorizedAccessMessage($method) { Chris@18: switch ($method) { Chris@18: case 'GET'; Chris@18: return "The 'access comments' permission is required and the comment must be published."; Chris@18: Chris@18: case 'POST'; Chris@18: return "The 'post comments' permission is required."; Chris@18: Chris@18: case 'PATCH': Chris@18: return "The 'edit own comments' permission is required, the user must be the comment author, and the comment must be published."; Chris@18: Chris@18: default: Chris@18: return parent::getExpectedUnauthorizedAccessMessage($method); Chris@18: } Chris@18: } Chris@18: Chris@18: /** Chris@18: * Tests POSTing a comment without critical base fields. Chris@18: * Chris@18: * Note that testPostIndividual() is testing with the most minimal Chris@18: * normalization possible: the one returned by ::getNormalizedPostEntity(). Chris@18: * Chris@18: * But Comment entities have some very special edge cases: Chris@18: * - base fields that are not marked as required in Chris@18: * \Drupal\comment\Entity\Comment::baseFieldDefinitions() yet in fact are Chris@18: * required. Chris@18: * - base fields that are marked as required, but yet can still result in Chris@18: * validation errors other than "missing required field". Chris@18: */ Chris@18: public function testPostIndividualDxWithoutCriticalBaseFields() { Chris@18: $this->setUpAuthorization('POST'); Chris@18: $this->config('jsonapi.settings')->set('read_only', FALSE)->save(TRUE); Chris@18: Chris@18: $url = Url::fromRoute(sprintf('jsonapi.%s.collection.post', static::$resourceTypeName)); Chris@18: $request_options = []; Chris@18: $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json'; Chris@18: $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json'; Chris@18: $request_options = NestedArray::mergeDeep($request_options, $this->getAuthenticationRequestOptions()); Chris@18: Chris@18: $remove_field = function (array $normalization, $type, $attribute_name) { Chris@18: unset($normalization['data'][$type][$attribute_name]); Chris@18: return $normalization; Chris@18: }; Chris@18: Chris@18: // DX: 422 when missing 'entity_type' field. Chris@18: $request_options[RequestOptions::BODY] = Json::encode($remove_field($this->getPostDocument(), 'attributes', 'entity_type')); Chris@18: $response = $this->request('POST', $url, $request_options); Chris@18: $this->assertResourceErrorResponse(422, 'entity_type: This value should not be null.', NULL, $response, '/data/attributes/entity_type'); Chris@18: Chris@18: // DX: 422 when missing 'entity_id' field. Chris@18: $request_options[RequestOptions::BODY] = Json::encode($remove_field($this->getPostDocument(), 'relationships', 'entity_id')); Chris@18: // @todo Remove the try/catch in https://www.drupal.org/node/2820364. Chris@18: try { Chris@18: $response = $this->request('POST', $url, $request_options); Chris@18: $this->assertResourceErrorResponse(422, 'entity_id: This value should not be null.', NULL, $response, '/data/attributes/entity_id'); Chris@18: } Chris@18: catch (\Exception $e) { Chris@18: if (version_compare(phpversion(), '7.0') >= 0) { Chris@18: $this->assertSame("Error: Call to a member function get() on null\nDrupal\\comment\\Plugin\\Validation\\Constraint\\CommentNameConstraintValidator->getAnonymousContactDetailsSetting()() (Line: 96)\n", $e->getMessage()); Chris@18: } Chris@18: else { Chris@18: $this->assertSame(500, $response->getStatusCode()); Chris@18: } Chris@18: } Chris@18: Chris@18: // DX: 422 when missing 'field_name' field. Chris@18: $request_options[RequestOptions::BODY] = Json::encode($remove_field($this->getPostDocument(), 'attributes', 'field_name')); Chris@18: $response = $this->request('POST', $url, $request_options); Chris@18: $this->assertResourceErrorResponse(422, 'field_name: This value should not be null.', NULL, $response, '/data/attributes/field_name'); Chris@18: } Chris@18: Chris@18: /** Chris@18: * Tests POSTing a comment with and without 'skip comment approval'. Chris@18: */ Chris@18: public function testPostIndividualSkipCommentApproval() { Chris@18: $this->setUpAuthorization('POST'); Chris@18: $this->config('jsonapi.settings')->set('read_only', FALSE)->save(TRUE); Chris@18: Chris@18: // Create request. Chris@18: $request_options = []; Chris@18: $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json'; Chris@18: $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json'; Chris@18: $request_options = NestedArray::mergeDeep($request_options, $this->getAuthenticationRequestOptions()); Chris@18: $request_options[RequestOptions::BODY] = Json::encode($this->getPostDocument()); Chris@18: Chris@18: $url = Url::fromRoute('jsonapi.comment--comment.collection.post'); Chris@18: Chris@18: // Status should be FALSE when posting as anonymous. Chris@18: $response = $this->request('POST', $url, $request_options); Chris@18: $this->assertResourceResponse(201, FALSE, $response); Chris@18: $this->assertFalse(Json::decode((string) $response->getBody())['data']['attributes']['status']); Chris@18: $this->assertFalse($this->entityStorage->loadUnchanged(2)->isPublished()); Chris@18: Chris@18: // Grant anonymous permission to skip comment approval. Chris@18: $this->grantPermissionsToTestedRole(['skip comment approval']); Chris@18: Chris@18: // Status must be TRUE when posting as anonymous and skip comment approval. Chris@18: $response = $this->request('POST', $url, $request_options); Chris@18: $this->assertResourceResponse(201, FALSE, $response); Chris@18: $this->assertTrue(Json::decode((string) $response->getBody())['data']['attributes']['status']); Chris@18: $this->assertTrue($this->entityStorage->loadUnchanged(3)->isPublished()); Chris@18: } Chris@18: Chris@18: /** Chris@18: * {@inheritdoc} Chris@18: */ Chris@18: protected function getExpectedUnauthorizedAccessCacheability() { Chris@18: // @see \Drupal\comment\CommentAccessControlHandler::checkAccess() Chris@18: return parent::getExpectedUnauthorizedAccessCacheability() Chris@18: ->addCacheTags(['comment:1']); Chris@18: } Chris@18: Chris@18: /** Chris@18: * {@inheritdoc} Chris@18: */ Chris@18: protected static function entityAccess(EntityInterface $entity, $operation, AccountInterface $account) { Chris@18: // Also reset the 'entity_test' entity access control handler because Chris@18: // comment access also depends on access to the commented entity type. Chris@18: \Drupal::entityTypeManager()->getAccessControlHandler('entity_test')->resetCache(); Chris@18: return parent::entityAccess($entity, $operation, $account); Chris@18: } Chris@18: Chris@18: /** Chris@18: * {@inheritdoc} Chris@18: */ Chris@18: public function testRelated() { Chris@18: $this->markTestSkipped('Remove this in https://www.drupal.org/project/jsonapi/issues/2940339'); Chris@18: } Chris@18: Chris@18: /** Chris@18: * {@inheritdoc} Chris@18: */ Chris@18: protected static function getIncludePermissions() { Chris@18: return [ Chris@18: 'type' => ['administer comment types'], Chris@18: 'uid' => ['access user profiles'], Chris@18: ]; Chris@18: } Chris@18: Chris@18: /** Chris@18: * {@inheritdoc} Chris@18: */ Chris@18: public function testCollectionFilterAccess() { Chris@18: // Verify the expected behavior in the common case. Chris@18: $this->doTestCollectionFilterAccessForPublishableEntities('subject', 'access comments', 'administer comments'); Chris@18: Chris@18: $collection_url = Url::fromRoute('jsonapi.entity_test--bar.collection'); Chris@18: $request_options = []; Chris@18: $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json'; Chris@18: $request_options = NestedArray::mergeDeep($request_options, $this->getAuthenticationRequestOptions()); Chris@18: Chris@18: // Go back to a simpler scenario: revoke the admin permission, publish the Chris@18: // comment and uninstall the query access test module. Chris@18: $this->revokePermissionsFromTestedRole(['administer comments']); Chris@18: $this->entity->setPublished()->save(); Chris@18: $this->assertTrue($this->container->get('module_installer')->uninstall(['jsonapi_test_field_filter_access'], TRUE), 'Uninstalled modules.'); Chris@18: // ?filter[spotlight.LABEL]: 1 result. Just as already tested above in Chris@18: // ::doTestCollectionFilterAccessForPublishableEntities(). Chris@18: $collection_filter_url = $collection_url->setOption('query', ["filter[spotlight.subject]" => $this->entity->label()]); Chris@18: $response = $this->request('GET', $collection_filter_url, $request_options); Chris@18: $doc = Json::decode((string) $response->getBody()); Chris@18: $this->assertCount(1, $doc['data']); Chris@18: // Mark the commented entity as inaccessible. Chris@18: \Drupal::state()->set('jsonapi__entity_test_filter_access_blacklist', [$this->entity->getCommentedEntityId()]); Chris@18: Cache::invalidateTags(['state:jsonapi__entity_test_filter_access_blacklist']); Chris@18: // ?filter[spotlight.LABEL]: 0 results. Chris@18: $response = $this->request('GET', $collection_filter_url, $request_options); Chris@18: $doc = Json::decode((string) $response->getBody()); Chris@18: $this->assertCount(0, $doc['data']); Chris@18: } Chris@18: Chris@18: /** Chris@18: * {@inheritdoc} Chris@18: */ Chris@18: protected static function getExpectedCollectionCacheability(AccountInterface $account, array $collection, array $sparse_fieldset = NULL, $filtered = FALSE) { Chris@18: $cacheability = parent::getExpectedCollectionCacheability($account, $collection, $sparse_fieldset, $filtered); Chris@18: if ($filtered) { Chris@18: $cacheability->addCacheTags(['state:jsonapi__entity_test_filter_access_blacklist']); Chris@18: } Chris@18: return $cacheability; Chris@18: } Chris@18: Chris@18: /** Chris@18: * {@inheritdoc} Chris@18: */ Chris@18: public function testPatchIndividual() { Chris@18: // Ensure ::getModifiedEntityForPatchTesting() can pick an alternative value Chris@18: // for the 'entity_id' field. Chris@18: EntityTest::create([ Chris@18: 'name' => $this->randomString(), Chris@18: 'type' => 'bar', Chris@18: ])->save(); Chris@18: Chris@18: return parent::testPatchIndividual(); Chris@18: } Chris@18: Chris@18: }