FrontMatterTest.php in Drupal 10
File
core/tests/Drupal/KernelTests/Core/Theme/FrontMatterTest.php
View source
<?php
namespace Drupal\KernelTests\Core\Theme;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\Component\FrontMatter\FrontMatterTest as ComponentFrontMatterTest;
use Symfony\Component\DependencyInjection\Definition;
use Twig\Error\Error;
use Twig\Error\SyntaxError;
use Twig\Loader\FilesystemLoader;
class FrontMatterTest extends KernelTestBase {
const BROKEN_SOURCE = '<div>Hello {{ world</div>';
protected $twig;
protected function setUp() : void {
parent::setUp();
$this->twig = \Drupal::service('twig');
}
public function register(ContainerBuilder $container) {
parent::register($container);
$definition = new Definition(FilesystemLoader::class, [
[
sys_get_temp_dir(),
],
]);
$definition
->setPublic(TRUE);
$container
->setDefinition('twig_loader__file_system', $definition)
->addTag('twig.loader');
}
protected function createTwigTemplate(string $content = '') : string {
$file = tempnam(sys_get_temp_dir(), 'twig') . ".html.twig";
file_put_contents($file, $content);
return $file;
}
public function testFrontMatterBroken() {
$source = "---\ncollection:\n- key: foo\n foo: bar\n---\n" . ComponentFrontMatterTest::SOURCE;
$file = $this
->createTwigTemplate($source);
$this
->expectException(SyntaxError::class);
$this
->expectExceptionMessage('An error occurred when attempting to parse front matter data on line 4 in ' . $file);
$this->twig
->getTemplateMetadata(basename($file));
}
public function testFrontMatter($yaml, $line, $content = ComponentFrontMatterTest::SOURCE) {
$source = ComponentFrontMatterTest::createFrontMatterSource($yaml, $content);
$file = $this
->createTwigTemplate($source);
$name = basename($file);
$metadata = $this->twig
->getTemplateMetadata($name);
$this
->assertEquals($yaml === NULL ? [] : $yaml, $metadata);
$output = $this->twig
->load($name)
->render();
$this
->assertEquals($content, $output);
$source = ComponentFrontMatterTest::createFrontMatterSource($yaml, static::BROKEN_SOURCE);
$file = $this
->createTwigTemplate($source);
$name = basename($file);
try {
$this->twig
->load($name);
} catch (Error $error) {
$this
->assertEquals($line, $error
->getTemplateLine());
}
try {
$this->twig
->createTemplate($source)
->render();
} catch (Error $error) {
$this
->assertEquals($line, $error
->getTemplateLine());
}
}
}