Version 1
[yaffs-website] / web / core / modules / file / src / Plugin / EntityReferenceSelection / FileSelection.php
1 <?php
2
3 namespace Drupal\file\Plugin\EntityReferenceSelection;
4
5 use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
6
7 /**
8  * Provides specific access control for the file entity type.
9  *
10  * @EntityReferenceSelection(
11  *   id = "default:file",
12  *   label = @Translation("File selection"),
13  *   entity_types = {"file"},
14  *   group = "default",
15  *   weight = 1
16  * )
17  */
18 class FileSelection extends DefaultSelection {
19
20   /**
21    * {@inheritdoc}
22    */
23   protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
24     $query = parent::buildEntityQuery($match, $match_operator);
25     // Allow referencing :
26     // - files with status "permanent"
27     // - or files uploaded by the current user (since newly uploaded files only
28     //   become "permanent" after the containing entity gets validated and
29     //   saved.)
30     $query->condition($query->orConditionGroup()
31       ->condition('status', FILE_STATUS_PERMANENT)
32       ->condition('uid', $this->currentUser->id()));
33     return $query;
34   }
35
36   /**
37    * {@inheritdoc}
38    */
39   public function createNewEntity($entity_type_id, $bundle, $label, $uid) {
40     $file = parent::createNewEntity($entity_type_id, $bundle, $label, $uid);
41
42     // In order to create a referenceable file, it needs to have a "permanent"
43     // status.
44     /** @var \Drupal\file\FileInterface $file */
45     $file->setPermanent();
46
47     return $file;
48   }
49
50   /**
51    * {@inheritdoc}
52    */
53   public function validateReferenceableNewEntities(array $entities) {
54     $entities = parent::validateReferenceableNewEntities($entities);
55     $entities = array_filter($entities, function ($file) {
56       /** @var \Drupal\file\FileInterface $file */
57       return $file->isPermanent() || $file->getOwnerId() === $this->currentUser->id();
58     });
59     return $entities;
60   }
61
62 }