function FrontMatter::parse

Same name in other branches
  1. 9 core/lib/Drupal/Component/FrontMatter/FrontMatter.php \Drupal\Component\FrontMatter\FrontMatter::parse()
  2. 8.9.x core/modules/help_topics/src/FrontMatter.php \Drupal\help_topics\FrontMatter::parse()
  3. 11.x core/lib/Drupal/Component/FrontMatter/FrontMatter.php \Drupal\Component\FrontMatter\FrontMatter::parse()

Parses the source.

Return value

array An associative array containing:

  • content: The real content.
  • data: The front matter data extracted and decoded.
  • line: The line number where the real content starts.

Throws

\Drupal\Component\FrontMatter\Exception\FrontMatterParseException

File

core/lib/Drupal/Component/FrontMatter/FrontMatter.php, line 121

Class

FrontMatter
Component for parsing front matter from a source.

Namespace

Drupal\Component\FrontMatter

Code

protected function parse() : array {
    if (!$this->parsed) {
        $content = $this->source;
        $data = [];
        $line = 1;
        // Parse front matter data.
        if (preg_match(static::REGEXP, $content, $matches)) {
            // Extract the source content.
            $content = !empty($matches[3]) ? trim($matches[3]) : '';
            // Extract the front matter data and typecast to an array to ensure
            // top level scalars are in an array.
            $raw = !empty($matches[2]) ? trim($matches[2]) : '';
            if ($raw) {
                try {
                    $data = (array) $this->serializer::decode($raw);
                } catch (InvalidDataTypeException $exception) {
                    // Rethrow a specific front matter parse exception.
                    throw new FrontMatterParseException($exception);
                }
            }
            // Determine the real source line by counting all newlines in the first
            // match (which includes the front matter separators) and append a new
            // line to denote that the content should start after it.
            if (!empty($matches[1])) {
                $line += preg_match_all('/\\R/', $matches[1] . "\n");
            }
        }
        // Set the parsed data.
        $this->parsed = [
            'content' => $content,
            'data' => $data,
            'line' => $line,
        ];
    }
    return $this->parsed;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.