hasImplementations example

    // make a message.     $number = $this->storage->countAssignedUsers($this->entity);
    $info = '';
    if ($number) {
      $info .= '<p>' . $this->formatPlural($number,
        '1 user has chosen or been assigned to this shortcut set.',
        '@count users have chosen or been assigned to this shortcut set.') . '</p>';
    }

    // Also, if a module implements hook_shortcut_default_set(), it's possible     // that this set is being used as a default set. Add a message about that too.     if ($this->moduleHandler->hasImplementations('shortcut_default_set')) {
      $info .= '<p>' . $this->t('If you have chosen this shortcut set as the default for some or all users, they may also be affected by deleting it.') . '</p>';
    }

    $form['info'] = [
      '#markup' => $info,
    ];

    return parent::buildForm($form$form_state);
  }

}
// Allows admins to view all nodes, by both disabling node_access       // query rewrite as well as not checking for the node status. The       // 'view own unpublished nodes' permission is ignored to not require cache       // entries per user.       $access_result = AccessResult::allowed()->cachePerPermissions();
      if ($this->account->hasPermission('bypass node access')) {
        $query->accessCheck(FALSE);
      }
      else {
        $access_result->addCacheContexts(['user.node_grants:view']);
        if (!$this->moduleHandler->hasImplementations('node_grants') && !$this->account->hasPermission('view any unpublished content')) {
          $query->condition('status', NodeInterface::PUBLISHED);
        }
      }

      $nids = $query->execute();
      foreach ($nids as $nid) {
        foreach ($node_links[$nid] as $key => $link) {
          $node_links[$nid][$key]->access = $access_result;
        }
      }
    }

    
// The Comment module doesn't implement per-comment access, so it         // checks instead that the user has access to the host entity.         $entity_alias = $query->innerJoin($host_entity_field_data_table, 'n', "[%alias].[$id_key] = [$data_table].[entity_id] AND [$data_table].[entity_type] = '$host_entity_type_id'");
        // Pass the query to the entity access control.         $this->reAlterQuery($query$host_entity_type_id . '_access', $entity_alias);

        // Additional checks for "node" entities.         if ($host_entity_type_id === 'node') {
          // Passing the query to node_query_node_access_alter() is sadly           // insufficient for nodes.           // @see \Drupal\node\Plugin\EntityReferenceSelection\NodeSelection::buildEntityQuery()           if (!$this->currentUser->hasPermission('bypass node access') && !$this->moduleHandler->hasImplementations('node_grants')) {
            $query->condition($entity_alias . '.status', 1);
          }
        }
      }
    }
  }

  /** * {@inheritdoc} */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    
$url = $node->toUrl('edit-form', $options);
    $this->drupalGet($url);
    $this->assertSession()->fieldValueEquals('edit-menu-title', $translated_node_title);
  }

  /** * Tests creating menu links via node form widget for nodes with grants. */
  public function testMenuNodeWithGrantsFormWidget() {
    \Drupal::service('module_installer')->install(['node_access_test']);
    node_access_rebuild();
    $this->assertTrue(\Drupal::moduleHandler()->hasImplementations('node_grants'));

    $admin_user = $this->drupalCreateUser([
      'access administration pages',
      'administer content types',
      'administer nodes',
      'administer menu',
      'create page content',
      'edit any page content',
    ]);
    $this->drupalLogin($admin_user);

    
$grants_context_parts[] = $realm . ':' . implode(',', $gids);
    }
    return $operation . '.' . implode(';', $grants_context_parts);
  }

  /** * {@inheritdoc} */
  public function getCacheableMetadata($operation = NULL) {
    $cacheable_metadata = new CacheableMetadata();

    if (!\Drupal::moduleHandler()->hasImplementations('node_grants')) {
      return $cacheable_metadata;
    }

    // The node grants may change if the user is updated. (The max-age is set to     // zero below, but sites may override this cache context, and change it to a     // non-zero value. In such cases, this cache tag is needed for correctness.)     $cacheable_metadata->setCacheTags(['user:' . $this->user->id()]);

    // If the site is using node grants, this cache context can not be     // optimized.     return $cacheable_metadata->setCacheMaxAge(0);
  }
/** * {@inheritdoc} */
  public function access(NodeInterface $node$operation, AccountInterface $account) {
    // Grants only support these operations.     if (!in_array($operation['view', 'update', 'delete'])) {
      return AccessResult::neutral();
    }

    // If no module implements the hook or the node does not have an id there is     // no point in querying the database for access grants.     if (!$this->moduleHandler->hasImplementations('node_grants') || !$node->id()) {
      // Return the equivalent of the default grant, defined by       // self::writeDefault().       if ($operation === 'view') {
        return AccessResult::allowedIf($node->isPublished());
      }
      else {
        return AccessResult::neutral();
      }
    }

    // Check the database for potential access grants.
public function invokeAllWith(string $hook, callable $callback): void {
    foreach (array_keys($this->getImplementationInfo($hook)) as $module) {
      $hookInvoker = \Closure::fromCallable($module . '_' . $hook);
      $callback($hookInvoker$module);
    }
  }

  /** * {@inheritdoc} */
  public function invoke($module$hook, array $args = []) {
    if (!$this->hasImplementations($hook$module)) {
      return;
    }
    $hookInvoker = \Closure::fromCallable($module . '_' . $hook);
    return call_user_func_array($hookInvoker$args);
  }

  /** * {@inheritdoc} */
  public function invokeAll($hook, array $args = []) {
    $return = [];
    


  /** * Tests the hooks. */
  public function testHooks() {
    $view = Views::getView('test_view');
    $view->setDisplay();

    // Test each hook is found in the implementations array and is invoked.     foreach (static::$hooks as $hook => $type) {
      $this->assertTrue($this->moduleHandler->hasImplementations($hook, 'views_test_data')new FormattableMarkup('The hook @hook was registered.', ['@hook' => $hook]));

      if ($hook == 'views_post_render') {
        $this->moduleHandler->invoke('views_test_data', $hook[$view, &$view->display_handler->output, $view->display_handler->getPlugin('cache')]);
        continue;
      }

      switch ($type) {
        case 'view':
          $this->moduleHandler->invoke('views_test_data', $hook[$view]);
          break;

        
    \Drupal::service('module_installer')->install(['module_test']);

    // Assert that the \Drupal::moduleHandler() instance has been replaced.     $this->assertNotSame(\Drupal::moduleHandler()$module_handler, 'The \Drupal::moduleHandler() instance has been replaced during \Drupal::moduleHandler()->install().');

    // Assert that module_test.module is now included.     $this->assertTrue(function_exists('module_test_modules_installed'),
      'The file module_test.module was successfully included.');

    $this->assertArrayHasKey('module_test', \Drupal::moduleHandler()->getModuleList());

    $this->assertTrue(\Drupal::moduleHandler()->hasImplementations('modules_installed', 'module_test'),
      'module_test implements hook_modules_installed().');

    $this->assertTrue(\Drupal::moduleHandler()->hasImplementations('module_implements_alter', 'module_test'),
      'module_test implements hook_module_implements_alter().');

    // Assert that module_test.implementations.inc is not included yet.     $this->assertFalse(function_exists('module_test_altered_test_hook'),
      'The file module_test.implementations.inc is not included yet.');

    // Trigger hook discovery for hook_altered_test_hook().     // Assert that module_test_module_implements_alter(*, 'altered_test_hook')

  public function helpPage($name) {
    $build = [];
    if ($this->moduleHandler()->hasImplementations('help', $name)) {
      $module_name = $this->moduleHandler()->getName($name);
      $build['#title'] = $module_name;

      $info = $this->moduleExtensionList->getExtensionInfo($name);
      if ($info[ExtensionLifecycle::LIFECYCLE_IDENTIFIER] === ExtensionLifecycle::EXPERIMENTAL) {
        $this->messenger()->addWarning($this->t('This module is experimental. <a href=":url">Experimental modules</a> are provided for testing purposes only. Use at your own risk.', [':url' => 'https://www.drupal.org/core/experimental']));
      }

      $temp = $this->moduleHandler()->invoke($name, 'help', ["help.page.$name", $this->routeMatch]);
      if (empty($temp)) {
        $build['top'] = ['#markup' => $this->t('No help is available for module %module.', ['%module' => $module_name])];
      }
try {
        $libraries = Yaml::decode(file_get_contents($this->root . '/' . $library_file)) ?? [];
      }
      catch (InvalidDataTypeException $e) {
        // Rethrow a more helpful exception to provide context.         throw new InvalidLibraryFileException(sprintf('Invalid library definition in %s: %s', $library_file$e->getMessage()), 0, $e);
      }
    }

    // Allow modules to add dynamic library definitions.     $hook = 'library_info_build';
    if ($this->moduleHandler->hasImplementations($hook$extension)) {
      $libraries = NestedArray::mergeDeep($libraries$this->moduleHandler->invoke($extension$hook));
    }

    // Allow modules to alter the module's registered libraries.     $this->moduleHandler->alter('library_info', $libraries$extension);
    $this->themeManager->alter('library_info', $libraries$extension);

    return $libraries;
  }

  /** * Apply libraries overrides specified for the current active theme. * * @param array $libraries * The libraries definitions. * @param string $extension * The extension in which these libraries are defined. * * @return array * The modified libraries definitions. */
EntityViewDisplay::create([
      'targetEntityType' => 'node',
      'bundle' => 'page',
      'mode' => 'default',
      'status' => TRUE,
    ])->setComponent('ref', ['type' => 'entity_reference_label'])
      ->save();

    // Check that at least one module implements hook_node_grants() as this test     // only tests this case.     // @see \node_test_node_grants()     $this->assertTrue(\Drupal::moduleHandler()->hasImplementations('node_grants'));

    // Create an unpublished node.     $referenced = $this->createNode(['status' => FALSE]);
    // Create a node referencing $referenced.     $node = $this->createNode(['ref' => $referenced]);

    // Check that the referenced entity link doesn't show on the host entity.     $this->drupalGet($node->toUrl());
    $this->assertSession()->linkNotExists($referenced->label());

    // Publish the referenced node.

              ],
          ])
        )->toString();
    }
    $row['description']['#markup'] = $this->t($module->info['description']);
    $row['version']['#markup'] = $module->info['version'];

    // Generate link for module's help page. Assume that if a hook_help()     // implementation exists then the module provides an overview page, rather     // than checking to see if the page exists, which is costly.     if ($this->moduleHandler->moduleExists('help') && $module->status && $this->moduleHandler->hasImplementations('help', $module->getName())) {
      $row['links']['help'] = [
        '#type' => 'link',
        '#title' => $this->t('Help <span class="visually-hidden">for @module</span>', ['@module' => $module->info['name']]),
        '#url' => Url::fromRoute('help.page', ['name' => $module->getName()]),
        '#options' => ['attributes' => ['class' => ['module-link', 'module-link-help']]],
      ];
    }

    // Generate link for module's permission, if the user has access to it.     if ($module->status && $this->currentUser->hasPermission('administer permissions') && $this->permissionHandler->moduleProvidesPermissions($module->getName())) {
      $row['links']['permissions'] = [
        
$this->assertNull($module_handler->invoke('module_handler_test_fake', 'hook', [FALSE]), 'Installed module runs hook.');
  }

  /** * Tests implementations methods when module is enabled. * * @covers ::hasImplementations * @covers ::loadAllIncludes */
  public function testImplementsHookModuleEnabled() {
    $module_handler = $this->getModuleHandler();
    $this->assertTrue($module_handler->hasImplementations('hook', 'module_handler_test'), 'Installed module implementation found.');

    $module_handler->addModule('module_handler_test_added', 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test_added');
    $this->assertTrue($module_handler->hasImplementations('hook', 'module_handler_test_added'), 'Runtime added module with implementation in include found.');

    $module_handler->addModule('module_handler_test_no_hook', 'core/tests/Drupal/Tests/Core/Extension/modules/module_handler_test_no_hook');
    $this->assertFalse($module_handler->hasImplementations('hook', 'module_handler_test_no_hook'), 'Missing implementation not found.');
  }

  /** * Tests hasImplementations. * * @covers ::hasImplementations */


  /** * Ensures modules not implementing help do not appear on admin/help. */
  public function testMainPageNoHelp() {
    $this->drupalLogin($this->adminUser);

    $this->drupalGet('admin/help');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->pageTextContains('Module overviews are provided by modules');
    $this->assertFalse(\Drupal::moduleHandler()->hasImplementations('help', 'menu_test'), 'The menu_test module does not implement hook_help');
    // Make sure the test module menu_test does not display a help link on     // admin/help.     $this->assertSession()->pageTextNotContains(\Drupal::moduleHandler()->getName('menu_test'));

    // Ensure that the module overview help page for a module that does not     // implement hook_help() results in a 404.     $this->drupalGet('admin/help/menu_test');
    $this->assertSession()->statusCodeEquals(404);
  }

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