3 namespace Drupal\comment;
5 use Drupal\Core\Access\AccessResult;
6 use Drupal\Core\Field\FieldItemList;
7 use Drupal\Core\Session\AccountInterface;
10 * Defines a item list class for comment fields.
12 class CommentFieldItemList extends FieldItemList {
17 public function get($index) {
18 // The Field API only applies the "field default value" to newly created
19 // entities. In the specific case of the "comment status", though, we need
20 // this default value to be also applied for existing entities created
21 // before the comment field was added, which have no value stored for the
23 if ($index == 0 && empty($this->list)) {
24 $field_default_value = $this->getFieldDefinition()->getDefaultValue($this->getEntity());
25 return $this->appendItem($field_default_value[0]);
27 return parent::get($index);
33 public function offsetExists($offset) {
34 // For consistency with what happens in get(), we force offsetExists() to
35 // be TRUE for delta 0.
39 return parent::offsetExists($offset);
45 public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
46 if ($operation === 'edit') {
47 // Only users with administer comments permission can edit the comment
49 $result = AccessResult::allowedIfHasPermission($account ?: \Drupal::currentUser(), 'administer comments');
50 return $return_as_object ? $result : $result->isAllowed();
52 if ($operation === 'view') {
53 // Only users with "post comments" or "access comments" permission can
54 // view the field value. The formatter,
55 // Drupal\comment\Plugin\Field\FieldFormatter\CommentDefaultFormatter,
56 // takes care of showing the thread and form based on individual
57 // permissions, so if a user only has ‘post comments’ access, only the
58 // form will be shown and not the comments.
59 $result = AccessResult::allowedIfHasPermission($account ?: \Drupal::currentUser(), 'access comments')
60 ->orIf(AccessResult::allowedIfHasPermission($account ?: \Drupal::currentUser(), 'post comments'));
61 return $return_as_object ? $result : $result->isAllowed();
63 return parent::access($operation, $account, $return_as_object);