LoginSignup
0
0

More than 3 years have passed since last update.

[PHP]クラスのプロパティーのDocコメントのannotaionの取得

Last updated at Posted at 2020-01-15

前提

c#のattribute的な書き方をしたい

作ったもの

PropertyのDocCommentにhiddenがあったら、

<input type="hidden" name="{property-name}" value="{property-value}"/>

を返します。

実装

まずは値を格納するだけのクラス。
ViewModelを想定しました。

class ExampleViewModel extends ViewModel{
    /**
     * 返す
     * @hidden true
     */
    public $hidden_prop;
    /**
     * 返さない
     * @oden
     */
    public $not_hidden_prop;
    /**
     * 返さない
     * @hidden false
     */
    public $false_hidden_prop;
    /**
     * 返す
     * @hidden true
     */
    public $hidden_prop2;
    // 返さない
    public $no_annotation;

    function __construct(){
        $this->hidden_prop = '1';
        $this->not_hidden_prop = '2';
        $this->not_hidden_prop = '3';
        //$hidden_prop2 valueがない時も返します
        $this->no_annotation = '5';
    }
}

お次はhtmlを作成するクラスです。

class HtmlHelper{

    /**
     * '@hidden true'が付いたプロパティーを
     * input tag のHTMLタグとして返す。
     *
     * @param ViewModel $class
     * @return string
     */
    public function getInputHiddenTags(ViewModel $class){
        // クラスからプロパティーを取得
        $reflection = new \ReflectionClass($class);
        $properties = $reflection->getProperties();

        $input_hidden_tags = '';

        // ぐるぐる
        foreach($properties as $property){

            // プロパティーのコメントを取得します

            // 下記コメントいただいた通り修正しました、ありがとうございます
            // $reflection_property = new \ReflectionProperty($class, $property->name);
            // $doc = $reflection_property->getDocComment();
            $name = htmlspecialchars($property->name, ENT_QUOTES, 'UTF-8');
            $value = htmlspecialchars($class->$name, ENT_QUOTES, 'UTF-8');

            // 正規表現の極み
            if(preg_match('/\@hidden true\s*\n/', $doc)){
                $name = $property->name;
                $value = $class->$name;
                $input_hidden_tags .= <<<HTML
                    <input type="hidden" name="${name}" value="${value}" />
                HTML;
            }
        }

        return $input_hidden_tags;
    }
}

まとめ

必要あらばアノテーション判定部分を切り出します。

参考

https://www.php.net/manual/ja/class.reflectionclass.php
https://www.php.net/manual/ja/class.reflectionproperty.php

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0