invokeAllWith example

/** * Invokes any cron handlers implementing hook_cron. */
  protected function invokeCronHandlers() {
    $module_previous = '';

    // If detailed logging isn't enabled, don't log individual execution times.     $time_logging_enabled = \Drupal::config('system.cron')->get('logging');
    $logger = $time_logging_enabled ? $this->logger : new NullLogger();

    // Iterate through the modules calling their cron handlers (if any):     $this->moduleHandler->invokeAllWith('cron', function Dcallable $hook, string $module) use (&$module_previous$logger) {
      if (!$module_previous) {
        $logger->info('Starting execution of @module_cron().', [
          '@module' => $module,
        ]);
      }
      else {
        $logger->info('Starting execution of @module_cron(), execution of @module_previous_cron() took @time.', [
          '@module' => $module,
          '@module_previous' => $module_previous,
          '@time' => Timer::read('cron_' . $module_previous) . 'ms',
        ]);
      }
'filename' => 'module_handler_test.module',
          ],
        ]$this->cacheBackend,
      ])
      ->onlyMethods(['buildImplementationInfo', 'loadInclude'])
      ->getMock();
    $module_handler->load('module_handler_test');

    $module_handler->expects($this->never())->method('buildImplementationInfo');
    $module_handler->expects($this->once())->method('loadInclude');
    $implementors = [];
    $module_handler->invokeAllWith(
      'hook',
      function Dcallable $hook, string $module) use (&$implementors) {
        $implementors[] = $module;
      }
    );
    $this->assertEquals(['module_handler_test']$implementors);
  }

  /** * Tests getImplementations. * * @covers ::invokeAllWith */
$plugin_id,
      $plugin_definition,
      $container->get('module_handler')
    );
  }

  /** * {@inheritdoc} */
  public function listTopics() {
    $topics = [];
    $this->moduleHandler->invokeAllWith(
      'help',
      function Dcallable $hook, string $module) use (&$topics) {
        $title = $this->moduleHandler->getName($module);
        $topics[$title] = Link::createFromRoute($title, 'help.page', ['name' => $module]);
      }
    );

    // Sort topics by title, which is the array key above.     ksort($topics);
    return $topics;
  }

}
protected function prepareEntity() {}

  /** * Invokes the specified prepare hook variant. * * @param string $hook * The hook variant name. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. */
  protected function prepareInvokeAll($hook, FormStateInterface $form_state) {
    $this->moduleHandler->invokeAllWith($hookfunction Dcallable $hook, string $module) use ($form_state) {
      // Ensure we pass an updated translation object and form display at       // each invocation, since they depend on form state which is alterable.       $hook($this->entity, $this->operation, $form_state);
    });
  }

  /** * {@inheritdoc} */
  public function getOperation() {
    return $this->operation;
  }
      $libraries_to_load = $this->getLibrariesToLoad($assets);
      $settings_required = in_array('core/drupalSettings', $libraries_to_load) || in_array('core/drupalSettings', $this->libraryDependencyResolver->getLibrariesWithDependencies($assets->getAlreadyLoadedLibraries()));
      $settings_have_changed = count($libraries_to_load) > 0 || count($assets->getSettings()) > 0;

      // Initialize settings to FALSE since they are not needed by default. This       // distinguishes between an empty array which must still allow       // hook_js_settings_alter() to be run.       $settings = FALSE;
      if ($settings_required && $settings_have_changed) {
        $settings = $this->getJsSettingsAssets($assets);
        // Allow modules to add cached JavaScript settings.         $this->moduleHandler->invokeAllWith('js_settings_build', function Dcallable $hook, string $module) use (&$settings$assets) {
          $hook($settings$assets);
        });
      }
      $settings_in_header = in_array('core/drupalSettings', $header_js_libraries);
      $this->cache->set($cid[$js_assets_header$js_assets_footer$settings$settings_in_header], CacheBackendInterface::CACHE_PERMANENT, ['library_info']);
    }

    if ($settings !== FALSE) {
      // Attached settings override both library definitions and       // hook_js_settings_build().       $settings = NestedArray::mergeDeepArray([$settings$assets->getSettings()], TRUE);
      
    // final array, not a subarray. However if there are multiple bundle classes     // involved, we only want to pass each one the entities that match.     if (count($entities_by_class) === 1) {
      $entity_class = array_key_first($entities_by_class);
      $entity_class::postLoad($this$entities);
    }
    else {
      foreach ($entities_by_class as $entity_class => &$items) {
        $entity_class::postLoad($this$items);
      }
    }
    $this->moduleHandler()->invokeAllWith('entity_load', function Dcallable $hook, string $module) use (&$entities) {
      $hook($entities$this->entityTypeId);
    });
    $this->moduleHandler()->invokeAllWith($this->entityTypeId . '_load', function Dcallable $hook, string $module) use (&$entities) {
      $hook($entities);
    });
  }

  /** * Maps from storage records to entity objects. * * @param array $records * Associative array of query results, keyed on the entity ID. * * @return \Drupal\Core\Entity\EntityInterface[] * An array of entity objects implementing the EntityInterface. */

  protected function build() {
    $cache = [];
    // First, preprocess the theme hooks advertised by modules. This will     // serve as the basic registry. Since the list of enabled modules is the     // same regardless of the theme used, this is cached in its own entry to     // save building it for every theme.     if ($cached = $this->cache->get('theme_registry:build:modules')) {
      $cache = $cached->data;
    }
    else {
      $this->moduleHandler->invokeAllWith('theme', function Dcallable $callback, string $module) use (&$cache) {
        $this->processExtension($cache$module, 'module', $module$this->moduleList->getPath($module));
      });
      // Only cache this registry if all modules are loaded.       if ($this->moduleHandler->isLoaded()) {
        $this->cache->set("theme_registry:build:modules", $cache, Cache::PERMANENT, ['theme_registry']);
      }
    }

    // Process each base theme.     // Ensure that we start with the root of the parents, so that both CSS files     // and preprocess functions comes first.
$base_field_definition = $this->prophesize(BaseFieldDefinition::class);
    $base_field_definition->setProvider('example_module')->shouldBeCalled();
    $base_field_definition->setName('base_field')->shouldBeCalled();
    $base_field_definition->setTargetEntityTypeId('test_entity_type')->shouldBeCalled();

    $definitions = [
      'base_field' => $base_field_definition->reveal(),
      'field_storage' => $field_storage_definition->reveal(),
    ];

    $this->moduleHandler->invokeAllWith('entity_base_field_info', Argument::any());
    $this->moduleHandler->invokeAllWith('entity_field_storage_info', Argument::any())
      ->will(function D$arguments) use ($definitions) {
        [$hook$callback] = $arguments;
        $callback(
          function D) use ($definitions) {
            return $definitions;
          },
          'example_module',
        );
      });
    $this->moduleHandler->alter('entity_field_storage_info', $definitions$this->entityType)->willReturn(NULL);

    
$combined_access_results = [
      JSONAPI_FILTER_AMONG_ALL => AccessResult::neutral(),
      JSONAPI_FILTER_AMONG_PUBLISHED => AccessResult::neutral(),
      JSONAPI_FILTER_AMONG_ENABLED => AccessResult::neutral(),
      JSONAPI_FILTER_AMONG_OWN => AccessResult::neutral(),
    ];

    // Invoke hook_jsonapi_entity_filter_access() and     // hook_jsonapi_ENTITY_TYPE_filter_access() for each module and merge its     // results with the combined results.     foreach (['jsonapi_entity_filter_access', 'jsonapi_' . $entity_type->id() . '_filter_access'] as $hook) {
      static::$moduleHandler->invokeAllWith(
        $hook,
        function Dcallable $hook, string $module) use (&$combined_access_results$entity_type$account) {
          $module_access_results = $hook($entity_type$account);
          if ($module_access_results) {
            foreach ($module_access_results as $subset => $access_result) {
              $combined_access_results[$subset] = $combined_access_results[$subset]->orIf($access_result);
            }
          }
        }
      );
    }

    


  /** * Invokes hook_search_preprocess() to simplify text. * * @param string $text * Text to preprocess, passed by reference and altered in place. * @param string|null $langcode * Language code for the language of $text, if known. */
  protected function invokePreprocess(string &$text, ?string $langcode = NULL): void {
    $this->moduleHandler->invokeAllWith(
      'search_preprocess',
      function Dcallable $hook, string $module) use (&$text, &$langcode) {
        $text = $hook($text$langcode);
      }
    );
  }

  /** * Splits CJK (Chinese, Japanese, Korean) text into tokens. * * The Search module matches exact words, where a word is defined to be a * sequence of characters delimited by spaces or punctuation. CJK languages * are written in long strings of characters, though, not split up into words. * So in order to allow search matching, we split up CJK text into tokens * consisting of consecutive, overlapping sequences of characters whose length * is equal to the 'minimum_word_size' variable. This tokenizing is only done * if the 'overlap_cjk' variable is TRUE. * * @param array $matches * This function is a callback for preg_replace_callback(), which is called * from self::analyze(). So, $matches is an array of regular expression * matches, which means that $matches[0] contains the matched text -- a * string of CJK characters to tokenize. * * @return string * Tokenized text, starting and ending with a space character. */
// Assign base field definitions the entity type provider.     $provider = $entity_type->getProvider();
    foreach ($base_field_definitions as $definition) {
      // @todo Remove this check once FieldDefinitionInterface exposes a proper       // provider setter. See https://www.drupal.org/node/2225961.       if ($definition instanceof BaseFieldDefinition) {
        $definition->setProvider($provider);
      }
    }

    // Retrieve base field definitions from modules.     $this->moduleHandler->invokeAllWith(
      'entity_base_field_info',
      function Dcallable $hook, string $module) use (&$base_field_definitions$entity_type) {
        $module_definitions = $hook($entity_type) ?? [];
        // Ensure the provider key actually matches the name of the provider         // defining the field.         foreach ($module_definitions as $field_name => $definition) {
          // @todo Remove this check once FieldDefinitionInterface exposes a           // proper provider setter. See https://www.drupal.org/node/2225961.           if ($definition instanceof BaseFieldDefinition && $definition->getProvider() == NULL) {
            $definition->setProvider($module);
          }
          

  public function invokePageAttachmentHooks(array &$page) {
    // Modules can add attachments.     $attachments = [];
    $this->moduleHandler->invokeAllWith(
      'page_attachments',
      function Dcallable $hook, string $module) use (&$attachments) {
        $hook($attachments);
      }
    );
    if (array_diff(array_keys($attachments)['#attached', '#cache']) !== []) {
      throw new \LogicException('Only #attached and #cache may be set in hook_page_attachments().');
    }

    // Modules and themes can alter page attachments.     $this->moduleHandler->alter('page_attachments', $attachments);
    

  protected function getData() {
    $this->fullyLoaded = TRUE;

    if ($data = $this->cacheGet($this->baseCid)) {
      return $data->data;
    }
    else {
      $data = [];
      $this->moduleHandler->invokeAllWith('views_data', function Dcallable $hook, string $module) use (&$data) {
        $views_data = $hook();
        // Set the provider key for each base table.         foreach ($views_data as &$table) {
          if (isset($table['table']) && !isset($table['table']['provider'])) {
            $table['table']['provider'] = $module;
          }
        }
        $data = NestedArray::mergeDeep($data$views_data);
      });
      $this->moduleHandler->alter('views_data', $data);

      
// Get the default access restriction as specified by the access control     // handler.     $entity_default = $this->checkFieldAccess($operation$field_definition$account$items);

    // Combine default access, denying access wins.     $default = $default->andIf($entity_default);

    // Invoke hook and collect grants/denies for field access from other     // modules.     $grants = [];
    $this->moduleHandler()->invokeAllWith(
      'entity_field_access',
      function Dcallable $hook, string $module) use ($operation$field_definition$account$items, &$grants) {
        $grants[] = [$module => $hook($operation$field_definition$account$items)];
      }
    );
    // Our default access flag is masked under the ':default' key.     $grants = array_merge([':default' => $default], ...$grants);

    // Also allow modules to alter the returned grants/denies.     $context = [
      'operation' => $operation,
      
return;
    }
    $hookInvoker = \Closure::fromCallable($module . '_' . $hook);
    return call_user_func_array($hookInvoker$args);
  }

  /** * {@inheritdoc} */
  public function invokeAll($hook, array $args = []) {
    $return = [];
    $this->invokeAllWith($hookfunction Dcallable $hook, string $module) use ($args, &$return) {
      $result = call_user_func_array($hook$args);
      if (isset($result) && is_array($result)) {
        $return = NestedArray::mergeDeep($return$result);
      }
      elseif (isset($result)) {
        $return[] = $result;
      }
    });
    return $return;
  }

  
Home | Imprint | This part of the site doesn't use cookies.