Problem/Motivation
Some blocks do require context's to work. Currently these kind of blocks cannot be loaded with the BlockPluginViewBuilder.
Proposed resolution
I would suggestion support for custom context mappings via an additional, optional parameter.
API changes
$blockPluginViewBuilder = \Drupal::service('block_plugin.view_builder');
// Pass optional configuration.
$configuration = [];
$build = $blockPluginViewBuilder->view(‘plugin_id', $configuration, [
'node' => new Context(new EntityContextDefinition('entity:node'), $node),
]));
Comments
Comment #3
wtrv commentedThanks for the suggestion.
I'll review asap and get back to you.
Comment #4
wtrv commentedI agree. the context-passing feature is needed -- some block plugins are context-aware and can't be rendered via BlockPluginViewBuilder without it.
However, serialize()/unserialize() should not be used here. unserialize() is a well-known PHP object injection vector: if an attacker can influence the serialized string, they can instantiate arbitrary objects and trigger magic methods (__destruct, __wakeup, etc.) to achieve remote code execution. In this case the serialized data flows through lazy builder arguments and the render cache, which makes the attack surface wider than it might seem.
Instead, we can extract safe scalar identifiers from context objects and reconstruct them in the lazy builder:
These are the only two ContextDefinition types in Drupal core (ContextDefinition for scalars, EntityContextDefinition for entities), and in practice block plugin contexts are always one of these two. ContextDefinition::create($dataType) is a built-in factory that automatically returns the correct subclass, so reconstruction is straightforward.
This approach keeps JSON as the only encoding format, avoids any PHP object serialization, and covers all real-world block context types.
Comment #6
wtrv commentedFixed in 1.0.6
Comment #7
hydra commentedThx for taking the time digging into this :) I use this module a lot and this will help. I also use custom data types and contexts so if I walk into limitations with this approach I will create a new issue for this, for the 98% of the usecases this seems reasonable.
Comment #8
wtrv commentedComment #9
wtrv commentedOkay, please do let me know. For now, your custom contextDefinitions will throw an exception.
Edit: I will probably create a new major version and use tagged service collector and a new interface. Will let you know in the new issue when I have the new version ready.