getCommentedEntityId example

$container->get('entity.memory_cache'),
      $container->get('entity_type.bundle.info'),
      $container->get('entity_type.manager')
    );
  }

  /** * {@inheritdoc} */
  public function getMaxThread(CommentInterface $comment) {
    $query = $this->database->select($this->getDataTable(), 'c')
      ->condition('entity_id', $comment->getCommentedEntityId())
      ->condition('field_name', $comment->getFieldName())
      ->condition('entity_type', $comment->getCommentedEntityTypeId())
      ->condition('default_langcode', 1);
    $query->addExpression('MAX([thread])', 'thread');
    return $query->execute()
      ->fetchField();
  }

  /** * {@inheritdoc} */
  
/** * {@inheritdoc} */
  protected function getUrlInfo(ResultRow $row) {
    /** @var \Drupal\comment\CommentInterface $comment */
    $comment = $this->getEntity($row);
    if (!$comment) {
      return NULL;
    }
    return Url::fromRoute('comment.reply', [
      'entity_type' => $comment->getCommentedEntityTypeId(),
      'entity' => $comment->getCommentedEntityId(),
      'field_name' => $comment->getFieldName(),
      'pid' => $comment->id(),
    ]);
  }

  /** * {@inheritdoc} */
  protected function getDefaultLabel() {
    return $this->t('Reply');
  }

}

  public function update(CommentInterface $comment) {
    // Allow bulk updates and inserts to temporarily disable the maintenance of     // the {comment_entity_statistics} table.     if (!$this->state->get('comment.maintain_entity_statistics')) {
      return;
    }

    $query = $this->database->select('comment_field_data', 'c');
    $query->addExpression('COUNT([cid])');
    $count = $query->condition('c.entity_id', $comment->getCommentedEntityId())
      ->condition('c.entity_type', $comment->getCommentedEntityTypeId())
      ->condition('c.field_name', $comment->getFieldName())
      ->condition('c.status', CommentInterface::PUBLISHED)
      ->condition('default_langcode', 1)
      ->execute()
      ->fetchField();

    if ($count > 0) {
      // Comments exist.       $last_reply = $this->database->select('comment_field_data', 'c')
        ->fields('c', ['cid', 'name', 'changed', 'uid'])
        
$this->assertInstanceOf(Comment::class$comment);
    $this->assertSame('TNG for the win!', $comment->getSubject());
    $this->assertSame('TNG is better than DS9.', $comment->comment_body->value);
    $this->assertSame('en', $comment->language()->getId());

    // Tests that the commented entity is correctly migrated when the comment     // was posted to a node translation.     $comment = Comment::load(3);
    $this->assertInstanceOf(Comment::class$comment);
    $this->assertSame('Comment to IS translation', $comment->getSubject());
    $this->assertSame('This is a comment to an Icelandic translation.', $comment->comment_body->value);
    $this->assertSame('2', $comment->getCommentedEntityId());
    $this->assertSame('node', $comment->getCommentedEntityTypeId());
    $this->assertSame('is', $comment->language()->getId());

    $node = $comment->getCommentedEntity();
    $this->assertInstanceOf(NodeInterface::class$node);
    $this->assertSame('2', $node->id());

    // Tests a comment migrated from Drupal 6 to Drupal 7 that did not have a     // language.     $comment = Comment::load(4);
    $this->assertInstanceOf(Comment::class$comment);
    
// Get the value at the correct depth.             $parts = explode('.', $max);
            $parent_depth = count(explode('.', $parent->getThread()));
            $n = Number::alphadecimalToInt($parts[$parent_depth]);
          }
        }
        // Finally, build the thread field for this new comment. To avoid         // race conditions, get a lock on the thread. If another process already         // has the lock, just move to the next integer.         do {
          $thread = $prefix . Number::intToAlphadecimal(++$n) . '/';
          $lock_name = "comment:{$this->getCommentedEntityId()}:$thread";
        } while (!\Drupal::lock()->acquire($lock_name));
        $this->threadLock = $lock_name;
      }
      $this->setThread($thread);
    }
    // The entity fields for name and mail have no meaning if the user is not     // Anonymous. Set them to NULL to make it clearer that they are not used.     // For anonymous users see \Drupal\comment\CommentForm::form() for mail,     // and \Drupal\comment\CommentForm::buildEntity() for name setting.     if (!$this->getOwner()->isAnonymous()) {
      $this->set('name', NULL);
      
$this->currentUser = $current_user;
    $this->renderer = $renderer;
    $this->entityFieldManager = $entity_field_manager ?: \Drupal::service('entity_field.manager');
  }

  /** * {@inheritdoc} */
  public function form(array $form, FormStateInterface $form_state) {
    /** @var \Drupal\comment\CommentInterface $comment */
    $comment = $this->entity;
    $entity = $this->entityTypeManager->getStorage($comment->getCommentedEntityTypeId())->load($comment->getCommentedEntityId());
    $field_name = $comment->getFieldName();
    $field_definition = $this->entityFieldManager->getFieldDefinitions($entity->getEntityTypeId()$entity->bundle())[$comment->getFieldName()];
    $config = $this->config('user.settings');

    // In several places within this function, we vary $form on:     // - The current user's permissions.     // - Whether the current user is authenticated or anonymous.     // - The 'user.settings' configuration.     // - The comment field's definition.     $form['#cache']['contexts'][] = 'user.permissions';
    $form['#cache']['contexts'][] = 'user.roles:authenticated';
    
$tests['[comment:body]'] = $comment->comment_body->processed;
    $tests['[comment:langcode]'] = $comment->language()->getId();
    $tests['[comment:url]'] = $comment->toUrl('canonical', $url_options + ['fragment' => 'comment-' . $comment->id()])->toString();
    $tests['[comment:edit-url]'] = $comment->toUrl('edit-form', $url_options)->toString();
    $tests['[comment:created]'] = \Drupal::service('date.formatter')->format($comment->getCreatedTime(), 'medium', ['langcode' => $language_interface->getId()]);
    $tests['[comment:created:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getCreatedTime()['langcode' => $language_interface->getId()]);
    $tests['[comment:changed:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($comment->getChangedTimeAcrossTranslations()['langcode' => $language_interface->getId()]);
    $tests['[comment:parent:cid]'] = $comment->hasParentComment() ? $comment->getParentComment()->id() : NULL;
    $tests['[comment:parent:title]'] = $parent_comment->getSubject();
    $tests['[comment:entity]'] = Html::escape($node->getTitle());
    // Test node specific tokens.     $tests['[comment:entity:nid]'] = $comment->getCommentedEntityId();
    $tests['[comment:entity:title]'] = Html::escape($node->getTitle());
    $tests['[comment:author:uid]'] = $comment->getOwnerId();
    $tests['[comment:author:name]'] = Html::escape($this->adminUser->getDisplayName());

    $base_bubbleable_metadata = BubbleableMetadata::createFromObject($comment);
    $metadata_tests = [];
    $metadata_tests['[comment:cid]'] = $base_bubbleable_metadata;
    $metadata_tests['[comment:hostname]'] = $base_bubbleable_metadata;
    $bubbleable_metadata = clone $base_bubbleable_metadata;
    $bubbleable_metadata->addCacheableDependency($this->adminUser);
    $metadata_tests['[comment:author]'] = $bubbleable_metadata;
    
/** @var \Drupal\comment\CommentInterface[] $comments */
    $comments = $this->commentStorage->loadMultiple($cids);

    // Build a table listing the appropriate comments.     $options = [];
    $destination = $this->getDestinationArray();

    $commented_entity_ids = [];
    $commented_entities = [];

    foreach ($comments as $comment) {
      $commented_entity_ids[$comment->getCommentedEntityTypeId()][] = $comment->getCommentedEntityId();
    }

    foreach ($commented_entity_ids as $entity_type => $ids) {
      $commented_entities[$entity_type] = $this->entityTypeManager
        ->getStorage($entity_type)
        ->loadMultiple($ids);
    }

    foreach ($comments as $comment) {
      /** @var \Drupal\Core\Entity\EntityInterface $commented_entity */
      $commented_entity = $commented_entities[$comment->getCommentedEntityTypeId()][$comment->getCommentedEntityId()];
      
// And if user has access to the host entity.       ->andIf(AccessResult::allowedIf($entity->access('view')));

    // $pid indicates that this is a reply to a comment.     if ($pid) {
      // Check if the user has the proper permissions.       $access = $access->andIf(AccessResult::allowedIfHasPermission($account, 'access comments'));

      // Load the parent comment.       $comment = $this->entityTypeManager()->getStorage('comment')->load($pid);
      // Check if the parent comment is published and belongs to the entity.       $access = $access->andIf(AccessResult::allowedIf($comment && $comment->isPublished() && $comment->getCommentedEntityId() == $entity->id()));
      if ($comment) {
        $access->addCacheableDependency($comment);
      }
    }
    return $access;
  }

  /** * Returns a set of nodes' last read timestamps. * * @param \Symfony\Component\HttpFoundation\Request $request * The request of the page. * * @return \Symfony\Component\HttpFoundation\JsonResponse * The JSON response. * * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException */
/** * {@inheritdoc} */
  public function getItems(ResultRow $values) {
    if (empty($this->loadedCommentedEntities)) {
      $result = $this->view->result;

      $entity_ids_per_type = [];
      foreach ($result as $value) {
        /** @var \Drupal\comment\CommentInterface $comment */
        if ($comment = $this->getEntity($value)) {
          $entity_ids_per_type[$comment->getCommentedEntityTypeId()][] = $comment->getCommentedEntityId();
        }
      }

      foreach ($entity_ids_per_type as $type => $ids) {
        $this->loadedCommentedEntities[$type] = $this->entityTypeManager->getStorage($type)->loadMultiple($ids);
      }
    }

    return parent::getItems($values);
  }

}


  /** * Tests the migrated comments. */
  public function testMigration() {
    $comment = Comment::load(1);
    $this->assertSame('The first comment.', $comment->getSubject());
    $this->assertSame('The first comment body.', $comment->comment_body->value);
    $this->assertSame('filtered_html', $comment->comment_body->format);
    $this->assertNull($comment->pid->target_id);
    $this->assertSame('1', $comment->getCommentedEntityId());
    $this->assertSame('node', $comment->getCommentedEntityTypeId());
    $this->assertSame('en', $comment->language()->getId());
    $this->assertSame('comment_node_story', $comment->getTypeId());
    $this->assertSame('203.0.113.1', $comment->getHostname());

    $node = $comment->getCommentedEntity();
    $this->assertInstanceOf(NodeInterface::class$node);
    $this->assertSame('1', $node->id());

    $comment = Comment::load(2);
    $this->assertSame('The response to the second comment.', $comment->subject->value);
    
    // comment and uninstall the query access test module.     $this->revokePermissionsFromTestedRole(['administer comments']);
    $this->entity->setPublished()->save();
    $this->assertTrue($this->container->get('module_installer')->uninstall(['jsonapi_test_field_filter_access'], TRUE), 'Uninstalled modules.');
    // ?filter[spotlight.LABEL]: 1 result. Just as already tested above in     // ::doTestCollectionFilterAccessForPublishableEntities().     $collection_filter_url = $collection_url->setOption('query', ["filter[spotlight.subject]" => $this->entity->label()]);
    $response = $this->request('GET', $collection_filter_url$request_options);
    $doc = Json::decode((string) $response->getBody());
    $this->assertCount(1, $doc['data']);
    // Mark the commented entity as inaccessible.     \Drupal::state()->set('jsonapi__entity_test_filter_access_blacklist', [$this->entity->getCommentedEntityId()]);
    Cache::invalidateTags(['state:jsonapi__entity_test_filter_access_blacklist']);
    // ?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']);
  }

  /** * {@inheritdoc} */
  protected static function getExpectedCollectionCacheability(AccountInterface $account, array $collection, array $sparse_fieldset = NULL, $filtered = FALSE) {
    
'title' => t('Edit'),
          'url' => $entity->toUrl('edit-form'),
        ];
      }
      $field_definition = $commented_entity->getFieldDefinition($entity->getFieldName());
      if ($entity->access('create')
        && $field_definition->getSetting('default_mode') === CommentManagerInterface::COMMENT_MODE_THREADED) {
        $links['comment-reply'] = [
          'title' => t('Reply'),
          'url' => Url::fromRoute('comment.reply', [
            'entity_type' => $entity->getCommentedEntityTypeId(),
            'entity' => $entity->getCommentedEntityId(),
            'field_name' => $entity->getFieldName(),
            'pid' => $entity->id(),
          ]),
        ];
      }
      if (!$entity->isPublished() && $entity->access('approve')) {
        $links['comment-approve'] = [
          'title' => t('Approve'),
          'url' => Url::fromRoute('comment.approve', ['comment' => $entity->id()]),
        ];
      }
      
Home | Imprint | This part of the site doesn't use cookies.