Commit e9500065 authored by xjm's avatar xjm

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
......@@ -105,6 +105,7 @@
"drupal/image": "self.version",
"drupal/inline_form_errors": "self.version",
"drupal/language": "self.version",
"drupal/layout_discovery": "self.version",
"drupal/link": "self.version",
"drupal/locale": "self.version",
"drupal/minimal": "self.version",
......
......@@ -361,6 +361,13 @@ display_variant.plugin:
type: string
label: 'UUID'
layout_plugin.settings:
type: mapping
label: 'Layout settings'
layout_plugin.settings.*:
type: layout_plugin.settings
base_entity_reference_field_settings:
type: mapping
mapping:
......
......@@ -2178,6 +2178,17 @@ function hook_display_variant_plugin_alter(array &$definitions) {
$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.
*
......
<?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();
}
}
This diff is collapsed.
<?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.
*