将setter与数组

时间:2015-07-15 21:11:30

标签: php arrays forms symfony

我的问题是:我正在开发我网站的安全性。在我的用户注册表单中,我有五个字段:1)名称2)电子邮件3)密码4)isActive 5)角色。显然,我不希望表格中显示最后两个项目,因为否则会违反我的安全期望。

因此,项目“isActive”我将一个设置为setter,但角色是一个数组,如果我得到以下内容:$user-> setRoles('ROLE_USER')无效。

我收到了这个错误:

  

ContextErrorException:Catchable Fatal Error:传递给的参数1   Doctrine \ Common \ Collections \ ArrayCollection :: __ construct()必须是   类型数组,给定的字符串,调用   C:\ XAMPP \ htdocs中\ Lavoc \供应商\原则\ ORM \ LIB \原则\ ORM \ UnitOfWork.php   在547行并在中定义   C:\ XAMPP \ htdocs中\ Lavoc \供应商\原则\收藏\ LIB \原则\ COMMON \收藏\ ArrayCollection.php   第47行

这是我的代码:

 public function registroAction()
{
    $peticion = $this->getRequest();
    $em = $this->getDoctrine()->getManager();
    $user = new User();
    $role = new Role();
    $role->addRole(array('ROLE_USER')); //it does not work
    $user->setRoles($role);  // User relate with Role
    $formulario = $this->createForm(new UserType(), $user);


    if ($peticion->getMethod() == 'POST') 
    {
        $formulario->submit($peticion);

        if ($formulario->isValid()) {
        $encoder = $this->get('security.encoder_factory')->getEncoder($user);
        $user->setSalt(md5(time()));
        $passwordCodificado = $encoder->encodePassword($user->getPassword(), $user->getSalt() );
        $user->setPassword($passwordCodificado);

        $em = $this->getDoctrine()->getManager();

        $em->persist($user);
        $em->flush();
        return $this->redirect($this->generateUrl('usuario_registro'));
        }
    }

    return $this->render( 'ProyectoSeguridadBundle:Seguridad:registro.html.twig',
    array('formulario' => $formulario->createView())
    );
}

以下是我的用户模型:

    <?php

namespace Proyecto\SeguridadBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Proyecto\SeguridadBundle\Entity\User
*
* @ORM\Table(name="lavoc_users")
* @ORM\Entity(repositoryClass="Proyecto\SeguridadBundle\Entity\UserRepository")
*/
class User implements AdvancedUserInterface
{
    /**
    * @var integer
    *
    * @ORM\Column(name="id", type="integer")
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    */
    private $id;


    /**
    * @var string
    *
    * @ORM\Column(name="username", type="string", length=25, unique=true )
    */
    private $username;


    /**
    * @var string
    *
    * @ORM\Column(name="salt", type="string", length=32)
    */
    private $salt;


    /**
    * @var string
    *
    * @ORM\Column(name="password", type="string", length=64)
    */
    private $password;


    /**
    * @var string
    *
    * @ORM\Column(name="email", type="string", length=60, unique=true)
    */
    private $email;


    /**
    * @var boolean
    *
    * @ORM\Column(name="isActive", type="boolean")
    */
    private $isActive;



    /**
    * @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
    *
    */
    private $roles;



    public function __construct()
    {
        $this->roles = new ArrayCollection();
        $this->isActive = true;
        $this->salt = md5(uniqid(null, true));

    }


    /**
    * Get id
    *
    * @return integer
    */
    public function getId()
    {
        return $this->id;
    }


    /**
    * Set username
    *
    * @param string $username
    * @return User
    */
    public function setUsername($username)
    {
        $this->username = $username;
        return $this;
    }


    /**
    * @inheritDoc
    */
    public function getUsername()
    {
        return $this->username;
    }


    /**
    * Set salt
    *
    * @param string $salt
    * @return User
    */
    public function setSalt($salt)
    {
        $this->salt = $salt;
        return $this;
    }


    /**
    * @inheritDoc
    */
    public function getSalt()
    {
        return $this->salt;
    }


    /**
    * Set password
    *
    * @param string $password
    * @return User
    */
    public function setPassword($password)
    {
        $this->password = $password;
        return $this;
    }


    /**
    * @inheritDoc
    */
    public function getPassword()
    {
        return $this->password;
    }


    /**
    * Set email
    *
    * @param string $email
    * @return User
    */
    public function setEmail($email)
    {
        $this->email = $email;
        return $this;
    }


    /**
    * Get email
    *
    * @return string
    */
    public function getEmail()
    {
        return $this->email;
    }


    /**
    * Set isActive
    *
    * @param boolean $isActive
    * @return User
    */
    public function setIsActive($isActive)
    {
        $this->isActive = $isActive;
        return $this;
    }


    /**
    * Get isActive
    *
    * @return boolean
    */
    public function getIsActive()
    {
        return $this->isActive;
    }


    /**
    * @inheritDoc
    */
    public function getRoles()
    {

        $roles = array();
        foreach ($this->roles as $role) {
            $roles[] = $role->getRole();
        }

        return $roles;
    }


    /**
    * @inheritDoc
    */
    public function eraseCredentials() {
    }


    /**
    * @see \Serializable::serialize()
    */
    public function serialize() {
        return serialize(array($this->id,));
    }


    /**
    * @see \Serializable::unserialize()
    */
    public function unserialize($serialized) {
        list ($this->id,) = unserialize($serialized);
    }


    public function isAccountNonExpired() {
        return true;
    }


    public function isAccountNonLocked() {
        return true;
    }


    public function isCredentialsNonExpired() {
        return true;
    }


    public function isEnabled() {
        return $this->isActive;
    }


    /**
    * Set roles
    *
    * @param string $roles
    * @return User
    */
    public function setRoles($roles)
    {
        $this->roles = $roles;
        return $this;
    }


}

我的Role.php

<?php
namespace Proyecto\SeguridadBundle\Entity;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Role
*
* @ORM\Table(name="lavoc_roles")
* @ORM\Entity(repositoryClass="Proyecto\SeguridadBundle\Entity\RoleRepository")
*/
class Role implements RoleInterface
{
    /**
    * @var integer
    *
    * @ORM\Column(name="id", type="integer")
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    */
    private $id;
    /**
    * @var string
    *
    * @ORM\Column(name="name", type="string", length=30)
    */
    private $name;
    /**
    * @var string
    *
    * @ORM\Column(name="role", type="string", length=20, unique=true)
    */
    private $role;
    /**
    * @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
    */
    private $users;
    /**
    * Get id
    *
    * @return integer
    */
    public function getId()
    {
    return $this->id;
    }
    /**
    * Set name
    *
    * @param string $name
    * @return Role
    */
    public function setName($name)
    {
    $this->name = $name;
    return $this;
    }
    /**
    * Get name
    *
    * @return string
    */
    public function getName()
    {
    return $this->name;
    }
    /**
    * Set role
    *
    * @param string $role
    * @return Role
    */
    public function setRole($role)
    {
    $this->role = $role;
    return $this;
    }
    /**
    * @see RoleInterface
    */
    public function getRole()
    {
    return $this->role;
    }
    /**
    * Set users
    *
    * @param string $users
    * @return Role
    */
    public function setUsers($users)
    {
    $this->users = $users;
    return $this;
    }
    /**
    * Get users
    *
    * @return string
    */
    public function getUsers()
    {
    return $this->users;
    }
    public function __toString()
    {
    return $this->getName().' '.$this->getRole();
    }

    /**
     * Add roles
     *
     * @param \Seguridad\Entity\Role $roles
     */
    public function addRole(\MyBundle\Entity\Role $role) {
        $this->roles[] = $roles;
    }

    /**
     * Remove roles
     *
     * @param \SeguridadBundle\Entity\Role $roles
     */
    public function removeRole(\MyBundle\Entity\Role $role) {
        $this->roles->removeElement($roles);
    }

}

3 个答案:

答案 0 :(得分:1)

在此行$user->setRoles('ROLE_USER')中,您尝试将string添加到ArrayCollection。这就是为什么你有ArrayCollection例外的原因。

您可以尝试添加此代码(请务必使用您自己的\MyBundle\Entity\Role模型替换Role

/**
 * Add roles
 *
 * @param \MyBundle\Entity\Role $roles
 */
public function addRole(\MyBundle\Entity\Role $role) {
    $this->roles[] = $roles;
}

/**
 * Remove roles
 *
 * @param \MyBundle\Entity\Role $roles
 */
public function removeRole(\MyBundle\Entity\Role $role) {
    $this->roles->removeElement($roles);
}

/**
* @inheritDoc
*/
public function getRoles()
{
    return $this->roles->toArray();
}

要使用它,您需要将Role对象传递给addRoleremoveRole方法。

其他信息

如果您想为isActive和/或其他值定义默认值,则只需在constructor模型的User中调用相应的设置器即可。

示例:

public function __construct()
{
    // your own logic
    $this->isActive = true;
}

希望它会有所帮助。

答案 1 :(得分:0)

role是一个ArrayCollection,所以你不能用字符串替换它,

你应该添加这样的功能

public function addRoles($role)
{
    $this->roles[] = $role;
    return $this
}

并使用setRoles()

的addRole而不是()

答案 2 :(得分:0)

您需要改为创建addRole(Role $role)方法。

请参阅establishing association in Doctine documentation

public function addRole(Role $role)
{ 
    $this->roles->add($role);
}

或检查角色是否存在:

public function addRole(Role $role)
{ 
    if (!$this->roles->contains($role)) {
        $this->roles->add($role);
    }
}