service example

$entity instanceof EntityInterface &&
        !in_array($entity->bundle()$definition['bundle'], TRUE)
      ) {
        return NULL;
      }
      return $entity;
    }

    // Do not inject the context repository as it is not an actual dependency:     // it will be removed once both the TODOs below are fixed.     /** @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface $contexts_repository */
    $contexts_repository = \Drupal::service('context.repository');
    // @todo Consider deprecating the legacy context operation altogether in     // https://www.drupal.org/node/3031124.     $contexts = $contexts_repository->getAvailableContexts();
    $contexts[EntityRepositoryInterface::CONTEXT_ID_LEGACY_CONTEXT_OPERATION] =
      new Context(new ContextDefinition('string'), 'entity_upcast');
    // @todo At the moment we do not need the current user context, which is     // triggering some test failures. We can remove these lines once     // https://www.drupal.org/node/2934192 is fixed.     $context_id = '@user.current_user_context:current_user';
    if (isset($contexts[$context_id])) {
      $account = $contexts[$context_id]->getContextValue();
      

    }

    $this->assertEmpty(array_keys(array_diff_key($result_accounts$accounts)), 'Ensure all accounts are listed.');
    foreach ($result_accounts as $name => $values) {
      $this->assertEquals($accounts[$name]->status->value, $values['status'] == 'active');
    }

    $expected_roles = ['custom_role_1', 'custom_role_2'];
    $this->assertEquals($expected_roles$result_accounts[$role_account_name]['roles'], 'Ensure roles are listed properly.');

    $this->assertEquals(\Drupal::service('date.formatter')->formatTimeDiffSince($accounts[$timestamp_user]->created->value)$result_accounts[$timestamp_user]['member_for'], 'Ensure the right member time is displayed.');

    $this->assertEquals('never', $result_accounts[$timestamp_user]['last_access'], 'Ensure the last access time is "never".');
  }

}

function system_post_update_linkset_settings() {
  $config = \Drupal::configFactory()->getEditable('system.feature_flags');
  $config->set('linkset_endpoint', FALSE)->save();
}

/** * Update timestamp formatter settings for entity view displays. */
function system_post_update_timestamp_formatter(array &$sandbox = NULL): void {
  /** @var \Drupal\Core\Field\FormatterPluginManager $field_formatter_manager */
  $field_formatter_manager = \Drupal::service('plugin.manager.field.formatter');

  \Drupal::classResolver(ConfigEntityUpdater::class)->update($sandbox, 'entity_view_display', function DEntityViewDisplayInterface $entity_view_display) use ($field_formatter_manager): bool {
    $update = FALSE;
    foreach ($entity_view_display->getComponents() as $name => $component) {
      if (empty($component['type'])) {
        continue;
      }

      $plugin_definition = $field_formatter_manager->getDefinition($component['type'], FALSE);
      // Check also potential plugins extending TimestampFormatter.       if (!is_a($plugin_definition['class'], TimestampFormatter::class, TRUE)) {
        

  protected function getTestFiles($type$size = NULL) {
    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
    $file_system = \Drupal::service('file_system');
    if (empty($this->generatedTestFiles)) {
      // Generate binary test files.       $lines = [64, 1024];
      $count = 0;
      foreach ($lines as $line) {
        $this->generateFile('binary-' . $count++, 64, $line, 'binary');
      }

      // Generate ASCII text test files.       $lines = [16, 256, 1024, 2048, 20480];
      $count = 0;
      
// Call file_cron() to clean up the file. Make sure the changed timestamp     // of the file is older than the system.file.temporary_maximum_age     // configuration value. We use an UPDATE statement because using the API     // would set the timestamp.     Database::getConnection()->update('file_managed')
      ->fields([
        'changed' => REQUEST_TIME - ($this->config('system.file')->get('temporary_maximum_age') + 1),
      ])
      ->condition('fid', $file->id())
      ->execute();
    \Drupal::service('cron')->run();

    // file_cron() loads     $this->assertFileHooksCalled(['delete']);
    $this->assertFileDoesNotExist($file->getFileUri());
    $this->assertNull(File::load($file->id()), 'File was removed from the database.');
  }

  /** * Tries to run cron deletion on file deleted from the file-system. */
  public function testCronDeleteNonExistingTemporary() {
    
/** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    $this->setUpCurrentUser();
    $this->installEntitySchema('entity_test');
  }

  public function testGetUrlIfValidWithoutAccessCheck() {
    $requestContext = \Drupal::service('router.request_context');
    $pathValidator = \Drupal::service('path.validator');

    $entity = EntityTest::create([
      'name' => 'test',
    ]);
    $entity->save();

    $methods = [
      'POST',
      'GET',
      'PUT',
      
'outdated' => $metadata->isOutdated(),
              ],
            ],
          ];

          if ($is_original) {
            $language_name = $this->t('<strong>@language_name (Original language)</strong>', ['@language_name' => $language_name]);
            $source_name = $this->t('n/a');
          }
          else {
            /** @var \Drupal\Core\Access\AccessResultInterface $delete_route_access */
            $delete_route_access = \Drupal::service('content_translation.delete_access')->checkAccess($translation);
            $cacheability->addCacheableDependency($delete_route_access);

            if ($delete_route_access->isAllowed()) {
              $source_name = isset($languages[$source]) ? $languages[$source]->getName() : $this->t('n/a');
              $delete_access = $entity->access('delete', NULL, TRUE);
              $translation_access = $handler->getTranslationAccess($entity, 'delete');
              $cacheability
                ->addCacheableDependency($delete_access)
                ->addCacheableDependency($translation_access);

              if ($delete_access->isAllowed() && $entity_type->hasLinkTemplate('delete-form')) {
                

  protected function assertPageCounts(string $path, array $counts, string $message): void {
    // Disable read more links.     \Drupal::service('entity_display.repository')
      ->getViewDisplay('node', 'page', 'teaser')
      ->removeComponent('links')
      ->save();

    // Get the text of the page.     $this->drupalGet($path);
    $text = $this->getTextContent();

    // Check the counts. Note that the title and body are both shown on the     // page, and they are the same. So the title/body string should appear on     // the page twice as many times as the input count.
$this->assertSession()->assertNoElementAfterWait('css', '[data-contextual-id]:empty');
  }

  /** * Enables a theme. * * @param string $theme * The theme. */
  protected function enableTheme($theme) {
    // Enable the theme.     \Drupal::service('theme_installer')->install([$theme]);
    $theme_config = \Drupal::configFactory()->getEditable('system.theme');
    $theme_config->set('default', $theme);
    $theme_config->save();
  }

  /** * Waits for off-canvas dialog to open. * * @param string $position * The position of the dialog. * * @throws \Behat\Mink\Exception\ElementNotFoundException */
use Twig\ExtensionSet;
use Twig\Loader\ChainLoader;
use Twig\Loader\FilesystemLoader;
use Twig\Profiler\Profile;
use Twig\RuntimeLoader\ContainerRuntimeLoader;
use Twig\Template;
use Twig\TemplateWrapper;

return static function DContainerConfigurator $container) {
    $container->services()
        ->set('twig', Environment::class)
            ->args([service('twig.loader')abstract_arg('Twig options')])
            ->call('addGlobal', ['app', service('twig.app_variable')])
            ->call('addRuntimeLoader', [service('twig.runtime_loader')])
            ->configurator([service('twig.configurator.environment'), 'configure'])
            ->tag('container.preload', ['class' => FilesystemCache::class])
            ->tag('container.preload', ['class' => CoreExtension::class])
            ->tag('container.preload', ['class' => EscaperExtension::class])
            ->tag('container.preload', ['class' => OptimizerExtension::class])
            ->tag('container.preload', ['class' => StagingExtension::class])
            ->tag('container.preload', ['class' => ExtensionSet::class])
            ->tag('container.preload', ['class' => Template::class])
            ->tag('container.preload', ['class' => TemplateWrapper::class])

        
$view->display_handler->overrideOption('cache', [
      'type' => 'time',
      'options' => [
        'results_lifespan' => '3600',
        'output_lifespan' => '3600',
      ],
    ]);
    $view->save();
    $this->container->get('router.builder')->rebuildIfNeeded();

    /** @var \Drupal\Core\Render\RenderCacheInterface $render_cache */
    $render_cache = \Drupal::service('render_cache');
    $cache_element = DisplayPluginBase::buildBasicRenderable('test_display', 'page_1');
    $cache_element['#cache'] += ['contexts' => $this->container->getParameter('renderer.config')['required_cache_contexts']];
    $this->assertFalse($render_cache->get($cache_element));

    $this->drupalGet('test-display');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertNotEmpty($render_cache->get($cache_element));
    $cache_tags = [
      'config:user.role.anonymous',
      'config:views.view.test_display',
      'node_list',
      

  protected $tips = [];

  /** * {@inheritdoc} */
  public function __construct(array $values$entity_type) {
    parent::__construct($values$entity_type);

    $this->tipsCollection = new TipsPluginCollection(\Drupal::service('plugin.manager.tour.tip')$this->tips);
  }

  /** * {@inheritdoc} */
  public function getRoutes() {
    return $this->routes;
  }

  /** * {@inheritdoc} */

  public function getCancelUrl() {
    return new Url('entity.search_page.collection');
  }

  /** * {@inheritdoc} */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($form['confirm']) {
      // Ask each active search page to mark itself for re-index.       $search_page_repository = \Drupal::service('search.search_page_repository');
      foreach ($search_page_repository->getIndexableSearchPages() as $entity) {
        $entity->getPlugin()->markForReindex();
      }
      $this->messenger()->addStatus($this->t('All search indexes will be rebuilt.'));
      $form_state->setRedirectUrl($this->getCancelUrl());
    }
  }

}
/** * @covers ::getRuntimeContexts */
  public function testGetRuntimeContexts() {
    // Create term.     $vocabulary = $this->createVocabulary();
    $term = $this->createTerm($vocabulary);

    // Create RouteMatch from term entity.     $url = $term->toUrl();
    $route_provider = \Drupal::service('router.route_provider');
    $route = $route_provider->getRouteByName($url->getRouteName());
    $route_match = new RouteMatch($url->getRouteName()$route[
      'taxonomy_term' => $term,
    ]);

    // Initiate TermRouteContext with RouteMatch.     $provider = new TermRouteContext($route_match);

    $runtime_contexts = $provider->getRuntimeContexts([]);
    $this->assertArrayHasKey('taxonomy_term', $runtime_contexts);
    $this->assertTrue($runtime_contexts['taxonomy_term']->hasContextValue());
  }
'headers' => ['Content-type' => 'text/html'],
      'subject' => $subject,
      'to' => 'foobar@example.com',
      'body' => $body,
    ];

    // Before we send the email, drupalGetMails should return an empty array.     $captured_emails = $this->drupalGetMails();
    $this->assertCount(0, $captured_emails, 'The captured emails queue is empty.');

    // Send the email.     \Drupal::service('plugin.manager.mail')->getInstance(['module' => 'test', 'key' => 'drupal_mail_test'])->mail($message);

    // Ensure that there is one email in the captured emails array.     $captured_emails = $this->drupalGetMails();
    $this->assertCount(1, $captured_emails, 'One email was captured.');

    // Assert that the email was sent by iterating over the message properties     // and ensuring that they are captured intact.     foreach ($message as $field => $value) {
      $this->assertMail($field$valuenew FormattableMarkup('The email was sent and the value for property @field is intact.', ['@field' => $field]));
    }

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