Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Form / ConfigFormBaseTrait.php
1 <?php
2
3 namespace Drupal\Core\Form;
4
5 use Drupal\Core\Config\ConfigFactoryInterface;
6
7 /**
8  * Provides access to configuration for forms.
9  *
10  * This trait provides a config() method that returns override free and mutable
11  * config objects if the configuration name is in the array returned by the
12  * getEditableConfigNames() implementation.
13  *
14  * Forms that present configuration to the user have to take care not to save
15  * configuration overrides to the stored configuration since overrides are often
16  * environment specific. Default values of form elements should be obtained from
17  * override free configuration objects. However, if a form reacts to
18  * configuration in any way, for example sends an email to the system.site:mail
19  * address, then it is important that the value comes from a configuration
20  * object with overrides. Therefore, override free and editable configuration
21  * objects are limited to those listed by the getEditableConfigNames() method.
22  */
23 trait ConfigFormBaseTrait {
24
25   /**
26    * Retrieves a configuration object.
27    *
28    * @param string $name
29    *   The name of the configuration object to retrieve. The name corresponds to
30    *   a configuration file. For @code \Drupal::config('book.admin') @endcode,
31    *   the config object returned will contain the contents of book.admin
32    *   configuration file.
33    *
34    * @return \Drupal\Core\Config\Config|\Drupal\Core\Config\ImmutableConfig
35    *   An editable configuration object if the given name is listed in the
36    *   getEditableConfigNames() method or an immutable configuration object if
37    *   not.
38    */
39   protected function config($name) {
40     /** @var \Drupal\Core\Config\ConfigFactoryInterface $config_factory */
41     if (method_exists($this, 'configFactory')) {
42       $config_factory = $this->configFactory();
43     }
44     elseif (property_exists($this, 'configFactory')) {
45       $config_factory = $this->configFactory;
46     }
47     if (!isset($config_factory) || !($config_factory instanceof ConfigFactoryInterface)) {
48       throw new \LogicException('No config factory available for ConfigFormBaseTrait');
49     }
50     if (in_array($name, $this->getEditableConfigNames())) {
51       // Get a mutable object from the factory.
52       $config = $config_factory->getEditable($name);
53     }
54     else {
55       $config = $config_factory->get($name);
56     }
57     return $config;
58   }
59
60   /**
61    * Gets the configuration names that will be editable.
62    *
63    * @return array
64    *   An array of configuration object names that are editable if called in
65    *   conjunction with the trait's config() method.
66    */
67   abstract protected function getEditableConfigNames();
68
69 }