Skip to content
Snippets Groups Projects
Commit e9500065 authored by Jess's avatar Jess
Browse files

Issue #2296423 by tim.plunkett, dsnopek, swentel, Manuel Garcia, tedbow,...

Issue #2296423 by tim.plunkett, dsnopek, swentel, Manuel Garcia, tedbow, alexpott, xjm, andypost, dawehner, effulgentsia, Berdir, jhedstrom, catch, benjy, jibran, Wim Leers, tstoeckler, larowlan, webchick: Implement layout plugin type in core
parent da0c4fa4
No related branches found
No related tags found
2 merge requests!7452Issue #1797438. HTML5 validation is preventing form submit and not fully...,!789Issue #3210310: Adjust Database API to remove deprecated Drupal 9 code in Drupal 10
Showing
with 1609 additions and 0 deletions
...@@ -105,6 +105,7 @@ ...@@ -105,6 +105,7 @@
"drupal/image": "self.version", "drupal/image": "self.version",
"drupal/inline_form_errors": "self.version", "drupal/inline_form_errors": "self.version",
"drupal/language": "self.version", "drupal/language": "self.version",
"drupal/layout_discovery": "self.version",
"drupal/link": "self.version", "drupal/link": "self.version",
"drupal/locale": "self.version", "drupal/locale": "self.version",
"drupal/minimal": "self.version", "drupal/minimal": "self.version",
......
...@@ -361,6 +361,13 @@ display_variant.plugin: ...@@ -361,6 +361,13 @@ display_variant.plugin:
type: string type: string
label: 'UUID' label: 'UUID'
layout_plugin.settings:
type: mapping
label: 'Layout settings'
layout_plugin.settings.*:
type: layout_plugin.settings
base_entity_reference_field_settings: base_entity_reference_field_settings:
type: mapping type: mapping
mapping: mapping:
......
...@@ -2178,6 +2178,17 @@ function hook_display_variant_plugin_alter(array &$definitions) { ...@@ -2178,6 +2178,17 @@ function hook_display_variant_plugin_alter(array &$definitions) {
$definitions['full_page']['admin_label'] = t('Block layout'); $definitions['full_page']['admin_label'] = t('Block layout');
} }
/**
* Allow modules to alter layout plugin definitions.
*
* @param \Drupal\Core\Layout\LayoutDefinition[] $definitions
* The array of layout definitions, keyed by plugin ID.
*/
function hook_layout_alter(&$definitions) {
// Remove a layout.
unset($definitions['twocol']);
}
/** /**
* Flush all persistent and static caches. * Flush all persistent and static caches.
* *
......
<?php
namespace Drupal\Core\Layout\Annotation;
use Drupal\Component\Annotation\Plugin;
use Drupal\Core\Layout\LayoutDefault;
use Drupal\Core\Layout\LayoutDefinition;
/**
* Defines a Layout annotation object.
*
* Layouts are used to define a list of regions and then output render arrays
* in each of the regions, usually using a template.
*
* Plugin namespace: Plugin\Layout
*
* @internal
* The layout system is currently experimental and should only be leveraged by
* experimental modules and development releases of contributed modules.
* See https://www.drupal.org/core/experimental for more information.
*
* @see \Drupal\Core\Layout\LayoutInterface
* @see \Drupal\Core\Layout\LayoutDefault
* @see \Drupal\Core\Layout\LayoutPluginManager
* @see plugin_api
*
* @Annotation
*/
class Layout extends Plugin {
/**
* The plugin ID.
*
* @var string
*/
public $id;
/**
* The human-readable name.
*
* @var string
*
* @ingroup plugin_translatable
*/
public $label;
/**
* An optional description for advanced layouts.
*
* Sometimes layouts are so complex that the name is insufficient to describe
* a layout such that a visually impaired administrator could layout a page
* for a non-visually impaired audience. If specified, it will provide a
* description that is used for accessibility purposes.
*
* @var string
*
* @ingroup plugin_translatable
*/
public $description;
/**
* The human-readable category.
*
* @var string
*
* @see \Drupal\Component\Plugin\CategorizingPluginManagerInterface
*
* @ingroup plugin_translatable
*/
public $category;
/**
* The template file to render this layout (relative to the 'path' given).
*
* If specified, then the layout_discovery module will register the template
* with hook_theme() and the module or theme registering this layout does not
* need to do it.
*
* @var string optional
*
* @see hook_theme()
*/
public $template;
/**
* The theme hook used to render this layout.
*
* If specified, it's assumed that the module or theme registering this layout
* will also register the theme hook with hook_theme() itself. This is
* mutually exclusive with 'template' - you can't specify both.
*
* @var string optional
*
* @see hook_theme()
*/
public $theme_hook = 'layout';
/**
* Path (relative to the module or theme) to resources like icon or template.
*
* @var string optional
*/
public $path;
/**
* The asset library.
*
* @var string optional
*/
public $library;
/**
* The path to the preview image (relative to the 'path' given).
*
* @var string optional
*/
public $icon;
/**
* An associative array of regions in this layout.
*
* The key of the array is the machine name of the region, and the value is
* an associative array with the following keys:
* - label: (string) The human-readable name of the region.
*
* Any remaining keys may have special meaning for the given layout plugin,
* but are undefined here.
*
* @var array
*/
public $regions = [];
/**
* The default region.
*
* @var string
*/
public $default_region;
/**
* The layout plugin class.
*
* This default value is used for plugins defined in layouts.yml that do not
* specify a class themselves.
*
* @var string
*/
public $class = LayoutDefault::class;
/**
* {@inheritdoc}
*/
public function get() {
return new LayoutDefinition($this->definition);
}
}
<?php
namespace Drupal\Core\Layout;
use Drupal\Component\Plugin\Definition\PluginDefinitionInterface;
/**
* Provides an interface for a derivable plugin definition.
*
* @see \Drupal\Component\Plugin\Derivative\DeriverInterface
* @see \Drupal\Core\Layout\ObjectDefinitionContainerDerivativeDiscoveryDecorator
*
* @internal
* The layout system is currently experimental and should only be leveraged by
* experimental modules and development releases of contributed modules.
* See https://www.drupal.org/core/experimental for more information.
*
* @todo Move into \Drupal\Component\Plugin\Definition in
* https://www.drupal.org/node/2821189.
*/
interface DerivablePluginDefinitionInterface extends PluginDefinitionInterface {
/**
* Gets the name of the deriver of this plugin definition, if it exists.
*
* @return string|null
* Either the deriver class name, or NULL if the plugin is not derived.
*/
public function getDeriver();
/**
* Sets the deriver of this plugin definition.
*
* @param string|null $deriver
* Either the name of a class that implements
* \Drupal\Component\Plugin\Derivative\DeriverInterface, or NULL.
*
* @return $this
*/
public function setDeriver($deriver);
}
<?php
namespace Drupal\Core\Layout;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Plugin\PluginBase;
/**
* Provides a default class for Layout plugins.
*
* @internal
* The layout system is currently experimental and should only be leveraged by
* experimental modules and development releases of contributed modules.
* See https://www.drupal.org/core/experimental for more information.
*/
class LayoutDefault extends PluginBase implements LayoutInterface {
/**
* The layout definition.
*
* @var \Drupal\Core\Layout\LayoutDefinition
*/
protected $pluginDefinition;
/**
* {@inheritdoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->setConfiguration($configuration);
}
/**
* {@inheritdoc}
*/
public function build(array $regions) {
$build = array_intersect_key($regions, $this->pluginDefinition->getRegions());
$build['#settings'] = $this->getConfiguration();
$build['#layout'] = $this->pluginDefinition;
$build['#theme'] = $this->pluginDefinition->getThemeHook();
if ($library = $this->pluginDefinition->getLibrary()) {
$build['#attached']['library'][] = $library;
}
return $build;
}
/**
* {@inheritdoc}
*/
public function getConfiguration() {
return $this->configuration;
}
/**
* {@inheritdoc}
*/
public function setConfiguration(array $configuration) {
$this->configuration = NestedArray::mergeDeep($this->defaultConfiguration(), $configuration);
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [];
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
return [];
}
/**
* {@inheritdoc}
*
* @return \Drupal\Core\Layout\LayoutDefinition
*/
public function getPluginDefinition() {
return parent::getPluginDefinition();
}
}
<?php
namespace Drupal\Core\Layout;
use Drupal\Component\Plugin\Definition\PluginDefinitionInterface;
/**
* Provides an implementation of a layout definition and its metadata.
*
* @internal
* The layout system is currently experimental and should only be leveraged by
* experimental modules and development releases of contributed modules.
* See https://www.drupal.org/core/experimental for more information.
*/
class LayoutDefinition implements PluginDefinitionInterface, DerivablePluginDefinitionInterface {
/**
* The plugin ID.
*
* @var string
*/
protected $id;
/**
* The name of the provider of this layout definition.
*
* @todo Make protected after https://www.drupal.org/node/2818653.
*
* @var string
*/
public $provider;
/**
* The name of the deriver of this layout definition, if any.
*
* @var string|null
*/
protected $deriver;
/**
* The dependencies of this layout definition.
*
* @todo Make protected after https://www.drupal.org/node/2821191.
*
* @var array
*/
public $config_dependencies;
/**
* The human-readable name.
*
* @var string
*/
protected $label;
/**
* An optional description for advanced layouts.
*
* @var string
*/
protected $description;
/**
* The human-readable category.
*
* @var string
*/
protected $category;
/**
* The template file to render this layout (relative to the 'path' given).
*
* @var string|null
*/
protected $template;
/**
* The path to the template.
*
* @var string
*/
protected $templatePath;
/**
* The theme hook used to render this layout.
*
* @var string|null
*/
protected $theme_hook;
/**
* Path (relative to the module or theme) to resources like icon or template.
*
* @var string
*/
protected $path;
/**
* The asset library.
*
* @var string|null
*/
protected $library;
/**
* The path to the preview image.
*
* @var string
*/
protected $icon;
/**
* An associative array of regions in this layout.
*
* The key of the array is the machine name of the region, and the value is
* an associative array with the following keys:
* - label: (string) The human-readable name of the region.
*
* Any remaining keys may have special meaning for the given layout plugin,
* but are undefined here.
*
* @var array
*/
protected $regions = [];
/**
* The default region.
*
* @var string
*/
protected $default_region;
/**
* The name of the layout class.
*
* @var string
*/
protected $class;
/**
* Any additional properties and values.
*
* @var array
*/
protected $additional = [];
/**
* LayoutDefinition constructor.
*
* @param array $definition
* An array of values from the annotation.
*/
public function __construct(array $definition) {
foreach ($definition as $property => $value) {
$this->set($property, $value);
}
}
/**
* Gets any arbitrary property.
*
* @param string $property
* The property to retrieve.
*
* @return mixed
* The value for that property, or NULL if the property does not exist.
*/
public function get($property) {
if (property_exists($this, $property)) {
$value = isset($this->{$property}) ? $this->{$property} : NULL;
}
else {
$value = isset($this->additional[$property]) ? $this->additional[$property] : NULL;
}
return $value;
}
/**
* Sets a value to an arbitrary property.
*
* @param string $property
* The property to use for the value.
* @param mixed $value
* The value to set.
*
* @return $this
*/
public function set($property, $value) {
if (property_exists($this, $property)) {
$this->{$property} = $value;
}
else {
$this->additional[$property] = $value;
}
return $this;
}
/**
* Gets the unique identifier of the layout definition.
*
* @return string
* The unique identifier of the layout definition.
*/
public function id() {
return $this->id;
}
/**
* {@inheritdoc}
*/
public function getClass() {
return $this->class;
}
/**
* {@inheritdoc}
*/
public function setClass($class) {
$this->class = $class;
return $this;
}
/**
* Gets the human-readable name of the layout definition.
*
* @return string|\Drupal\Core\StringTranslation\TranslatableMarkup
* The human-readable name of the layout definition.
*/
public function getLabel() {
return $this->label;
}
/**
* Sets the human-readable name of the layout definition.
*
* @param string|\Drupal\Core\StringTranslation\TranslatableMarkup $label
* The human-readable name of the layout definition.
*
* @return $this
*/
public function setLabel($label) {
$this->label = $label;
return $this;
}
/**
* Gets the description of the layout definition.
*
* @return string|\Drupal\Core\StringTranslation\TranslatableMarkup
* The description of the layout definition.
*/
public function getDescription() {
return $this->description;
}
/**
* Sets the description of the layout definition.
*
* @param string|\Drupal\Core\StringTranslation\TranslatableMarkup $description
* The description of the layout definition.
*
* @return $this
*/
public function setDescription($description) {
$this->description = $description;
return $this;
}
/**
* Gets the human-readable category of the layout definition.
*
* @return string|\Drupal\Core\StringTranslation\TranslatableMarkup
* The human-readable category of the layout definition.
*/
public function getCategory() {
return $this->category;
}
/**
* Sets the human-readable category of the layout definition.
*
* @param string|\Drupal\Core\StringTranslation\TranslatableMarkup $category
* The human-readable category of the layout definition.
*
* @return $this
*/
public function setCategory($category) {
$this->category = $category;
return $this;
}
/**
* Gets the template name.
*
* @return string|null
* The template name, if it exists.
*/
public function getTemplate() {
return $this->template;
}
/**
* Sets the template name.
*
* @param string|null $template
* The template name.
*
* @return $this
*/
public function setTemplate($template) {
$this->template = $template;
return $this;
}
/**
* Gets the template path.
*
* @return string
* The template path.
*/
public function getTemplatePath() {
return $this->templatePath;
}
/**
* Sets the template path.
*
* @param string $template_path
* The template path.
*
* @return $this
*/
public function setTemplatePath($template_path) {
$this->templatePath = $template_path;
return $this;
}
/**
* Gets the theme hook.
*
* @return string|null
* The theme hook, if it exists.
*/
public function getThemeHook() {
return $this->theme_hook;
}
/**
* Sets the theme hook.
*
* @param string $theme_hook
* The theme hook.
*
* @return $this
*/
public function setThemeHook($theme_hook) {
$this->theme_hook = $theme_hook;
return $this;
}
/**
* Gets the base path for this layout definition.
*
* @return string
* The base path.
*/
public function getPath() {
return $this->path;
}
/**
* Sets the base path for this layout definition.
*
* @param string $path
* The base path.
*
* @return $this
*/
public function setPath($path) {
$this->path = $path;
return $this;
}
/**
* Gets the asset library for this layout definition.
*
* @return string|null
* The asset library, if it exists.
*/
public function getLibrary() {
return $this->library;
}
/**
* Sets the asset library for this layout definition.
*
* @param string|null $library
* The asset library.
*
* @return $this
*/
public function setLibrary($library) {
$this->library = $library;
return $this;
}
/**
* Gets the icon path for this layout definition.
*
* @return string|null
* The icon path, if it exists.
*/
public function getIconPath() {
return $this->icon;
}
/**
* Sets the icon path for this layout definition.
*
* @param string|null $icon
* The icon path.
*
* @return $this
*/
public function setIconPath($icon) {
$this->icon = $icon;
return $this;
}
/**
* Gets the regions for this layout definition.
*
* @return array[]
* The layout regions. The keys of the array are the machine names of the
* regions, and the values are an associative array with the following
* keys:
* - label: (string) The human-readable name of the region.
* Any remaining keys may have special meaning for the given layout plugin,
* but are undefined here.
*/
public function getRegions() {
return $this->regions;
}
/**
* Sets the regions for this layout definition.
*
* @param array[] $regions
* An array of regions, see ::getRegions() for the format.
*
* @return $this
*/
public function setRegions(array $regions) {
$this->regions = $regions;
return $this;
}
/**
* Gets the machine-readable region names.
*
* @return string[]
* An array of machine-readable region names.
*/
public function getRegionNames() {
return array_keys($this->getRegions());
}
/**
* Gets the human-readable region labels.
*
* @return string[]
* An array of human-readable region labels.
*/
public function getRegionLabels() {
$regions = $this->getRegions();
return array_combine(array_keys($regions), array_column($regions, 'label'));
}
/**
* Gets the default region.
*
* @return string
* The machine-readable name of the default region.
*/
public function getDefaultRegion() {
return $this->default_region;
}
/**
* Sets the default region.
*
* @param string $default_region
* The machine-readable name of the default region.
*
* @return $this
*/
public function setDefaultRegion($default_region) {
$this->default_region = $default_region;
return $this;
}
/**
* Gets the name of the provider of this layout definition.
*
* @return string
* The name of the provider of this layout definition.
*/
public function getProvider() {
return $this->provider;
}
/**
* Gets the config dependencies of this layout definition.
*
* @return array
* An array of config dependencies.
*
* @see \Drupal\Core\Plugin\PluginDependencyTrait::calculatePluginDependencies()
*/
public function getConfigDependencies() {
return $this->config_dependencies;
}
/**
* Sets the config dependencies of this layout definition.
*
* @param array $config_dependencies
* An array of config dependencies.
*
* @return $this
*/
public function setConfigDependencies(array $config_dependencies) {
$this->config_dependencies = $config_dependencies;
return $this;
}
/**
* {@inheritdoc}
*/
public function getDeriver() {
return $this->deriver;
}
/**
* {@inheritdoc}
*/
public function setDeriver($deriver) {
$this->deriver = $deriver;
return $this;
}
}
<?php
namespace Drupal\Core\Layout;
use Drupal\Component\Plugin\DerivativeInspectionInterface;
use Drupal\Component\Plugin\PluginInspectionInterface;
use Drupal\Component\Plugin\ConfigurablePluginInterface;
/**
* Provides an interface for static Layout plugins.
*
* @internal
* The layout system is currently experimental and should only be leveraged by
* experimental modules and development releases of contributed modules.
* See https://www.drupal.org/core/experimental for more information.
*/
interface LayoutInterface extends PluginInspectionInterface, DerivativeInspectionInterface, ConfigurablePluginInterface {
/**
* Build a render array for layout with regions.
*
* @param array $regions
* An associative array keyed by region name, containing render arrays
* representing the content that should be placed in each region.
*
* @return array
* Render array for the layout with regions.
*/
public function build(array $regions);
/**
* {@inheritdoc}
*
* @return \Drupal\Core\Layout\LayoutDefinition
*/
public function getPluginDefinition();
}
<?php
namespace Drupal\Core\Layout;
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Plugin\Discovery\AnnotatedClassDiscovery;
use Drupal\Core\Plugin\Discovery\YamlDiscoveryDecorator;
use Drupal\Core\Layout\Annotation\Layout;
/**
* Provides a plugin manager for layouts.
*
* @internal
* The layout system is currently experimental and should only be leveraged by
* experimental modules and development releases of contributed modules.
* See https://www.drupal.org/core/experimental for more information.
*/
class LayoutPluginManager extends DefaultPluginManager implements LayoutPluginManagerInterface {
/**
* The theme handler.
*
* @var \Drupal\Core\Extension\ThemeHandlerInterface
*/
protected $themeHandler;
/**
* LayoutPluginManager constructor.
*
* @param \Traversable $namespaces
* An object that implements \Traversable which contains the root paths
* keyed by the corresponding namespace to look for plugin implementations.
* @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
* Cache backend instance to use.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler to invoke the alter hook with.
* @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
* The theme handler to invoke the alter hook with.
*/
public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler, ThemeHandlerInterface $theme_handler) {
parent::__construct('Plugin/Layout', $namespaces, $module_handler, LayoutInterface::class, Layout::class);
$this->themeHandler = $theme_handler;
$this->setCacheBackend($cache_backend, 'layout');
$this->alterInfo('layout');
}
/**
* {@inheritdoc}
*/
protected function providerExists($provider) {
return $this->moduleHandler->moduleExists($provider) || $this->themeHandler->themeExists($provider);
}
/**
* {@inheritdoc}
*/
protected function getDiscovery() {
if (!$this->discovery) {
$discovery = new AnnotatedClassDiscovery($this->subdir, $this->namespaces, $this->pluginDefinitionAnnotationName, $this->additionalAnnotationNamespaces);
$discovery = new YamlDiscoveryDecorator($discovery, 'layouts', $this->moduleHandler->getModuleDirectories() + $this->themeHandler->getThemeDirectories());
$discovery = new ObjectDefinitionDiscoveryDecorator($discovery, $this->pluginDefinitionAnnotationName);
$discovery = new ObjectDefinitionContainerDerivativeDiscoveryDecorator($discovery);
$this->discovery = $discovery;
}
return $this->discovery;
}
/**
* {@inheritdoc}
*/
public function processDefinition(&$definition, $plugin_id) {
parent::processDefinition($definition, $plugin_id);
if (!$definition instanceof LayoutDefinition) {
throw new InvalidPluginDefinitionException($plugin_id, sprintf('The "%s" layout definition must extend %s', $plugin_id, LayoutDefinition::class));
}
// Keep class definitions standard with no leading slash.
// @todo Remove this once https://www.drupal.org/node/2824655 is resolved.
$definition->setClass(ltrim($definition->getClass(), '\\'));
// Add the module or theme path to the 'path'.
$provider = $definition->getProvider();
if ($this->moduleHandler->moduleExists($provider)) {
$base_path = $this->moduleHandler->getModule($provider)->getPath();
}
elseif ($this->themeHandler->themeExists($provider)) {
$base_path = $this->themeHandler->getTheme($provider)->getPath();
}
else {
$base_path = '';
}
$path = $definition->getPath();
$path = !empty($path) ? $base_path . '/' . $path : $base_path;
$definition->setPath($path);
// Add the base path to the icon path.
if ($icon_path = $definition->getIconPath()) {
$definition->setIconPath($path . '/' . $icon_path);
}
// Add a dependency on the provider of the library.
if ($library = $definition->getLibrary()) {
$config_dependencies = $definition->getConfigDependencies();
list($library_provider) = explode('/', $library, 2);
if ($this->moduleHandler->moduleExists($library_provider)) {
$config_dependencies['module'][] = $library_provider;
}
elseif ($this->themeHandler->themeExists($library_provider)) {
$config_dependencies['theme'][] = $library_provider;
}
$definition->setConfigDependencies($config_dependencies);
}
// If 'template' is set, then we'll derive 'template_path' and 'theme_hook'.
$template = $definition->getTemplate();
if (!empty($template)) {
$template_parts = explode('/', $template);
$template = array_pop($template_parts);
$template_path = $path;
if (count($template_parts) > 0) {
$template_path .= '/' . implode('/', $template_parts);
}
$definition->setTemplate($template);
// Prepend 'layout__' so the base theme hook will be used.
// @todo Remove this workaround for https://www.drupal.org/node/2559825 in
// https://www.drupal.org/node/2834019.
$definition->setThemeHook('layout__' . strtr($template, '-', '_'));
$definition->setTemplatePath($template_path);
}
if (!$definition->getDefaultRegion()) {
$definition->setDefaultRegion(key($definition->getRegions()));
}
}
/**
* {@inheritdoc}
*/
public function getThemeImplementations() {
$hooks = [];
$hooks['layout'] = [
'render element' => 'content',
];
/** @var \Drupal\Core\Layout\LayoutDefinition[] $definitions */
$definitions = $this->getDefinitions();
foreach ($definitions as $definition) {
if ($template = $definition->getTemplate()) {
$hooks[$definition->getThemeHook()] = [
'render element' => 'content',
'base hook' => 'layout',
'template' => $template,
'path' => $definition->getTemplatePath(),
];
}
}
return $hooks;
}
/**
* {@inheritdoc}
*/
public function getCategories() {
// Fetch all categories from definitions and remove duplicates.
$categories = array_unique(array_values(array_map(function (LayoutDefinition $definition) {
return $definition->getCategory();
}, $this->getDefinitions())));
natcasesort($categories);
return $categories;
}
/**
* {@inheritdoc}
*
* @return \Drupal\Core\Layout\LayoutDefinition[]
*/
public function getSortedDefinitions(array $definitions = NULL, $label_key = 'label') {
// Sort the plugins first by category, then by label.
$definitions = isset($definitions) ? $definitions : $this->getDefinitions();
// Suppress errors because PHPUnit will indirectly modify the contents,
// triggering https://bugs.php.net/bug.php?id=50688.
@uasort($definitions, function (LayoutDefinition $a, LayoutDefinition $b) {
if ($a->getCategory() != $b->getCategory()) {
return strnatcasecmp($a->getCategory(), $b->getCategory());
}
return strnatcasecmp($a->getLabel(), $b->getLabel());
});
return $definitions;
}
/**
* {@inheritdoc}
*
* @return \Drupal\Core\Layout\LayoutDefinition[][]
*/
public function getGroupedDefinitions(array $definitions = NULL, $label_key = 'label') {
$definitions = $this->getSortedDefinitions(isset($definitions) ? $definitions : $this->getDefinitions(), $label_key);
$grouped_definitions = [];
foreach ($definitions as $id => $definition) {
$grouped_definitions[(string) $definition->getCategory()][$id] = $definition;
}
return $grouped_definitions;
}
/**
* {@inheritdoc}
*/
public function getLayoutOptions() {
$layout_options = [];
foreach ($this->getGroupedDefinitions() as $category => $layout_definitions) {
foreach ($layout_definitions as $name => $layout_definition) {
$layout_options[$category][$name] = $layout_definition->getLabel();
}
}
return $layout_options;
}
}
<?php
namespace Drupal\Core\Layout;
use Drupal\Component\Plugin\CategorizingPluginManagerInterface;
/**
* Provides the interface for a plugin manager of layouts.
*
* @internal
* The layout system is currently experimental and should only be leveraged by
* experimental modules and development releases of contributed modules.
* See https://www.drupal.org/core/experimental for more information.
*/
interface LayoutPluginManagerInterface extends CategorizingPluginManagerInterface {
/**
* Gets theme implementations for layouts.
*
* @return array
* An associative array of the same format as returned by hook_theme().
*
* @see hook_theme()
*/
public function getThemeImplementations();
/**
* {@inheritdoc}
*
* @return \Drupal\Core\Layout\LayoutInterface
*/
public function createInstance($plugin_id, array $configuration = []);
/**
* {@inheritdoc}
*
* @return \Drupal\Core\Layout\LayoutDefinition|null
*/
public function getDefinition($plugin_id, $exception_on_invalid = TRUE);
/**
* {@inheritdoc}
*
* @return \Drupal\Core\Layout\LayoutDefinition[]
*/
public function getDefinitions();
/**
* {@inheritdoc}
*
* @return \Drupal\Core\Layout\LayoutDefinition[]
*/
public function getSortedDefinitions(array $definitions = NULL);
/**
* {@inheritdoc}
*
* @return \Drupal\Core\Layout\LayoutDefinition[][]
*/
public function getGroupedDefinitions(array $definitions = NULL);
/**
* Returns an array of layout labels grouped by category.
*
* @return string[][]
* A nested array of labels suitable for #options.
*/
public function getLayoutOptions();
}
<?php
namespace Drupal\Core\Layout;
use Drupal\Component\Plugin\Exception\InvalidDeriverException;
use Drupal\Core\Plugin\Discovery\ContainerDerivativeDiscoveryDecorator;
/**
* Allows object-based definitions to use derivatives.
*
* @internal
* The layout system is currently experimental and should only be leveraged by
* experimental modules and development releases of contributed modules.
* See https://www.drupal.org/core/experimental for more information.
*
* @todo In https://www.drupal.org/node/2821189 merge into
* \Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator.
*/
class ObjectDefinitionContainerDerivativeDiscoveryDecorator extends ContainerDerivativeDiscoveryDecorator {
/**
* {@inheritdoc}
*/
protected function getDeriverClass($base_definition) {
$class = NULL;
if ($base_definition instanceof DerivablePluginDefinitionInterface && $class = $base_definition->getDeriver()) {
if (!class_exists($class)) {
throw new InvalidDeriverException(sprintf('Plugin (%s) deriver "%s" does not exist.', $base_definition['id'], $class));
}
if (!is_subclass_of($class, '\Drupal\Component\Plugin\Derivative\DeriverInterface')) {
throw new InvalidDeriverException(sprintf('Plugin (%s) deriver "%s" must implement \Drupal\Component\Plugin\Derivative\DeriverInterface.', $base_definition['id'], $class));
}
}
return $class;
}
}
<?php
namespace Drupal\Core\Layout;
use Drupal\Component\Plugin\Discovery\DiscoveryInterface;
use Drupal\Component\Plugin\Discovery\DiscoveryTrait;
/**
* Ensures that all array-based definitions are converted to objects.
*
* @internal
* The layout system is currently experimental and should only be leveraged by
* experimental modules and development releases of contributed modules.
* See https://www.drupal.org/core/experimental for more information.
*
* @todo Move into \Drupal\Component\Plugin\Discovery in
* https://www.drupal.org/node/2822752.
*/
class ObjectDefinitionDiscoveryDecorator implements DiscoveryInterface {
use DiscoveryTrait;
/**
* The decorated plugin discovery.
*
* @var \Drupal\Component\Plugin\Discovery\DiscoveryInterface
*/
protected $decorated;
/**
* The name of the annotation that contains the plugin definition.
*
* The class corresponding to this name must implement
* \Drupal\Component\Annotation\AnnotationInterface.
*
* @var string|null
*/
protected $pluginDefinitionAnnotationName;
/**
* ObjectDefinitionDiscoveryDecorator constructor.
*
* @param \Drupal\Component\Plugin\Discovery\DiscoveryInterface $decorated
* The discovery object that is being decorated.
* @param string $plugin_definition_annotation_name
* The name of the annotation that contains the plugin definition.
*/
public function __construct(DiscoveryInterface $decorated, $plugin_definition_annotation_name) {
$this->decorated = $decorated;
$this->pluginDefinitionAnnotationName = $plugin_definition_annotation_name;
}
/**
* {@inheritdoc}
*/
public function getDefinitions() {
$definitions = $this->decorated->getDefinitions();
foreach ($definitions as $id => $definition) {
if (is_array($definition)) {
$definitions[$id] = (new $this->pluginDefinitionAnnotationName($definition))->get();
}
}
return $definitions;
}
/**
* Passes through all unknown calls onto the decorated object.
*
* @param string $method
* The method to call on the decorated plugin discovery.
* @param array $args
* The arguments to send to the method.
*
* @return mixed
* The method result.
*/
public function __call($method, $args) {
return call_user_func_array([$this->decorated, $method], $args);
}
}
name: 'Layout Discovery'
type: module
description: 'Provides a way for modules or themes to register layouts.'
package: Core (Experimental)
version: VERSION
core: 8.x
<?php
/**
* @file
* Install, update, and uninstall functions for the Layout Discovery module.
*/
/**
* Implements hook_requirements().
*/
function layout_discovery_requirements($phase) {
$requirements = [];
if ($phase === 'install') {
if (\Drupal::moduleHandler()->moduleExists('layout_plugin')) {
$requirements['layout_discovery'] = [
'description' => t('Layout Discovery cannot be installed because the Layout Plugin module is installed and incompatible.'),
'severity' => REQUIREMENT_ERROR,
];
}
}
return $requirements;
}
<?php
/**
* @file
* Provides hook implementations for Layout Discovery.
*/
/**
* Implements hook_help().
*/
function layout_discovery_help($route_name) {
switch ($route_name) {
case 'help.page.layout_discovery':
$output = '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('Layout Discovery allows modules or themes to register layouts, and for other modules to list the available layouts and render them.') . '</p>';
$output .= '<p>' . t('For more information, see the <a href=":layout-discovery-documentation">online documentation for the Layout Discovery module</a>.', [':layout-discovery-documentation' => 'https://www.drupal.org/node/2619128']) . '</p>';
return $output;
}
}
/**
* Implements hook_theme().
*/
function layout_discovery_theme() {
return \Drupal::service('plugin.manager.core.layout')->getThemeImplementations();
}
/**
* Prepares variables for layout templates.
*
* @param array &$variables
* An associative array containing:
* - content: An associative array containing the properties of the element.
* Properties used: #settings, #layout.
*/
function template_preprocess_layout(&$variables) {
$variables['settings'] = isset($variables['content']['#settings']) ? $variables['content']['#settings'] : [];
$variables['layout'] = isset($variables['content']['#layout']) ? $variables['content']['#layout'] : [];
}
services:
plugin.manager.core.layout:
class: Drupal\Core\Layout\LayoutPluginManager
arguments: ['@container.namespaces', '@cache.discovery', '@module_handler', '@theme_handler']
{#
/**
* @file
* Template for a generic layout.
*/
#}
{% set classes = [
'layout--' ~ layout.id|clean_class,
] %}
{% if content %}
<div{{ attributes.addClass(classes) }}>
{% for region in layout.getRegionNames %}
<div class="{{ 'region--' ~ region|clean_class }}">
{{ content[region] }}
</div>
{% endfor %}
</div>
{% endif %}
<?php
namespace Drupal\Tests\layout_discovery\Kernel;
use Drupal\Core\Form\FormState;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests Layout functionality.
*
* @group Layout
*/
class LayoutTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['system', 'layout_discovery', 'layout_test'];
/**
* The layout plugin manager.
*
* @var \Drupal\Core\Layout\LayoutPluginManagerInterface
*/
protected $layoutPluginManager;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->layoutPluginManager = $this->container->get('plugin.manager.core.layout');
}
/**
* Test rendering a layout.
*
* @dataProvider renderLayoutData
*/
public function testRenderLayout($layout_id, $config, $regions, $html) {
$layout = $this->layoutPluginManager->createInstance($layout_id, $config);
$built['layout'] = $layout->build($regions);
// Assume each layout is contained by a form, in order to ensure the
// building of the layout does not interfere with form processing.
$form_state = new FormState();
$form_builder = $this->container->get('form_builder');
$form_builder->prepareForm('the_form_id', $built, $form_state);
$form_builder->processForm('the_form_id', $built, $form_state);
$this->render($built);
$this->assertRaw($html);
$this->assertRaw('<input data-drupal-selector="edit-the-form-id" type="hidden" name="form_id" value="the_form_id" />');
}
/**
* Data provider for testRenderLayout().
*/
public function renderLayoutData() {
$data['layout_test_1col_with_form'] = [
'layout_test_1col',
[],
[
'top' => [
'#process' => [[static::class, 'processCallback']],
],
'bottom' => [
'#markup' => 'This is the bottom',
],
],
];
$data['layout_test_1col'] = [
'layout_test_1col',
[],
[
'top' => [
'#markup' => 'This is the top',
],
'bottom' => [
'#markup' => 'This is the bottom',
],
],
];
$data['layout_test_1col_no_template'] = [
'layout_test_1col_no_template',
[],
[
'top' => [
'#markup' => 'This is the top',
],
'bottom' => [
'#markup' => 'This is the bottom',
],
],
];
$data['layout_test_2col'] = [
'layout_test_2col',
[],
[
'left' => [
'#markup' => 'This is the left',
],
'right' => [
'#markup' => 'This is the right',
],
],
];
$data['layout_test_plugin'] = [
'layout_test_plugin',
[
'setting_1' => 'Config value',
],
[
'main' => [
'#markup' => 'Main region',
],
],
];
$data['layout_test_1col_with_form'][] = <<<'EOD'
<div class="layout-example-1col clearfix">
<div class="region-top">
This string added by #process.
</div>
<div class="region-bottom">
This is the bottom
</div>
</div>
EOD;
$data['layout_test_1col'][] = <<<'EOD'
<div class="layout-example-1col clearfix">
<div class="region-top">
This is the top
</div>
<div class="region-bottom">
This is the bottom
</div>
</div>
EOD;
$data['layout_test_1col_no_template'][] = <<<'EOD'
<div data-drupal-selector="edit-layout" class="layout--layout-test-1col-no-template">
<div class="region--top">
This is the top
</div>
<div class="region--bottom">
This is the bottom
</div>
</div>
EOD;
$data['layout_test_2col'][] = <<<'EOD'
<div class="layout-example-2col clearfix">
<div class="region-left">
This is the left
</div>
<div class="region-right">
This is the right
</div>
</div>
EOD;
$data['layout_test_plugin'][] = <<<'EOD'
<div class="layout-test-plugin clearfix">
<div>
<span class="setting-1-label">Blah: </span>
Config value
</div>
<div class="region-main">
Main region
</div>
</div>
EOD;
return $data;
}
/**
* Provides a test #process callback.
*/
public static function processCallback($element) {
$element['#markup'] = 'This string added by #process.';
return $element;
}
}
layout_plugin.settings.layout_test_plugin:
type: layout_plugin.settings
label: 'Layout test plugin settings'
mapping:
setting_1:
type: string
label: 'Setting 1'
.layout-example-2col .region-left {
float: left;
width: 50%;
}
* html .layout-example-2col .region-left {
width: 49.9%;
}
.layout-example-2col .region-right {
float: left;
width: 50%;
}
* html .layout-example-2col .region-right {
width: 49.9%;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment