2015-07-15 3 views
2

Моя проблема заключается в следующем: Я разрабатываю безопасность своего веб-сайта. В моей учетной записи пользователя у меня есть пять полей: 1) Имя 2) email 3) Пароль 4) isActive 5). Очевидно, что я не хочу, чтобы последние две позиции были видны в форме, потому что в противном случае я нарушал бы ожидания в отношении безопасности.Использование сеттера с массивом

Следовательно, элемент «isActive» Я помещаю его в сеттер, но роль - это массив, и если я получу следующее: $user-> setRoles('ROLE_USER') не работает.

Я получил эту ошибку:

ContextErrorException: Catchable Fatal Error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be of the type array, string given, called in C:\xampp\htdocs\Lavoc\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php on line 547 and defined in C:\xampp\htdocs\Lavoc\vendor\doctrine\collections\lib\Doctrine\Common\Collections\ArrayCollection.php line 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); 
    } 

} 

ответ

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 к addRole или removeRole методами.

Другая информация

Если вы хотите определить значение по умолчанию для isActive и/или других значений, вы можете просто вызвать соответствующий метод установки в constructor вашей User модели.

Пример:

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

Надеется, что это поможет.

+0

Здравствуйте, таких, кажется, очень логично, что вы подняли меня и реализовать его в своем коде. Setter isActive работает хорошо и дает мне истинную isActive успешно. Но я получаю ошибку в отношении этих ролей: ContextErrorException: Warning: spl_object_hash() ожидает, что параметр 1 будет объектом, строка указана в C: \ xampp \ htdocs \ Lavoc \ vendor \ doctrine \ orm \ lib \ Doctrine \ ORM \ UnitOfWork.php line 1375 – Geronimo

+1

Можете ли вы показать нам код вашей модели 'User'? – zilongqiu

+0

Я изменил вопрос – Geronimo

0

роль является ArrayCollection, так что вы не можете заменить его строкой,

вы должны добавить функцию как этот

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

и использовать addRole вместо() из setRoles()

+0

Я реализовал то, что вы подняли, но не так, как в роли водителя ROLE_USER. Вы можете мне помочь? – Geronimo

+0

в коде другого ответа они набирают параметр с вашей сущностью «\ MyBundle \ Entity \ Role», это означает, что вы должны передать объект Role этой функции addRoles(), поэтому вам нужно получить объект ROLE_USER а затем добавить его в arraycollection – ThomasP1988

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); 
    } 
} 
+0

Я реализовал то, что вы подняли меня, но не так, как в роли драйвера ROLE_USER. Вы можете мне помочь? – Geronimo

+0

Я не понимаю, что вы комментируете. Не могли бы вы обновить код в своем вопросе и получить ошибку? –

Смежные вопросы