TypedConfigManager.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. <?php
  2. namespace Drupal\Core\Config;
  3. use Drupal\Component\Utility\NestedArray;
  4. use Drupal\Core\Cache\CacheBackendInterface;
  5. use Drupal\Core\Config\Schema\ConfigSchemaAlterException;
  6. use Drupal\Core\Config\Schema\ConfigSchemaDiscovery;
  7. use Drupal\Core\DependencyInjection\ClassResolverInterface;
  8. use Drupal\Core\Config\Schema\Undefined;
  9. use Drupal\Core\Extension\ModuleHandlerInterface;
  10. use Drupal\Core\TypedData\TypedDataManager;
  11. /**
  12. * Manages config schema type plugins.
  13. */
  14. class TypedConfigManager extends TypedDataManager implements TypedConfigManagerInterface {
  15. /**
  16. * A storage instance for reading configuration data.
  17. *
  18. * @var \Drupal\Core\Config\StorageInterface
  19. */
  20. protected $configStorage;
  21. /**
  22. * A storage instance for reading configuration schema data.
  23. *
  24. * @var \Drupal\Core\Config\StorageInterface
  25. */
  26. protected $schemaStorage;
  27. /**
  28. * The array of plugin definitions, keyed by plugin id.
  29. *
  30. * @var array
  31. */
  32. protected $definitions;
  33. /**
  34. * Creates a new typed configuration manager.
  35. *
  36. * @param \Drupal\Core\Config\StorageInterface $configStorage
  37. * The storage object to use for reading schema data
  38. * @param \Drupal\Core\Config\StorageInterface $schemaStorage
  39. * The storage object to use for reading schema data
  40. * @param \Drupal\Core\Cache\CacheBackendInterface $cache
  41. * The cache backend to use for caching the definitions.
  42. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
  43. * The module handler.
  44. * @param \Drupal\Core\DependencyInjection\ClassResolverInterface $class_resolver
  45. * (optional) The class resolver.
  46. */
  47. public function __construct(StorageInterface $configStorage, StorageInterface $schemaStorage, CacheBackendInterface $cache, ModuleHandlerInterface $module_handler, ClassResolverInterface $class_resolver = NULL) {
  48. $this->configStorage = $configStorage;
  49. $this->schemaStorage = $schemaStorage;
  50. $this->setCacheBackend($cache, 'typed_config_definitions');
  51. $this->alterInfo('config_schema_info');
  52. $this->moduleHandler = $module_handler;
  53. $this->classResolver = $class_resolver ?: \Drupal::service('class_resolver');
  54. }
  55. /**
  56. * {@inheritdoc}
  57. */
  58. protected function getDiscovery() {
  59. if (!isset($this->discovery)) {
  60. $this->discovery = new ConfigSchemaDiscovery($this->schemaStorage);
  61. }
  62. return $this->discovery;
  63. }
  64. /**
  65. * {@inheritdoc}
  66. */
  67. public function get($name) {
  68. $data = $this->configStorage->read($name);
  69. return $this->createFromNameAndData($name, $data);
  70. }
  71. /**
  72. * {@inheritdoc}
  73. */
  74. public function buildDataDefinition(array $definition, $value, $name = NULL, $parent = NULL) {
  75. // Add default values for data type and replace variables.
  76. $definition += ['type' => 'undefined'];
  77. $replace = [];
  78. $type = $definition['type'];
  79. if (strpos($type, ']')) {
  80. // Replace variable names in definition.
  81. $replace = is_array($value) ? $value : [];
  82. if (isset($parent)) {
  83. $replace['%parent'] = $parent;
  84. }
  85. if (isset($name)) {
  86. $replace['%key'] = $name;
  87. }
  88. $type = $this->replaceName($type, $replace);
  89. // Remove the type from the definition so that it is replaced with the
  90. // concrete type from schema definitions.
  91. unset($definition['type']);
  92. }
  93. // Add default values from type definition.
  94. $definition += $this->getDefinitionWithReplacements($type, $replace);
  95. $data_definition = $this->createDataDefinition($definition['type']);
  96. // Pass remaining values from definition array to data definition.
  97. foreach ($definition as $key => $value) {
  98. if (!isset($data_definition[$key])) {
  99. $data_definition[$key] = $value;
  100. }
  101. }
  102. return $data_definition;
  103. }
  104. /**
  105. * Determines the typed config type for a plugin ID.
  106. *
  107. * @param string $base_plugin_id
  108. * The plugin ID.
  109. * @param array $definitions
  110. * An array of typed config definitions.
  111. *
  112. * @return string
  113. * The typed config type for the given plugin ID.
  114. */
  115. protected function determineType($base_plugin_id, array $definitions) {
  116. if (isset($definitions[$base_plugin_id])) {
  117. $type = $base_plugin_id;
  118. }
  119. elseif (strpos($base_plugin_id, '.') && $name = $this->getFallbackName($base_plugin_id)) {
  120. // Found a generic name, replacing the last element by '*'.
  121. $type = $name;
  122. }
  123. else {
  124. // If we don't have definition, return the 'undefined' element.
  125. $type = 'undefined';
  126. }
  127. return $type;
  128. }
  129. /**
  130. * Gets a schema definition with replacements for dynamic names.
  131. *
  132. * @param string $base_plugin_id
  133. * A plugin ID.
  134. * @param array $replacements
  135. * An array of replacements for dynamic type names.
  136. * @param bool $exception_on_invalid
  137. * (optional) This parameter is passed along to self::getDefinition().
  138. * However, self::getDefinition() does not respect this parameter, so it is
  139. * effectively useless in this context.
  140. *
  141. * @return array
  142. * A schema definition array.
  143. */
  144. protected function getDefinitionWithReplacements($base_plugin_id, array $replacements, $exception_on_invalid = TRUE) {
  145. $definitions = $this->getDefinitions();
  146. $type = $this->determineType($base_plugin_id, $definitions);
  147. $definition = $definitions[$type];
  148. // Check whether this type is an extension of another one and compile it.
  149. if (isset($definition['type'])) {
  150. $merge = $this->getDefinition($definition['type'], $exception_on_invalid);
  151. // Preserve integer keys on merge, so sequence item types can override
  152. // parent settings as opposed to adding unused second, third, etc. items.
  153. $definition = NestedArray::mergeDeepArray([$merge, $definition], TRUE);
  154. // Replace dynamic portions of the definition type.
  155. if (!empty($replacements) && strpos($definition['type'], ']')) {
  156. $sub_type = $this->determineType($this->replaceName($definition['type'], $replacements), $definitions);
  157. $sub_definition = $definitions[$sub_type];
  158. if (isset($definitions[$sub_type]['type'])) {
  159. $sub_merge = $this->getDefinition($definitions[$sub_type]['type'], $exception_on_invalid);
  160. $sub_definition = NestedArray::mergeDeepArray([$sub_merge, $definitions[$sub_type]], TRUE);
  161. }
  162. // Merge the newly determined subtype definition with the original
  163. // definition.
  164. $definition = NestedArray::mergeDeepArray([$sub_definition, $definition], TRUE);
  165. $type = "$type||$sub_type";
  166. }
  167. // Unset type so we try the merge only once per type.
  168. unset($definition['type']);
  169. $this->definitions[$type] = $definition;
  170. }
  171. // Add type and default definition class.
  172. $definition += [
  173. 'definition_class' => '\Drupal\Core\TypedData\DataDefinition',
  174. 'type' => $type,
  175. 'unwrap_for_canonical_representation' => TRUE,
  176. ];
  177. return $definition;
  178. }
  179. /**
  180. * {@inheritdoc}
  181. */
  182. public function getDefinition($base_plugin_id, $exception_on_invalid = TRUE) {
  183. return $this->getDefinitionWithReplacements($base_plugin_id, [], $exception_on_invalid);
  184. }
  185. /**
  186. * {@inheritdoc}
  187. */
  188. public function clearCachedDefinitions() {
  189. $this->schemaStorage->reset();
  190. parent::clearCachedDefinitions();
  191. }
  192. /**
  193. * Gets fallback configuration schema name.
  194. *
  195. * @param string $name
  196. * Configuration name or key.
  197. *
  198. * @return null|string
  199. * The resolved schema name for the given configuration name or key. Returns
  200. * null if there is no schema name to fallback to. For example,
  201. * breakpoint.breakpoint.module.toolbar.narrow will check for definitions in
  202. * the following order:
  203. * breakpoint.breakpoint.module.toolbar.*
  204. * breakpoint.breakpoint.module.*.*
  205. * breakpoint.breakpoint.module.*
  206. * breakpoint.breakpoint.*.*.*
  207. * breakpoint.breakpoint.*
  208. * breakpoint.*.*.*.*
  209. * breakpoint.*
  210. * Colons are also used, for example,
  211. * block.settings.system_menu_block:footer will check for definitions in the
  212. * following order:
  213. * block.settings.system_menu_block:*
  214. * block.settings.*:*
  215. * block.settings.*
  216. * block.*.*:*
  217. * block.*
  218. */
  219. protected function getFallbackName($name) {
  220. // Check for definition of $name with filesystem marker.
  221. $replaced = preg_replace('/([^\.:]+)([\.:\*]*)$/', '*\2', $name);
  222. if ($replaced != $name) {
  223. if (isset($this->definitions[$replaced])) {
  224. return $replaced;
  225. }
  226. else {
  227. // No definition for this level. Collapse multiple wildcards to a single
  228. // wildcard to see if there is a greedy match. For example,
  229. // breakpoint.breakpoint.*.* becomes
  230. // breakpoint.breakpoint.*
  231. $one_star = preg_replace('/\.([:\.\*]*)$/', '.*', $replaced);
  232. if ($one_star != $replaced && isset($this->definitions[$one_star])) {
  233. return $one_star;
  234. }
  235. // Check for next level. For example, if breakpoint.breakpoint.* has
  236. // been checked and no match found then check breakpoint.*.*
  237. return $this->getFallbackName($replaced);
  238. }
  239. }
  240. }
  241. /**
  242. * Replaces variables in configuration name.
  243. *
  244. * The configuration name may contain one or more variables to be replaced,
  245. * enclosed in square brackets like '[name]' and will follow the replacement
  246. * rules defined by the replaceVariable() method.
  247. *
  248. * @param string $name
  249. * Configuration name with variables in square brackets.
  250. * @param mixed $data
  251. * Configuration data for the element.
  252. * @return string
  253. * Configuration name with variables replaced.
  254. */
  255. protected function replaceName($name, $data) {
  256. if (preg_match_all("/\[(.*)\]/U", $name, $matches)) {
  257. // Build our list of '[value]' => replacement.
  258. $replace = [];
  259. foreach (array_combine($matches[0], $matches[1]) as $key => $value) {
  260. $replace[$key] = $this->replaceVariable($value, $data);
  261. }
  262. return strtr($name, $replace);
  263. }
  264. else {
  265. return $name;
  266. }
  267. }
  268. /**
  269. * Replaces variable values in included names with configuration data.
  270. *
  271. * Variable values are nested configuration keys that will be replaced by
  272. * their value or some of these special strings:
  273. * - '%key', will be replaced by the element's key.
  274. * - '%parent', to reference the parent element.
  275. * - '%type', to reference the schema definition type. Can only be used in
  276. * combination with %parent.
  277. *
  278. * There may be nested configuration keys separated by dots or more complex
  279. * patterns like '%parent.name' which references the 'name' value of the
  280. * parent element.
  281. *
  282. * Example patterns:
  283. * - 'name.subkey', indicates a nested value of the current element.
  284. * - '%parent.name', will be replaced by the 'name' value of the parent.
  285. * - '%parent.%key', will be replaced by the parent element's key.
  286. * - '%parent.%type', will be replaced by the schema type of the parent.
  287. * - '%parent.%parent.%type', will be replaced by the schema type of the
  288. * parent's parent.
  289. *
  290. * @param string $value
  291. * Variable value to be replaced.
  292. * @param mixed $data
  293. * Configuration data for the element.
  294. *
  295. * @return string
  296. * The replaced value if a replacement found or the original value if not.
  297. */
  298. protected function replaceVariable($value, $data) {
  299. $parts = explode('.', $value);
  300. // Process each value part, one at a time.
  301. while ($name = array_shift($parts)) {
  302. if (!is_array($data) || !isset($data[$name])) {
  303. // Key not found, return original value
  304. return $value;
  305. }
  306. elseif (!$parts) {
  307. $value = $data[$name];
  308. if (is_bool($value)) {
  309. $value = (int) $value;
  310. }
  311. // If no more parts left, this is the final property.
  312. return (string) $value;
  313. }
  314. else {
  315. // Get nested value and continue processing.
  316. if ($name == '%parent') {
  317. /** @var \Drupal\Core\Config\Schema\ArrayElement $parent */
  318. // Switch replacement values with values from the parent.
  319. $parent = $data['%parent'];
  320. $data = $parent->getValue();
  321. $data['%type'] = $parent->getDataDefinition()->getDataType();
  322. // The special %parent and %key values now need to point one level up.
  323. if ($new_parent = $parent->getParent()) {
  324. $data['%parent'] = $new_parent;
  325. $data['%key'] = $new_parent->getName();
  326. }
  327. }
  328. else {
  329. $data = $data[$name];
  330. }
  331. }
  332. }
  333. }
  334. /**
  335. * {@inheritdoc}
  336. */
  337. public function hasConfigSchema($name) {
  338. // The schema system falls back on the Undefined class for unknown types.
  339. $definition = $this->getDefinition($name);
  340. return is_array($definition) && ($definition['class'] != Undefined::class);
  341. }
  342. /**
  343. * {@inheritdoc}
  344. */
  345. protected function alterDefinitions(&$definitions) {
  346. $discovered_schema = array_keys($definitions);
  347. parent::alterDefinitions($definitions);
  348. $altered_schema = array_keys($definitions);
  349. if ($discovered_schema != $altered_schema) {
  350. $added_keys = implode(',', array_diff($altered_schema, $discovered_schema));
  351. $removed_keys = implode(',', array_diff($discovered_schema, $altered_schema));
  352. if (!empty($added_keys) && !empty($removed_keys)) {
  353. $message = "Invoking hook_config_schema_info_alter() has added ($added_keys) and removed ($removed_keys) schema definitions";
  354. }
  355. elseif (!empty($added_keys)) {
  356. $message = "Invoking hook_config_schema_info_alter() has added ($added_keys) schema definitions";
  357. }
  358. else {
  359. $message = "Invoking hook_config_schema_info_alter() has removed ($removed_keys) schema definitions";
  360. }
  361. throw new ConfigSchemaAlterException($message);
  362. }
  363. }
  364. /**
  365. * {@inheritdoc}
  366. */
  367. public function createFromNameAndData($config_name, array $config_data) {
  368. $definition = $this->getDefinition($config_name);
  369. $data_definition = $this->buildDataDefinition($definition, $config_data);
  370. return $this->create($data_definition, $config_data);
  371. }
  372. }