Ivan Montilla Ivan Montilla - 11 months ago 41
PHP Question

Getting annotation of comment in PHP, I get too an email of comment

I'm making an ORM in PHP, and I thinked annotate table, column, database, etc. in comment annotation, can be a good idea.

For get annotations of comment, I try this

How to find annotations in a PHP5 object?

But I've some problem, this include some email, or other text that not are annotation, if these have an @ character.

This is my function:

public function getAnnotationArrayFromDocComment($docComment) {
$annotationsArray = [];
preg_match_all('#@(.*?)\n#s', $docComment, $annotations);
foreach ($annotations[1] as $annotation) {
$explotedAnnotation = explode(" ", $annotation);
if (isset($explotedAnnotation[1])) $annotationsArray[trim($explotedAnnotation[0])] = trim($explotedAnnotation[1]);
else $annotationsArray[trim($explotedAnnotation[0])] = "";
return $annotationsArray;

Basically, this function, return an array with this structure:

["annotation" => "valueOfAnnotation"]

I'm concient of the "mistake" that only get the first word, my next step is fix this.

The problem here, is for some comment, if the comment have some email address, or other text with an @ character, these appear in array like an annotation, for example:

* Created by Someone <email@example.com>
* This class do anything
* @package namespace

I want this return:

["package" => "namespace"]

But this return:

["example.com>" => "", "package" => "namespace"]

┬┐Have someone a idea for do this?

Thanks and sorry any mistake in my English, it isn't my natural language.

Answer Source

In an email address the @ is always just close other characters, while in the real annotations it's always preceded by at least one space.

So you might merely change your regex to reflect that:

    preg_match_all('# @(.*?)\n#s', $docComment, $annotations);

and it'll work fine without anything else, since in your function you're already trim()ing the annotation... which was useless till now :)