Skip to content

PhpAnnotationParser: Clean the docblock before parsing? #2

Description

@donquixote

Docblocks usually have unpleasant characters like '' and '/*' that we want to ignore.
Doing this directly in the parser seems fragile and intransparent.

$this->ws = new Ignore(new Many(new WhitespaceParser(1), '(/\*\*|\*/|\*)'));

This probably silently eats asterisks in places where we really prefer an error to be generated.
Yes, Doctrine does this too (afaik), but I don't think it is intended nor desirable.
Instead, what about a static method to clean up the stars before even going into the parser?

class Util {

  /**
   * @param string $docComment
   *
   * @return bool|string
   *   The cleaned-up string, or false if it is not a valid docblock.
   */
  static function peelDocComment($docComment) {
    if ('/**' !== substr($docComment, 0, 3)) {
      return false;
    }
    if ('*/' !== substr($docComment, -2)) {
      return false;
    }
    $peeled = substr($docComment, 3, -2);
    $lines = explode("\n", $peeled);
    $firstline = array_shift($lines);
    if ('' !== rtrim($firstline)) {
      return false;
    }
    $lastline = array_pop($lines);
    if ('' !== rtrim($lastline)) {
      return false;
    }
    foreach ($lines as &$line) {
      $line = trim($line);
      if ('' === $line) {
        return false;
      }
      if ('*' !== $line{0}) {
        // We require every line to begin with '*', optionally with some space
        // before.
        return false;
      }
      $line = substr($line, 1);
    }
    return implode("\n", $lines);
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions