getCache example

unset($_SESSION['batch_form_state']);
      return $this->rebuildForm($form_id$form_state);
    }

    // If the incoming input contains a form_build_id, we'll check the cache for     // a copy of the form in question. If it's there, we don't have to rebuild     // the form to proceed. In addition, if there is stored form_state data from     // a previous step, we'll retrieve it so it can be passed on to the form     // processing code.     $check_cache = isset($input['form_id']) && $input['form_id'] == $form_id && !empty($input['form_build_id']);
    if ($check_cache) {
      $form = $this->getCache($input['form_build_id']$form_state);
    }

    // If the previous bit of code didn't result in a populated $form object, we     // are hitting the form for the first time and we need to build it from     // scratch.     if (!isset($form)) {
      // If we attempted to serve the form from cache, uncacheable $form_state       // keys need to be removed after retrieving and preparing the form, except       // any that were already set prior to retrieving the form.       if ($check_cache) {
        $form_state_before_retrieval = clone $form_state;
      }
$item
            ->expects(self::once())
            ->method('set')
            ->with(self::callback(function D$item) use ($responseContent) {
                $this->assertSame('W/"625d11cf081b1697cbc216edf6ebb13c"', $item['etag']);
                $this->assertSame('Wed, 28 Dec 2022 13:16:45 GMT', $item['modified']);
                $this->assertSame($responseContent$item['content']);

                return true;
            }));

        $this->getCache()
            ->expects(self::once())
            ->method('getItem')
            ->with(self::callback(function D$v) use ($locale$domain) {
                $this->assertStringStartsWith($locale.'.'.$domain.'.', $v);

                return true;
            }))
            ->willReturn($item);

        $responses = [
            'init locales' => $this->getInitLocaleResponseMock(),
            
$this->formCacheStore->expects($this->once())
      ->method('get')
      ->with($form_build_id)
      ->willReturn($cached_form);
    $this->csrfToken->expects($this->once())
      ->method('validate')
      ->with($cache_token)
      ->willReturn(TRUE);
    $this->account->expects($this->never())
      ->method('isAnonymous');

    $form = $this->formCache->getCache($form_build_id$form_state);
    $this->assertSame($cached_form$form);
  }

  /** * @covers ::getCache */
  public function testGetCacheInvalidToken() {
    $form_build_id = 'the_form_build_id';
    $form_state = new FormState();
    $cache_token = 'the_cache_token';
    $cached_form = ['#cache_token' => $cache_token];

    

  #[\ReturnTypeWillChange]   public function count($refresh = FALSE) {
    if ($this->skipCount) {
      return MigrateSourceInterface::NOT_COUNTABLE;
    }

    // Return the cached count if we are caching counts and a refresh is not     // requested.     if ($this->cacheCounts && !$refresh) {
      $cache_object = $this->getCache()->get($this->cacheKey, 'cache');
      if (is_object($cache_object)) {
        return $cache_object->data;
      }
    }
    $count = $this->doCount();
    // Update the cache if we are caching counts.     if ($this->cacheCounts) {
      $this->getCache()->set($this->cacheKey, $count);
    }
    return $count;
  }

  
public function testChangeCacheOnDifferentPlugins(): void
    {
        [$twig$templateFinder] = $this->createFinder([
            new BundleFixture('Storefront', __DIR__ . '/fixtures/Storefront/'),
            new BundleFixture('TestPlugin2', __DIR__ . '/fixtures/Plugins/TestPlugin2'),
        ]);

        $templateName = 'storefront/frontend/index.html.twig';

        $templateFinder->find($templateName);

        $cache = $twig->getCache(false);
        static::assertInstanceOf(CacheInterface::class$cache);
        $firstCacheKey = $cache->generateKey($templateNamestatic::class);

        [$twig$templateFinder] = $this->createFinder([
            new BundleFixture('Storefront', __DIR__ . '/fixtures/Storefront/'),
            new BundleFixture('TestPlugin1', __DIR__ . '/fixtures/Plugins/TestPlugin1'),
            new BundleFixture('TestPlugin2', __DIR__ . '/fixtures/Plugins/TestPlugin2'),
        ]);

        $templateFinder->find($templateName);
        $cache = $twig->getCache(false);
        
    // having them, use the 'entity type:ID' pattern as the cache $cid.     $cid = $entity->uuid() ?: $entity->getEntityTypeId() . ':' . $entity->id();

    // If the entity is revisionable, then append the revision ID to allow     // individual revisions to have specific access control and be cached     // separately.     if ($entity instanceof RevisionableInterface) {
      /** @var \Drupal\Core\Entity\RevisionableInterface $entity */
      $cid .= ':' . $entity->getRevisionId();
    }

    if (($return = $this->getCache($cid$operation$langcode$account)) !== NULL) {
      // Cache hit, no work necessary.       return $return_as_object ? $return : $return->isAllowed();
    }

    // Invoke hook_entity_access() and hook_ENTITY_TYPE_access(). Hook results     // take precedence over overridden implementations of     // EntityAccessControlHandler::checkAccess(). Entities that have checks that     // need to be done before the hook is invoked should do so by overriding     // this method.
    // We grant access to the entity if both of these conditions are met:
public function getCache($name)
    {
        if (isset($this->_caches[$name])) {
            return $this->_caches[$name];
        }
        if (isset($this->_optionTemplates[$name])) {
            if ($name == self::PAGECACHE
                && (!isset($this->_optionTemplates[$name]['backend']['options']['tag_cache'])
                || !$this->_optionTemplates[$name]['backend']['options']['tag_cache'] instanceof Zend_Cache_Core)
            ) {
                $this->_optionTemplates[$name]['backend']['options']['tag_cache']
                    = $this->getCache(self::PAGETAGCACHE);
            }

            $this->_caches[$name] = Zend_Cache::factory(
                $this->_optionTemplates[$name]['frontend']['name'],
                $this->_optionTemplates[$name]['backend']['name'],
                isset($this->_optionTemplates[$name]['frontend']['options']) ? $this->_optionTemplates[$name]['frontend']['options'] : array(),
                isset($this->_optionTemplates[$name]['backend']['options']) ? $this->_optionTemplates[$name]['backend']['options'] : array(),
                isset($this->_optionTemplates[$name]['frontend']['customFrontendNaming']) ? $this->_optionTemplates[$name]['frontend']['customFrontendNaming'] : false,
                isset($this->_optionTemplates[$name]['backend']['customBackendNaming']) ? $this->_optionTemplates[$name]['backend']['customBackendNaming'] : false,
                isset($this->_optionTemplates[$name]['frontendBackendAutoload']) ? $this->_optionTemplates[$name]['frontendBackendAutoload'] : false
            );

            
$this->assertEquals('no-store', $response->headers->get('surrogate-control'));

        $response->headers->set('Surrogate-Control', 'content="SSI/1.0", no-store');
        $ssi->process($request$response);
        $this->assertEquals('SSI', $response->headers->get('x-body-eval'));
        $this->assertEquals('no-store', $response->headers->get('surrogate-control'));
    }

    public function testHandle()
    {
        $ssi = new Ssi();
        $cache = $this->getCache(Request::create('/')new Response('foo'));
        $this->assertEquals('foo', $ssi->handle($cache, '/', '/alt', true));
    }

    public function testHandleWhenResponseIsNot200()
    {
        $this->expectException(\RuntimeException::class);
        $ssi = new Ssi();
        $response = new Response('foo');
        $response->setStatusCode(404);
        $cache = $this->getCache(Request::create('/')$response);
        $ssi->handle($cache, '/', '/alt', false);
    }

    $expected = 'Llamas sometimes spit and wrestle with their necks. Kittens are soft and fuzzy and they sometimes say meow. Flamingos have long legs and they are usually pink. Pandas eat bamboo and they are bears. Giraffes have long necks and long tongues and they eat leaves.';
    $element_copy = $element;

    // Render it twice so that twig caching is triggered.     $this->assertEquals($expected$renderer->renderRoot($element));
    $this->assertEquals($expected$renderer->renderRoot($element_copy));

    $name = '{# inline_template_start #}' . $element['test']['#template'];
    $prefix = $environment->getTwigCachePrefix();

    $cache = $environment->getCache();
    $class = $environment->getTemplateClass($name);
    $expected = $prefix . '_inline-template_' . substr(Crypt::hashBase64($class), 0, TwigPhpStorageCache::SUFFIX_SUBSTRING_LENGTH);
    $this->assertEquals($expected$cache->generateKey($name$class));
  }

  /** * Tests that exceptions are thrown when a template is not found. */
  public function testTemplateNotFoundException() {
    /** @var \Drupal\Core\Template\TwigEnvironment $environment */
    $environment = \Drupal::service('twig');

    
yield 'supported' => [true, 'phrase://PROJECT_ID:API_TOKEN@default?userAgent=myProject'];
        yield 'not supported' => [false, 'unsupported://PROJECT_ID:API_TOKEN@default?userAgent=myProject'];
    }

    private function createFactory(): PhraseProviderFactory
    {
        return new PhraseProviderFactory(
            $this->getHttpClient(),
            $this->getLogger(),
            $this->getLoader(),
            $this->getXliffFileDumper(),
            $this->getCache(),
            $this->getDefaultLocale()
        );
    }

    private function getHttpClient(): MockObject&MockHttpClient
    {
        return $this->httpClient ??= $this->createMock(MockHttpClient::class);
    }

    private function getLogger(): MockObject&LoggerInterface
    {
        
$this->defineCache($namespaceHierarchy);

        return $this->namespaceHierarchy = array_keys($namespaceHierarchy);
    }

    /** * @param string[] $queue */
    private function defineCache(array $queue): void
    {
        if ($this->twig->getCache(false) instanceof FilesystemCache) {
            $configHash = md5((string) json_encode($queue, \JSON_THROW_ON_ERROR));

            $fileSystemCache = new ConfigurableFilesystemCache($this->cacheDir);
            $fileSystemCache->setConfigHash($configHash);
            $fileSystemCache->setTemplateScopes($this->templateScopeDetector->getScopes());
            // Set individual twig cache for different configurations             $this->twig->setCache($fileSystemCache);
        }
    }
}
    // reset() is necessary to invalidate caches tagged with 'theme_registry'.     $registry = $this->container->get('theme.registry');
    $registry->reset();
    $templates = $registry->getRuntime();

    // Get the template filename and the cache filename for     // theme_test.template_test.html.twig.     $info = $templates->get('theme_test_template_test');
    $template_filename = $info['path'] . '/' . $info['template'] . $extension;

    $environment = $this->container->get('twig');
    $cache = $environment->getCache();
    $class = $environment->getTemplateClass($template_filename);
    $cache_filename = $cache->generateKey($template_filename$class);

    // Navigate to the page and make sure the template gets cached.     $this->drupalGet('theme-test/template-test');
    $this->assertTrue(PhpStorageFactory::get('twig')->exists($cache_filename), 'Cached Twig template found.');

    // Disable the Twig cache and rebuild the service container.     $parameters = $this->container->getParameter('twig.config');
    $parameters['cache'] = FALSE;
    $this->setContainerParameter('twig.config', $parameters);
    

        return $this->_adapter;
    }

    /** * Returns the set cache * * @return Zend_Cache_Core The set cache */
    public static function getCache()
    {
        return Zend_Translate_Adapter::getCache();
    }

    /** * Sets a cache for all instances of Zend_Translate * * @param Zend_Cache_Core $cache Cache to store to * @return void */
    public static function setCache(Zend_Cache_Core $cache)
    {
        Zend_Translate_Adapter::setCache($cache);
    }

        if ($options->mapping || $options->exclude) {
            return false;
        }

        $id = $this->getIdentifier($request$options$name);
        if (false === $id || null === $id) {
            return $id;
        }

        if ($options->evictCache && $manager instanceof EntityManagerInterface) {
            $cacheProvider = $manager->getCache();
            if ($cacheProvider && $cacheProvider->containsEntity($options->class, $id)) {
                $cacheProvider->evictEntity($options->class, $id);
            }
        }

        try {
            return $manager->getRepository($options->class)->find($id);
        } catch (NoResultException|ConversionException) {
            return null;
        }
    }

    
$this->assertEquals('no-store', $response->headers->get('surrogate-control'));

        $response->headers->set('Surrogate-Control', 'content="ESI/1.0", no-store');
        $this->assertSame($response$esi->process($request$response));
        $this->assertEquals('ESI', $response->headers->get('x-body-eval'));
        $this->assertEquals('no-store', $response->headers->get('surrogate-control'));
    }

    public function testHandle()
    {
        $esi = new Esi();
        $cache = $this->getCache(Request::create('/')new Response('foo'));
        $this->assertEquals('foo', $esi->handle($cache, '/', '/alt', true));
    }

    public function testHandleWhenResponseIsNot200()
    {
        $this->expectException(\RuntimeException::class);
        $esi = new Esi();
        $response = new Response('foo');
        $response->setStatusCode(404);
        $cache = $this->getCache(Request::create('/')$response);
        $esi->handle($cache, '/', '/alt', false);
    }
Home | Imprint | This part of the site doesn't use cookies.