You are here

protected function FrontMatter::parse in Drupal 9

Same name and namespace in other branches
  1. 10 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;
}