Allow mgv plugins to be context-aware
>>> [!note] Migrated issue
<!-- Drupal.org comment -->
<!-- Migrated from issue #3450202. -->
Reported by: [erik.erskine](https://www.drupal.org/user/375884)
Related to !17
>>>
<h3 id="summary-problem-motivation">Problem/Motivation</h3>
<p>We have a use case for making a context-aware <code>@Mgv</code> plugin, like the following, which shows the title of the "current" node.</p>
<pre>/**<br> * @Mgv(<br> * id = "current_node_title",<br> * context_definitions = {<br> * "node" = @ContextDefinition("entity:node", label = @Translation("Node"), required = FALSE),<br> * },<br> * );<br> */<br>class CurrentNodeTitle extends GlobalVariable implements ContextAwarePluginInterface {<br> public function getValue(): string {<br> $node = $this->getContextValue('node');<br> ...<br> }<br><br> // MGV plugins aren't configurable, so we hardcode the mapping here.<br> // In this case we always want the "Node from URL" context value.<br> public function getContextMapping() {<br> return [<br> 'node' => '@node.node_route_context:node',<br> ];<br> }<br><br>}</pre><p>At the moment this is impossible because <code>MgvPluginManager</code> does not anticipate <code>@Mgv</code> plugins being context-aware, and doesn't pass the necessary values to them.</p>
<h4 id="summary-steps-reproduce">Steps to reproduce</h4>
<p>Try something like the above. <code>$node</code> will always be <code>NULL</code>.</p>
<h3 id="summary-proposed-resolution">Proposed resolution</h3>
<p>Add the following to <code>MgvPluginManager::getVariables()</code>: (based on what <code>BlockViewBuilder</code> does for block plugins)</p>
<pre> if ($variable instanceof ContextAwarePluginInterface) {<br> $contexts = \Drupal::service('context.repository')->getRuntimeContexts($variable->getContextMapping());<br> \Drupal::service('context.handler')->applyContextMapping($variable, $contexts);<br> }</pre><h3 id="summary-remaining-tasks">Remaining tasks</h3>
<p>Patch, test, get feedback.</p>
<h3 id="summary-ui-changes">User interface changes</h3>
<p>None.</p>
<h3 id="summary-api-changes">API changes</h3>
<p>None. Existing plugins are unaffected.</p>
<h3 id="summary-data-model-changes">Data model changes</h3>
<p>None.</p>
issue