You are here

public function CacheMetadataExtractorTest::testCacheMetadataExtractor in Twig Tweak 3.x

Same name and namespace in other branches
  1. 3.1.x tests/src/Kernel/CacheMetadataExtractorTest.php \Drupal\Tests\twig_tweak\Kernel\CacheMetadataExtractorTest::testCacheMetadataExtractor()

Test callback.

File

tests/src/Kernel/CacheMetadataExtractorTest.php, line 25

Class

CacheMetadataExtractorTest
A test for Cache Metadata Extractor service.

Namespace

Drupal\Tests\twig_tweak\Kernel

Code

public function testCacheMetadataExtractor() : void {
  $extractor = $this->container
    ->get('twig_tweak.cache_metadata_extractor');

  // -- Object.
  $input = new CacheableMetadata();
  $input
    ->setCacheMaxAge(5);
  $input
    ->setCacheContexts([
    'url',
    'user.permissions',
  ]);
  $input
    ->setCacheTags([
    'node',
    'node.view',
  ]);
  $build = $extractor
    ->extractCacheMetadata($input);
  $expected_build['#cache'] = [
    'contexts' => [
      'url',
      'user.permissions',
    ],
    'tags' => [
      'node',
      'node.view',
    ],
    'max-age' => 5,
  ];
  self::assertSame($expected_build, $build);

  // -- Render array.
  $input = [
    'foo' => [
      '#cache' => [
        'tags' => [
          'foo',
          'foo.view',
        ],
      ],
      'bar' => [
        0 => [
          '#cache' => [
            'tags' => [
              'bar-0',
            ],
          ],
        ],
        1 => [
          '#cache' => [
            'tags' => [
              'bar-1',
            ],
          ],
        ],
        '#cache' => [
          'tags' => [
            'bar',
            'bar.view',
          ],
          'contexts' => [
            'url.path',
          ],
          'max-age' => 10,
        ],
      ],
    ],
    '#cache' => [
      'contexts' => [
        'url',
        'user.permissions',
      ],
      'tags' => [
        'node',
        'node.view',
      ],
      'max-age' => 20,
    ],
  ];
  $build = $extractor
    ->extractCacheMetadata($input);
  $expected_build = [
    '#cache' => [
      'contexts' => [
        'url',
        'url.path',
        'user.permissions',
      ],
      'tags' => [
        'bar',
        'bar-0',
        'bar-1',
        'bar.view',
        'foo',
        'foo.view',
        'node',
        'node.view',
      ],
      'max-age' => 10,
    ],
  ];
  self::assertSame($expected_build, $build);

  // -- Wrong type.
  self::expectErrorMessage('The input should be either instance of Drupal\\Core\\Cache\\CacheableDependencyInterface or array. stdClass was given.');

  /* @noinspection PhpParamsInspection */
  $extractor
    ->extractCacheMetadata(new \stdClass());
}