允许在Symfony 3中加载具有特定角色的doctrine数据夹具

时间:2016-12-26 10:55:48

标签: php symfony doctrine-orm doctrine

我正在使用FOSCommentBundle并尝试使用doctrine fixtures加载评论。问题是FOSCommentBundle配置为只允许ROLE_USER在我的项目中创建注释,如下所示:

acl_roles:
    comment:
        create: ROLE_USER
        view: IS_AUTHENTICATED_ANONYMOUSLY
        edit: ROLE_ADMIN
        delete: ROLE_ADMIN
    thread:
        create: ROLE_USER
        view: IS_AUTHENTICATED_ANONYMOUSLY
        edit: ROLE_ADMIN
        delete: ROLE_ADMIN
    vote:
        create: ROLE_USER
        view: IS_AUTHENTICATED_ANONYMOUSLY
        edit: ROLE_ADMIN
        delete: ROLE_ADMIN

但是在加载灯具时,不允许Doctrine添加它们,因为它必须以ROLE_USER身份登录。

这是我的评论夹具加载:

//First depth comments array
    $comments = [];
    //Create a data faker
    $faker = \Faker\Factory::create();
    //FOS Comment manager
    $commentManager = $this->container->get('fos_comment.manager.comment');
    //First depth comments creation
    for($i=0; $i<$this->nb; $i++){
        $comment = $commentManager->createComment($this->getReference('thread '.rand(0, $this->nb-1)));
        $comment->setAuthor($this->getReference('user '.rand(0, $this->nb-1)));
        $comment->setBody($faker->text(250));
        $comment->setState($faker->boolean);
        $commentManager->saveComment($comment);
        $comments[] = $comment;
    }
    $manager->flush();
  • 是否有与教条相关的角色(如ROLE_FIXTURES_LOAD)?
  • 是否可以在灯具中模拟ROLE_USER?

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

你应该绕过fos_comment.manager.comment,它正在应用适用于&#34;生产的验证逻辑。环境。你想要的是让你的灯具坚持下去?坚持他们与您的实体经理的传统方式? Doctrine并不关心应用程序中的角色,它可以通过自己的方式向数据库写入任何内容。如果出现问题,这是经理的错。

$manager = $this->container->get('doctrine')->getManager();
for($i=0; $i<$this->nb; $i++){
    $comment = $commentManager->createComment($this->getReference('thread '.rand(0, $this->nb-1)));
    $comment->setAuthor($this->getReference('user '.rand(0, $this->nb-1)));
    $comment->setBody($faker->text(250));
    $comment->setState($faker->boolean);
    $manager->persist($comment)
    $comments[] = $comment;
}
$manager->flush();

如果您想继续使用FOSComments Manager,您应该尝试手动验证用户:

$repo  = $this->get('doctrine')->getRepository("AppBundle:User");
$user = $repo->findOneBy(['username' => 'a_valid_and_authorized_user']);
$token = new UsernamePasswordToken(
    $user,
    null,
    'main',
    $user->getRoles()
);
$this->container->get('security.token_storage')->setToken($token);