RoleInterface throws "call on a non-object" error - symfony

I'm working over Symfony 2.0.16
I have in my UserProvider the method getRoles
public function getRoles()
{
/**
* #var \Doctrine\Common\Collections\ArrayCollection $rol
*/
return $this->rol->toArray();
}
and my Rol entity has the role interface
class Rol implements \Symfony\Component\Security\Core\Role\RoleInterface
//...
public function getRole()
{
return $this->getName();
}
but when I try to login I get the following error
Fatal error: Call to a member function getRole() on a non-object in C:\Users\julian\Code\parqueadero\vendor\symfony\src\Symfony\Bundle\SecurityBundle\DataCollector\SecurityDataCollector.php on line 57
Reading the class SecurityDataCollector, the error is thrown by a Closure
array_map(function ($role){ return $role->getRole();}, $token->getRoles()
Now I change this to
array_map(function ($role){ var_dump($role); return $role->getRole();}, $token->getRoles()
To my surprise, $role is a object Rol but I can't understand why I get the error.

I found the solution the problem is a bug in PHP 5.4 (the php i'm using) serialize method the github user yoannch proposed this solution, is overwrite the serialize/unserialize methods using json_encode/json_decode methods
class User implements \Serializable
//...
/**
* Serializes the content of the current User object
* #return string
*/
public function serialize()
{
return \json_encode(
array($this->username, $this->password, $this->salt,
$this->rol, $this->id));
}
/**
* Unserializes the given string in the current User object
* #param serialized
*/
public function unserialize($serialized)
{
list($this->username, $this->password, $this->salt,
$this->rol, $this->id) = \json_decode(
$serialized);
}
only need change the correct name properties

I had the same problem (Windows, PHP 5.4.5), updated to 5.4.7 and it still did not work. Nevertheless, I came up with a workaround that needs less maintenance (when overwriting the serialization functions as described in the article you mentioned, you'll have to keep them up to date when adding/removing fields). So far it works for me, I hope there are no other problems resulting from the workaround I might have forgotten. Just alter the User's getRoles() function like that:
/**
* #inheritDoc
*/
public function getRoles()
{
$roles = array();
foreach ($this->userRoles as $role) {
$roles[] = $role->getRole();
}
return $roles;
}
Note that $role->getRole() returns the role name as a String (e.g. ROLE_ADMIN).

solution of this problem is very simple.
All problems associated with circular references at yours User and Role objects.
So you have not to serialize User::$roles and Role::$users fields.
Look at Symfony\Component\Security\Core\Authentication\Token\AbstractToken::__construct() and Symfony\Component\Security\Core\Authentication\Token\AbstractToken::serialize().
How you can see, Symfony take your user's roles by invoking UserInterface::getRoles() before serialization. And serialize User and Roles separately.
You have to implement \Serializable interface in User and Role entities.
Example:
/**
* Acme\Bundle\UserBundle\Entity\User
*
* #ORM\Table(name="`user`")
* #ORM\Entity(repositoryClass="Acme\Bundle\UserBundle\Entity\UserRepository")
*/
class User implements AdvancedUserInterface, EquatableInterface, \Serializable
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $username
*
* #ORM\Column(type="string", length=30, unique=true)
*/
private $username;
/**
* #var string $email
*
* #ORM\Column(type="string", length=100, unique=true)
*/
private $email;
/**
* #var string $salt
*
* #ORM\Column(type="string", length=40)
*/
private $salt;
/**
* #var string $password
*
* #ORM\Column(type="string", length=128)
*/
private $password;
/**
* #var boolean $isActive
*
* #ORM\Column(type="boolean")
*/
private $isActive;
/**
* User's roles. (Owning Side)
*
* #var ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*/
private $roles;
// .....
/**
* #see \Serializable::serialize()
*/
public function serialize()
{
/*
* ! Don't serialize $roles field !
*/
return \serialize(array(
$this->id,
$this->username,
$this->email,
$this->salt,
$this->password,
$this->isActive
));
}
/**
* #see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->email,
$this->salt,
$this->password,
$this->isActive
) = \unserialize($serialized);
}
}
/**
* Acme\Bundle\UserBundle\Entity\Role
*
* #ORM\Table(name="role")
* #ORM\Entity
*
*/
class Role implements RoleInterface, \Serializable
{
/**
* #var integer $id
*
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $role
*
* #ORM\Column(name="role", type="string", length=20, unique=true)
*/
private $role;
/**
* Users in group (Inverse Side)
*
* #var ArrayCollection
*
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
// .....
/**
* #see \Serializable::serialize()
*/
public function serialize()
{
/*
* ! Don't serialize $users field !
*/
return \serialize(array(
$this->id,
$this->role
));
}
/**
* #see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list(
$this->id,
$this->role
) = \unserialize($serialized);
}
}
And all will be serialized/unserialized correctly.
See discus at https://github.com/symfony/symfony/issues/3691
See also:
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/entities-in-session.html#serializing-entity-into-the-session

Related

Symfony Iterating over ArrayCollection

In my app I have 2 entities; User & Booking.
Booking entity:
namespace App\Entity;
/**
* #ORM\Table(name="booking")
* #ORM\Entity(repositoryClass="App\Repository\BookingRepository")
*/
class Booking
{
/**
* #ORM\Column(type="boolean")
* #Assert\NotBlank()
*/
private $isActive;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="bookings")
*/
private $user;
User entity:
/**
* #ORM\Table(name="app_user")
* #ORM\Entity(repositoryClass="App\Repository\UserRepository")
* #UniqueEntity(fields="email", message="This email address is already in use")
*/
class User implements AdvancedUserInterface
{
/**
* #ORM\Column(type="string", length=255, unique=true)
* #Assert\NotBlank()
* #Assert\Email()
*/
private $email;
/**
* #ORM\OneToMany(targetEntity="App\Entity\Booking", mappedBy="user")
* #Expose
*/
private $bookings;
/**
* User constructor.
*/
public function __construct()
{
$this->bookings = new ArrayCollection();
}
I tried to add a function to my user entity that returns the active booking, I tried this:
/**
* #return mixed
*/
public function getActiveBooking()
{
foreach( $this->bookings as $booking ) {
if( $booking->getIsActive() ) {
return $booking;
}
}
}
But I get the following error: Error: Call to a member function getRoom() on null
When I call it using $user->getActiveBooking()->getRoom()->getId()
Make sure that the user you are working with has an active booking.
getActiveBooking() is returning null because it seems user does not have an active booking.
That's why you are getting an error that you cannot call getRoom() on null because the previous function has returned null.
Have you tried to add a joinColumn like this:
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="bookings")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
*/
private $user;

How to get the mapping entity in PrePersist LifecycleEvent within a form in Symfony2 for a OneToOne relationship

I have two entities in my code: Session and SessionPicture.
There is a OneToOne relationship between Session and SessionPicture. Session is the mapping entity and SessionPicture the inverse one.
I have a SessionType form, which embeds a SessionPictureType form. I would like the user to be able to upload an image for each session when he fille the SessionType form.
The SessionPicture class contains a file attribute (UploadedFile class) and I have used LifecycleEvents to upload the image file and save it in the right directory.
This is what my code looks for the session class:
/**
* Session
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="MyBundle\Entity\SessionRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Session
{
/**
* #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=255, nullable=false)
*/
private $name;
/**
* #ORM\OneToOne(targetEntity="MyBundle\Entity\SessionPicture", cascade={"persist", "remove"}, inversedBy="session")
* #ORM\JoinColumn(name="session_picture_id", referencedColumnName="id", nullable=true)
*/
private $sessionPicture;
/**
* Set name
*
* #param string $name
*
* #return Session
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set sessionPicture
*
* #param \MyBundle\Entity\SessionPicture $sessionPicture
*
* #return Session
*/
public function setSessionPicture(MyBundle\Entity\SessionPicture $sessionPicture = null)
{
$this->sessionPicture = $sessionPicture;
return $this;
}
/**
* Get sessionPicture
*
* #return \MyBundle\Session\SessionPicture
*/
public function getSessionPicture()
{
return $this->sessionPicture;
}
And this one for my SessionPicture class:
/**
* SessionPicture
*
* #ORM\Table(name="at_session_picture")
* #ORM\Entity(repositoryClass="MyBundle\Entity\SessionPictureRepository")
* #ORM\HasLifecycleCallbacks()
*/
class SessionPicture
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="extension", type="string", length=255)
*/
private $extension;
/**
* #var string
*
* #ORM\Column(name="alt", type="string", length=255)
*/
private $alt;
/**
* #var string
*
* #ORM\Column(name="path", type="string", length=255, nullable=true)
*/
private $path;
/**
* #ORM\OneToOne(targetEntity="MyBundle\Entity\Session", mappedBy="sessionPicture")
*/
private $session;
public $file;
private $fileNameForRemove;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set extension
*
* #param string $extension
*
* #return SessionPicture
*/
public function setExtension($extension)
{
$this->extension = $extension;
return $this;
}
/**
* Get extension
*
* #return string
*/
public function getExtension()
{
return $this->extension;
}
/**
* Set alt
*
* #param string $alt
*
* #return SessionPicture
*/
public function setAlt($alt)
{
$this->alt = $alt;
return $this;
}
/**
* Get alt
*
* #return string
*/
public function getAlt()
{
return $this->alt;
}
/**
* Set path
*
* #param string $path
*
* #return SessionPicture
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* Set session
*
* #param \MyBundle\Entity\Session $session
*
* #return SessionPicture
*/
public function setSession(\NyBundle\Entity\Session $session = null)
{
$this->session = $session;
return $this;
}
/**
* Get session
*
* #return \MyBundle\Entity\Session
*/
public function getSession()
{
return $this->session;
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if($this->file === null)
return ;
$extension = $this->file->guessExtension();
$name = $this->getSession()->getName();
$this->extension = (string)$extension;
$this->alt = (string)strval($name);
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
$this->path = $this->alt.'.'.$this->extension;
if ($this->file === null)
return ;
$this->file->move($this->getUploadRootDir(), $this->path);
unset($this->file);
}
I would like to draw your attention on the preUpload() function in my SessionPicture.php
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if($this->file === null)
return ;
$extension = $this->file->guessExtension();
$name = $this->getSession()->getName();
$this->extension = (string)$extension;
$this->alt = (string)strval($name);
}
I use this function to give my SessionPicture the same name as the mapping session name and save it in my server with the same name after form validation. Below is an excerpt of my SessionType.php. As you can notice, I embedded a SessionPictureType inside my SessionType.
class SessionType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text', array(
'required' => true
))
->add('sessionPicture', new SessionPictureType(), array(
'required' => false
))
->add('Submit', 'submit');
When I validate this form, I get the error
Error: Call to a member function getName() on a non-object
It seems that in my preUpload() function in my SessionPicture.php, trying to call $this->getSession() returns nothing instead of returning the mapping session. The same applies if I use $this->getSession() in the upload function.
Can anyone help with that? How can I get the mapping entity before or during form validation and use it in my inversing entity to update its attributes?
Many thanks in advance.

Generate Slug in Prepersist Lifecycle for Symfony2 with StofDoctrineExtensionsBundle

I have two entities in my code: Session and SessionPicture.
There is a OneToOne relationship between Session and SessionPicture. SessionPicture is the mapping entity and Session is the inverse one.
Session has an attribute called "Slug", which is generated thanks to the StofDoctrineExtensionsBundle https://github.com/stof/StofDoctrineExtensionsBundle, and using the Gedmo\Sluggable annotation.
I have a form to create a Session (so a SessionType), and this SessionType embeds a SessionPictureType. The SessionPicture class contains a file attribute (UploadedFile class) and I have used LifecycleEvents (PostPersist/PostUpdate) to upload the file of the SessionPicture, and give it the "slug" property of the related Session when I save it.
My issue is that when I try to change another property of my SessionPicture (let's say "alt") and give it the value of the "slug" of the session , I cannot do it in the PostPersist Lifecycle and then save it to my database, because this event takes place after the onFlush, which is too late. I have to do it in the PrePersist Lifecyle. But then the "slug" of my session is not available yet, because it is generated during the onFlush by the extension.
So how can I get the slug of the related session in the prePersist lifecyle?
(PS: I have a found a solution, which is to persist the session in my controller, flush with the Manager, and then to persist again and redo a flush() but it is not very elegant).
Please find my code below:
/**
* Session
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="MyBundle\Entity\SessionRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Session
{
/**
* #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=255, nullable=false)
*/
private $name;
/**
* #ORM\OneToOne(targetEntity="MyBundle\Entity\SessionPicture", cascade={"persist", "remove"}, mappedBy="session")
* #ORM\JoinColumn(name="session_picture_id", referencedColumnName="id", nullable=true)
*/
private $sessionPicture;
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set sessionPicture
*
* #param \MyBundle\Entity\SessionPicture $sessionPicture
*
* #return Session
*/
public function setSessionPicture(MyBundle\Entity\SessionPicture $sessionPicture = null)
{
$this->sessionPicture = $sessionPicture;
return $this;
}
/**
* Get sessionPicture
*
* #return \MyBundle\Session\SessionPicture
*/
public function getSessionPicture()
{
return $this->sessionPicture;
}
And my SessionPicture code:
/**
* #var string
*
* #ORM\Column(name="alt", type="string", length=255, nullable=true)
*/
private $alt;
/**
* #var string
*
* #ORM\Column(name="path", type="string", length=255, nullable=true)
*/
private $path;
/**
* #ORM\OneToOne(targetEntity="MyBundle\Entity\Session", inversedBy="sessionPicture")
*/
private $session;
public $file;
private $fileNameForRemove;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set extension
*
* #param string $extension
*
* #return SessionPicture
*/
public function setExtension($extension)
{
$this->extension = $extension;
return $this;
}
/**
* Get extension
*
* #return string
*/
public function getExtension()
{
return $this->extension;
}
/**
* Set alt
*
* #param string $alt
*
* #return SessionPicture
*/
public function setAlt($alt)
{
$this->alt = $alt;
return $this;
}
/**
* Get alt
*
* #return string
*/
public function getAlt()
{
return $this->alt;
}
/**
* Set path
*
* #param string $path
*
* #return SessionPicture
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* Set session
*
* #param \MyBundle\Entity\Session $session
*
* #return SessionPicture
*/
public function setSession(\NyBundle\Entity\Session $session = null)
{
$this->session = $session;
return $this;
}
/**
* Get session
*
* #return \MyBundle\Entity\Session
*/
public function getSession()
{
return $this->session;
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
if($this->file === null)
return ;
$extension = $this->file->guessExtension();
$this->extension = (string)$extension;
My issue is below, I cannot get the slug before the flush of the session
$this->alt = $this->getSession()->getSlug();
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
But here, I can get the slug because my session has already been flushed and the slug generated
$this->alt = $this->getSession()->getSlug();
$this->path = $this->alt.'.'.$this->extension;
if ($this->file === null)
return ;
$this->file->move($this->getUploadRootDir(), $this->path);
unset($this->file);
}
Finally, here is an extract my controller code:
$form->handlerequest($request);
$validator = $this->get('validator');
$errorList = $validator->validate($session);
if (count($errorList) == 0)
{
$em = $this->getDoctrine()->getManager();
$em->persist($session);
$em->flush();
$em->persist($session);
$em->flush();
As you can see, I had to persist the $session and to flush it once, so that the slug is generated at the flush. Then persist again so that the slug is now available for the "alt" property of the SessionPicture at the prePersist n2, and flush again to save the alt property. But it is not very clean.
Thanks for any hel or advice. Thanks.

How to use Sluggable with a custom mapping type?

In a Symfony2 project, I created a custom mapping field in order to encrypt strings in the database as suggested in this StackOverflow question.
I want to slugify one of the database fields using the Gedmo\Sluggable Doctrine extension. But obviously I get the following error message because the "encrypted_string" is not an allowed type:
[Gedmo\Exception\InvalidMappingException]
Cannot use field - [username] for slug storage, type is not valid and must
be 'string' or 'text' in class - My\PrivateApplication\Bundle\UserBundle
\Entity\User
--EDIT--
This is my Entity:
<?php
namespace My\PrivateApplication\Bundle\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo,
Gedmo\Translatable\Translatable;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* My\PrivateApplication\Bundle\UserBundle\Entity\User
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="UserRepository")
*/
class User implements AdvancedUserInterface, \Serializable {
/**
* #var int
*
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(type="encrypted_string", length=255)
*/
private $surname;
/**
* #var string
*
* #ORM\Column(type="encrypted_string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(type="encrypted_string", length=255, unique=true)
*/
private $username;
/**
* #var string
*
* #ORM\Column(type="string", length=255)
*/
private $password;
/**
* #var string
*
* #ORM\Column(type="encrypted_string", length=255)
*/
private $email;
/**
* #var string
*
* #ORM\Column(type="string", length=255, unique=true)
* #Gedmo\Slug(fields={"username"})
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="salt", type="string", length=40)
*/
private $salt;
/**
* Whether the account is active or not
*
* #var boolean
*
* #ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
/**
* Whether the account is locked or not
*
* #var boolean
*
* #ORM\Column(name="is_locked", type="boolean")
*/
private $isLocked;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime", nullable=true)
* #Gedmo\Timestampable(on="create")
*
*/
private $createdAt;
/**
* #var \DateTime
*
* #ORM\Column(name="updated_at", type="datetime", nullable=true)
* #Gedmo\Timestampable(on="update")
*/
private $updatedAt;
/**
* #var string
*
* #Gedmo\Locale
*/
private $locale;
/**
* Set the locale for the translatable behavior
*
* #param string $locale
*/
public function setTranslatableLocale($locale) {
$this->locale = $locale;
}
public function eraseCredentials()
{
}
public function getPassword()
{
return $this->password;
}
public function getRoles()
{
return array((string)$this->getRole());
}
public function getSalt()
{
return $this->salt;
}
public function getUsername()
{
return $this->username;
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return ($this->isLocked()==0)? false : true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return ($this->isActive==0) ? false : true;
}
/**
* Serialize the User object
* #see Serializable::serialize()
*/
public function serialize()
{
return serialize(array($this->id, $this->username, $this->password, $this->salt));
}
/**
* Unserialize the User object
* #see Serializable::unserialize()
*/
public function unserialize($serialized)
{
list($this->id, $this->username, $this->password, $this->salt) = unserialize($serialized);
}
//other accessor methods
}
The property $validTypes of the class Gedmo\Sluggable\Mapping\Driver\Annotation seems to define the valid types for the sluggable. How I can modify the SluggableListener to use my new custom type?
Thank you very much.

Symfony: User roles with doctrine: no entities or tables created

I followed the instructions given in the Symfony-Book to get a user-role relation with doctrine updating them in my database.
Symfony - User/Role - Doctrine
But when I update my entities via doctrine:generate:entities, it only generates the existing User.php, but doesn't touch the Role.php. This wouldn't bother me, if the tables in my databse would update with doctrine:schema:update --force. But they don't. The mentioned tables aren't created. In fact, nothing happens. Can you please help me? I am looking forward to any good solution.
My User.php
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*/
class User implements AdvancedUserInterface, \Serializable
{
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=255, nullable=false)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255, nullable=false)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=24, nullable=false)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="isActive", type="string", length=255, nullable=false)
*/
private $isactive;
/**
* #var string
*
* #ORM\Column(name="type", type="string", length=10, nullable=false)
*/
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
private $roles;
public function __construct()
{
$this->isActive = true;
$this->roles = new ArrayCollection();
// may not be needed, see section on salt below
// $this->salt = md5(uniqid(null, true));
}
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
/**
* Set username
*
* #param string $username
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* #param string $password
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
public function getRoles()
{
return $this->roles->toArray();
}
/**
* 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 string $isactive
* #return User
*/
public function setIsactive($isactive)
{
$this->isactive = $isactive;
return $this;
}
/**
* Get isactive
*
* #return string
*/
public function getIsactive()
{
return $this->isactive;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function eraseCredentials()
{
}
/**
* #see \Serializable::serialize()
*/
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/**
* #see \Serializable::unserialize()
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
/**
* #var string
*/
private $type;
/**
* Set type
*
* #param string $type
* #return User
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->isActive;
}
}
Role.php:
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Role
*
* #ORM\Table(name="user_role")
* #ORM\Entity()
*/
class Role implements RoleInterface
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="name", type="string", length=30)
*/
private $name;
/**
* #ORM\Column(name="role", type="string", length=20, unique=true)
*/
private $role;
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
/**
* #see RoleInterface
*/
public function getRole()
{
return $this->role;
}
}
First tip: give your user table a different name, eg #ORM\Table(name="acme_user").
Second: add in your user class:
/**
* User's roles.
*
* #var ArrayCollection
*
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*/
private $roles;
and in your role class
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
#see: http://symfony.com/doc/2.3/cookbook/security/entity_provider.html

Resources