pattern_library-8.x-2.x-dev/pattern_library.module
pattern_library.module
<?php
/**
* @file
* The hook implementations for the pattern library module.
*/
use Drupal\Core\Render\Element;
use Drupal\Core\Template\Attribute;
use Drupal\pattern_library\PatternLibraryManager;
use Drupal\pattern_library\Plugin\Pattern;
/**
* Implements hook_theme().
*/
function pattern_library_theme($existing, $type, $theme, $path) {
return [
'pattern_library_layout' => [
'render element' => 'content',
]
];
}
/**
* Implements hook_library_info_build().
*/
function pattern_library_library_info_build() {
/** @var PatternLibraryManager $manager */
$manager = \Drupal::service('plugin.manager.pattern_library');
$libraries = [];
/** @var Pattern $instance */
foreach ($manager->getDefinitionInstances() as $plugin_id => $instance) {
if (!$instance->hasLibraries()) {
continue;
}
$libraries[$instance->libraryKey()] = $instance->getLibraries();
}
return $libraries;
}
/**
* Template preprocess for pattern library layout.
*
* @param $variables
* An array of the template variables.
*/
function template_preprocess_pattern_library_layout(&$variables) {
$variables['source'] = isset($variables['content']['#source'])
? $variables['content']['#source']
: NULL;
$variables['layout'] = isset($variables['content']['#layout'])
? $variables['content']['#layout']
: [];
foreach (Element::children($variables['content']) as $name) {
if (!isset($variables['content'][$name]['#attributes'])) {
$variables['content'][$name]['#attributes'] = [];
}
$variables['region_attributes'][$name] = new Attribute($variables['content'][$name]['#attributes']);
}
$variables['source_args'] = pattern_library_extract_layout_arguments($variables);
}
/**
* Pattern library extract layout arguments.
*
* @param array $variables
* An array of template variables.
*
* @return array
* An array of layout arguments.
*/
function pattern_library_extract_layout_arguments(array $variables) {
$arguments = array_intersect_key(
$variables['content'],
array_flip(Element::children($variables['content']))
);
// Modifiers are unique to the pattern library module and provides a seamless
// way to pass modifiers to the pattern library patterns.
$arguments['modifiers'] = isset($variables['content']['#modifiers'])
? $variables['content']['#modifiers']
: [];
// Attributes aren't truly needed, but emulsify will thrown an error when
// using the bem() function without the attributes in the context.
$arguments['attributes'] = new Attribute($variables['attributes']);
// This is required to allow layout blocks to be dragged and dropped between
// the regions within the layout builder interface.
$arguments['region_attributes'] = $variables['region_attributes'];
return $arguments;
}
