neuraflow-1.0.0/neuraflow.module
neuraflow.module
<?php
/**
* @file
* Primary module hooks for Neuraflow module.
*/
use Drupal\Core\Condition\ConditionPluginCollection;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
/**
* Implements hook_page_attachments().
*/
function neuraflow_page_attachments(&$variables): void {
if (neuraflow__is_neurabot_active()) {
$config = \Drupal::service('config.factory')->get('neuraflow.settings');
$variables['#attached']['library'][] = 'neuraflow/neurabot';
$variables['#attached']['drupalSettings']['neuraflow'] = [
'neurabot' => [
'neurabotConfig' => $config->get('neurabot.neurabotConfig'),
],
];
}
}
/**
* Evaluates all conditions and determines if it is active.
*
* @return bool
* Whether this rule is active.
*/
function neuraflow__is_neurabot_active(): bool {
/** @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface $contextRepository */
$contextRepository = \Drupal::service('context.repository');
/** @var \Drupal\Core\Config\ConfigFactory $configFactory */
$configFactory = \Drupal::service('config.factory');
$config = $configFactory->get('neuraflow.settings');
/** @var \Drupal\Core\Executable\ExecutableManagerInterface $conditionPluginManager */
$conditionPluginManager = \Drupal::service('plugin.manager.condition');
$visibilityConditions = new ConditionPluginCollection($conditionPluginManager, $config->get('neurabot.visibility') ?? []);
// Rules are good unless told otherwise by the conditions.
foreach ($visibilityConditions as $condition) {
// Need to get context for this condition.
if ($condition instanceof ContextAwarePluginInterface) {
// Get runtime contexts and set them for this condition.
$runtime_contexts = $contextRepository
->getRuntimeContexts($condition->getContextMapping());
$condition_contexts = $condition->getContextDefinitions();
foreach ($condition->getContextMapping() as $name => $context) {
// Attach appropriate context.
if (isset($runtime_contexts[$context])
&& $runtime_contexts[$context]->hasContextValue()) {
$condition->setContext($name, $runtime_contexts[$context]);
}
// Does not have context but is required means this rule is inactive.
elseif ($condition_contexts[$name]->isRequired()) {
return FALSE;
}
}
}
// If this condition evaluates to false, rule is inactive.
if (!$condition->execute()) {
return FALSE;
}
}
// No objections, rule is active.
return TRUE;
}
