View source
<?php
namespace Drupal\Tests\Component\FrontMatter;
use Drupal\Component\FrontMatter\Exception\FrontMatterParseException;
use Drupal\Component\FrontMatter\FrontMatter;
use Drupal\Component\Serialization\Yaml;
use PHPUnit\Framework\TestCase;
class FrontMatterTest extends TestCase {
const SOURCE = '<div>Hello world</div>';
public static function createFrontMatterSource(?array $yaml, string $content = self::SOURCE) : string {
$frontMatter = '';
if (is_array($yaml)) {
$yaml = $yaml ? trim(Yaml::encode($yaml)) . "\n" : '';
$frontMatter = FrontMatter::SEPARATOR . "\n{$yaml}" . FrontMatter::SEPARATOR . "\n";
}
return $frontMatter . $content;
}
public function testFrontMatterSerializerException() {
$this
->expectException(\AssertionError::class);
$this
->expectExceptionMessage('The $serializer parameter must reference a class that implements Drupal\\Component\\Serialization\\SerializationInterface.');
FrontMatter::create('', '');
}
public function testFrontMatterBroken() {
$this
->expectException(FrontMatterParseException::class);
$this
->expectExceptionMessage('An error occurred when attempting to parse front matter data on line 4');
$source = "---\ncollection:\n- key: foo\n foo: bar\n---\n";
FrontMatter::create($source)
->getData();
}
public function testFrontMatterData($yaml, $line, $content = self::SOURCE) {
$source = static::createFrontMatterSource($yaml, $content);
$frontMatter = FrontMatter::create($source);
$this
->assertEquals($content, $frontMatter
->getContent());
$this
->assertEquals($yaml === NULL ? [] : $yaml, $frontMatter
->getData());
$this
->assertEquals($line, $frontMatter
->getLine());
}
public static function providerFrontMatterData() {
$data['none'] = [
'yaml' => NULL,
'line' => 1,
];
$data['scalar'] = [
'yaml' => [
'string' => 'value',
'number' => 42,
'bool' => TRUE,
'null' => NULL,
],
'line' => 7,
];
$data['indexed_arrays'] = [
'yaml' => [
'brackets' => [
1,
2,
3,
],
'items' => [
'item1',
'item2',
'item3',
],
],
'line' => 11,
];
$data['associative_arrays'] = [
'yaml' => [
'brackets' => [
'a' => 1,
'b' => 2,
'c' => 3,
],
'items' => [
'a' => 'item1',
'b' => 'item2',
'c' => 'item3',
],
],
'line' => 11,
];
$data['empty_data'] = [
'yaml' => [],
'line' => 3,
];
$data['empty_content'] = [
'yaml' => [
'key' => 'value',
],
'line' => 4,
'content' => '',
];
$data['empty_data_and_content'] = [
'yaml' => [],
'line' => 3,
'content' => '',
];
$data['empty_string'] = [
'yaml' => NULL,
'line' => 1,
'content' => '',
];
$data['multiple_separators'] = [
'yaml' => [
'key' => '---',
],
'line' => 4,
'content' => "Something\n---\nSomething more",
];
return $data;
}
}