syl.fabre
syl.fabre

Reputation: 746

Reading annotations with Symfony4

I'm trying to read annotations with Symfony4 but looks like something is not working!

The class I'm trying to read from:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\OAuthClientRepository")
 */
class OAuthClient {
{

    /**
     * @Assert\NotBlank()
     * @ORM\Column(type="string")
     */
    protected $name;

}

The code I'm using to read the annotations:

<?php

namespace App\Test;

use Doctrine\Common\Annotations\SimpleAnnotationReader as DocReader;

/**
 * Helper AnnotationReader
 */
class AnnotationReader
{

    /**
     * @param $class
     * @return null|\StdClass
     */
    public static function getClass($class)
    {
        $reader = new DocReader;
        $reflector = new \ReflectionClass($class);
        return $reader->getClassAnnotations($reflector);
    }

    /**
     * @param $class
     * @param $property
     * @return array
     */
    public static function getProperty($class, $property)
    {
        $reader = new DocReader;
        $reflector = new \ReflectionProperty($class, $property);
        return $reader->getPropertyAnnotations($reflector);
    }

    /**
     * @param $class
     * @param $method
     * @return array
     */
    public static function getMethod($class, $method)
    {
        $reader = new DocReader;
        $reflector = new \ReflectionMethod($class, $method);
        return $reader->getMethodAnnotations($reflector);
    }

}

I get empty arrays when I call:

App\Test\AnnotationReader::getClass(App\Entity\OAuthClient::class);
App\Test\AnnotationReader::getProperty(App\Entity\OAuthClient::class, 'name');

What am I doing wrong? What is the best way to read annotation?

I'm looking to read the validations used on a class property.

Thank you for your help!

Upvotes: 2

Views: 5964

Answers (2)

rapaelec
rapaelec

Reputation: 1330

change

use Doctrine\Common\Annotations\SimpleAnnotationReader as DocReader;

to

use Doctrine\Common\Annotations\AnnotationReader as DocReader;

and it works.

Upvotes: 1

conradkleinespel
conradkleinespel

Reputation: 6987

You may have to call the addNamespace() method on the SimpleAnnotationReader instance.

For instance, for ORM annotations:

$reader->addNamespace('Doctrine\ORM\Mapping');

And for validation annotations:

$reader->addNamespace('Symfony\Component\Validator\Constraints');

See:

Upvotes: 0

Related Questions