larammerce/annotation-parser

基于PHP-doc的PHP注释解析系统。

1.1.1 2019-07-12 16:30 UTC

This package is auto-updated.

Last update: 2024-09-14 07:22:35 UTC


README

Build Status

PHP 注释解析器。

安装

composer require larammerce/annotation-parser 

默认情况下,PHP语言中没有注释,但为了编写更清晰、更有意义的代码,如果您需要注释,那么PHP注释解析可以是一个解决方案。

使用方法

假设我们有一个名为FakeClassWithAnnotation的类,它有一个名为fake_method_with_annotation的方法,如下所示,并且存在一个名为fake_helper_function的函数,它位于类外部。

<?php

/**
 * Class FakerClassWithAnnotation
 * @role(enabled=true)
 * @package Larammerce\AnnotationParser\Tests\Faker
 */
class FakeClassWithAnnotation
{
    /**
     * @annotation(name="Ali", username="Ali".fake_helper_function(), roles=['salams', "ali goft: \"che khabar\""],
     *      another_attr=array(1, 2, 3), extras=["role_1" => "role_2"], some_special_id, manager, super_user,
     *      this.is.*="another hard system.")
     * @param string $param1
     * @param bool $param2
     * @return string
     */
    public function fakeMethodWithAnnotation($param1, $param2)
    {
        return "I am fake";
    }
}
<?php

function fake_helper_function()
{
    return "this is fake helper function";
}

我们想要解析phpdoc部分中的@role、@annotation或其他任何注释中的数据。

<?php
use Larammerce\AnnotationParser\ReflectiveClass;
use Larammerce\AnnotationParser\ReflectiveMethod;
use Larammerce\AnnotationParser\Tests\Faker\FakeClassWithAnnotation;

        
$class_name = FakeClassWithAnnotation::class;
$function_name = "fakeMethodWithAnnotation";

$reflective_class = new ReflectiveClass($class_name); //construct the Reflective class.
$reflective_method = new ReflectiveMethod($class_name, $function_name); //construct the reflective method.


$reflective_class->getComment(); //returns the phpdoc on top of class.
$reflective_method->getComment(); //returns the phpdoc on top of method.

$reflective_class->getAnnotations(); //returns a list of annotations.
$reflective_class->hasAnnotation("specific_annotation"); //checks if specific annotations exists or not.
$reflective_class->getAnnotation(("specific_annotation")); //returns the specific annotation with passed title.