File.php 7.24 KB
Newer Older
1
2
<?php

3
namespace Drupal\file\Entity;
4

5
use Drupal\Core\Entity\ContentEntityBase;
6
use Drupal\Core\Entity\EntityChangedTrait;
7
use Drupal\Core\Entity\EntityStorageInterface;
8
use Drupal\Core\Entity\EntityTypeInterface;
9
use Drupal\Core\Field\BaseFieldDefinition;
10
use Drupal\Core\File\Exception\FileException;
11
use Drupal\file\FileInterface;
12
use Drupal\user\EntityOwnerTrait;
13
14
15

/**
 * Defines the file entity class.
16
 *
17
18
 * @ingroup file
 *
19
 * @ContentEntityType(
20
21
 *   id = "file",
 *   label = @Translation("File"),
22
23
24
25
26
27
28
 *   label_collection = @Translation("Files"),
 *   label_singular = @Translation("file"),
 *   label_plural = @Translation("files"),
 *   label_count = @PluralTranslation(
 *     singular = "@count file",
 *     plural = "@count files",
 *   ),
29
 *   handlers = {
30
 *     "storage" = "Drupal\file\FileStorage",
31
 *     "storage_schema" = "Drupal\file\FileStorageSchema",
32
 *     "access" = "Drupal\file\FileAccessControlHandler",
33
 *     "views_data" = "Drupal\file\FileViewsData",
34
 *   },
35
36
37
38
 *   base_table = "file_managed",
 *   entity_keys = {
 *     "id" = "fid",
 *     "label" = "filename",
39
 *     "langcode" = "langcode",
40
41
 *     "uuid" = "uuid",
 *     "owner" = "uid",
42
43
 *   }
 * )
44
 */
45
class File extends ContentEntityBase implements FileInterface {
46

47
  use EntityChangedTrait;
48
  use EntityOwnerTrait;
49

50
  /**
51
   * {@inheritdoc}
52
   */
53
54
55
  public function getFilename() {
    return $this->get('filename')->value;
  }
56
57

  /**
58
   * {@inheritdoc}
59
   */
60
61
62
  public function setFilename($filename) {
    $this->get('filename')->value = $filename;
  }
63
64

  /**
65
   * {@inheritdoc}
66
   */
67
68
69
  public function getFileUri() {
    return $this->get('uri')->value;
  }
70
71

  /**
72
   * {@inheritdoc}
73
   */
74
75
76
  public function setFileUri($uri) {
    $this->get('uri')->value = $uri;
  }
77

78
79
80
81
82
83
84
85
86
87
88
  /**
   * {@inheritdoc}
   */
  public function createFileUrl($relative = TRUE) {
    $url = file_create_url($this->getFileUri());
    if ($relative && $url) {
      $url = file_url_transform_relative($url);
    }
    return $url;
  }

89
  /**
90
   * {@inheritdoc}
91
92
   *
   * @see file_url_transform_relative()
93
   */
94
  public function url($rel = 'canonical', $options = []) {
95
96
    @trigger_error('File entities returning the URL to the physical file in File::url() is deprecated, use $file->createFileUrl() instead. See https://www.drupal.org/node/3019830', E_USER_DEPRECATED);
    return $this->createFileUrl(FALSE);
97
98
99
100
  }

  /**
   * {@inheritdoc}
101
   */
102
103
104
  public function getMimeType() {
    return $this->get('filemime')->value;
  }
105
106

  /**
107
   * {@inheritdoc}
108
   */
109
110
111
  public function setMimeType($mime) {
    $this->get('filemime')->value = $mime;
  }
112
113

  /**
114
   * {@inheritdoc}
115
   */
116
117
118
  public function getSize() {
    return $this->get('filesize')->value;
  }
119
120

  /**
121
   * {@inheritdoc}
122
   */
123
124
125
  public function setSize($size) {
    $this->get('filesize')->value = $size;
  }
126

127
128
129
130
131
132
133
  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
  /**
   * {@inheritdoc}
   */
  public function isPermanent() {
    return $this->get('status')->value == FILE_STATUS_PERMANENT;
  }

  /**
   * {@inheritdoc}
   */
  public function isTemporary() {
    return $this->get('status')->value == 0;
  }

  /**
   * {@inheritdoc}
   */
  public function setPermanent() {
    $this->get('status')->value = FILE_STATUS_PERMANENT;
  }

  /**
   * {@inheritdoc}
   */
  public function setTemporary() {
    $this->get('status')->value = 0;
160
161
  }

162
163
164
  /**
   * {@inheritdoc}
   */
165
  public static function preCreate(EntityStorageInterface $storage, array &$values) {
166
167
    // Automatically detect filename if not set.
    if (!isset($values['filename']) && isset($values['uri'])) {
168
      $values['filename'] = \Drupal::service('file_system')->basename($values['uri']);
169
170
171
172
    }

    // Automatically detect filemime if not set.
    if (!isset($values['filemime']) && isset($values['uri'])) {
173
      $values['filemime'] = \Drupal::service('file.mime_type.guesser')->guess($values['uri']);
174
175
176
177
178
179
    }
  }

  /**
   * {@inheritdoc}
   */
180
181
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);
182

183
184
    // The file itself might not exist or be available right now.
    $uri = $this->getFileUri();
185
186
187
188
    $size = @filesize($uri);

    // Set size unless there was an error.
    if ($size !== FALSE) {
189
190
      $this->setSize($size);
    }
191
192
193
194
195
  }

  /**
   * {@inheritdoc}
   */
196
197
  public static function preDelete(EntityStorageInterface $storage, array $entities) {
    parent::preDelete($storage, $entities);
198

199
200
    foreach ($entities as $entity) {
      // Delete all remaining references to this file.
201
      $file_usage = \Drupal::service('file.usage')->listUsage($entity);
202
203
      if (!empty($file_usage)) {
        foreach ($file_usage as $module => $usage) {
204
          \Drupal::service('file.usage')->delete($entity, $module);
205
206
207
208
209
        }
      }
      // Delete the actual file. Failures due to invalid files and files that
      // were already deleted are logged to watchdog but ignored, the
      // corresponding file entity will be deleted.
210
211
212
213
214
215
      try {
        \Drupal::service('file_system')->delete($entity->getFileUri());
      }
      catch (FileException $e) {
        // Ignore and continue.
      }
216
217
218
    }
  }

219
220
221
  /**
   * {@inheritdoc}
   */
222
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
223
224
    /** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
    $fields = parent::baseFieldDefinitions($entity_type);
225
    $fields += static::ownerBaseFieldDefinitions($entity_type);
226
227
228
229
230
231
232

    $fields['fid']->setLabel(t('File ID'))
      ->setDescription(t('The file ID.'));

    $fields['uuid']->setDescription(t('The file UUID.'));

    $fields['langcode']->setLabel(t('Language code'))
233
      ->setDescription(t('The file language code.'));
234

235
236
    $fields['uid']
      ->setDescription(t('The user ID of the file.'));
237

238
    $fields['filename'] = BaseFieldDefinition::create('string')
239
240
241
      ->setLabel(t('Filename'))
      ->setDescription(t('Name of the file with no path components.'));

242
    $fields['uri'] = BaseFieldDefinition::create('file_uri')
243
      ->setLabel(t('URI'))
244
      ->setDescription(t('The URI to access the file (either local or remote).'))
245
      ->setSetting('max_length', 255)
246
247
      ->setSetting('case_sensitive', TRUE)
      ->addConstraint('FileUriUnique');
248

249
    $fields['filemime'] = BaseFieldDefinition::create('string')
250
      ->setLabel(t('File MIME type'))
251
      ->setSetting('is_ascii', TRUE)
252
253
      ->setDescription(t("The file's MIME type."));

254
    $fields['filesize'] = BaseFieldDefinition::create('integer')
255
      ->setLabel(t('File size'))
256
      ->setDescription(t('The size of the file in bytes.'))
257
258
      ->setSetting('unsigned', TRUE)
      ->setSetting('size', 'big');
259

260
    $fields['status'] = BaseFieldDefinition::create('boolean')
261
      ->setLabel(t('Status'))
262
263
      ->setDescription(t('The status of the file, temporary (FALSE) and permanent (TRUE).'))
      ->setDefaultValue(FALSE);
264

265
    $fields['created'] = BaseFieldDefinition::create('created')
266
      ->setLabel(t('Created'))
267
268
      ->setDescription(t('The timestamp that the file was created.'));

269
    $fields['changed'] = BaseFieldDefinition::create('changed')
270
271
      ->setLabel(t('Changed'))
      ->setDescription(t('The timestamp that the file was last changed.'));
272
273

    return $fields;
274
275
  }

276
277
278
279
280
281
282
  /**
   * {@inheritdoc}
   */
  public static function getDefaultEntityOwner() {
    return NULL;
  }

283
}