private function FrontMatter::parse in Drupal 8
Parses the source.
Return value
array An associative array containing:
- code: The real source code.
- data: The front matter data extracted and decoded.
- line: The line number where the real source code starts.
Throws
\Drupal\Component\Serialization\Exception\InvalidDataTypeException Exception thrown when the Front Matter cannot be parsed.
File
- core/
modules/ help_topics/ src/ FrontMatter.php, line 95
Class
- FrontMatter
- Extracts Front Matter from the beginning of a source.
Namespace
Drupal\help_topicsCode
private function parse() {
if (!$this->parsed) {
$this->parsed = [
'code' => $this->source,
'data' => [],
'line' => 1,
];
// Check for front matter data.
$len = strlen(static::FRONT_MATTER_SEPARATOR);
$matches = [];
if (substr($this->parsed['code'], 0, $len + 1) === static::FRONT_MATTER_SEPARATOR . "\n" || substr($this->parsed['code'], 0, $len + 2) === static::FRONT_MATTER_SEPARATOR . "\r\n") {
preg_match(static::FRONT_MATTER_REGEXP, $this->parsed['code'], $matches);
$matches = array_map('trim', $matches);
}
// Immediately return if the code doesn't contain front matter data.
if (empty($matches)) {
return $this->parsed;
}
// Set the extracted source code.
$this->parsed['code'] = $matches[2];
// Set the extracted front matter data. Do not catch any exceptions here
// as doing so would only obfuscate any errors found in the front matter
// data. Typecast to an array to ensure top level scalars are in an array.
if ($matches[1]) {
$this->parsed['data'] = (array) $this->serializer::decode($matches[1]);
}
// Determine the real source line by counting newlines from the data and
// then adding 2 to account for the front matter separator (---) wrappers
// and then adding 1 more for the actual line number after the data.
$this->parsed['line'] = count(preg_split('/\\r\\n|\\n/', $matches[1])) + 3;
}
return $this->parsed;
}