how to get the type of a doctrine entity property

后端 未结 4 696
温柔的废话
温柔的废话 2021-01-06 04:09

Actually I have a doctrine entity that I need to fill its prperties dynamically.

I\'d like to be able to do something like this:

$entity = new Entity         


        
4条回答
  •  天涯浪人
    2021-01-06 04:46

    For case if you have few different annotations for entity field in any order.
    Note: this code is not detect related entities (ManyToOne, OneToMany and etc).

    use Doctrine\Common\Annotations\AnnotationReader;
    
    /**
     * @param $entity
     * @param $fieldName
     * @return mixed|null
     */
    private function getFieldType($entity, $fieldName)
    {
        $annotationReader = new AnnotationReader();
        $refClass = new ReflectionClass($entity);
        $annotations = $annotationReader->getPropertyAnnotations($refClass->getProperty($fieldName));
    
        if (count($annotations) > 0) {
            foreach ($annotations as $annotation) {
                if (
                    $annotation instanceof \Doctrine\ORM\Mapping\Column
                    && property_exists($annotation, 'type')
                ) {
                    return $annotation->type;
                }
            }
        }
    
        return null;
    }
    

提交回复
热议问题