Пример #1
0
 /**
  * {@inheritdoc}
  */
 public function cacheGet($type)
 {
     if ($type != 'results') {
         return parent::cacheGet($type);
     }
     // Values to set: $view->result, $view->total_rows, $view->execute_time,
     // $view->current_page.
     if ($cache = \Drupal::cache($this->resultsBin)->get($this->generateResultsKey())) {
         $cutoff = $this->cacheExpire($type);
         if (!$cutoff || $cache->created > $cutoff) {
             $this->view->result = $cache->data['result'];
             $this->view->total_rows = $cache->data['total_rows'];
             $this->view->setCurrentPage($cache->data['current_page']);
             $this->view->execute_time = 0;
             // Trick Search API into believing a search happened, to make faceting
             // et al. work.
             /** @var \Drupal\search_api\Query\ResultSetInterface $results */
             $results = $cache->data['search_api results'];
             /** @var \Drupal\search_api\Query\ResultsCacheInterface $static_results_cache */
             $static_results_cache = \Drupal::service('search_api.results_static_cache');
             $static_results_cache->addResults($results);
             try {
                 $this->getQuery()->setSearchApiResults($results);
                 $this->getQuery()->setSearchApiQuery($results->getQuery());
             } catch (SearchApiException $e) {
                 // Ignore.
             }
             return TRUE;
         }
     }
     return FALSE;
 }
Пример #2
0
 /**
  * Constructs a TwigEnvironment object and stores cache and storage
  * internally.
  */
 public function __construct(\Twig_LoaderInterface $loader = NULL, $options = array(), ModuleHandlerInterface $module_handler, ThemeHandlerInterface $theme_handler)
 {
     // @todo Pass as arguments from the DIC.
     $this->cache_object = \Drupal::cache();
     // Ensure that twig.engine is loaded, given that it is needed to render a
     // template because functions like twig_drupal_escape_filter are called.
     require_once DRUPAL_ROOT . '/core/themes/engines/twig/twig.engine';
     // Set twig path namespace for themes and modules.
     $namespaces = array();
     foreach ($module_handler->getModuleList() as $name => $extension) {
         $namespaces[$name] = $extension->getPath();
     }
     foreach ($theme_handler->listInfo() as $name => $extension) {
         $namespaces[$name] = $extension->getPath();
     }
     foreach ($namespaces as $name => $path) {
         $templatesDirectory = $path . '/templates';
         if (file_exists($templatesDirectory)) {
             $loader->addPath($templatesDirectory, $name);
         }
     }
     $this->templateClasses = array();
     $this->stringLoader = new \Twig_Loader_String();
     parent::__construct($loader, $options);
 }
Пример #3
0
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     drupal_set_message('Settings saved');
     $this->configFactory()->getEditable('itk_instagram_hashtag.settings')->set('itk_instagram_hashtag.client_id', $form_state->getValue('client_id'))->set('itk_instagram_hashtag.resolution', $form_state->getValue('resolution'))->set('itk_instagram_hashtag.sort_by', $form_state->getValue('sort_by'))->set('itk_instagram_hashtag.limit', $form_state->getValue('limit'))->set('itk_instagram_hashtag.enable_caption', $form_state->getValue('enable_caption'))->save();
     // Make sure the new settings are available to the js.
     \Drupal::cache('render')->deleteAll();
 }
Пример #4
0
 /**
  * Tests the path cache.
  */
 function testPathCache()
 {
     // Create test node.
     $node1 = $this->drupalCreateNode();
     // Create alias.
     $edit = array();
     $edit['source'] = '/node/' . $node1->id();
     $edit['alias'] = '/' . $this->randomMachineName(8);
     $this->drupalPostForm('admin/config/search/path/add', $edit, t('Save'));
     // Check the path alias whitelist cache.
     $whitelist = \Drupal::cache()->get('path_alias_whitelist');
     $this->assertTrue($whitelist->data['node']);
     $this->assertFalse($whitelist->data['admin']);
     // Visit the system path for the node and confirm a cache entry is
     // created.
     \Drupal::cache('data')->deleteAll();
     // Make sure the path is not converted to the alias.
     $this->drupalGet(trim($edit['source'], '/'), array('alias' => TRUE));
     $this->assertTrue(\Drupal::cache('data')->get('preload-paths:' . $edit['source']), 'Cache entry was created.');
     // Visit the alias for the node and confirm a cache entry is created.
     \Drupal::cache('data')->deleteAll();
     // @todo Remove this once https://www.drupal.org/node/2480077 lands.
     Cache::invalidateTags(['rendered']);
     $this->drupalGet(trim($edit['alias'], '/'));
     $this->assertTrue(\Drupal::cache('data')->get('preload-paths:' . $edit['source']), 'Cache entry was created.');
 }
 /**
  * Tests the behavior of the theme registry class.
  */
 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, array('theme_registry'), $this->container->get('module_handler')->isLoaded());
     $this->assertTrue(\Drupal::cache()->get($cid), 'Cache entry was created.');
     // Trigger a cache miss for an offset.
     $this->assertTrue($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.
     \Drupal::cache()->delete($cid);
     // Destroy the class so that it triggers a cache write for the offset.
     $registry->destruct();
     $this->assertTrue(\Drupal::cache()->get($cid), 'Cache entry was created.');
     // Create a new instance of the class. Confirm that both the offset
     // requested previously, and one that has not yet been requested are both
     // available.
     $registry = new ThemeRegistry($cid, $cache, $lock_backend, array('theme_registry'), $this->container->get('module_handler')->isLoaded());
     $this->assertTrue($registry->get('theme_test_template_test'), 'Offset was returned correctly from the theme registry');
     $this->assertTrue($registry->get('theme_test_template_test_2'), 'Offset was returned correctly from the theme registry');
 }
 /**
  * Asserts page cache miss, then hit for the given URL; checks cache headers.
  *
  * @param \Drupal\Core\Url $url
  *   The URL to test.
  * @param string[] $expected_contexts
  *   The expected cache contexts for the given URL.
  * @param string[] $expected_tags
  *   The expected cache tags for the given URL.
  */
 protected function assertPageCacheContextsAndTags(Url $url, array $expected_contexts, array $expected_tags)
 {
     $absolute_url = $url->setAbsolute()->toString();
     sort($expected_contexts);
     sort($expected_tags);
     // Assert cache miss + expected cache contexts + tags.
     $this->drupalGet($absolute_url);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     $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 = array($url->setAbsolute()->toString(), 'html');
     $cid = implode(':', $cid_parts);
     $cache_entry = \Drupal::cache('render')->get($cid);
     sort($cache_entry->tags);
     $this->assertEqual($cache_entry->tags, $expected_tags);
     if ($cache_entry->tags !== $expected_tags) {
         debug('Missing cache tags: ' . implode(',', array_diff($cache_entry->tags, $expected_tags)));
         debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $cache_entry->tags)));
     }
 }
Пример #7
0
/**
 * Renders a form with a list of available database updates.
 */
function update_selection_page()
{
    // Make sure there is no stale theme registry.
    \Drupal::cache()->deleteAll();
    $build = \Drupal::formBuilder()->getForm('Drupal\\Core\\Update\\Form\\UpdateScriptSelectionForm');
    $build['#title'] = 'Drupal database update';
    return $build;
}
Пример #8
0
 /**
  * Asserts a view's result & render cache items' cache tags.
  *
  * This methods uses a full view object in order to render the view.
  *
  * @param \Drupal\views\ViewExecutable $view
  *   The view to test, must have caching enabled.
  * @param null|string[] $expected_results_cache
  *   NULL when expecting no results cache item, a set of cache tags expected
  *   to be set on the results cache item otherwise.
  * @param bool $views_caching_is_enabled
  *   Whether to expect an output cache item. If TRUE, the cache tags must
  *   match those in $expected_render_array_cache_tags.
  * @param string[] $expected_render_array_cache_tags
  *   A set of cache tags expected to be set on the built view's render array.
  *
  * @return array
  *   The render array.
  */
 protected function assertViewsCacheTags(ViewExecutable $view, $expected_results_cache, $views_caching_is_enabled, array $expected_render_array_cache_tags)
 {
     /** @var \Drupal\Core\Render\RendererInterface $renderer */
     $renderer = \Drupal::service('renderer');
     /** @var \Drupal\Core\Render\RenderCacheInterface $render_cache */
     $render_cache = \Drupal::service('render_cache');
     $build = $view->buildRenderable();
     $original = $build;
     // Ensure the current request is a GET request so that render caching is
     // active for direct rendering of views, just like for actual requests.
     /** @var \Symfony\Component\HttpFoundation\RequestStack $request_stack */
     $request_stack = \Drupal::service('request_stack');
     $request = new Request();
     $request->server->set('REQUEST_TIME', REQUEST_TIME);
     $view->setRequest($request);
     $request_stack->push($request);
     $renderer->renderRoot($build);
     // Render array cache tags.
     $this->pass('Checking render array cache tags.');
     sort($expected_render_array_cache_tags);
     $this->assertEqual($build['#cache']['tags'], $expected_render_array_cache_tags);
     $this->debugCacheTags($build['#cache']['tags'], $expected_render_array_cache_tags);
     if ($views_caching_is_enabled) {
         $this->pass('Checking Views results cache item cache tags.');
         /** @var \Drupal\views\Plugin\views\cache\CachePluginBase $cache_plugin */
         $cache_plugin = $view->display_handler->getPlugin('cache');
         // Results cache.
         // Ensure that the views query is built.
         $view->build();
         $results_cache_item = \Drupal::cache('data')->get($cache_plugin->generateResultsKey());
         if (is_array($expected_results_cache)) {
             $this->assertTrue($results_cache_item, 'Results cache item found.');
             if ($results_cache_item) {
                 sort($expected_results_cache);
                 $this->assertEqual($results_cache_item->tags, $expected_results_cache);
                 $this->debugCacheTags($results_cache_item->tags, $expected_results_cache);
             }
         } else {
             $this->assertFalse($results_cache_item, 'Results cache item not found.');
         }
         $this->pass('Checking Views render cache item cache tags.');
         $original['#cache'] += ['contexts' => []];
         $original['#cache']['contexts'] = Cache::mergeContexts($original['#cache']['contexts'], $this->container->getParameter('renderer.config')['required_cache_contexts']);
         $render_cache_item = $render_cache->get($original);
         if ($views_caching_is_enabled === TRUE) {
             $this->assertTrue(!empty($render_cache_item), 'Render cache item found.');
             if ($render_cache_item) {
                 $this->assertEqual($render_cache_item['#cache']['tags'], $expected_render_array_cache_tags);
                 $this->debugCacheTags($render_cache_item['#cache']['tags'], $expected_render_array_cache_tags);
             }
         } else {
             $this->assertFalse($render_cache_item, 'Render cache item not found.');
         }
     }
     $view->destroy();
     $request_stack->pop();
     return $build;
 }
Пример #9
0
 /**
  * Asserts that a cache entry has been removed.
  *
  * @param $message
  *   Message to display.
  * @param $cid
  *   The cache id.
  * @param $bin
  *   The bin the cache item was stored in.
  */
 function assertCacheRemoved($message, $cid = NULL, $bin = NULL)
 {
     if ($bin == NULL) {
         $bin = $this->defaultBin;
     }
     if ($cid == NULL) {
         $cid = $this->defaultCid;
     }
     $cached = \Drupal::cache($bin)->get($cid);
     $this->assertFalse($cached, $message);
 }
 /**
  * Asserts page cache miss, then hit for the given URL; checks cache headers.
  *
  * @param \Drupal\Core\Url $url
  *   The URL to test.
  * @param string[] $expected_contexts
  *   The expected cache contexts for the given URL.
  * @param string[] $expected_tags
  *   The expected cache tags for the given URL.
  */
 protected function assertPageCacheContextsAndTags(Url $url, array $expected_contexts, array $expected_tags)
 {
     $absolute_url = $url->setAbsolute()->toString();
     sort($expected_contexts);
     sort($expected_tags);
     $get_cache_header_values = function ($header_name) {
         $header_value = $this->drupalGetHeader($header_name);
         if (empty($header_value)) {
             return [];
         } else {
             return explode(' ', $header_value);
         }
     };
     // Assert cache miss + expected cache contexts + tags.
     $this->drupalGet($absolute_url);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     $actual_contexts = $get_cache_header_values('X-Drupal-Cache-Contexts');
     $actual_tags = $get_cache_header_values('X-Drupal-Cache-Tags');
     $this->assertIdentical($actual_contexts, $expected_contexts);
     if ($actual_contexts !== $expected_contexts) {
         debug('Missing cache contexts: ' . implode(',', array_diff($actual_contexts, $expected_contexts)));
         debug('Unwanted cache contexts: ' . implode(',', array_diff($expected_contexts, $actual_contexts)));
     }
     $this->assertIdentical($actual_tags, $expected_tags);
     if ($actual_tags !== $expected_tags) {
         debug('Missing cache tags: ' . implode(',', array_diff($actual_tags, $expected_tags)));
         debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $actual_tags)));
     }
     // Assert cache hit + expected cache contexts + tags.
     $this->drupalGet($absolute_url);
     $actual_contexts = $get_cache_header_values('X-Drupal-Cache-Contexts');
     $actual_tags = $get_cache_header_values('X-Drupal-Cache-Tags');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     $this->assertIdentical($actual_contexts, $expected_contexts);
     if ($actual_contexts !== $expected_contexts) {
         debug('Missing cache contexts: ' . implode(',', array_diff($actual_contexts, $expected_contexts)));
         debug('Unwanted cache contexts: ' . implode(',', array_diff($expected_contexts, $actual_contexts)));
     }
     $this->assertIdentical($actual_tags, $expected_tags);
     if ($actual_tags !== $expected_tags) {
         debug('Missing cache tags: ' . implode(',', array_diff($actual_tags, $expected_tags)));
         debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $actual_tags)));
     }
     // Assert page cache item + expected cache tags.
     $cid_parts = array($url->setAbsolute()->toString(), 'html');
     $cid = implode(':', $cid_parts);
     $cache_entry = \Drupal::cache('render')->get($cid);
     sort($cache_entry->tags);
     $this->assertEqual($cache_entry->tags, $expected_tags);
     if ($cache_entry->tags !== $expected_tags) {
         debug('Missing cache tags: ' . implode(',', array_diff($cache_entry->tags, $expected_tags)));
         debug('Unwanted cache tags: ' . implode(',', array_diff($expected_tags, $cache_entry->tags)));
     }
 }
 /**
  * Tests that when creating a feed item, the feed tag is invalidated.
  */
 public function testEntityCreation()
 {
     // Create a cache entry that is tagged with a feed cache tag.
     \Drupal::cache('render')->set('foo', 'bar', \Drupal\Core\Cache\CacheBackendInterface::CACHE_PERMANENT, $this->entity->getCacheTag());
     // Verify a cache hit.
     $this->verifyRenderCache('foo', array('aggregator_feed:1'));
     // Now create a feed item in that feed.
     Item::create(array('fid' => $this->entity->getFeedId(), 'title' => t('Llama 2'), 'path' => 'https://groups.drupal.org/'))->save();
     // Verify a cache miss.
     $this->assertFalse(\Drupal::cache('render')->get('foo'), 'Creating a new feed item invalidates the cache tag of the feed.');
 }
Пример #12
0
 /**
  * Get a list of cloudflare IP Ranges
  */
 function cloudflare_ip_ranges()
 {
     if ($cache = \Drupal::cache()->get('cloudflare_ip_ranges')) {
         return $cache->data;
     } else {
         $ip_blocks = file_get_contents(CLOUDFLARE_URL_IPV4_RANGE);
         $cloudflare_ips = explode("\n", $ip_blocks);
         $cloudflare_ips = array_map('trim', $cloudflare_ips);
         \Drupal::cache()->set('cloudflare_ip_ranges', $cloudflare_ips, Cache::PERMANENT);
         return $cloudflare_ips;
     }
 }
Пример #13
0
 /**
  * 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.');
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     $config = $this->config('medium.settings');
     // Invalidate library cache if devmode has changed.
     $devmode = $form_state->getValue('devmode');
     if ($config->get('devmode') != $devmode) {
         \Drupal::cache('discovery')->invalidate('library_info');
     }
     // Save config
     $config->set('devmode', $devmode)->save();
     parent::submitForm($form, $form_state);
 }
Пример #15
0
 /**
  * {@inheritdoc}
  */
 public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state)
 {
     /* @var $item LanguageItem */
     $item = $items[$delta];
     $value = $item->value;
     // Add Languages to custom values: $this->options and $element[]
     $this->options = $languages = $item->getSettableOptions();
     // Cache available languages for this field for a day.
     $field_name = $this->fieldDefinition->id();
     \Drupal::cache('data')->set('languagefield:languages:' . $field_name, $languages, strtotime('+1 day', time()));
     $element['value'] = $element + array('#type' => 'textfield', '#default_value' => !empty($value) && isset($languages[$value]) ? $languages[$value] : '', '#languagefield_options' => $languages, '#autocomplete_route_name' => $this->getSetting('autocomplete_route_name'), '#autocomplete_route_parameters' => array('field_name' => $field_name), '#size' => $this->getSetting('size'), '#placeholder' => $this->getSetting('placeholder'), '#maxlength' => 255, '#element_validate' => array(array(get_class($this), 'validateElement')));
     return $element;
 }
 public function get_flickrimages($lat, $lon)
 {
     $cache = \Drupal::cache()->get($lat . $lon);
     if (isset($cache->data)) {
         return $cache->data;
     }
     $content = file_get_contents("https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=5e1801b26daedd466cf264a797f25b74&lat=" . $lat . "&lon=" . $lon . "&radius=1&format=json");
     $content = str_replace('jsonFlickrApi(', '', $content);
     $content = substr($content, 0, strlen($content) - 1);
     $result = json_decode($content);
     \Drupal::cache()->set($lat . $lon, $result, time() + 3600, array('flickrimages_cache'));
     return $result;
 }
 public function get_weather($lat, $lon)
 {
     //if cache is available we return the cache result
     $cache = \Drupal::cache()->get($lat . $lon);
     if (isset($cache->data)) {
         return $cache->data;
     }
     $content = file_get_contents("http://api.openweathermap.org/data/2.5/weather?lat=" . $lat . "&lon=" . $lon . "&APPID=0b7f42c9896d550960889ce7122a06e7");
     $result = json_decode($content);
     //We set the cache for one hour
     \Drupal::cache()->set($lat . $lon, $result, time() + 3600, array('html5weather_cache'));
     return $result;
 }
 /**
  * Get matches for the autocompletion of languages.
  *
  * @param string $string
  *   The string to match for languages.
  * @param $string $field_name
  *   The name of the autocomplete field.
  *
  * @return array
  *   An array containing the matching languages.
  */
 public function getMatches($string, $field_name)
 {
     $matches = array();
     if ($string) {
         $languages = \Drupal::cache('data')->get('languagefield:languages:' . $field_name)->data;
         foreach ($languages as $langcode => $language) {
             if (strpos(Unicode::strtolower($language), Unicode::strtolower($string)) !== FALSE) {
                 $matches[] = array('value' => $language, 'label' => $language);
             }
         }
     }
     return $matches;
 }
Пример #19
0
 /**
  * Verify that when loading a given page, it's a page cache hit or miss.
  *
  * @param string $path
  *   The page at this path will be loaded.
  * @param string $hit_or_miss
  *   'HIT' if a page cache hit is expected, 'MISS' otherwise.
  *
  * @param array|FALSE $tags
  *   When expecting a page cache hit, you may optionally specify an array of
  *   expected cache tags. While FALSE, the cache tags will not be verified.
  */
 protected function verifyPageCache($path, $hit_or_miss, $tags = FALSE)
 {
     $this->drupalGet($path);
     $message = String::format('Page cache @hit_or_miss for %path.', array('@hit_or_miss' => $hit_or_miss, '%path' => $path));
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), $hit_or_miss, $message);
     if ($hit_or_miss === 'HIT' && is_array($tags)) {
         $cid_parts = array(url($path, array('absolute' => TRUE)), 'html');
         $cid = sha1(implode(':', $cid_parts));
         $cache_entry = \Drupal::cache('render')->get($cid);
         sort($cache_entry->tags);
         sort($tags);
         $this->assertIdentical($cache_entry->tags, $tags);
     }
 }
Пример #20
0
 /**
  * Constructs a TwigEnvironment object and stores cache and storage
  * internally.
  *
  * @param string $root
  *   The app root.
  * @param \Twig_LoaderInterface $loader
  *   The Twig loader or loader chain.
  * @param array $options
  *   The options for the Twig environment.
  */
 public function __construct($root, \Twig_LoaderInterface $loader = NULL, $options = array())
 {
     // @todo Pass as arguments from the DIC.
     $this->cache_object = \Drupal::cache();
     // Ensure that twig.engine is loaded, given that it is needed to render a
     // template because functions like TwigExtension::escapeFilter() are called.
     require_once $root . '/core/themes/engines/twig/twig.engine';
     $this->templateClasses = array();
     $options += array('cache' => TRUE, 'debug' => FALSE, 'auto_reload' => NULL);
     // Ensure autoescaping is always on.
     $options['autoescape'] = TRUE;
     $this->loader = $loader;
     parent::__construct($this->loader, $options);
 }
Пример #21
0
 /**
  * Constructs a new \Drupal\bootstrap\Plugin\UpdateManager object.
  *
  * @param \Drupal\bootstrap\Theme $theme
  *   The theme to use for discovery.
  */
 public function __construct(Theme $theme)
 {
     // Unlike other plugins in this base theme, this one should only discover
     // update plugins that are unique to its own theme to avoid plugin ID
     // collision (e.g. base and sub-theme both implement an update plugin
     // with the id "8001").
     $this->namespaces = new \ArrayObject(['Drupal\\' . $theme->getName() => [DRUPAL_ROOT . '/' . $theme->getPath() . '/src']]);
     $this->theme = $theme;
     $this->subdir = 'Plugin/Update';
     $this->pluginDefinitionAnnotationName = 'Drupal\\bootstrap\\Annotation\\BootstrapUpdate';
     $this->pluginInterface = 'Drupal\\bootstrap\\Plugin\\Update\\UpdateInterface';
     $this->themeHandler = \Drupal::service('theme_handler');
     $this->themeManager = \Drupal::service('theme.manager');
     $this->setCacheBackend(\Drupal::cache('discovery'), 'theme:' . $theme->getName() . ':update', $this->getCacheTags());
 }
 /**
  * Ensures that Stable overrides all relevant core templates.
  */
 public function testStableTemplateOverrides()
 {
     $registry = new Registry(\Drupal::root(), \Drupal::cache(), \Drupal::lock(), \Drupal::moduleHandler(), $this->themeHandler, \Drupal::service('theme.initialization'), 'stable');
     $registry->setThemeManager(\Drupal::theme());
     $registry_full = $registry->get();
     foreach ($registry_full as $hook => $info) {
         if (isset($info['template'])) {
             // Allow skipping templates.
             if (in_array($info['template'], $this->templatesToSkip)) {
                 continue;
             }
             $this->assertEquals('core/themes/stable', $info['theme path'], $info['template'] . '.html.twig overridden in Stable.');
         }
     }
 }
 /**
  * Verify that when loading a given page, it's a page cache hit or miss.
  *
  * @param \Drupal\Core\Url $url
  *   The page for this URL will be loaded.
  * @param string $hit_or_miss
  *   'HIT' if a page cache hit is expected, 'MISS' otherwise.
  *
  * @param array|FALSE $tags
  *   When expecting a page cache hit, you may optionally specify an array of
  *   expected cache tags. While FALSE, the cache tags will not be verified.
  */
 protected function verifyPageCache(Url $url, $hit_or_miss, $tags = FALSE)
 {
     $this->drupalGet($url);
     $message = String::format('Page cache @hit_or_miss for %path.', array('@hit_or_miss' => $hit_or_miss, '%path' => $url->toString()));
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), $hit_or_miss, $message);
     if ($hit_or_miss === 'HIT' && is_array($tags)) {
         $absolute_url = $url->setAbsolute()->toString();
         $cid_parts = array($absolute_url, 'html');
         $cid = implode(':', $cid_parts);
         $cache_entry = \Drupal::cache('render')->get($cid);
         sort($cache_entry->tags);
         $tags = array_unique($tags);
         sort($tags);
         $this->assertIdentical($cache_entry->tags, $tags);
     }
 }
Пример #24
0
 public function cache($date, $days_to_fore, $hourly_interval, $location)
 {
     $data = [];
     for ($x = 0; $x <= $days_to_fore; $x++) {
         $newdate = strtotime('+' . $x . ' day', strtotime($date));
         $newdate = date('Y-m-j', $newdate);
         $CACHE_ID = md5($newdate . $location . $hourly_interval);
         if ($cache = \Drupal::cache()->get($CACHE_ID)) {
             $data[] = $cache->data;
         } else {
             $data[] = $this->response($newdate, $location, $hourly_interval);
             \Drupal::cache()->set($CACHE_ID, $data);
         }
     }
     return array($data);
 }
Пример #25
0
 /**
  * {@inheritdoc}
  */
 public function LayoutConfig($type)
 {
     $config_data = array();
     if ($cache = \Drupal::cache()->get($this->layout_cid . ':' . $type)) {
         $config_data = $cache->data;
     } else {
         $config_file = $this->layout_path . '/' . $this->layout_name . '.' . $type . '.yml';
         if (file_exists($config_file)) {
             $parser = new Parser();
             $config_data = $parser->parse(file_get_contents($config_file));
         }
         if (!empty($config_data)) {
             \Drupal::cache()->set($this->layout_cid . ':' . $type, $config_data);
         }
     }
     return $config_data;
 }
Пример #26
0
 /**
  * Tests the output caching on an actual page.
  */
 public function testCacheOutputOnPage()
 {
     $view = Views::getView('test_display');
     $view->storage->setStatus(TRUE);
     $view->setDisplay('page_1');
     $view->display_handler->overrideOption('cache', array('type' => 'time', 'options' => array('results_lifespan' => '3600', 'output_lifespan' => '3600')));
     $view->save();
     $this->container->get('router.builder')->rebuildIfNeeded();
     $output_key = $view->getDisplay()->getPlugin('cache')->generateOutputKey();
     $this->assertFalse(\Drupal::cache('render')->get($output_key));
     $this->drupalGet('test-display');
     $this->assertResponse(200);
     $this->assertTrue(\Drupal::cache('render')->get($output_key));
     $this->drupalGet('test-display');
     $this->assertResponse(200);
     $this->assertTrue(\Drupal::cache('render')->get($output_key));
 }
 /**
  * @param string[] $toBeAdded
  * @param string[] $toBeRemoved
  *
  * @return string[]
  */
 protected function updateClassFiles($toBeAdded, $toBeRemoved)
 {
     $class_files = $toBeAdded;
     // Other requests may have already written to the cache, so we get an up to
     // date version.
     $cached = \Drupal::cache()->get($this->cacheName);
     if (isset($cached->data)) {
         $class_files += $cached->data;
         foreach ($toBeRemoved as $class => $file) {
             if (isset($class_files[$class]) && $class_files[$class] === $file) {
                 unset($class_files[$class]);
             }
         }
     }
     \Drupal::cache()->set($this->cacheName, $class_files);
     return $class_files;
 }
Пример #28
0
 /**
  * Asserts a view's result & output cache items' cache tags.
  *
  * @param \Drupal\views\ViewExecutable $view
  *   The view to test, must have caching enabled.
  * @param null|string[] $expected_results_cache
  *   NULL when expecting no results cache item, a set of cache tags expected
  *   to be set on the results cache item otherwise.
  * @param bool $views_caching_is_enabled
  *   Whether to expect an output cache item. If TRUE, the cache tags must
  *   match those in $expected_render_array_cache_tags.
  * @param string[] $expected_render_array_cache_tags
  *   A set of cache tags expected to be set on the built view's render array.
  *
  * @return array
  *   The render array
  */
 protected function assertViewsCacheTags(ViewExecutable $view, $expected_results_cache, $views_caching_is_enabled, array $expected_render_array_cache_tags)
 {
     $build = $view->preview();
     // Ensure the current request is a GET request so that render caching is
     // active for direct rendering of views, just like for actual requests.
     /** @var \Symfony\Component\HttpFoundation\RequestStack $request_stack */
     $request_stack = \Drupal::service('request_stack');
     $request_stack->push(new Request());
     \Drupal::service('renderer')->renderRoot($build);
     $request_stack->pop();
     // Render array cache tags.
     $this->pass('Checking render array cache tags.');
     sort($expected_render_array_cache_tags);
     $this->assertEqual($build['#cache']['tags'], $expected_render_array_cache_tags);
     if ($views_caching_is_enabled) {
         $this->pass('Checking Views results cache item cache tags.');
         /** @var \Drupal\views\Plugin\views\cache\CachePluginBase $cache_plugin */
         $cache_plugin = $view->display_handler->getPlugin('cache');
         // Results cache.
         $results_cache_item = \Drupal::cache('data')->get($cache_plugin->generateResultsKey());
         if (is_array($expected_results_cache)) {
             $this->assertTrue($results_cache_item, 'Results cache item found.');
             if ($results_cache_item) {
                 sort($expected_results_cache);
                 $this->assertEqual($results_cache_item->tags, $expected_results_cache);
             }
         } else {
             $this->assertFalse($results_cache_item, 'Results cache item not found.');
         }
         // Output cache.
         $this->pass('Checking Views output cache item cache tags.');
         $output_cache_item = \Drupal::cache('render')->get($cache_plugin->generateOutputKey());
         if ($views_caching_is_enabled === TRUE) {
             $this->assertTrue($output_cache_item, 'Output cache item found.');
             if ($output_cache_item) {
                 $this->assertEqual($output_cache_item->tags, Cache::mergeTags($expected_render_array_cache_tags, ['rendered']));
             }
         } else {
             $this->assertFalse($output_cache_item, 'Output cache item not found.');
         }
     }
     $view->destroy();
     return $build;
 }
 /**
  * Fills page cache for the given path, verify cache tags on page cache hit.
  *
  * @param $path
  *   The Drupal page path to test.
  * @param $expected_tags
  *   The expected cache tags for the page cache entry of the given $path.
  */
 protected function verifyPageCacheTags($path, $expected_tags)
 {
     sort($expected_tags);
     $this->drupalGet($path);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     $actual_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
     sort($actual_tags);
     $this->assertIdentical($actual_tags, $expected_tags);
     $this->drupalGet($path);
     $actual_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
     sort($actual_tags);
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     $this->assertIdentical($actual_tags, $expected_tags);
     $cid_parts = array(url($path, array('absolute' => TRUE)), 'html');
     $cid = sha1(implode(':', $cid_parts));
     $cache_entry = \Drupal::cache('render')->get($cid);
     sort($cache_entry->tags);
     $this->assertEqual($cache_entry->tags, $expected_tags);
 }
Пример #30
0
 /**
  * Tests entity render cache handling.
  */
 public function testEntityViewBuilderCache()
 {
     /** @var \Drupal\Core\Render\RendererInterface $renderer */
     $renderer = $this->container->get('renderer');
     $cache_contexts_manager = \Drupal::service("cache_contexts_manager");
     $cache = \Drupal::cache();
     // Force a request via GET so we can get drupal_render() cache working.
     $request = \Drupal::request();
     $request_method = $request->server->get('REQUEST_METHOD');
     $request->setMethod('GET');
     $entity_test = $this->createTestEntity('entity_test');
     // Test that new entities (before they are saved for the first time) do not
     // generate a cache entry.
     $build = $this->container->get('entity.manager')->getViewBuilder('entity_test')->view($entity_test, 'full');
     $this->assertTrue(isset($build['#cache']) && array_keys($build['#cache']) == ['tags', 'contexts', 'max-age'], 'The render array element of new (unsaved) entities is not cached, but does have cache tags set.');
     // Get a fully built entity view render array.
     $entity_test->save();
     $build = $this->container->get('entity.manager')->getViewBuilder('entity_test')->view($entity_test, 'full');
     $cid_parts = array_merge($build['#cache']['keys'], $cache_contexts_manager->convertTokensToKeys(['languages:' . LanguageInterface::TYPE_INTERFACE, 'theme', 'user.permissions'])->getKeys());
     $cid = implode(':', $cid_parts);
     $bin = $build['#cache']['bin'];
     // Mock the build array to not require the theme registry.
     unset($build['#theme']);
     $build['#markup'] = 'entity_render_test';
     // Test that a cache entry is created.
     $renderer->renderRoot($build);
     $this->assertTrue($this->container->get('cache.' . $bin)->get($cid), 'The entity render element has been cached.');
     // Re-save the entity and check that the cache entry has been deleted.
     $cache->set('kittens', 'Kitten data', Cache::PERMANENT, $build['#cache']['tags']);
     $entity_test->save();
     $this->assertFalse($this->container->get('cache.' . $bin)->get($cid), 'The entity render cache has been cleared when the entity was saved.');
     $this->assertFalse($cache->get('kittens'), 'The entity saving has invalidated cache tags.');
     // Rebuild the render array (creating a new cache entry in the process) and
     // delete the entity to check the cache entry is deleted.
     unset($build['#printed']);
     $renderer->renderRoot($build);
     $this->assertTrue($this->container->get('cache.' . $bin)->get($cid), 'The entity render element has been cached.');
     $entity_test->delete();
     $this->assertFalse($this->container->get('cache.' . $bin)->get($cid), 'The entity render cache has been cleared when the entity was deleted.');
     // Restore the previous request method.
     $request->setMethod($request_method);
 }