ConfigEntityBase.php 10.5 KB
Newer Older
1
2
3
4
<?php

/**
 * @file
5
 * Definition of Drupal\Core\Config\Entity\ConfigEntityBase.
6
7
 */

8
namespace Drupal\Core\Config\Entity;
9

10
use Drupal\Component\Utility\String;
11
use Drupal\Core\Cache\Cache;
12
use Drupal\Core\Entity\Entity;
13
use Drupal\Core\Config\ConfigDuplicateUUIDException;
14
use Drupal\Core\Entity\EntityStorageInterface;
15
use Drupal\Core\Language\Language;
16
17

/**
18
 * Defines a base configuration entity class.
19
 */
20
abstract class ConfigEntityBase extends Entity implements ConfigEntityInterface {
21
22

  /**
23
   * The original ID of the configuration entity.
24
   *
25
26
   * The ID of a configuration entity is a unique string (machine name). When a
   * configuration entity is updated and its machine name is renamed, the
27
28
29
30
   * original ID needs to be known.
   *
   * @var string
   */
31
  protected $originalId;
32

33
34
35
36
37
38
39
40
41
42
  /**
   * The name of the property that is used to store plugin configuration.
   *
   * This is needed when the entity utilizes a PluginBag, to dictate where the
   * plugin configuration should be stored.
   *
   * @var string
   */
  protected $pluginConfigKey;

43
44
45
46
47
  /**
   * The enabled/disabled status of the configuration entity.
   *
   * @var bool
   */
48
  public $status = TRUE;
49

50
51
52
53
54
55
56
  /**
   * The UUID for this entity.
   *
   * @var string
   */
  public $uuid;

57
58
59
60
61
62
63
64
  /**
   * Whether the config is being created, updated or deleted through the
   * import process.
   *
   * @var bool
   */
  private $isSyncing = FALSE;

65
66
67
68
69
70
71
72
73
74
75
76
77
78
  /**
   * Whether the config is being deleted by the uninstall process.
   *
   * @var bool
   */
  private $isUninstalling = FALSE;

  /**
   * The configuration entity's dependencies.
   *
   * @var array
   */
  protected $dependencies = array();

79
80
81
82
83
84
85
  /**
   * The language code of the entity's default language.
   *
   * @var string
   */
  public $langcode = Language::LANGCODE_NOT_SPECIFIED;

86
87
88
  /**
   * Overrides Entity::__construct().
   */
89
  public function __construct(array $values, $entity_type) {
90
91
92
    parent::__construct($values, $entity_type);

    // Backup the original ID, if any.
93
94
95
    // Configuration entity IDs are strings, and '0' is a valid ID.
    $original_id = $this->id();
    if ($original_id !== NULL && $original_id !== '') {
96
      $this->setOriginalId($original_id);
97
98
99
100
    }
  }

  /**
101
   * {@inheritdoc}
102
   */
103
104
  public function getOriginalId() {
    return $this->originalId;
105
106
107
  }

  /**
108
   * {@inheritdoc}
109
   */
110
111
112
  public function setOriginalId($id) {
    $this->originalId = $id;

113
    return parent::setOriginalId($id);
114
115
116
  }

  /**
117
   * Overrides Entity::isNew().
118
   *
119
120
121
   * EntityInterface::enforceIsNew() is only supported for newly created
   * configuration entities but has no effect after saving, since each
   * configuration entity is unique.
122
   */
123
  public function isNew() {
124
    return !empty($this->enforceIsNew);
125
126
127
  }

  /**
128
   * {@inheritdoc}
129
   */
130
  public function get($property_name) {
131
132
133
134
    return isset($this->{$property_name}) ? $this->{$property_name} : NULL;
  }

  /**
135
   * {@inheritdoc}
136
   */
137
  public function set($property_name, $value) {
138
139
140
141
142
143
144
    if ($this instanceof EntityWithPluginBagInterface) {
      if ($property_name == $this->pluginConfigKey) {
        // If external code updates the settings, pass it along to the plugin.
        $this->getPluginBag()->setConfiguration($value);
      }
    }

145
    $this->{$property_name} = $value;
146
147

    return $this;
148
149
  }

150
  /**
151
   * {@inheritdoc}
152
153
   */
  public function enable() {
154
    return $this->setStatus(TRUE);
155
156
157
  }

  /**
158
   * {@inheritdoc}
159
160
   */
  public function disable() {
161
162
    // An entity was disabled, invalidate its own cache tag.
    Cache::invalidateTags(array($this->entityTypeId => array($this->id())));
163
164
165
166
    return $this->setStatus(FALSE);
  }

  /**
167
   * {@inheritdoc}
168
   */
169
170
  public function setStatus($status) {
    $this->status = (bool) $status;
171
172
173
174
    return $this;
  }

  /**
175
   * {@inheritdoc}
176
177
178
179
180
   */
  public function status() {
    return !empty($this->status);
  }

181
  /**
182
183
184
185
   * {@inheritdoc}
   */
  public function setSyncing($syncing) {
    $this->isSyncing = $syncing;
186
187

    return $this;
188
189
190
191
192
193
194
195
196
  }

  /**
   * {@inheritdoc}
   */
  public function isSyncing() {
    return $this->isSyncing;
  }

197
198
199
200
201
202
203
204
205
206
207
208
209
210
  /**
   * {@inheritdoc}
   */
  public function setUninstalling($uninstalling) {
    $this->isUninstalling = $uninstalling;
  }

  /**
   * {@inheritdoc}
   */
  public function isUninstalling() {
    return $this->isUninstalling;
  }

211
212
  /**
   * {@inheritdoc}
213
214
   */
  public function createDuplicate() {
215
    $duplicate = parent::createDuplicate();
216

217
    // Prevent the new duplicate from being misinterpreted as a rename.
218
    $duplicate->setOriginalId(NULL);
219
220
221
    return $duplicate;
  }

222
  /**
223
   * Helper callback for uasort() to sort configuration entities by weight and label.
224
   */
225
  public static function sort(ConfigEntityInterface $a, ConfigEntityInterface $b) {
226
227
228
229
230
231
232
233
234
    $a_weight = isset($a->weight) ? $a->weight : 0;
    $b_weight = isset($b->weight) ? $b->weight : 0;
    if ($a_weight == $b_weight) {
      $a_label = $a->label();
      $b_label = $b->label();
      return strnatcasecmp($a_label, $b_label);
    }
    return ($a_weight < $b_weight) ? -1 : 1;
  }
235
236

  /**
237
   * {@inheritdoc}
238
   */
239
  public function toArray() {
240
241
242
243
244
245
246
247
    // Configuration objects do not have a schema. Extract all key names from
    // class properties.
    $class_info = new \ReflectionClass($this);
    $properties = array();
    foreach ($class_info->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
      $name = $property->getName();
      $properties[$name] = $this->get($name);
    }
248
249
    // Add protected dependencies property.
    $properties['dependencies'] = $this->dependencies;
250
251
    return $properties;
  }
252
253
254
255

  /**
   * {@inheritdoc}
   */
256
257
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);
258

259
260
261
    if ($this instanceof EntityWithPluginBagInterface) {
      // Any changes to the plugin configuration must be saved to the entity's
      // copy as well.
262
263
      $plugin_bag = $this->getPluginBag();
      $this->set($this->pluginConfigKey, $plugin_bag->getConfiguration());
264
265
    }

266
267
    // Ensure this entity's UUID does not exist with a different ID, regardless
    // of whether it's new or updated.
268
    $matching_entities = $storage->getQuery()
269
270
271
      ->condition('uuid', $this->uuid())
      ->execute();
    $matched_entity = reset($matching_entities);
272
    if (!empty($matched_entity) && ($matched_entity != $this->id()) && $matched_entity != $this->getOriginalId()) {
273
      throw new ConfigDuplicateUUIDException(String::format('Attempt to save a configuration entity %id with UUID %uuid when this UUID is already used for %matched', array('%id' => $this->id(), '%uuid' => $this->uuid(), '%matched' => $matched_entity)));
274
275
    }

276
    // If this entity is not new, load the original entity for comparison.
277
    if (!$this->isNew()) {
278
      $original = $storage->loadUnchanged($this->getOriginalId());
279
280
      // Ensure that the UUID cannot be changed for an existing entity.
      if ($original && ($original->uuid() != $this->uuid())) {
281
        throw new ConfigDuplicateUUIDException(String::format('Attempt to save a configuration entity %id with UUID %uuid when this entity already exists with UUID %original_uuid', array('%id' => $this->id(), '%uuid' => $this->uuid(), '%original_uuid' => $original->uuid())));
282
283
      }
    }
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
    if (!$this->isSyncing()) {
      // Ensure the correct dependencies are present. If the configuration is
      // being written during a configuration synchronisation then there is no
      // need to recalculate the dependencies.
      $this->calculateDependencies();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    // Dependencies should be recalculated on every save. This ensures stale
    // dependencies are never saved.
    $this->dependencies = array();
    // @todo When \Drupal\Core\Config\Entity\EntityWithPluginBagInterface moves
    //   to a trait, switch to class_uses() instead.
    if ($this instanceof EntityWithPluginBagInterface) {
      // Configuration entities need to depend on the providers of any plugins
      // that they store the configuration for.
      $plugin_bag = $this->getPluginBag();
      foreach($plugin_bag as $instance) {
        $definition = $instance->getPluginDefinition();
        $this->addDependency('module', $definition['provider']);
308
309
310
311
312
313
314
315
        // Plugins can declare additional dependencies in their definition.
        if (isset($definition['config_dependencies'])) {
          foreach ($definition['config_dependencies'] as $type => $dependencies) {
            foreach ($dependencies as $dependency) {
              $this->addDependency($type, $dependency);
            }
          }
        }
316
317
318
      }
    }
    return $this->dependencies;
319
320
  }

321
322
323
  /**
   * {@inheritdoc}
   */
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
  public function urlInfo($rel = 'edit-form') {
    return parent::urlInfo($rel);
  }

  /**
   * {@inheritdoc}
   */
  public function getSystemPath($rel = 'edit-form') {
    return parent::getSystemPath($rel);
  }

  /**
   * {@inheritdoc}
   */
  public function url($rel = 'edit-form', $options = array()) {
    return parent::url($rel, $options);
340
341
  }

342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
  /**
   * Creates a dependency.
   *
   * @param string $type
   *   The type of dependency being checked. Either 'module', 'theme', 'entity'.
   * @param string $name
   *   If $type equals 'module' or 'theme' then it should be the name of the
   *   module or theme. In the case of entity it should be the full
   *   configuration object name.
   *
   * @see \Drupal\Core\Config\Entity\ConfigEntityInterface::getConfigDependencyName()
   *
   * @return $this
   */
  protected function addDependency($type, $name) {
    // A config entity is always dependent on its provider. There is no need to
    // explicitly declare the dependency. An explicit dependency on Core, which
    // provides some plugins, is also not needed.
    // @see \Drupal\Core\Config\Entity\ConfigEntityDependency::hasDependency()
    if ($type == 'module' && ($name == $this->getEntityType()->getProvider() || $name == 'Core')) {
      return $this;
    }
    if (empty($this->dependencies[$type])) {
      $this->dependencies[$type] = array($name);
      if (count($this->dependencies) > 1) {
        // Ensure a consistent order of type keys.
        ksort($this->dependencies);
      }
    }
    elseif (!in_array($name, $this->dependencies[$type])) {
      $this->dependencies[$type][] = $name;
      // Ensure a consistent order of dependency names.
      sort($this->dependencies[$type], SORT_FLAG_CASE);
    }
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getConfigDependencyName() {
    return $this->getEntityType()->getConfigPrefix() . '.' . $this->id();
  }

386
}