Skip to content

Instantly share code, notes, and snippets.

@Berdir
Created March 11, 2015 12:12

Revisions

  1. Berdir created this gist Mar 11, 2015.
    57 changes: 57 additions & 0 deletions gistfile1.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    <?php

    /**
    * Minifies and removes unneeded cache tags.
    *
    * @param array $cache_tags
    * List of cache tags.
    *
    * @return array
    * Shortened and cleaned up cache tag list.
    */
    public function minifyTags(array $cache_tags) {
    $minified_tags = [];

    $has_node_list_tag = in_array('node_list', $cache_tags);
    $has_block_list_tag = in_array('config:block_list', $cache_tags);
    $add_menu_list_tag = FALSE;

    foreach ($cache_tags as $tag) {
    // Skip specific node tags if the list cache tag is present.
    if ($has_node_list_tag && strpos($tag, 'node:') !== FALSE) {
    continue;
    }

    // Skip specific block cache tags if the list cache tag is present.
    if ($has_block_list_tag && strpos($tag, 'config:block.block.') !== FALSE) {
    continue;
    }

    // Skip specific node tags if the list cache tag is present.
    if (strpos($tag, 'config:system.menu.') !== FALSE) {
    $add_menu_list_tag = TRUE;
    continue;
    }

    $minified_tags[] = $tag;
    };

    // @todo Replace this with a fancy algorithm.
    $replacements = [
    'config:' => 'c:',
    'block_content:' => 'bc:',
    'page_manager.page.' => 'pmp.',
    'file:' => 'f:',
    'taxonomy_term:' => 'tm:',
    'theme_global_setting' => 'tgs',
    'user:' => 'u:',
    ];

    // Shorten known cache tags.
    $minified_tags = str_replace(array_keys($replacements), array_values($replacements), $minified_tags);

    if ($add_menu_list_tag) {
    $minified_tags[] = 'c:menu_list';
    }
    return $minified_tags;
    }