ConfigEntityBase.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. <?php
  2. namespace Drupal\Core\Config\Entity;
  3. use Drupal\Component\Utility\NestedArray;
  4. use Drupal\Core\Cache\Cache;
  5. use Drupal\Core\Config\Schema\SchemaIncompleteException;
  6. use Drupal\Core\Entity\EntityBase;
  7. use Drupal\Core\Config\ConfigDuplicateUUIDException;
  8. use Drupal\Core\Entity\EntityStorageInterface;
  9. use Drupal\Core\Entity\EntityTypeInterface;
  10. use Drupal\Core\Entity\EntityWithPluginCollectionInterface;
  11. use Drupal\Core\Entity\SynchronizableEntityTrait;
  12. use Drupal\Core\Plugin\PluginDependencyTrait;
  13. /**
  14. * Defines a base configuration entity class.
  15. *
  16. * @ingroup entity_api
  17. */
  18. abstract class ConfigEntityBase extends EntityBase implements ConfigEntityInterface {
  19. use PluginDependencyTrait {
  20. addDependency as addDependencyTrait;
  21. }
  22. use SynchronizableEntityTrait;
  23. /**
  24. * The original ID of the configuration entity.
  25. *
  26. * The ID of a configuration entity is a unique string (machine name). When a
  27. * configuration entity is updated and its machine name is renamed, the
  28. * original ID needs to be known.
  29. *
  30. * @var string
  31. */
  32. protected $originalId;
  33. /**
  34. * The enabled/disabled status of the configuration entity.
  35. *
  36. * @var bool
  37. */
  38. protected $status = TRUE;
  39. /**
  40. * The UUID for this entity.
  41. *
  42. * @var string
  43. */
  44. protected $uuid;
  45. /**
  46. * Whether the config is being deleted by the uninstall process.
  47. *
  48. * @var bool
  49. */
  50. private $isUninstalling = FALSE;
  51. /**
  52. * The language code of the entity's default language.
  53. *
  54. * Assumed to be English by default. ConfigEntityStorage will set an
  55. * appropriate language when creating new entities. This default applies to
  56. * imported default configuration where the language code is missing. Those
  57. * should be assumed to be English. All configuration entities support third
  58. * party settings, so even configuration entities that do not directly
  59. * store settings involving text in a human language may have such third
  60. * party settings attached. This means configuration entities should be in one
  61. * of the configured languages or the built-in English.
  62. *
  63. * @var string
  64. */
  65. protected $langcode = 'en';
  66. /**
  67. * Third party entity settings.
  68. *
  69. * An array of key/value pairs keyed by provider.
  70. *
  71. * @var array
  72. */
  73. protected $third_party_settings = [];
  74. /**
  75. * Information maintained by Drupal core about configuration.
  76. *
  77. * Keys:
  78. * - default_config_hash: A hash calculated by the config.installer service
  79. * and added during installation.
  80. *
  81. * @var array
  82. */
  83. protected $_core = [];
  84. /**
  85. * Trust supplied data and not use configuration schema on save.
  86. *
  87. * @var bool
  88. */
  89. protected $trustedData = FALSE;
  90. /**
  91. * {@inheritdoc}
  92. */
  93. public function __construct(array $values, $entity_type) {
  94. parent::__construct($values, $entity_type);
  95. // Backup the original ID, if any.
  96. // Configuration entity IDs are strings, and '0' is a valid ID.
  97. $original_id = $this->id();
  98. if ($original_id !== NULL && $original_id !== '') {
  99. $this->setOriginalId($original_id);
  100. }
  101. }
  102. /**
  103. * {@inheritdoc}
  104. */
  105. public function getOriginalId() {
  106. return $this->originalId;
  107. }
  108. /**
  109. * {@inheritdoc}
  110. */
  111. public function setOriginalId($id) {
  112. // Do not call the parent method since that would mark this entity as no
  113. // longer new. Unlike content entities, new configuration entities have an
  114. // ID.
  115. // @todo https://www.drupal.org/node/2478811 Document the entity life cycle
  116. // and the differences between config and content.
  117. $this->originalId = $id;
  118. return $this;
  119. }
  120. /**
  121. * Overrides Entity::isNew().
  122. *
  123. * EntityInterface::enforceIsNew() is only supported for newly created
  124. * configuration entities but has no effect after saving, since each
  125. * configuration entity is unique.
  126. */
  127. public function isNew() {
  128. return !empty($this->enforceIsNew);
  129. }
  130. /**
  131. * {@inheritdoc}
  132. */
  133. public function get($property_name) {
  134. return isset($this->{$property_name}) ? $this->{$property_name} : NULL;
  135. }
  136. /**
  137. * {@inheritdoc}
  138. */
  139. public function set($property_name, $value) {
  140. if ($this instanceof EntityWithPluginCollectionInterface) {
  141. $plugin_collections = $this->getPluginCollections();
  142. if (isset($plugin_collections[$property_name])) {
  143. // If external code updates the settings, pass it along to the plugin.
  144. $plugin_collections[$property_name]->setConfiguration($value);
  145. }
  146. }
  147. $this->{$property_name} = $value;
  148. return $this;
  149. }
  150. /**
  151. * {@inheritdoc}
  152. */
  153. public function enable() {
  154. return $this->setStatus(TRUE);
  155. }
  156. /**
  157. * {@inheritdoc}
  158. */
  159. public function disable() {
  160. return $this->setStatus(FALSE);
  161. }
  162. /**
  163. * {@inheritdoc}
  164. */
  165. public function setStatus($status) {
  166. $this->status = (bool) $status;
  167. return $this;
  168. }
  169. /**
  170. * {@inheritdoc}
  171. */
  172. public function status() {
  173. return !empty($this->status);
  174. }
  175. /**
  176. * {@inheritdoc}
  177. */
  178. public function setUninstalling($uninstalling) {
  179. $this->isUninstalling = $uninstalling;
  180. }
  181. /**
  182. * {@inheritdoc}
  183. */
  184. public function isUninstalling() {
  185. return $this->isUninstalling;
  186. }
  187. /**
  188. * {@inheritdoc}
  189. */
  190. public function createDuplicate() {
  191. $duplicate = parent::createDuplicate();
  192. // Prevent the new duplicate from being misinterpreted as a rename.
  193. $duplicate->setOriginalId(NULL);
  194. return $duplicate;
  195. }
  196. /**
  197. * Helper callback for uasort() to sort configuration entities by weight and label.
  198. */
  199. public static function sort(ConfigEntityInterface $a, ConfigEntityInterface $b) {
  200. $a_weight = isset($a->weight) ? $a->weight : 0;
  201. $b_weight = isset($b->weight) ? $b->weight : 0;
  202. if ($a_weight == $b_weight) {
  203. $a_label = $a->label();
  204. $b_label = $b->label();
  205. return strnatcasecmp($a_label, $b_label);
  206. }
  207. return ($a_weight < $b_weight) ? -1 : 1;
  208. }
  209. /**
  210. * {@inheritdoc}
  211. */
  212. public function toArray() {
  213. $properties = [];
  214. /** @var \Drupal\Core\Config\Entity\ConfigEntityTypeInterface $entity_type */
  215. $entity_type = $this->getEntityType();
  216. $id_key = $entity_type->getKey('id');
  217. $property_names = $entity_type->getPropertiesToExport($this->id());
  218. if (empty($property_names)) {
  219. throw new SchemaIncompleteException(sprintf("Entity type '%s' is missing 'config_export' definition in its annotation", get_class($entity_type)));
  220. }
  221. foreach ($property_names as $property_name => $export_name) {
  222. // Special handling for IDs so that computed compound IDs work.
  223. // @see \Drupal\Core\Entity\EntityDisplayBase::id()
  224. if ($property_name == $id_key) {
  225. $properties[$export_name] = $this->id();
  226. }
  227. else {
  228. $properties[$export_name] = $this->get($property_name);
  229. }
  230. }
  231. if (empty($this->third_party_settings)) {
  232. unset($properties['third_party_settings']);
  233. }
  234. if (empty($this->_core)) {
  235. unset($properties['_core']);
  236. }
  237. return $properties;
  238. }
  239. /**
  240. * Gets the typed config manager.
  241. *
  242. * @return \Drupal\Core\Config\TypedConfigManagerInterface
  243. */
  244. protected function getTypedConfig() {
  245. return \Drupal::service('config.typed');
  246. }
  247. /**
  248. * {@inheritdoc}
  249. */
  250. public function preSave(EntityStorageInterface $storage) {
  251. parent::preSave($storage);
  252. if ($this instanceof EntityWithPluginCollectionInterface) {
  253. // Any changes to the plugin configuration must be saved to the entity's
  254. // copy as well.
  255. foreach ($this->getPluginCollections() as $plugin_config_key => $plugin_collection) {
  256. $this->set($plugin_config_key, $plugin_collection->getConfiguration());
  257. }
  258. }
  259. // Ensure this entity's UUID does not exist with a different ID, regardless
  260. // of whether it's new or updated.
  261. $matching_entities = $storage->getQuery()
  262. ->condition('uuid', $this->uuid())
  263. ->execute();
  264. $matched_entity = reset($matching_entities);
  265. if (!empty($matched_entity) && ($matched_entity != $this->id()) && $matched_entity != $this->getOriginalId()) {
  266. throw new ConfigDuplicateUUIDException("Attempt to save a configuration entity '{$this->id()}' with UUID '{$this->uuid()}' when this UUID is already used for '$matched_entity'");
  267. }
  268. // If this entity is not new, load the original entity for comparison.
  269. if (!$this->isNew()) {
  270. $original = $storage->loadUnchanged($this->getOriginalId());
  271. // Ensure that the UUID cannot be changed for an existing entity.
  272. if ($original && ($original->uuid() != $this->uuid())) {
  273. throw new ConfigDuplicateUUIDException("Attempt to save a configuration entity '{$this->id()}' with UUID '{$this->uuid()}' when this entity already exists with UUID '{$original->uuid()}'");
  274. }
  275. }
  276. if (!$this->isSyncing()) {
  277. // Ensure the correct dependencies are present. If the configuration is
  278. // being written during a configuration synchronization then there is no
  279. // need to recalculate the dependencies.
  280. $this->calculateDependencies();
  281. }
  282. }
  283. /**
  284. * {@inheritdoc}
  285. */
  286. public function __sleep() {
  287. $keys_to_unset = [];
  288. if ($this instanceof EntityWithPluginCollectionInterface) {
  289. // Get the plugin collections first, so that the properties are
  290. // initialized in $vars and can be found later.
  291. $plugin_collections = $this->getPluginCollections();
  292. $vars = get_object_vars($this);
  293. foreach ($plugin_collections as $plugin_config_key => $plugin_collection) {
  294. // Save any changes to the plugin configuration to the entity.
  295. $this->set($plugin_config_key, $plugin_collection->getConfiguration());
  296. // If the plugin collections are stored as properties on the entity,
  297. // mark them to be unset.
  298. $keys_to_unset += array_filter($vars, function ($value) use ($plugin_collection) {
  299. return $plugin_collection === $value;
  300. });
  301. }
  302. }
  303. $vars = parent::__sleep();
  304. if (!empty($keys_to_unset)) {
  305. $vars = array_diff($vars, array_keys($keys_to_unset));
  306. }
  307. return $vars;
  308. }
  309. /**
  310. * {@inheritdoc}
  311. */
  312. public function calculateDependencies() {
  313. // All dependencies should be recalculated on every save apart from enforced
  314. // dependencies. This ensures stale dependencies are never saved.
  315. $this->dependencies = array_intersect_key($this->dependencies, ['enforced' => '']);
  316. if ($this instanceof EntityWithPluginCollectionInterface) {
  317. // Configuration entities need to depend on the providers of any plugins
  318. // that they store the configuration for.
  319. foreach ($this->getPluginCollections() as $plugin_collection) {
  320. foreach ($plugin_collection as $instance) {
  321. $this->calculatePluginDependencies($instance);
  322. }
  323. }
  324. }
  325. if ($this instanceof ThirdPartySettingsInterface) {
  326. // Configuration entities need to depend on the providers of any third
  327. // parties that they store the configuration for.
  328. foreach ($this->getThirdPartyProviders() as $provider) {
  329. $this->addDependency('module', $provider);
  330. }
  331. }
  332. return $this;
  333. }
  334. /**
  335. * {@inheritdoc}
  336. */
  337. public function urlInfo($rel = 'edit-form', array $options = []) {
  338. // Unless language was already provided, avoid setting an explicit language.
  339. $options += ['language' => NULL];
  340. return parent::urlInfo($rel, $options);
  341. }
  342. /**
  343. * {@inheritdoc}
  344. */
  345. public function url($rel = 'edit-form', $options = []) {
  346. // Do not remove this override: the default value of $rel is different.
  347. return parent::url($rel, $options);
  348. }
  349. /**
  350. * {@inheritdoc}
  351. */
  352. public function link($text = NULL, $rel = 'edit-form', array $options = []) {
  353. // Do not remove this override: the default value of $rel is different.
  354. return parent::link($text, $rel, $options);
  355. }
  356. /**
  357. * {@inheritdoc}
  358. */
  359. public function toUrl($rel = 'edit-form', array $options = []) {
  360. // Unless language was already provided, avoid setting an explicit language.
  361. $options += ['language' => NULL];
  362. return parent::toUrl($rel, $options);
  363. }
  364. /**
  365. * {@inheritdoc}
  366. */
  367. public function getCacheTagsToInvalidate() {
  368. // Use cache tags that match the underlying config object's name.
  369. // @see \Drupal\Core\Config\ConfigBase::getCacheTags()
  370. return ['config:' . $this->getConfigDependencyName()];
  371. }
  372. /**
  373. * Overrides \Drupal\Core\Entity\DependencyTrait:addDependency().
  374. *
  375. * Note that this function should only be called from implementations of
  376. * \Drupal\Core\Config\Entity\ConfigEntityInterface::calculateDependencies(),
  377. * as dependencies are recalculated during every entity save.
  378. *
  379. * @see \Drupal\Core\Config\Entity\ConfigEntityDependency::hasDependency()
  380. */
  381. protected function addDependency($type, $name) {
  382. // A config entity is always dependent on its provider. There is no need to
  383. // explicitly declare the dependency. An explicit dependency on Core, which
  384. // provides some plugins, is also not needed.
  385. if ($type == 'module' && ($name == $this->getEntityType()->getProvider() || $name == 'core')) {
  386. return $this;
  387. }
  388. return $this->addDependencyTrait($type, $name);
  389. }
  390. /**
  391. * {@inheritdoc}
  392. */
  393. public function getDependencies() {
  394. $dependencies = $this->dependencies;
  395. if (isset($dependencies['enforced'])) {
  396. // Merge the enforced dependencies into the list of dependencies.
  397. $enforced_dependencies = $dependencies['enforced'];
  398. unset($dependencies['enforced']);
  399. $dependencies = NestedArray::mergeDeep($dependencies, $enforced_dependencies);
  400. }
  401. return $dependencies;
  402. }
  403. /**
  404. * {@inheritdoc}
  405. */
  406. public function getConfigDependencyName() {
  407. return $this->getEntityType()->getConfigPrefix() . '.' . $this->id();
  408. }
  409. /**
  410. * {@inheritdoc}
  411. */
  412. public function getConfigTarget() {
  413. // For configuration entities, use the config ID for the config target
  414. // identifier. This ensures that default configuration (which does not yet
  415. // have UUIDs) can be provided and installed with references to the target,
  416. // and also makes config dependencies more readable.
  417. return $this->id();
  418. }
  419. /**
  420. * {@inheritdoc}
  421. */
  422. public function onDependencyRemoval(array $dependencies) {
  423. $changed = FALSE;
  424. if (!empty($this->third_party_settings)) {
  425. $old_count = count($this->third_party_settings);
  426. $this->third_party_settings = array_diff_key($this->third_party_settings, array_flip($dependencies['module']));
  427. $changed = $old_count != count($this->third_party_settings);
  428. }
  429. return $changed;
  430. }
  431. /**
  432. * {@inheritdoc}
  433. *
  434. * Override to never invalidate the entity's cache tag; the config system
  435. * already invalidates it.
  436. */
  437. protected function invalidateTagsOnSave($update) {
  438. Cache::invalidateTags($this->getListCacheTagsToInvalidate());
  439. }
  440. /**
  441. * {@inheritdoc}
  442. *
  443. * Override to never invalidate the individual entities' cache tags; the
  444. * config system already invalidates them.
  445. */
  446. protected static function invalidateTagsOnDelete(EntityTypeInterface $entity_type, array $entities) {
  447. $tags = $entity_type->getListCacheTags();
  448. foreach ($entities as $entity) {
  449. $tags = Cache::mergeTags($tags, $entity->getListCacheTagsToInvalidate());
  450. }
  451. Cache::invalidateTags($tags);
  452. }
  453. /**
  454. * {@inheritdoc}
  455. */
  456. public function setThirdPartySetting($module, $key, $value) {
  457. $this->third_party_settings[$module][$key] = $value;
  458. return $this;
  459. }
  460. /**
  461. * {@inheritdoc}
  462. */
  463. public function getThirdPartySetting($module, $key, $default = NULL) {
  464. if (isset($this->third_party_settings[$module][$key])) {
  465. return $this->third_party_settings[$module][$key];
  466. }
  467. else {
  468. return $default;
  469. }
  470. }
  471. /**
  472. * {@inheritdoc}
  473. */
  474. public function getThirdPartySettings($module) {
  475. return isset($this->third_party_settings[$module]) ? $this->third_party_settings[$module] : [];
  476. }
  477. /**
  478. * {@inheritdoc}
  479. */
  480. public function unsetThirdPartySetting($module, $key) {
  481. unset($this->third_party_settings[$module][$key]);
  482. // If the third party is no longer storing any information, completely
  483. // remove the array holding the settings for this module.
  484. if (empty($this->third_party_settings[$module])) {
  485. unset($this->third_party_settings[$module]);
  486. }
  487. return $this;
  488. }
  489. /**
  490. * {@inheritdoc}
  491. */
  492. public function getThirdPartyProviders() {
  493. return array_keys($this->third_party_settings);
  494. }
  495. /**
  496. * {@inheritdoc}
  497. */
  498. public static function preDelete(EntityStorageInterface $storage, array $entities) {
  499. parent::preDelete($storage, $entities);
  500. foreach ($entities as $entity) {
  501. if ($entity->isUninstalling() || $entity->isSyncing()) {
  502. // During extension uninstall and configuration synchronization
  503. // deletions are already managed.
  504. break;
  505. }
  506. // Fix or remove any dependencies.
  507. $config_entities = static::getConfigManager()->getConfigEntitiesToChangeOnDependencyRemoval('config', [$entity->getConfigDependencyName()], FALSE);
  508. /** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $dependent_entity */
  509. foreach ($config_entities['update'] as $dependent_entity) {
  510. $dependent_entity->save();
  511. }
  512. foreach ($config_entities['delete'] as $dependent_entity) {
  513. $dependent_entity->delete();
  514. }
  515. }
  516. }
  517. /**
  518. * Gets the configuration manager.
  519. *
  520. * @return \Drupal\Core\Config\ConfigManager
  521. * The configuration manager.
  522. */
  523. protected static function getConfigManager() {
  524. return \Drupal::service('config.manager');
  525. }
  526. /**
  527. * {@inheritdoc}
  528. */
  529. public function isInstallable() {
  530. return TRUE;
  531. }
  532. /**
  533. * {@inheritdoc}
  534. */
  535. public function trustData() {
  536. $this->trustedData = TRUE;
  537. return $this;
  538. }
  539. /**
  540. * {@inheritdoc}
  541. */
  542. public function hasTrustedData() {
  543. return $this->trustedData;
  544. }
  545. /**
  546. * {@inheritdoc}
  547. */
  548. public function save() {
  549. $return = parent::save();
  550. $this->trustedData = FALSE;
  551. return $return;
  552. }
  553. }