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> *&nbsp;&nbsp; id = "current_node_title",<br> *&nbsp;&nbsp; context_definitions = {<br> *&nbsp;&nbsp;&nbsp;&nbsp; "node" = @ContextDefinition("entity:node", label = @Translation("Node"), required = FALSE),<br> *&nbsp;&nbsp; },<br> * );<br> */<br>class CurrentNodeTitle extends GlobalVariable implements ContextAwarePluginInterface {<br>&nbsp; public function getValue(): string {<br>&nbsp;&nbsp;&nbsp; $node = $this-&gt;getContextValue('node');<br>&nbsp;&nbsp;&nbsp; ...<br>&nbsp; }<br><br>&nbsp; // MGV plugins aren't configurable, so we hardcode the mapping here.<br>&nbsp; // In this case we always want the "Node from URL" context value.<br>&nbsp; public function getContextMapping() {<br>&nbsp;&nbsp;&nbsp; return [<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 'node' =&gt; '@node.node_route_context:node',<br>&nbsp;&nbsp;&nbsp; ];<br>&nbsp; }<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>&nbsp; if ($variable instanceof ContextAwarePluginInterface) {<br>&nbsp;&nbsp;&nbsp; $contexts = \Drupal::service('context.repository')-&gt;getRuntimeContexts($variable-&gt;getContextMapping());<br>&nbsp;&nbsp;&nbsp; \Drupal::service('context.handler')-&gt;applyContextMapping($variable, $contexts);<br>&nbsp; }</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