Browse Source

Transform into a twig filter.

merge-requests/17/head
Rodrigo Aguilera 3 years ago
parent
commit
d352a3bf95
  1. 9
      docs/cheat-sheet.md
  2. 75
      src/TwigTweakExtension.php

9
docs/cheat-sheet.md

@ -351,13 +351,12 @@ ensure that cache metadata are bubbled up.
{{ content.field_media|cache_metadata }} {{ content.field_media|cache_metadata }}
``` ```
## Conditions from context ## Conditions from context for access to render arrays
The system that controls the visibility of blocks can be used to evaluate The system that controls the visibility of blocks can be used to evaluate
if a condition is fullfilled. if a condition is fullfilled. Set the `#access` key to a render array to control visibility.
```twig ```twig
{% if languageIsSpanish = drupal_condition_evaluate('language', {'langcodes': {'es':'es'}}) %} {# Display content only for the spanish language #}
Hola {{ content|set_conditional_access('language', {'langcodes': {'es':'es'}}) }}
{% endif %}
``` ```
## PHP ## PHP

75
src/TwigTweakExtension.php

@ -5,6 +5,7 @@ namespace Drupal\twig_tweak;
use Drupal\Component\Utility\NestedArray; use Drupal\Component\Utility\NestedArray;
use Drupal\Component\Utility\Unicode; use Drupal\Component\Utility\Unicode;
use Drupal\Component\Uuid\Uuid; use Drupal\Component\Uuid\Uuid;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableMetadata; use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityInterface; use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Extension\ModuleHandlerInterface; use Drupal\Core\Extension\ModuleHandlerInterface;
@ -86,8 +87,6 @@ class TwigTweakExtension extends AbstractExtension {
new TwigFunction('drupal_breakpoint', [self::class, 'drupalBreakpoint'], $all_options), new TwigFunction('drupal_breakpoint', [self::class, 'drupalBreakpoint'], $all_options),
// @phpcs:ignore Drupal.Arrays.Array.LongLineDeclaration // @phpcs:ignore Drupal.Arrays.Array.LongLineDeclaration
new TwigFunction('drupal_contextual_links', [self::class, 'drupalContextualLinks']), new TwigFunction('drupal_contextual_links', [self::class, 'drupalContextualLinks']),
// @phpcs:ignore Drupal.Arrays.Array.LongLineDeclaration
new TwigFunction('drupal_condition_evaluate', [self::class, 'drupalConditionEvaluate']),
]; ];
$this->moduleHandler->alter('twig_tweak_functions', $functions); $this->moduleHandler->alter('twig_tweak_functions', $functions);
@ -118,6 +117,8 @@ class TwigTweakExtension extends AbstractExtension {
new TwigFilter('entity_link', [self::class, 'entityLink']), new TwigFilter('entity_link', [self::class, 'entityLink']),
new TwigFilter('translation', [self::class, 'entityTranslation']), new TwigFilter('translation', [self::class, 'entityTranslation']),
new TwigFilter('cache_metadata', [self::class, 'CacheMetadata']), new TwigFilter('cache_metadata', [self::class, 'CacheMetadata']),
// @phpcs:ignore Drupal.Arrays.Array.LongLineDeclaration
new TwigFilter('set_conditional_access', [self::class, 'setConditionalAccess']),
]; ];
if (Settings::get('twig_tweak_enable_php_filter')) { if (Settings::get('twig_tweak_enable_php_filter')) {
@ -422,37 +423,6 @@ class TwigTweakExtension extends AbstractExtension {
return $build; return $build;
} }
/**
* Use a condition plugin to evaluate based on the context.
*
* @param string $plugin_id
* The plugin ID.
* @param array $configuration
* Configuration for the plugin.
*
* @return bool
* The evaluation of the plugin.
*/
public static function drupalConditionEvaluate(string $plugin_id, array $configuration = []): bool {
$pluginInstance = \Drupal::service('plugin.manager.condition')->createInstance($plugin_id);
$pluginInstance->setConfiguration($configuration);
$contextRepository = \Drupal::service('context.repository');
$availableContexts = $contextRepository->getAvailableContexts();
// Ensure that the contexts have data by getting corresponding runtime contexts.
$availableRuntimeContexts = $contextRepository->getRuntimeContexts(array_keys($availableContexts));
$pluginContextDefinitions = $pluginInstance->getContextDefinitions();
foreach ($pluginContextDefinitions as $name => $pluginContextDefinition) {
// Identify and fetch the matching runtime context, with the plugin's context definition.
$matches = \Drupal::service('context.handler')->getMatchingContexts($availableRuntimeContexts, $pluginContextDefinition);
$matchingContext = reset($matches);
// Set the value to the plugin's context, from runtime context value.
$pluginInstance->setContextValue($name, $matchingContext->getContextValue());
}
return $pluginInstance->evaluate();
}
/** /**
* Emits a breakpoint to the debug client. * Emits a breakpoint to the debug client.
* *
@ -719,6 +689,45 @@ class TwigTweakExtension extends AbstractExtension {
return \Drupal::service('twig_tweak.cache_metadata_extractor')->extractCacheMetadata($input); return \Drupal::service('twig_tweak.cache_metadata_extractor')->extractCacheMetadata($input);
} }
/**
* Use a condition plugin to give access to a render array.
*
* The evaluation is based on the context.
*
* @param string $build
* A render array.
* @param string $plugin_id
* The plugin ID.
* @param array $configuration
* Configuration for the plugin.
*
* @return array
* The render array with the evaluation of the plugin in the #access key.
*/
public static function setConditionalAccess($build, string $plugin_id, array $configuration = []): array {
$pluginInstance = \Drupal::service('plugin.manager.condition')->createInstance($plugin_id);
$pluginInstance->setConfiguration($configuration);
$contextRepository = \Drupal::service('context.repository');
$availableContexts = $contextRepository->getAvailableContexts();
// Ensure that the contexts have data by getting corresponding runtime contexts.
$availableRuntimeContexts = $contextRepository->getRuntimeContexts(array_keys($availableContexts));
$pluginContextDefinitions = $pluginInstance->getContextDefinitions();
foreach ($pluginContextDefinitions as $name => $pluginContextDefinition) {
// Identify and fetch the matching runtime context, with the plugin's context definition.
$matches = \Drupal::service('context.handler')->getMatchingContexts($availableRuntimeContexts, $pluginContextDefinition);
$matchingContext = reset($matches);
$build['#cache']['contexts'] = Cache::mergeContexts($matchingContext->getCacheContexts(), $build['#cache']['contexts'] ?? []);
$build['#cache']['tags'] = Cache::mergeTags($matchingContext->getCacheTags(), $build['#cache']['tags'] ?? []);
$build['#cache']['max-age'] = Cache::mergeMaxAges($matchingContext->getCacheMaxAge(), $build['#cache']['max-age'] ?? Cache::PERMANENT);
// Set the value to the plugin's context, from runtime context value.
$pluginInstance->setContextValue($name, $matchingContext->getContextValue());
}
$build['#access'] = $pluginInstance->evaluate();
return $build;
}
/** /**
* Evaluates a string of PHP code. * Evaluates a string of PHP code.
* *

Loading…
Cancel
Save