ConfigEntityBase.php 18 KB

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