Version 1
[yaffs-website] / web / core / modules / node / src / Plugin / EntityReferenceSelection / NodeSelection.php
1 <?php
2
3 namespace Drupal\node\Plugin\EntityReferenceSelection;
4
5 use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\node\NodeInterface;
8
9 /**
10  * Provides specific access control for the node entity type.
11  *
12  * @EntityReferenceSelection(
13  *   id = "default:node",
14  *   label = @Translation("Node selection"),
15  *   entity_types = {"node"},
16  *   group = "default",
17  *   weight = 1
18  * )
19  */
20 class NodeSelection extends DefaultSelection {
21
22   /**
23    * {@inheritdoc}
24    */
25   public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
26     $form = parent::buildConfigurationForm($form, $form_state);
27     $form['target_bundles']['#title'] = $this->t('Content types');
28     return $form;
29   }
30
31   /**
32    * {@inheritdoc}
33    */
34   protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
35     $query = parent::buildEntityQuery($match, $match_operator);
36     // Adding the 'node_access' tag is sadly insufficient for nodes: core
37     // requires us to also know about the concept of 'published' and
38     // 'unpublished'. We need to do that as long as there are no access control
39     // modules in use on the site. As long as one access control module is there,
40     // it is supposed to handle this check.
41     if (!$this->currentUser->hasPermission('bypass node access') && !count($this->moduleHandler->getImplementations('node_grants'))) {
42       $query->condition('status', NodeInterface::PUBLISHED);
43     }
44     return $query;
45   }
46
47   /**
48    * {@inheritdoc}
49    */
50   public function createNewEntity($entity_type_id, $bundle, $label, $uid) {
51     $node = parent::createNewEntity($entity_type_id, $bundle, $label, $uid);
52
53     // In order to create a referenceable node, it needs to published.
54     /** @var \Drupal\node\NodeInterface $node */
55     $node->setPublished(TRUE);
56
57     return $node;
58   }
59
60   /**
61    * {@inheritdoc}
62    */
63   public function validateReferenceableNewEntities(array $entities) {
64     $entities = parent::validateReferenceableNewEntities($entities);
65     // Mirror the conditions checked in buildEntityQuery().
66     if (!$this->currentUser->hasPermission('bypass node access') && !count($this->moduleHandler->getImplementations('node_grants'))) {
67       $entities = array_filter($entities, function ($node) {
68         /** @var \Drupal\node\NodeInterface $node */
69         return $node->isPublished();
70       });
71     }
72     return $entities;
73   }
74
75 }