Coder Social home page Coder Social logo

annotations's Introduction

โš ๏ธ PHP 8 introduced attributes, which are a native replacement for annotations. As such, this library is considered feature complete, and should receive exclusively bugfixes and security fixes.

Doctrine Annotations

Build Status Dependency Status Reference Status Total Downloads Latest Stable Version

Docblock Annotations Parser library (extracted from Doctrine Common).

Documentation

See the doctrine-project website.

Contributing

When making a pull request, make sure your changes follow the Coding Standard Guidelines.

annotations's People

Contributors

akkie avatar alcaeus avatar beberlei avatar carusogabriel avatar chx avatar derrabus avatar fabiobatsilva avatar fabpot avatar greg0ire avatar gregberge avatar guilhermeblanco avatar hobodave avatar jrjohnson avatar jwage avatar kubawerlos avatar lcobucci avatar localheinz avatar majkl578 avatar malarzm avatar marioblazek avatar mikesimonson avatar ocramius avatar ondrejmirtes avatar poldridge avatar romanb avatar schmittjoh avatar seldaek avatar senseexception avatar stof avatar vincz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

annotations's Issues

Broken autoloading for use statements with leading \

Having issues for some Symfony controllers:

<?php

namespace FancyBundle\Controller;

use \Symfony\Bundle\FrameworkBundle\Controller\Controller;
use \Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

class FancyController extends Controller
{
    /**
     * @Route("/fancy")
     */
    public function fancyAction()

When executing php app/console cache:warmup or trying to request a page (using PHP 5.4 in my case, not sure if that matters), I get the following error:

// Warming up the cache for the prod environment with debug false                                                      

  [Symfony\Component\Config\Exception\FileLoaderLoadException]                                                                                     
  [Semantical Error] The annotation "@\Sensio\Bundle\FrameworkExtraBundle\Configuration\Route" in method FancyBundle\Controller\FancyController::fancyAction() does not exist, or could not be auto-loaded in /app/fancyProject/current/src/FancyBundle/Controller/ (which is being imported from "/app/fancyProject/current/app/config/routing.yml").
                                                                     
  [Doctrine\Common\Annotations\AnnotationException]               
  [Semantical Error] The annotation "@\Sensio\Bundle\FrameworkExtraBundle\Configuration\Route" in method FancyBundle\Controller\FancyController::fancyAction() does not exist, or could not be auto-loaded.

Took me a while, but looks like it only works when the use statement in the controller doesn't contain the leading backslash (fully allowed in PHP), so ... some of that magic happening here is broken.

DocParser does not interpret/validate multiple type docblocks correctly on annotation properties.

I have just ran into an issue on a Symfony app, where a property on a custom annotation that can either be a string or null causes an exception to be thrown upon parsing when used.

Example:

<?php
namespace AppBundle\Annotations;

use Doctrine\Common\Annotations\Annotation;

/**
 * @Annotation
 * @Target("PROPERTY")
 */
final class MyAnnotation 
{
    /**
     * @var string|null
     */
    public $theProperty;
}

When using this annotation and specifying a string value for theProperty, an AnnotationException is thrown with the following message:

[Type Error] Attribute "theProperty" of @MyAnnotation declared on property AppBundle\TestEntity::$test expects a(n) string|null, but got string.

As far as I can see this is happening because it is not interpreting the pipe convention of declaring multiple types on the parameter.

Improve handling of multiline attribute values

Example docblock:

/**
 * @Test(
 *     description="This is a very long description
 *                  which needs multiple lines"
 * )
 */

The description will result in

This is a very long description
 *     which needs multiple lines

I'd like that * and whitespaces are removed from the parsed string. I tried doing this in DocParser.php#L1017 by replacing the return with this:

return preg_replace('/^[\t ]*\*[\t ]+/m', '', $this->lexer->token['value']);

It works but I'm not sure if that has any side effects or is the right place to do it.

Memory leak in AnnotationRegistry::registerLoader() when called multiple times

If we call AnnotationRegistry::registerLoader() multiple times we've got an self::$loaders array growing indefinitely.

Consider to append self::$loaders with a keyed value.

A key for callable can be determined by spl_object_hash() for anonymous functions and by a combination of md5() and spl_object_hash() for other types of callable.

I can provide a non BC breaking PR for this issue if interested.

annotations 2.0: Rename library to doctrine/annotations2 ?

The following is an idea I am not so sure about myself.

In the PHP / Composer / Packagist ecosystem, we often see problems when popular packages get a new version out. The arguments from this kind of discussion also happened here, #75.

The problem:

  • A major version is often not fully backwards compatible to the previous version.
  • It is not possible to install two major versions side by side on a project. It causes name clashes for PHP classes and namespaces, and it is not supported by the package manager.

So I have been wondering: Why not make the version number (beyond 1) part of the package name? E.g. if the 2.0 version would become doctrine/annotations2, it could be safely installed alongside the old version, and we/you could quite happily break things.

It seems like a solution to the problem, but I am not aware of any PHP libraries doing this. So I asked this on stackexchange, see Major version number as part of package name / namespace?.

One person, in this answer, mentioned that some projects actually do this, e.g. python3, openjdk-9, libgtk2.

So I am wondering why this is not more common in the PHP world, and whether doctrine/annotations should follow this idea.

Enchancement: Allow to specify custom method in place of constructor

One improvement would be nice to have: ability to specify named constructor method via annotation on annotation, to free constructors to normal usage

As an example:

/**
 * @Annotation
 * @Constructor("fromValues")
 */
class SomeClass
{
    public function __construct(string $name, string $pattern, bool $sync);

    public static function fromValues(array $values)
    {
        return new static(
            $values['name'] ?? $values['value'] ?? 'DefaultName',
            $values['pattern'] ?? '*'
        ); 
    }
}

This class can be safely used both as an annotation and as a standalone VO, constructor ensures that all the required values are set, there is no way to accidentally forget something: i "forgot" to add $sync parameter in fromValues() and that will cause error.

Annotation + Group use declarations - PHP7

Hello,

got the following bug in symfony 3.1.5 which use this project for annotation reading (symfony/symfony#20683)

The doctrine/annotation version is v1.2.7

use Sensio\Bundle\FrameworkExtraBundle\Configuration\{
    ParamConverter, Route, Method
};

/**
 * @ParamConverter("website")
 *
 * @Route("{websiteCode}", requirements={"website": "\w+"})
 */
class CategoryController extends Controller
{
}

The error is: [Semantical Error] The annotation "@ParamConverter" in class CategoryController was never imported.

When I dont use the use group feature of PHP, it works.

Best,
Geoffrey

IgnoreAnnotation not aplied to parent classes.

doctrine/annotations v1.6.0

/**
* @IgnoreAnnotation("bad")
**/
class A extends B {}

class B extends C {}

class C {
  /**
  * some comment @bad some other
  **/
   public $aaa;
}

Result:

In AnnotationException.php line 54:
                                                                               
  [Semantical Error] The annotation "@bad" in property C::$aaa was never imported. Did you mayb  
  e forget to add a "use" statement for this annotation?

Doctrine\Annotations is unfriendly to extending

I wanted to extend CachedReader with functionality described here only to find that most internals are private although they should be protected. This way I can't use cache with my implementation. Why aren't they declared as protected? I have to work around this cumbersomely, duplicate lots of code etc. That is a shame.

FileCacheReader putting contents in a tempfile before being allowed to write to it

Hey there,

we have a little problem with the https://github.com/doctrine/annotations/blob/master/lib/Doctrine/Common/Annotations/FileCacheReader.php.

In its saveCacheFile method it creates a temporary and tries to write to it before setting its permission.

This is a usually not a big problem, because the created file belongs automatically to the creator in a normal filesystem.
BUT if the location where the cache is saved is a location that is a shared storage for example in a virtual machine or maybe a network storage (which is pretty similar) the user is automatically changed.

What is the reason for this seemingly inverted behavior of trying to write before actually having permission to do so for sure?

Provide support for array constants (PHP 5.6+)

When using annotations with constant values (ie : SomeClass:CONSTANT), it is currently assumed that said constant will not be an array.

Starting PHP 5.6 constants can be arrays and while the doctrine parser does not fail reading the constant even if it is an array, it does not allow to access a single entry in the array without throwing the following error :

[Syntax Error] Expected Doctrine\Common\Annotations\DocLexer::T_CLOSE_CURLY_BRACES, got '['

It would be nice if we could use the array notation to access a specific element in the constant (i.e : SomeClass::CONSTANT[1])

Problem with autoloaded classes that aren't namespaced and have the same name as any docblock comment

I have an part of legacy application that is added in symfony and i have a problem with annitationparser.

Annotation parser finds "@author" annotation, then immediatly tries to find annotation class for this annotation.

It finds my class named "author" (it's withouth namespace), properly parses it as not annotation (annotation metadata array has "is_annotation" set to false.

But then in DocParser.php (line 749) it does additional check for "author" class and this fails, as it check if this class is in array $this->ignoredAnnotationNames (and this array is empty, it never gets set).

And AnnotationReader global ignored annotation names is checked later in code :/

DCOM-229: DocParser - add support for php5 MyClass::class call to get path of the class

From @doctrinebot on January 6, 2014 7:2

Jira issue originally created by user umed:

When I try to use in my annotations

Career::class

I get Semantical Error. Career is imported, so I dont want to use full class path name again. How about to add this feature to support by annotations?
We need to add some code like this (DocParser#Constant):

            if ($found) {
                 if ($const === 'class') {
                    return $className;
                 }

                 $identifier = $className . '::' . $const;
            }
        }

        if (!defined($identifier)) {
            throw AnnotationException::semanticalErrorConstants($identifier, $this->context);
        }

        return constant($identifier);

Copied from original issue: doctrine/common#536

[feature] Group annotation

When you use a lot of annotations it's look like this

    /**
     * @Serializer\Expose()
     * @Serializer\Type("integer")
     * @Serializer\Groups({"Editor"})
     * @Assert\NotBlank()
     * @ORM\Column(type="integer")
     */
    protected $val1;

And if there are several fields of the same type, all summaries must be applied to each field

    /**
     * @ODM\EmbedOne(targetDocument="App\Models\Product\Lang")
     * @JMS\Type("App\Models\Product\Lang")
     * @var Lang
     */
    public $description;
    /**
     * @ODM\EmbedOne(targetDocument="App\Models\Product\Lang")
     * @JMS\Type("App\Models\Product\Lang")
     * @var Lang
     */
    public $hours_operations;
    /**
     * @ODM\EmbedOne(targetDocument="App\Models\Product\Lang")
     * @JMS\Type("App\Models\Product\Lang")
     * @var Lang
     */
    public $duration;

I would like to see such a possibility

/**
 * @GroupAnnotation()
 */
final class LangField
{
    /**
     * @ODM\EmbedOne(targetDocument="App\Models\Product\Lang")
     * @JMS\Type("App\Models\Product\Lang")
     */
    public $field;

}

/**
 * @GroupAnnotation(params={'type'})
 */
final class EditorField
{
    /**
     * @Serializer\Expose()
     * @Serializer\Type("$type")
     * @Serializer\Groups({"Editor"})
     * @Assert\NotBlank()
     * @ORM\Column(type="$type")
     */
    public $field;

}

usage

    /**
     * @EditorField(type="integer")
     */
    protected $val1;


    /**
     * @LangField
     * @var Lang
     */
    public $description;
    /**
     * @LangField
     * @var Lang
     */
    public $hours_operations;
    /**
     * @LangField
     * @var Lang
     */
    public $duration;

Autoloading annotation classes

Why aren't annotation classes loaded by currently configured PHP autoload mechanisms?

It is called neither in https://github.com/doctrine/annotations/blob/master/lib/Doctrine/Common/Annotations/AnnotationRegistry.php#L123
nor in https://github.com/doctrine/annotations/blob/master/lib/Doctrine/Common/Annotations/DocParser.php#L457 (implicit autoload is explicitly turned off using class_exists($className, false) ).

It leads to this weird behavior:

spl_autoload_register(function() { eval('/** @Annotation */ class MyAnnotation {}'); });
$docParser = new DocParser();

// uncomment the following line to change the result
// class_exists('MyAnnotation');
try {
    $docParser->parse('/** @MyAnnotation */');
    echo "MyAnnotation exists";
} catch (AnnotationException $ex) {
    echo "MyAnnotation does not exist";
}

My suggestion would be to let the DocParser try to autoload the class.

P.S. I know that I can bypass it by adding custom loader to AnnotationRegistry that just executes class_exists(), but isn't it unnecessary (and non-intuitive)?

Annotation parameters

Don't know if I do not understand correctly how annotation parameters work, but given the following annotation definition:

/**
 * Class Parameter
 *
 * @Annotation
 * @Target("METHOD")
 */
class Parameter
{
    /**
     * @var string
     */
    public $name;

    /**
     * @var array<Symfony\Component\Validator\Constraint>
     */
    public $constraints = array();

    /**
     * @var string
     */
    public $validationGroup;

    /**
     * @param array $data
     */
    public function __construct(array $data)
    {
        // constructor logic
    }
}

Why doesn't the following work:

@Direct\Parameter("a", { @Assert\NotNull() }, "myGroup")

I'm getting a Expected Value, got 'myGroup' at position 70 in method... exception.

This however works:

@Direct\Parameter("a", { @Assert\NotNull() }, validationGroup="myGroup")

as does this:

@Direct\Parameter(name="a", constraints={ @Assert\NotNull() }, validationGroup="myGroup")

and this:

@Direct\Parameter("a", { @Assert\NotNull() })

DCOM-253: Support use statements for annotations property type

From @doctrinebot on September 20, 2014 12:23

Jira issue originally created by user enumag:

For example in doctrine/orm there is this annotation class:

namespace Doctrine\ORM\Mapping;

/****
 * @Annotation
 * @Target({"PROPERTY","ANNOTATION"})
 */
final class JoinTable implements Annotation
{
    /****
     * @var string
     */
    public $name;

    /****
     * @var string
     */
    public $schema;

    /****
     * @var array<\Doctrine\ORM\Mapping\JoinColumn>
     */
    public $joinColumns = array();

    /****
     * @var array<\Doctrine\ORM\Mapping\JoinColumn>
     */
    public $inverseJoinColumns = array();
}

Note the @var array<\Doctrine\ORM\Mapping\JoinColumn>. In my opinion @var array<JoinColumn> should be enough here as JoinColumn is in the same namespace. Use statements should also be supported.

Copied from original issue: doctrine/common#562

Fatal error after upgrade to 1.5.0

After upgraded from 1.4.0 to 1.5.0 (I am using doctrine/or: 2.5.6 with all the default requires) the flowing error appeared:

"Uncaught TypeError: Return value of Doctrine\Common\Annotations\AnnotationRegistry::registerFile() must be an instance of Doctrine\Common\Annotations\void, none returned in /library/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php:67"

When explicitly downgraded back to 1.4.0 all is good. Please, have a look at the return type annotations.

Thanks.

how to ignore user define @xxxx?

"doctrine/annotations": "^1.5",
parser->setImports([
'xxxx'
]);
but parse to extend it ,and not way to do like this .
can support like this,

AnnotationRegistry::ignoreAnnotations([
'xxxx'
]);

DCOM-243: 'Zend OPcache' PHP extension might prevent AnnotationReader from getting entity class comments

From @doctrinebot on May 22, 2014 8:0

Jira issue originally created by user VictorSmirnov:

If module Zend OPcache is installed and configured not to save comments the AnnotationReader class fails to parse data for entities.

Output from php -m contains line Zend OPcache.
The module is configured with the following parameter opcache.save_comments=0.

I would expect the AnnotationReader constructor to throw an exception. But it does not check if the module is loaded.

In addition to the check for opcache module

        if (extension*loaded('opcache') && ini_get('opcache.save*comments') == 0) {
            throw AnnotationException::optimizerPlusSaveComments();
        }

we might have a new check for the Zend OPcache module

        if (extension*loaded('Zend OPcache') && ini_get('opcache.save*comments') == 0) {
            throw AnnotationException::optimizerPlusSaveComments();
        }

Copied from original issue: doctrine/common#551

Uncaught exception 'Doctrine\Common\Annotations\AnnotationException'

From @cedrictailly on August 20, 2013 19:45

Hi,

I found a bug on a this call :

$reader = $em->getConfiguration()->getMetadataDriverImpl()->getReader();

(...)

$reader->getClassMetadata($classname)

...were $em is the EntityManager and $classname a string, here is the error :

[Semantical Error] The class "Annotation" is not annotated with @annotation. Are you sure this class can be used as annotation? If so, then you need to add @annotation to the class doc comment of "Annotation". If it is indeed no annotation, then you need to add @IgnoreAnnotation("Annotation") to the class doc comment of class @doctrine\ORM\Mapping\Entity.

The context is too complex to reproduce but after a session of debugging, it seems there is a miss on a condition in class Doctrine\Common\Annotations\DocParser, in :

if (self::$annotationMetadata[$name]['is_annotation'] === false) {
    if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$originalName])) {
        return false;
    }

...replacing :

isset($this->ignoredAnnotationNames[$originalName])

...by :

$this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$originalName])

...should correct the problem.

Copied from original issue: doctrine/common#292

Swagger (CRUD)operation with model Annotation in Yii2

Hello,

I am using swagger with Yii2. i wants to know about operation ex. registration with swagger-ui for that i have to first give text boxes etc to enter in swagger-ui or in body its self i don't know where how i can add those parameters and how can i perform registration via swagger-ui.

DCOM-302: Wrong check for opcache.save_comments

From @doctrinebot on October 9, 2015 6:21

Jira issue originally created by user mabe.berlin:

We have disabled the comments by opcache for performance reasons and because of this also disables annotations to work we also disabled this in development environment as out application doesn't need to read annotations at all.

Anyway if we are running PHP from command line opcache is disabled by opcache.enable_cli=0 - therefor reading doc comments works but "Doctrine/Common/Annotations/AnnotationReader.php" throws an exception because it wrongly detects opcache with disabled comments.

-> if we want to run phpdoc for example we get an error and need to manually enable comments in opcache disable afterwards :(

The current code looks as follows:

        if (extension*loaded('Zend Optimizer</ins>') && (ini_get('zend_optimizerplus.save_comments') === "0" || ini_get('opcache.save*comments') === "0")) {
            throw AnnotationException::optimizerPlusSaveComments();
        }
        if (extension*loaded('Zend OPcache') && ini_get('opcache.save*comments') == 0) {
            throw AnnotationException::optimizerPlusSaveComments();
        }
        if (PHP*VERSION*ID < 70000) {
            if (extension*loaded('Zend Optimizer<ins>') && (ini_get('zend_optimizerplus.load_comments') === "0" || ini_get('opcache.load*comments') === "0")) {
                throw AnnotationException::optimizerPlusLoadComments();
            }
            if (extension*loaded('Zend OPcache') && ini_get('opcache.load*comments') == 0) {
                throw AnnotationException::optimizerPlusLoadComments();
            }
        }

and should be changed to (not tested):

        if (extension_loaded('Zend OPcache') && (
            (PHP*SAPI !== 'cli' && ini*get('opcache.enable') === '1')
            || (PHP*SAPI === 'cli' && ini_get('opcache.enable*cli') === '1')
        )) {
            if (ini*get('opcache.save*comments') === '0') {
                throw AnnotationException::optimizerPlusSaveComments();
            } elseif (PHP*VERSION_ID < 70000 && ini_get('opcache.load*comments') === '0') {
                throw AnnotationException::optimizerPlusLoadComments();
            }
        } elseif (extension_loaded('Zend Optimizer</ins>') && (
            (PHP*SAPI !== 'cli' && (ini_get('zend_optimizerplus.enable') === '1') || ini*get('opcache.enable') === '1')
            || (PHP*SAPI === 'cli' && (ini_get('zend_optimizerplus.enable_cli') === '1') || ini_get('opcache.enable*cli') === '1')
        )) {
            if (ini*get('zend_optimizerplus.save_comments') === '0' || ini_get('opcache.save*comments') === '0') {
                throw AnnotationException::optimizerPlusSaveComments();
            } elseif (PHP*VERSION*ID < 70000
                && (ini*get('zend_optimizerplus.load_comments') === '0' || ini_get('opcache.load*comments') === '0')
            ) {
                throw AnnotationException::optimizerPlusLoadComments();
            }
        }

Copied from original issue: doctrine/common#616

AnnotationReader may incorrectly throw exceptions

From @arnaud-lb on July 6, 2012 17:11

The AnnotationReader pre-parses classes' doc block with a PreParser that doesn't have import (use) informations.

Due to this, it can happen that an annotation resolves to a wrong class.

The parser will then attempt to validate the class and fail (no @annotation, cannot be used on classes, etc).

Here is a test case: doctrine/common#161

The ArrayObject annotation is resolved as \ArrayObject, which is not a valid annotation. This results in the following exception:

Doctrine\Common\Annotations\AnnotationException: [Semantical Error] The class "ArrayObject" is not annotated with @Annotation. Are you sure this class can be used as annotation? If so, then you need to add @Annotation to the _class_ doc comment of "ArrayObject". If it is indeed no annotation, then you need to add @IgnoreAnnotation("ArrayObject") to the _class_ doc comment of class Doctrine\Tests\Common\Annotations\Issue159\ParseMe.

Copied from original issue: doctrine/common#159

Php5 to php7

Hello,
Changing minimal version from 5 to 7 is a breaking change. You maybe should up the major version.
It will break all old builds.

DCOM-207: Add AnnotationReader::getFunctionAnnotations()

From @doctrinebot on July 9, 2013 14:26

Jira issue originally created by user benjamin:

Currently, the annotation reader supports reading annotations on class, method and property.
This could be extended to read annotations on any kind of function, by adding the following methods:

public function getFunctionAnnotations(\ReflectionFunctionAbstract $function);
public function getFunctionAnnotation(\ReflectionFunctionAbstract $function, $annotationName);

This could be done without breaking BC in the following ways:

  • Keep the Reader interface as it is
  • Add a new interface, for example FullReader, that would extend Reader to add these two methods
  • Add the new methods to AnnotationReader, CachedReader, etc.
  • Update these classes to implement FullReader; thus they would still implement Reader and stay compatible.

Then, on the next major release (3.0.0), we could:

  • Add the two methods to Reader
  • Remove FullReader
  • Add a note to the UPGRADE file to rename FullReader to Reader in application code.

In case you're wondering why I'm proposing this feature, I'm developing a lightweight framework, which allows any method, function, or closure to be used as a controller.
I can currently parse annotations when using a class method, but cannot provide support for annotations on the others.

That would be a great addition.
I've checked the code, and it looks like the only difficulty would be to parse "use" statements for the file where the function is declared, whereas for now it is always assumed that there is a class, and that the file name will be inferred from there. But as ReflectionFunctionAbstract provides a getFileName() method, it's technically feasible as well.

Let me know what you think!
If you have no objection to the concept, I can start working on a PR for this feature.

Copied from original issue: doctrine/common#512

Regex spaces

Spaces are not parsed correctly within requirements regex and must be replaced with \s. For example:

Does not work

* @QueryParam(name="departureTime", requirements="\d{4}-[01]\d-[0-3]\d [0-2]\d:[0-5]\d:[0-5]\d", strict=true, nullable=false)

Works

* @QueryParam(name="departureTime", requirements="\d{4}-[01]\d-[0-3]\d\s[0-2]\d:[0-5]\d:[0-5]\d", strict=true, nullable=false)

This may be a FOSRestBundle issue or an annotations issue, Im unsure.

Wrong parsing of DocBlocks with quotes in irrelevant text

In the following docblock:

/**
 * @param mixed description with a single " character.
 *
 * @Marker
 *
 * @This is an irrelevant text with a single " character.
 */

@Marker is not correctly parsed because the lexer sees it as part of a string.

Is this expected? I wrote tests that cover this here but I'm not sure how to fix this.

Not registered annotations support

If we'd like to have not registered annotations (e.g. @custom_documentation_url_address), AnnotationReader will fail if we don't exclude then via AnnotationReader::addGlobalIgnoredName().

It's very inconvenient to support all not registered annotations in our codebase in this way.

The solution is very simple - allow to setIgnoreNotImportedAnnotations to true for AnnotationReader::$parser object, AnnotationReader::$preParser object has this flag turned on.

/**
 * @param bool $notImportedAnnotationsIgnored
 */
public function setParserIgnoreNotImportedAnnotations($notImportedAnnotationsIgnored)
{
    $this->parser->setIgnoreNotImportedAnnotations($notImportedAnnotationsIgnored);
}

Cache naming collision with v1.3.0

The PR #98 introduced a bug (or somehow a bc-break).

When you use the same cache for validations, annotations and metadata cache from jms serializer in a symfony-standard application, the cache key for class annotation (used here by jms-serializer) will be the same as the one for symfony validation metadata (used here).

How to reproduce:

  • Use the same cache for validations, annotations and jms metadatacache
  • Create a model class
  • Use validation annotations for properties on this class
  • Use jms serializer annotations for properties on this class too
  • Serialize the model
  • Validate the model

Thrown exception:

[1] Symfony\Component\Validator\Exception\UnsupportedMetadataException: The metadata factory should return instances of "Symfony\Component\Validator\Mapping\ClassMetadataInterface", got: "array".
    at n/a
        in /Users/spea/workspace/symfony-standard/vendor/symfony/symfony/src/Symfony/Component/Validator/Validator/RecursiveContextualValidator.php line 347

    at Symfony\Component\Validator\Validator\RecursiveContextualValidator->validateObject(object(Address), '', array('Default'), '1', object(ExecutionContext))
        in /Users/spea/workspace/symfony-standard/vendor/symfony/symfony/src/Symfony/Component/Validator/Validator/RecursiveContextualValidator.php line 152

    at Symfony\Component\Validator\Validator\RecursiveContextualValidator->validate(object(Address), null, array('Default'))
        in /Users/spea/workspace/symfony-standard/vendor/symfony/symfony/src/Symfony/Component/Validator/Validator/RecursiveValidator.php line 132

    at Symfony\Component\Validator\Validator\RecursiveValidator->validate(object(Address))
        in /Users/spea/workspace/symfony-standard/src/AppBundle/Controller/DefaultController.php line 21

    at AppBundle\Controller\DefaultController->indexAction(object(Request))
        in  line 

    at call_user_func_array(array(object(DefaultController), 'indexAction'), array(object(Request)))
        in /Users/spea/workspace/symfony-standard/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php line 144

    at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), '1')
        in /Users/spea/workspace/symfony-standard/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/HttpKernel.php line 64

    at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), '1', true)
        in /Users/spea/workspace/symfony-standard/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/DependencyInjection/ContainerAwareHttpKernel.php line 69

    at Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel->handle(object(Request), '1', true)
        in /Users/spea/workspace/symfony-standard/vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php line 185

    at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
        in /Users/spea/workspace/symfony-standard/web/app_dev.php line 28

    at require('/Users/spea/workspace/symfony-standard/web/app_dev.php')
        in /Users/spea/workspace/symfony-standard/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Resources/config/router_dev.php line 40

I could reproduce this in a symfony-standard application

I guess for now we will set different namespaces for the different caches, but maybe I'm not the only one who experiences this bug/behaviour and this should be fixed

DCOM-165: Entities seems not be recognized by AnnotationDriver

From @doctrinebot on September 2, 2012 20:7

Jira issue originally created by user maartendekeizer:

Problem:

"$em->getMetadataFactory()->getAllMetadata()"
Will result in an empty array. The entitiy manager is correctly configured and the entities files are loaded (echo's in the files will be displayed).

Debug steps:

Looking in the code for the problem I created the following debug points first:

file AnnotationDriver.php method getAllClassNames()
after the line: "$includedFiles[] = $sourceFile;"
add: "echo $sourceFile . ' is loaded' . PHP_EOL;"

file AnnotationDriver.php method getAllClassNames()
after the line: "$sourceFile = $rc->getFileName();"
add: "echo $className . ' is loaded from: ' . $sourceFile . ' in the includedFiles array? ' . (in_array($sourceFile, $includedFiles) ? 'YES' : 'not found :-(') . PHP_EOL;"

the following output will be displayed:
...
f:\workspace\nl.markei.posto-2.3\lib\relaties\Contact.php is loaded
...
nl\markei\posto\relaties\Contact is loaded from: F:\workspace\nl.markei.posto-2.3\lib\relaties\Contact.php in the includedFiles array? not found :-(

It seems that Doctrine includes the file from f: but ReflectionClass say it is loaded from F:. The in_array() will fail and Doctrine will not recognized the entity.

But this is not the full problem. I created a new debug point:

file AnnotationDriver.php method getAllClassNames()
after the line: "foreach ($this->_paths as $path) {"
add: "echo 'path: ' . $path . ' after realpath: ' . realpath($path) . PHP_EOL;"

This will result in the following output:
"path: F:\domains\markei.nl\lib\nl.markei.posto\ after realpath: f:\workspace\nl.markei.posto-2.3\lib"

So the conversion of the F: to f: is done by realpath; its look like :-)

A simple fix should be in AnnotationDriver.php / getAllClassNames()
replace: "$sourceFile = $rc->getFileName();"
by: "$sourceFile = realpath($rc->getFileName());"

After I did that, the problem still exists. So I add to echo's (one with realpath and one without at the part of the code). And both echo's result in a path starting with "F:".

So my first reaction was freaky!

After some frustrating hours I found the problem in the symlink I used.
"F:\domains\markei.nl\lib\nl.markei.posto" was a symlink to "f:\workspace\nl.markei.posto-2.3\lib" and realpath will not convert the driver char in the target of the symlink for some freaky reason. After changing the symlink target to "F:\workspace...." everything works fine.

Summary:

realpath results are not consistent on Windows. This will resulting in problems under Windows.

Possible solutions:

Saying "this is a PHP bug".
It is possible that there are more case sensitive problems hidding here on Windows. Maybe it is better to use (for Windows only!) a case insensitive in_array-alternative in AnnotationDriver.php getAllClassNames() (or convert all paths for to lowercase for Windows)

Copied from original issue: doctrine/common#466

System parameters cannot be used as requirements on a QueryParam annotation

The following code does not work when a 'my_regex' parameter is listed in the parameters.yml file. Stepping through the code, this seems to be because the code sees this as class Fos\RestBundle\Validator\Constraints\Regex, which does not implement the ResolvableConstraintInterface. This happens even when my_regex is set to a simple string like 'test'

* @QueryParam(name="departureTime", requirements="%my_regex%", strict=true, nullable=false)

Build an AST (Abstract syntax tree), before resolving classes and constants?

Hello there,
every time I looked at the Doctrine annotation discovery (today, and many years ago), it made me wonder: How would I implement an annotation parser?

Currently, \Doctrine\Common\Annotations\DocParser does two things at once:

  • Parse annotations in the doc comment.
  • Resolve class aliases and constants.

This makes the component more complex than it needs to be.

Instead, this could be split up:

  • One component to parse the doc comment as an abstract syntax tree.
  • A separate component to resolve class aliases and constants.

For absolutely no reason, I am posting a link to my own annotation parser, which follows this philosophy (but does not care about annotation classes).
https://github.com/donquixote/annotation-parser

This entire issue is "food for thought". I currently do not have a personal use case where I would absolutely need this change.

PHP7 Grouped Use Statements ignored

When I use the new PHP7 grouped use statements feature, Doctrine doesn't use the namespace to import the annotation.

For example, this works:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;

class MyController
{

    /**
     * @Route("/example")
     * @Method("GET")
     */     
    public function exampleAction() {...}

}

But changing the namespaces to this fails:

use Sensio\Bundle\FrameworkExtraBundle\Configuration\{
    Route, Method
}

I'm using Doctrine Annotations 1.2.7

Use semantic versioning

Version 1.3.0 bumped the minimum PHP version to 5.6, which is a BC-break (right?). This should have resulted in a major version change.

It's annoying to do a composer install on the server and see

Problem 1
- Installation request for doctrine/annotations v1.3.1 -> satisfiable by doctrine/annotations[v1.3.1].
- doctrine/annotations v1.3.1 requires php ^5.6 || ^7.0 -> your PHP version (5.5.9) does not satisfy that requirement.

Error with composer install --optimize-autoloader

As reported here : FriendsOfSymfony/FOSRestBundle#1637

When I try to clear/warm cache on production after composer install --optimize-autoloader I get this error :

Type error: Argument 1 passed to FOS\RestBundle\Request\ParamReader::getParamsFromAnnotationArray() must be of the type
array, null given, called in /var/www/infoflora/symfony/vendor/friendsofsymfony/rest-bundle/Request/ParamReader.php on
line 60

The problem come with annotations like that :

@QueryParam(map=true, name="sort", requirements=@sort, allowBlank=false, default={Sort::DEFAULT_FIELD : Sort::DEFAULT_ORDER})

But everything is OK when I do not use the optimize option. Or when I use the full namespace in the annotation despite the use in the top of the class...

DCOM-295: Deprecate the SimpleAnnotationReader

From @doctrinebot on August 31, 2015 5:3

Jira issue originally created by user @Ocramius:

The SimpleAnnotationReader is often causing confusion and brings little advantage over the more useful and generic AnnotationReader.

Getting rid of it will remove some of this confusion and make the mechanisms for loading/reading annotations more clear to doctrine/annotations users.

Copied from original issue: doctrine/common#607

Missing annotations with the latest composer version

Hey guys,

I have already posted this issue in the doctrine2 Repository as well as the composer repository itself see:

doctrine/orm#6214
composer/composer#6038

Just a short briefing: Since the latest update to the composer version 1.3 some annotations can't be found in our Symfony applications for example the PrePersist Annotation in our entity.

This only happens if we prefix the use statement with a "" like:

use \Doctrine\ORM\Mapping as ORM;

Once we remove that prefix everything works out fine.

Before composer version 1.3 it worked out fine as composer itself replaced the first character if it was an backslash as an workaround for an old PHP 5.3 issue.

According to Seladek, one of the composer members, this issue is related to the way the parser handles the namespace as it is and not replaces the prefixed slash.

I was about to start a PR for this but then I found a comment here:

// only process names which are not fully qualified, yet

And was wondering if all of this is intended or not?

Would appreciate any answer.

orphan removal removes children, not orphans

Upgrade from doctrine annotations 1.2.7 to 1.6.0 in our Symfony based application caused the removal of our EnvironmentAccesses records. Before, in version 1.2.7, the orphanRemoval=true annotation worked as expected and only removed orphans. After upgrade to version 1.6.0 the orphanRemoval annotation removed all children, not only orphans.

User parent

/**
     * @ORM\OneToMany(targetEntity="Apptimize\AccountsBundle\Entity\EnvironmentAccess", mappedBy="user", cascade={"persist", "remove"}, orphanRemoval=true)
     * @Type("array<Apptimize\AccountsBundle\Entity\EnvironmentAccess>")
     * @var \Apptimize\AccountsBundle\Entity\EnvironmentAccess[]
     */
    private $environmentAccess;

EnvironmentAccess child

    /**
     * @ORM\ManyToOne(targetEntity="Apptimize\AccountsBundle\Entity\User", inversedBy="environmentAccess")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    private $user;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.