cache example

/** * Tests that Subqueries are cached as expected. */
  public function testSubqueryStringCache() {
    // Execute the view.     $view = Views::getView('test_groupwise_term_ui');
    $view->setDisplay();
    $this->executeView($view);
    // Request for the cache.     $cid = 'views_relationship_groupwise_max:test_groupwise_term_ui:default:tid_representative';
    $cache = \Drupal::cache('data')->get($cid);
    $this->assertEquals($cid$cache->cid, 'Subquery String cached as expected.');
  }

  /** * Tests the data contained in cached items. */
  public function testCacheData() {
    for ($i = 1; $i <= 5; $i++) {
      Node::create([
        'title' => $this->randomMachineName(8),
        'type' => 'page',
      ])
$this->loadFallbackCatalogues($locale);
    }

    private function initializeCacheCatalogue(string $locale): void
    {
        if (isset($this->catalogues[$locale])) {
            /* Catalogue already initialized. */
            return;
        }

        $this->assertValidLocale($locale);
        $cache = $this->getConfigCacheFactory()->cache($this->getCatalogueCachePath($locale),
            function DConfigCacheInterface $cache) use ($locale) {
                $this->dumpCatalogue($locale$cache);
            }
        );

        if (isset($this->catalogues[$locale])) {
            /* Catalogue has been initialized as it was written out to cache. */
            return;
        }

        /* Read catalogue from cache. */
        
/** * {@inheritdoc} */
  public function getFormId() {
    return 'condition_node_type_test_form';
  }

  /** * Constructs a \Drupal\condition_test\FormController object. */
  public function __construct() {
    $manager = new ConditionManager(\Drupal::service('container.namespaces'), \Drupal::cache('discovery'), \Drupal::moduleHandler());
    $this->condition = $manager->createInstance('entity_bundle:node');
    $this->conditionCurrentTheme = $manager->createInstance('current_theme');
  }

  /** * {@inheritdoc} */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#tree'] = TRUE;
    $form['entity_bundle'] = [];
    $subformState = SubformState::createForSubform($form['entity_bundle']$form$form_state);
    
/** * Tests the behavior of the theme registry class. */
  public function testRaceCondition() {
    // The theme registry is not marked as persistable in case we don't have a     // proper request.     \Drupal::request()->setMethod('GET');
    $cid = 'test_theme_registry';

    // Directly instantiate the theme registry, this will cause a base cache     // entry to be written in __construct().     $cache = \Drupal::cache();
    $lock_backend = \Drupal::lock();
    $registry = new ThemeRegistry($cid$cache$lock_backend['theme_registry']$this->container->get('module_handler')->isLoaded());

    $this->assertNotEmpty(\Drupal::cache()->get($cid), 'Cache entry was created.');

    // Trigger a cache miss for an offset.     $this->assertNotEmpty($registry->get('theme_test_template_test'), 'Offset was returned correctly from the theme registry.');
    // This will cause the ThemeRegistry class to write an updated version of     // the cache entry when it is destroyed, usually at the end of the request.     // Before that happens, manually delete the cache entry we created earlier     // so that the new entry is written from scratch.
$this->assertCacheTags($expected_tags);
    $this->assertCacheContexts($expected_contexts);

    // Assert cache hit + expected cache contexts + tags.     $this->drupalGet($absolute_url);
    $this->assertCacheTags($expected_tags);
    $this->assertCacheContexts($expected_contexts);

    // Assert page cache item + expected cache tags.     $cid_parts = [$url->setAbsolute()->toString(), ''];
    $cid = implode(':', $cid_parts);
    $cache_entry = \Drupal::cache('page')->get($cid);
    sort($cache_entry->tags);
    $this->assertEquals($expected_tags$cache_entry->tags);
  }

  /** * Ensures that some cache tags are present in the current response. * * @param string[] $expected_tags * The expected tags. * @param bool $include_default_tags * (optional) Whether the default cache tags should be included. */

  protected function checkCacheExists($cid$var$bin = NULL) {
    if ($bin == NULL) {
      $bin = $this->defaultBin;
    }

    $cached = \Drupal::cache($bin)->get($cid);

    return isset($cached->data) && $cached->data == $var;
  }

  /** * Asserts that a cache entry exists. * * @param $message * Message to display. * @param $var * The variable the cache should contain. * @param $cid * The cache id. * @param $bin * The bin the cache item was stored in. */
'id' => 2],
        ],
      ],
    ];
    $migration = $this->migrationPluginManager->createStubMigration($migration_definition);
    $migration_source = $migration->getSourcePlugin();
    $this->assertCount(2, $migration_source);

    // Pollute the cache.     $cache_key_property = new \ReflectionProperty($migration_source, 'cacheKey');
    $cache_key = $cache_key_property->getValue($migration_source);
    \Drupal::cache('migrate')->set($cache_key, 7);
    $this->assertCount(7, $migration_source);
    $this->assertSame(2, $migration_source->count(TRUE));
  }

}
foreach ($entities as $menu) {
      // Delete all links from the menu.       $menu_link_manager->deleteLinksInMenu($menu->id());
    }
  }

  /** * {@inheritdoc} */
  public function save() {
    $return = parent::save();
    \Drupal::cache('menu')->invalidateAll();
    // Invalidate the block cache to update menu-based derivatives.     if (\Drupal::moduleHandler()->moduleExists('block')) {
      \Drupal::service('plugin.manager.block')->clearCachedDefinitions();
    }
    return $return;
  }

  /** * {@inheritdoc} */
  public function delete() {
    

            $this->matcher = new $this->options['matcher_class']($routes$this->context);
            if (method_exists($this->matcher, 'addExpressionLanguageProvider')) {
                foreach ($this->expressionLanguageProviders as $provider) {
                    $this->matcher->addExpressionLanguageProvider($provider);
                }
            }

            return $this->matcher;
        }

        $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/url_matching_routes.php',
            function DConfigCacheInterface $cache) {
                $dumper = $this->getMatcherDumperInstance();
                if (method_exists($dumper, 'addExpressionLanguageProvider')) {
                    foreach ($this->expressionLanguageProviders as $provider) {
                        $dumper->addExpressionLanguageProvider($provider);
                    }
                }

                $cache->write($dumper->dump()$this->getRouteCollection()->getResources());
            }
        );

        
// Register a database cache backend rather than memory-based.     $container->register('cache_factory', DatabaseBackendFactory::class)
      ->addArgument(new Reference('database'))
      ->addArgument(new Reference('cache_tags.invalidator.checksum'))
      ->addArgument(new Reference('settings'));
  }

  /** * Tests an entity save. */
  public function testEntitySave(): void {
    \Drupal::cache()->set('test_cache_pretransaction_foobar', 'something', Cache::PERMANENT, ['foobar']);
    \Drupal::cache()->set('test_cache_pretransaction_entity_test_list', 'something', Cache::PERMANENT, ['entity_test_list']);

    $entity = EntityTest::create(['name' => $this->randomString()]);

    Database::startLog('testEntitySave');
    $entity->save();

    $executed_statements = [];
    foreach (Database::getLog('testEntitySave') as $log) {
      $executed_statements[] = $log['query'];
    }
    


    if ($this->isDefaultDisplay() && isset($options['defaults'])) {
      unset($options['defaults']);
    }

    $skip_cache = \Drupal::config('views.settings')->get('skip_cache');

    if (!$skip_cache) {
      $cid = 'views:unpack_options:' . hash('sha256', serialize([$this->options, $options])) . ':' . \Drupal::languageManager()->getCurrentLanguage()->getId();
      if (empty(static::$unpackOptions[$cid])) {
        $cache = \Drupal::cache('data')->get($cid);
        if (!empty($cache->data)) {
          $this->options = $cache->data;
        }
        else {
          $this->unpackOptions($this->options, $options);
          \Drupal::cache('data')->set($cid$this->options, Cache::PERMANENT, $this->view->storage->getCacheTags());
        }
        static::$unpackOptions[$cid] = $this->options;
      }
      else {
        $this->options = static::$unpackOptions[$cid];
      }
$start = microtime(true);
        if ($saveData === null) {
            $saveData = $this->config->saveData;
        }

        $fileExt = pathinfo($view, PATHINFO_EXTENSION);
        $view    = empty($fileExt) ? $view . '.php' : $view; // allow Views as .html, .tpl, etc (from CI3)
        $cacheName = $options['cache_name'] ?? str_replace('.php', '', $view);

        // Was it cached?         if (isset($options['cache']) && ($output = cache($cacheName))) {
            $this->logPerformance($startmicrotime(true)$view);

            return $output;
        }

        $file = $this->viewPath . $view;

        if (is_file($file)) {
            $fileOrig = $file;
            $file     = $this->loader->locateFile($view, 'Views');

            
$shortcut->save();

    return $shortcut;
  }

  /** * Tests that when creating a shortcut, the shortcut set tag is invalidated. */
  public function testEntityCreation() {
    // Create a cache entry that is tagged with a shortcut set cache tag.     $cache_tags = ['config:shortcut.set.default'];
    \Drupal::cache('render')->set('foo', 'bar', CacheBackendInterface::CACHE_PERMANENT, $cache_tags);

    // Verify a cache hit.     $this->verifyRenderCache('foo', $cache_tags);

    // Now create a shortcut entity in that shortcut set.     $this->createEntity();

    // Verify a cache miss.     $this->assertFalse(\Drupal::cache('render')->get('foo'), 'Creating a new shortcut invalidates the cache tag of the shortcut set.');
  }

  
$modules_list_url_absolute = Url::fromRoute('system.modules_list', [][
      'fragment' => 'module-content-moderation',
      'absolute' => TRUE,
    ])->toString();
    $this->assertSame($this->getSession()->getCurrentUrl()$modules_list_url_absolute);
    // The current user does not have the 'administer modules' permission.     $this->assertSession()->statusCodeEquals(403);

    $this->container->get('module_installer')->install(['workflow_type_test']);
    // The render cache needs to be cleared because although the cache tags are     // correctly set the render cache does not pick it up.     \Drupal::cache('render')->deleteAll();

    $this->drupalGet('admin/config/workflow/workflows');
    $this->assertSession()->pageTextNotContains('There are no workflow types available. In order to create workflows you need to install a module that provides a workflow type. For example, the Content Moderation module provides a workflow type that enables workflows for content entities.');
    $this->assertSession()->linkExists('Add workflow');
    $this->assertSession()->pageTextContains('There are no workflows yet.');
  }

}
// Prime the page cache.     $this->drupalGet('<front>');
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'MISS');

    // Verify a cache hit, but also the presence of the correct cache tags in     // both the page and block caches.     $this->drupalGet('<front>');
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'HIT');
    $cid_parts = [Url::fromRoute('<front>', []['absolute' => TRUE])->toString(), ''];
    $cid = implode(':', $cid_parts);
    $cache_entry = \Drupal::cache('page')->get($cid);
    $expected_cache_tags = [
      'config:block_list',
      'block_view',
      'config:block.block.powered',
      'config:user.role.anonymous',
      'http_response',
      'rendered',
    ];
    sort($expected_cache_tags);
    $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
    $this->assertSame($expected_cache_tags$cache_entry->tags);
    
Home | Imprint | This part of the site doesn't use cookies.