getCommentedEntity example

$this->set('mail', NULL);
    }
  }

  /** * {@inheritdoc} */
  public function postSave(EntityStorageInterface $storage$update = TRUE) {
    parent::postSave($storage$update);

    // Always invalidate the cache tag for the commented entity.     if ($commented_entity = $this->getCommentedEntity()) {
      Cache::invalidateTags($commented_entity->getCacheTagsToInvalidate());
    }

    $this->releaseThreadLock();
    // Update the {comment_entity_statistics} table prior to executing the hook.     \Drupal::service('comment.statistics')->update($this);
  }

  /** * Release the lock acquired for the thread in preSave(). */
  

  }

  /** * {@inheritdoc} */
  protected function getBuildDefaults(EntityInterface $entity$view_mode) {
    $build = parent::getBuildDefaults($entity$view_mode);

    /** @var \Drupal\comment\CommentInterface $entity */
    // Store a threading field setting to use later in self::buildComponents().     $commented_entity = $entity->getCommentedEntity();
    $build['#comment_threaded'] =
      is_null($commented_entity)
      || $commented_entity->getFieldDefinition($entity->getFieldName())
        ->getSetting('default_mode') === CommentManagerInterface::COMMENT_MODE_THREADED;
    // If threading is enabled, don't render cache individual comments, but do     // keep the cacheability metadata, so it can bubble up.     if ($build['#comment_threaded']) {
      unset($build['#cache']['keys']);
    }

    return $build;
  }

  public function renderLinks($comment_entity_id$view_mode$langcode$is_in_preview) {
    $links = [
      '#theme' => 'links__comment',
      '#pre_render' => [[Link::class, 'preRenderLinks']],
      '#attributes' => ['class' => ['links', 'inline']],
    ];

    if (!$is_in_preview) {
      /** @var \Drupal\comment\CommentInterface $entity */
      $entity = $this->entityTypeManager->getStorage('comment')->load($comment_entity_id);
      if ($commented_entity = $entity->getCommentedEntity()) {
        $links['comment'] = $this->buildLinks($entity$commented_entity);
      }

      // Allow other modules to alter the comment links.       $hook_context = [
        'view_mode' => $view_mode,
        'langcode' => $langcode,
        'commented_entity' => $commented_entity,
      ];
      $this->moduleHandler->alter('comment_links', $links$entity$hook_context);
    }
    
return parent::form($form$form_state);
  }

  /** * {@inheritdoc} */
  protected function actions(array $form, FormStateInterface $form_state) {
    $element = parent::actions($form$form_state);
    /** @var \Drupal\comment\CommentInterface $comment */
    $comment = $this->entity;
    $entity = $comment->getCommentedEntity();
    $field_definition = $this->entityFieldManager->getFieldDefinitions($entity->getEntityTypeId()$entity->bundle())[$comment->getFieldName()];
    $preview_mode = $field_definition->getSetting('preview');

    // No delete action on the comment form.     unset($element['delete']);

    // Mark the submit action as the primary action, when it appears.     $element['submit']['#button_type'] = 'primary';

    // Only show the save button if comment previews are optional or if we are     // already previewing the submission.
$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);
    $this->assertSame('3', $comment->pid->target_id);
    $this->assertSame('203.0.113.2', $comment->getHostname());

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

    
'last_comment_uid' => $last_reply->uid,
        ])
        ->keys([
          'entity_id' => $comment->getCommentedEntityId(),
          'entity_type' => $comment->getCommentedEntityTypeId(),
          'field_name' => $comment->getFieldName(),
        ])
        ->execute();
    }
    else {
      // Comments do not exist.       $entity = $comment->getCommentedEntity();
      // Get the user ID from the entity if it's set, or default to the       // currently logged in user.       if ($entity instanceof EntityOwnerInterface) {
        $last_comment_uid = $entity->getOwnerId();
      }
      if (!isset($last_comment_uid)) {
        // Default to current user when entity does not implement         // EntityOwnerInterface or author is not set.         $last_comment_uid = $this->currentUser->id();
      }
      $this->database->update('comment_entity_statistics')
        
$owner = $this->userStorage->load($owner_id);
      if ($owner->getAccountName() != $author_name) {
        $this->context->buildViolation($constraint->messageMatch)
          ->atPath('name')
          ->addViolation();
      }
    }

    // Anonymous account might be required - depending on field settings. We     // can't validate this without a valid commented entity, which will fail     // the validation elsewhere.     if ($owner_id === 0 && empty($author_name) && $entity->getCommentedEntity() && $entity->getFieldName() &&
      $this->getAnonymousContactDetailsSetting($entity) === CommentInterface::ANONYMOUS_MUST_CONTACT) {
      $this->context->buildViolation($constraint->messageRequired)
        ->atPath('name')
        ->addViolation();
    }
  }

  /** * Gets the anonymous contact details setting from the comment. * * @param \Drupal\comment\CommentInterface $comment * The entity. * * @return int * The anonymous contact setting. */

  public function commentPermalink(Request $request, CommentInterface $comment) {
    if ($entity = $comment->getCommentedEntity()) {
      // Check access permissions for the entity.       if (!$entity->access('view')) {
        throw new AccessDeniedHttpException();
      }
      $field_definition = $this->entityFieldManager->getFieldDefinitions($entity->getEntityTypeId()$entity->bundle())[$comment->getFieldName()];

      // Find the current display page for this comment.       $page = $this->entityTypeManager()->getStorage('comment')->getDisplayOrdinal($comment$field_definition->getSetting('default_mode')$field_definition->getSetting('per_page'));
      // @todo: Cleaner sub request handling.       $subrequest_url = $entity->toUrl()->setOption('query', ['page' => $page])->toString(TRUE);
      $redirect_request = Request::create($subrequest_url->getGeneratedUrl(), 'GET', $request->query->all()$request->cookies->all()[]$request->server->all());
      
/** @var \Drupal\comment\CommentInterface|\Drupal\user\EntityOwnerInterface $entity */

    $comment_admin = $account->hasPermission('administer comments');
    if ($operation == 'approve') {
      return AccessResult::allowedIf($comment_admin && !$entity->isPublished())
        ->cachePerPermissions()
        ->addCacheableDependency($entity);
    }

    if ($comment_admin) {
      $access = AccessResult::allowed()->cachePerPermissions();
      return ($operation != 'view') ? $access : $access->andIf($entity->getCommentedEntity()->access($operation$account, TRUE));
    }

    switch ($operation) {
      case 'view':
        $access_result = AccessResult::allowedIf($account->hasPermission('access comments') && $entity->isPublished())->cachePerPermissions()->addCacheableDependency($entity)
          ->andIf($entity->getCommentedEntity()->access($operation$account, TRUE));
        if (!$access_result->isAllowed()) {
          $access_result->setReason("The 'access comments' permission is required and the comment must be published.");
        }

        return $access_result;

      
$this->assertSame('1421727536', $comment->getCreatedTime());
    $this->assertSame(1421727536, $comment->getChangedTime());
    $this->assertTrue($comment->isPublished());
    $this->assertSame('admin', $comment->getAuthorName());
    $this->assertSame('admin@local.host', $comment->getAuthorEmail());
    $this->assertSame('This is a comment', $comment->comment_body->value);
    $this->assertSame('filtered_html', $comment->comment_body->format);
    $this->assertSame('2001:db8:ffff:ffff:ffff:ffff:ffff:ffff', $comment->getHostname());
    $this->assertSame('en', $comment->language()->getId());
    $this->assertSame('1000000', $comment->field_integer->value);

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

    // Tests that comments that used the Drupal 7 Title module and that have     // their subject replaced by a real field are correctly migrated.     $comment = Comment::load(2);
    $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());

    
// Check create-only fields.     foreach ($this->createOnlyFields as $field) {
      // Check view operation.       foreach ($permutations as $set) {
        $may_view = $set['comment']->{$field}->access('view', $set['user']);
        $may_update = $set['comment']->{$field}->access('edit', $set['user']);
        $this->assertTrue($may_viewnew FormattableMarkup('User @user can view field @field on comment @comment', [
          '@user' => $set['user']->getAccountName(),
          '@comment' => $set['comment']->getSubject(),
          '@field' => $field,
        ]));
        $expected = $set['user']->hasPermission('post comments') && $set['comment']->isNew() && (int) $set['comment']->getCommentedEntity()->get($set['comment']->getFieldName())->status !== CommentItemInterface::CLOSED;
        $this->assertEquals($expected$may_updatenew FormattableMarkup('User @user @state update field @field on comment @comment', [
          '@user' => $set['user']->getAccountName(),
          '@state' => $expected ? 'can' : 'cannot',
          '@comment' => $set['comment']->getSubject(),
          '@field' => $field,
        ]));
      }
    }

    // Check contact fields.     foreach ($this->contactFields as $field) {
      
Home | Imprint | This part of the site doesn't use cookies.