hasService example


  public static function basePath($site_path = NULL) {
    if ($site_path === NULL) {
      // Find the site path. Kernel service is not always available at this       // point, but is preferred, when available.       if (\Drupal::hasService('kernel')) {
        $site_path = \Drupal::getContainer()->getParameter('site.path');
      }
      else {
        // If there is no kernel available yet, we call the static         // findSitePath().         $site_path = DrupalKernel::findSitePath(Request::createFromGlobals());
      }
    }
    return Settings::get('file_public_path', $site_path . '/files');
  }

  

  public function dispatchEvent(DatabaseEvent $event, ?string $eventName = NULL): DatabaseEvent {
    if (\Drupal::hasService('event_dispatcher')) {
      return \Drupal::service('event_dispatcher')->dispatch($event$eventName);
    }
    throw new EventException('The event dispatcher service is not available. Database API events can only be fired if the container is initialized');
  }

  /** * Determine the last non-database method that called the database API. * * Traversing the call stack from the very first call made during the * request, we define "the routine that called this query" as the last entry * in the call stack that is not any method called from the namespace of the * database driver, is not inside the Drupal\Core\Database namespace and does * have a file (which excludes call_user_func_array(), anonymous functions * and similar). That makes the climbing logic very simple, and handles the * variable stack depth caused by the query builders. * * See the @link http://php.net/debug_backtrace debug_backtrace() @endlink * function. * * @return array * This method returns a stack trace entry similar to that generated by * debug_backtrace(). However, it flattens the trace entry and the trace * entry before it so that we get the function and args of the function that * called into the database system, not the function and args of the * database call itself. */
protected $root;

  /** * InfoParserDynamic constructor. * * @param string|null $app_root * The root directory of the Drupal installation. */
  public function __construct(string $app_root = NULL) {
    if ($app_root === NULL) {
      @trigger_error('Calling InfoParserDynamic::__construct() without the $app_root argument is deprecated in drupal:10.1.0 and will be required in drupal:11.0.0. See https://www.drupal.org/node/3293709', E_USER_DEPRECATED);
      $app_root = \Drupal::hasService('kernel') ? \Drupal::root() : DRUPAL_ROOT;
    }
    $this->root = $app_root;
  }

  /** * {@inheritdoc} */
  public function parse($filename) {
    if (!file_exists($filename)) {
      $parsed_info = [];
    }
    
    // Therefore, add the site directory of the parent site to the search paths,     // so that contained extensions are still discovered.     // @see \Drupal\Core\Test\FunctionalTestSetupTrait::prepareSettings().     if ($parent_site = Settings::get('test_parent_site')) {
      $searchdirs[static::ORIGIN_PARENT_SITE] = $parent_site;
    }

    // Find the site-specific directory to search. Since we are using this     // method to discover extensions including profiles, we might be doing this     // at install time. Therefore Kernel service is not always available, but is     // preferred.     if (\Drupal::hasService('kernel')) {
      $searchdirs[static::ORIGIN_SITE] = \Drupal::getContainer()->getParameter('site.path');
    }
    else {
      $searchdirs[static::ORIGIN_SITE] = $this->sitePath ?: DrupalKernel::findSitePath(Request::createFromGlobals());
    }

    // Unless an explicit value has been passed, manually check whether we are     // in a test environment, in which case test extensions must be included.     // Test extensions can also be included for debugging purposes by setting a     // variable in settings.php.     if (!isset($include_tests)) {
      
protected function getFileUploadMaxSize() {
    return Environment::getUploadMaxSize();
  }

  /** * Gets the current active user. * * @return \Drupal\Core\Session\AccountInterface * The current account. */
  protected function currentUser() {
    if (!$this->currentUser && \Drupal::hasService('current_user')) {
      $this->currentUser = \Drupal::currentUser();
    }
    return $this->currentUser;
  }

  /** * {@inheritdoc} */
  public static function trustedCallbacks() {
    return ['renderPlaceholderFormAction', 'renderFormTokenPlaceholder'];
  }

}

  protected function getPluralIndex() {
    // We have to test both if the function and the service exist since in     // certain situations it is possible that locale code might be loaded but     // the service does not exist. For example, where the parent test site has     // locale installed but the child site does not.     // @todo Refactor in https://www.drupal.org/node/2660338 so this code does     // not depend on knowing that the Locale module exists.     if (function_exists('locale_get_plural') && \Drupal::hasService('locale.plural.formula')) {
      return locale_get_plural($this->count, $this->getOption('langcode'));
    }
    return -1;
  }

  /** * {@inheritdoc} */
  public function __sleep() {
    return array_merge(parent::__sleep()['count']);
  }

}

  protected static $modules = ['file', 'service_provider_test', 'system'];

  /** * Tests that services provided by module service providers get registered to the DIC. */
  public function testServiceProviderRegistration() {
    $definition = $this->container->getDefinition('file.usage');
    $this->assertSame('Drupal\\service_provider_test\\TestFileUsage', $definition->getClass(), 'Class has been changed');
    $this->assertTrue(\Drupal::hasService('service_provider_test_class'), 'The service_provider_test_class service has been registered to the DIC');
  }

  /** * Tests that the DIC keeps up with module enable/disable in the same request. */
  public function testServiceProviderRegistrationDynamic() {
    // Uninstall the module and ensure the service provider's service is not registered.     \Drupal::service('module_installer')->uninstall(['service_provider_test']);
    $this->assertFalse(\Drupal::hasService('service_provider_test_class'), 'The service_provider_test_class service does not exist in the DIC.');

    // Install the module and ensure the service provider's service is registered.

  protected function formatPlural($count$singular$plural, array $args = [], array $options = []) {
    return new PluralTranslatableMarkup($count$singular$plural$args$options$this->getStringTranslation());
  }

  /** * Returns the number of plurals supported by a given language. * * @see \Drupal\locale\PluralFormulaInterface::getNumberOfPlurals() */
  protected function getNumberOfPlurals($langcode = NULL) {
    if (\Drupal::hasService('locale.plural.formula')) {
      return \Drupal::service('locale.plural.formula')->getNumberOfPlurals($langcode);
    }
    // We assume 2 plurals if Locale's services are not available.     return 2;
  }

  /** * Gets the string translation service. * * @return \Drupal\Core\StringTranslation\TranslationInterface * The string translation service. */
protected function buildUrl($path, array $options = []) {
    global $base_path;

    if ($path instanceof Url) {
      $url_options = $path->getOptions();
      $options = $url_options + $options;
      $path->setOptions($options);
      return $path->setAbsolute()->toString();
    }
    // The URL generator service is not necessarily available yet; e.g., in     // interactive installer tests.     elseif (\Drupal::hasService('url_generator')) {
      // Strip $base_path, if existent.       $length = strlen($base_path);
      if (substr($path, 0, $length) === $base_path) {
        $path = substr($path$length);
      }

      $force_internal = isset($options['external']) && $options['external'] == FALSE;
      if (!$force_internal && UrlHelper::isExternal($path)) {
        return Url::fromUri($path$options)->toString();
      }
      else {
        
node_reindex_node_search($this->id());
    }
  }

  /** * {@inheritdoc} */
  public static function preDelete(EntityStorageInterface $storage, array $entities) {
    parent::preDelete($storage$entities);

    // Ensure that all nodes deleted are removed from the search index.     if (\Drupal::hasService('search.index')) {
      /** @var \Drupal\search\SearchIndexInterface $search_index */
      $search_index = \Drupal::service('search.index');
      foreach ($entities as $entity) {
        $search_index->clear('node_search', $entity->nid->value);
      }
    }
  }

  /** * {@inheritdoc} */
  

  protected $defaultTheme = 'stark';

  /** * Tests that module service providers get registered to the DIC. * * Also tests that services provided by module service providers get * registered to the DIC. */
  public function testServiceProviderRegistrationIntegration() {
    $this->assertTrue(\Drupal::hasService('service_provider_test_class'), 'The service_provider_test_class service has been registered to the DIC');
    // The event subscriber method in the test class calls     // \Drupal\Core\Messenger\MessengerInterface::addStatus() with a message     // saying it has fired. This will fire on every page request so it should     // show up on the front page.     $this->drupalGet('');
    $this->assertSession()->pageTextContains('The service_provider_test event subscriber fired!');
  }

}
// Record the fact that it was installed.         \Drupal::logger('system')->info('%module module installed.', ['%module' => $module]);
      }
    }

    // If any modules were newly installed, invoke hook_modules_installed().     if (!empty($modules_installed)) {
      if (!InstallerKernel::installationAttempted()) {
        // If the container was rebuilt during hook_install() it might not have         // the 'router.route_provider.old' service.         if (\Drupal::hasService('router.route_provider.old')) {
          \Drupal::getContainer()->set('router.route_provider', \Drupal::service('router.route_provider.old'));
        }
        if (!\Drupal::service('router.route_provider.lazy_builder')->hasRebuilt()) {
          // Rebuild routes after installing module. This is done here on top of           // \Drupal\Core\Routing\RouteBuilder::destruct to not run into errors on           // fastCGI which executes ::destruct() after the module installation           // page was sent already.           \Drupal::service('router.builder')->rebuild();
        }
      }

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