3 namespace Drupal\bootstrap\Plugin\Preprocess;
5 use Drupal\bootstrap\Plugin\PluginBase;
6 use Drupal\bootstrap\Utility\Element;
7 use Drupal\bootstrap\Utility\Variables;
8 use Drupal\Core\Template\Attribute;
11 * Base preprocess class used to build the necessary variables for templates.
13 * @ingroup plugins_preprocess
15 class PreprocessBase extends PluginBase implements PreprocessInterface {
18 * The theme hook invoked.
25 * The theme hook info array from the theme registry.
32 * The Variables object.
34 * @var \Drupal\bootstrap\Utility\Variables
41 public function preprocess(array &$variables, $hook, array $info) {
44 $this->variables = Variables::create($variables);
45 if ($this->variables->element) {
46 // Check for errors and set the "has_error" property flag.
47 if (!$this->variables->element->hasProperty('has_error')) {
48 $errors = $this->variables->element->getProperty('errors');
49 $this->variables->element->setProperty('has_error', isset($errors) || ($this->variables->element->getProperty('required') && $this->theme->getSetting('forms_required_has_error')));
51 $this->preprocessElement($this->variables->element, $this->variables);
53 $this->preprocessVariables($this->variables);
57 * Ensures all attributes have been converted to an Attribute object.
59 protected function preprocessAttributes() {
60 foreach ($this->variables as $name => $value) {
61 if (strpos($name, 'attributes') !== FALSE && is_array($value)) {
62 $this->variables[$name] = new Attribute($value);
68 * Converts any set description variable into a traversable array.
70 * @see https://www.drupal.org/node/2324025
72 protected function preprocessDescription() {
73 if ($this->variables->offsetGet('description')) {
74 // Retrieve the description attributes.
75 $description_attributes = $this->variables->offsetGet('description_attributes', []);
77 // Remove standalone description attributes.
78 $this->variables->offsetUnset('description_attributes');
80 // Build the description attributes.
81 if ($id = $this->variables->getAttribute('id')) {
82 $this->variables->setAttribute('aria-describedby', "$id--description");
83 $description_attributes['id'] = "$id--description";
86 // Replace the description variable.
87 $this->variables->offsetSet('description', [
88 'attributes' => new Attribute($description_attributes),
89 'content' => $this->variables['description'],
90 'position' => $this->variables->offsetGet('description_display', 'after'),
96 * Preprocess the variables array if an element is present.
98 * @param \Drupal\bootstrap\Utility\Element $element
100 * @param \Drupal\bootstrap\Utility\Variables $variables
101 * The Variables object.
103 protected function preprocessElement(Element $element, Variables $variables) {}
106 * Preprocess the variables array.
108 * @param \Drupal\bootstrap\Utility\Variables $variables
109 * The Variables object.
111 protected function preprocessVariables(Variables $variables) {}