Search code examples
symfonyattributessymfony6php-8.1

annotation to attribute syntax: The annotation "@Security" in method App\Controller\… was never imported


By switching my app from Sf5 to Sf6, I have annotation to attribute issues :

[Semantical Error] The annotation "@Security" in method App\Controller\MyController::delete() was never imported. Did you maybe forget to add a "use" statement for this annotation? in {"path":"..\/..\/src\/Controller\/","namespace":"App\\Controller"} (which is being imported from "/var/www/config/routes/attributes.yaml"). Make sure there is a loader supporting the "attribute" type.

Solution

  • A first step was to move config/routes.yaml if you have it to config/routes/attributes.yaml and update the controller path (adding ../) as mentionned at https://symfony.com/doc/current/routing.html#creating-routes-as-attributes

    Second step was to convert security annotations to attributes. I used rector to convert routes annotations to attributes but I didn't find rule to security, so to do something like :

    // annotation :
        /**
         * @Security("is_granted('ROLE_ADMIN')")
         */
    // --> attribute :
        #[IsGranted('ROLE_ADMIN')]
    

    I used vim (neovim) rexeg

    %s/\(\s*\)\/\*\*\n\s*\* @Security("is_granted\(('ROLE_.*')\)")\n\s*\*\//\1#[IsGranted\2]/cg
    

    and I removed use on FrameworkExtraBundle :

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
    

    and removed deprecated FrameworkExtraBundle :
    composer remove sensio/framework-extra-bundle

    and the error was gone