Symfony 3 find closest date from now - php

I have three database tables. user, meeting, group. The meetings and group table are manytomany associations from the user table. So I can do user->getmeetings(), or user->getgroups().
I want to get just the next meeting comping up for the user, and I don't know how to achieve this. Whether by SQL Query or simply in the controller. Here is what I have done so far.
$loggedInUser = $em->getRepository('AppBundle\Entity\User')
->find($id);
foreach ($loggedInUser->getMeetings() as $userMeetings) {
$nextMeeting[$userMeetings->getId()]['id'] = $userMeetings->getId();
$nextMeeting[$userMeetings->getId()]['group'] = $userMeetings->getGroup();
$nextMeeting[$userMeetings->getId()]['name'] = $userMeetings->getName();
$nextMeeting[$userMeetings->getId()]['info'] = $userMeetings->getInfo();
$nextMeeting[$userMeetings->getId()]['bring'] = $userMeetings->getBring();
$nextMeeting[$userMeetings->getId()]['summary'] = $userMeetings->getSummary();
$nextMeeting[$userMeetings->getId()]['files'] = $userMeetings->getFiles();
$nextMeeting[$userMeetings->getId()]['meetingDate'] = $userMeetings->getMeetingDate();
$nextMeeting[$userMeetings->getId()]['meetingAddress'] = $userMeetings->getMeetingAddress();
$nextMeeting[$userMeetings->getId()]['time_diff'] = date_diff($userMeetings->getMeetingDate(), new \DateTime());
}
I have added a time_diff field in the new array to calculate the time from now to the meeting time. All I need to do now is select the smallest one.How can I do this? Thank you.
UPDATE - Below is my User Repository
namespace AppBundle\Repository;
use AppBundle\Entity\User;
use AppBundle\Entity\Meeting;
use Doctrine\ORM\EntityRepository;
use Doctrine\Common\Collections\Criteria;
class UserRepository extends EntityRepository
{
public function getComingMeeting()
{
$criteria = Criteria::create()
->where(Criteria::expr()->gte("meetingDate", new \DateTime('now')))
->orderBy(array("meetingDate" => Criteria::ASC))
->setMaxResults(1);
$this->getMeetings()->matching($criteria);
}
}
Below is my User Entity
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
* #ORM\Table(name="user")
*/
class User
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $first_name;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $last_name;
/**
* #ORM\Column(type="string", nullable=false, unique=true)
*/
private $email_address;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $phone_number;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $password;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $last_login;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $reset_password;
/**
* #ORM\ManyToMany(targetEntity="Meeting", inversedBy="users")
*/
private $meetings;
/**
* #ORM\ManyToMany(targetEntity="Group", inversedBy="users")
*/
private $groups;
public function __construct()
{
$this->groups = new arrayCollection();
$this->meetings = new arrayCollection();
}
/**
* #return mixed
*/
public function getFirstName()
{
return $this->first_name;
}
/**
* #param mixed $first_name
*/
public function setFirstName($first_name)
{
$this->first_name = $first_name;
}
/**
* #return mixed
*/
public function getLastName()
{
return $this->last_name;
}
/**
* #param mixed $last_name
*/
public function setLastName($last_name)
{
$this->last_name = $last_name;
}
/**
* #return mixed
*/
public function getEmailAddress()
{
return $this->email_address;
}
/**
* #param mixed $email_address
*/
public function setEmailAddress($email_address)
{
$this->email_address = $email_address;
}
/**
* #return mixed
*/
public function getPhoneNumber()
{
return $this->phone_number;
}
/**
* #param mixed $phone_number
*/
public function setPhoneNumber($phone_number)
{
$this->phone_number = $phone_number;
}
/**
* #return mixed
*/
public function getPassword()
{
return $this->password;
}
/**
* #param mixed $password
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* #return mixed
*/
public function getLastLogin()
{
return $this->last_login;
}
/**
* #param mixed $last_login
*/
public function setLastLogin($last_login)
{
$this->last_login = $last_login;
}
/**
* #return mixed
*/
public function getResetPassword()
{
return $this->reset_password;
}
/**
* #param mixed $reset_password
*/
public function setResetPassword($reset_password)
{
$this->reset_password = $reset_password;
}
/**
* #return arrayCollection|Meeting[]
*/
public function getMeetings()
{
return $this->meetings;
}
/**
* #return ArrayCollection|Group[]
*/
public function getGroups()
{
return $this->groups;
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
}
below is my HomeControlller.php
class HomeController extends Controller
{
/**
* #Route("/home", name="home_show")
*/
public function showAction()
{
$em = $this->getDoctrine()->getManager();
//logged in user
$id = 1;
$loggedInUser = $em->getRepository('AppBundle\Entity\User')
->find($id);
foreach ($loggedInUser->getMeetings() as $userMeetings) {
$nextMeeting[$userMeetings->getId()]['id'] = $userMeetings->getId();
$nextMeeting[$userMeetings->getId()]['group'] = $userMeetings->getGroup();
$nextMeeting[$userMeetings->getId()]['name'] = $userMeetings->getName();
$nextMeeting[$userMeetings->getId()]['info'] = $userMeetings->getInfo();
$nextMeeting[$userMeetings->getId()]['bring'] = $userMeetings->getBring();
$nextMeeting[$userMeetings->getId()]['summary'] = $userMeetings->getSummary();
$nextMeeting[$userMeetings->getId()]['files'] = $userMeetings->getFiles();
$nextMeeting[$userMeetings->getId()]['meetingDate'] = $userMeetings->getMeetingDate();
$nextMeeting[$userMeetings->getId()]['meetingAddress'] = $userMeetings->getMeetingAddress();
$nextMeeting[$userMeetings->getId()]['time_diff'] = date_diff($userMeetings->getMeetingDate(), new \DateTime());
}
$groups = $em->getRepository('AppBundle\Entity\Group')
->findAll();
return $this->render('home/show.html.twig', [
'loggedInUser' => $loggedInUser,
'groups' => $groups,
]);
}
}

You can add a method in your UserEntity with a matching criteria on meeting collection
namespace AppBundle\Entity;
use Doctrine\Common\Collections\Criteria;
....
public function getComingMeeting()
{
$criteria = Criteria::create()
->where(Criteria::expr()->gte("meetingDate", new \DateTime('now')))
->orderBy(array("meetingDate" => Criteria::ASC))
->setMaxResults(1);
return $this->getMeetings()->matching($criteria);
}
see http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/working-with-associations.html

Related

Symfony 4 & Doctrine, multiple relations with same entity

And Sorry I'm French :)
For my diploma I have to make a Tickets/Reports app and I'm stuck at the Doctrine mapping.
Clone project on GitHUB
Here is my 'Transaction.php' class:
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\TransactionRepository")
*/
class Transaction
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
************************** PROBLEM STARTS HERE *************************
/**
* #ORM\OneToOne(targetEntity="User")
*/
private $sender;
/**
* #ORM\OneToOne(targetEntity="User")
*/
private $receiver;
************************** PROBLEM ENDS HERE *************************
/**
* #ORM\Column(type="integer")
*/
private $amount;
/**
* #ORM\Column(type="datetime",nullable=true)
*/
private $date;
/**
* #ORM\Column(type="text")
*/
private $comment;
/**
* #return mixed
*/
public function getComment()
{
return $this->comment;
}
/**
* #param mixed $comment
*/
public function setComment($comment): void
{
$this->comment = $comment;
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #return mixed
*/
public function getSender()
{
return $this->sender;
}
/**
* #param mixed $sender
*/
public function setSender($sender): void
{
$this->sender = $sender;
}
/**
* #return mixed
*/
public function getReceiver()
{
return $this->receiver;
}
/**
* #param mixed $receiver
*/
public function setReceiver($receiver): void
{
$this->receiver = $receiver;
}
/**
* #return mixed
*/
public function getAmount()
{
return $this->amount;
}
/**
* #param mixed $amount
*/
public function setAmount($amount): void
{
$this->amount = $amount;
}
/**
* #return mixed
*/
public function getDate()
{
return $this->date;
}
/**
* #param mixed
*/
public function setDate()
{
$this->date = new \DateTime("now");
}
}
And my 'User.php' class
<?php
// src/Entity/User.php
namespace App\Entity;
use App\Repository\TransactionRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #UniqueEntity(fields="email", message="Email already taken")
* #UniqueEntity(fields="username", message="Username already taken")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=255, unique=true)
* #Assert\NotBlank()
* #Assert\Email()
*/
private $email;
/**
* #ORM\Column(type="string", length=255, unique=true)
* #Assert\NotBlank()
*/
private $username;
/**
* #Assert\NotBlank()
* #Assert\Length(max=4096)
*/
private $plainPassword;
/**
* The below length depends on the "algorithm" you use for encoding
* the password, but this works well with bcrypt.
*
* #ORM\Column(type="string", length=64)
*/
private $password;
/**
* #var Monycks
*/
private $monycks = 10000;
/**
* #var Skill
* #ORM\ManyToOne(targetEntity="Skill",inversedBy="users")
*/
private $skill;
/**
* #return Skill
*/
public function getSkill()
{
return $this->skill;
}
/**
* #param mixed $skill
*/
public function setSkill(Skill $skill): void
{
$this->skill = $skill;
$skill->addUser($this);
}
/**
* #return Monycks
*/
public function getMonycks()
{
return $this->monycks;
}
/**
* #param Monycks $monycks
*/
public function setMonycks($monycks): void
{
$this->monycks = $monycks;
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
// other properties and methods
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
$this->email = $email;
}
public function getUsername()
{
return $this->username;
}
public function setUsername($username)
{
$this->username = $username;
}
public function getPlainPassword()
{
return $this->plainPassword;
}
public function setPlainPassword($password)
{
$this->plainPassword = $password;
}
public function getPassword()
{
return $this->password;
}
public function setPassword($password)
{
$this->password = $password;
}
public function getSalt()
{
// The bcrypt algorithm doesn't require a separate salt.
// You *may* need a real salt if you choose a different encoder.
return null;
}
public function getRoles()
{
if($this->getUsername()=='admin')
return array('ROLE_ADMIN', 'ROLE_USER');
return array('ROLE_USER');
}
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);
}
public function isSender()
{
return $this->getId();
}
public function isReceiver()
{
return $this->getId();
}
}
My problem is that Users can have multiple Transactions as sender or receiver an Transaction have at least 2 user (Send & receive)
With this config, I can add one transaction for each user....
I still do not manage very well Doctrine relation yet...
So somedy can EXPLAIN me how to do the tricks and how it works....
Clone project on GitHUB
I finaly found a workinf solution but I don't now if it's the right way to do
it...
I make a contrustor with two ArrayCollection(); in my User.php class and I put users_id into.
And in my Transaction.php class #ORM\JoinColumn
In my 'Transaction.php' class I put:
Everything is working now, but I don't really understand what's appened...
Someone can explain me correctly what was the problem .??
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="senders")
* #ORM\JoinColumn(nullable=true)
*/
private $sender;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="receivers")
* #ORM\JoinColumn(nullable=true)
*/
private $receiver;
public function getSender()
{
return $this->sender;
}
public function setSender(User $user)
{
$this->sender = $user;
}
public function getReceiver()
{
return $this->receiver;
}
public function setReceiver(User $user)
{
$this->receiver = $user;
}
And in my 'User.php' class:
/**
* #ORM\OneToMany(targetEntity="Transaction", mappedBy="receiver")
*/
private $receivers;
/**
* #ORM\OneToMany(targetEntity="Transaction", mappedBy="receiver")
*/
private $receivers;
/**
* #ORM\OneToMany(targetEntity="Transaction", mappedBy="sender")
*/
private $senders;
public function __construct()
{
$this->senders = new ArrayCollection();
$this->receivers = new ArrayCollection();
}
/**
* #return Collection|Transaction[]
*/
public function getReceivers()
{
return $this->receivers;
}
/**
* #return Collection|Transaction[]
*/
public function getSenders()
{
return $this->senders;
}

encoding password with symfony3: Catchable Fatal Error: Argument 3 passed to

I'm trying to encode the password in symfony3 but i'm facing some problems.
this is the error i got.
Catchable Fatal Error: Argument 3 passed to GMAOBundle\Security\LoginFormAuthentificator::__construct() must be an instance of Symfony\Component\Security\Core\Encoder\UserPasswordEncoder, none given, called in C:\xampp\htdocs\ProjetSomadiag\var\cache\dev\appDevDebugProjectContainer.php on line 483 and defined
I'm working with guard in the authentification.
this is the authentification class name loginformauthentificator.
namespace GMAOBundle\Security;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\EncoderFactory;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder;
class LoginFormAuthentificator extends AbstractGuardAuthenticator
{
private $em;
private $router;
private $passwordEncoder;
public function __construct($em, $router,UserPasswordEncoder $PasswordEncoder )
{
$this->em = $em;
$this->router = $router;
//$this->passwordEncoder = new UserPasswordEncoder();
$this->passwordEncoder = $PasswordEncoder;
}
public function getCredentials(Request $request)
{
if ($request->getPathInfo() != '/login' || !$request->isMethod('POST')) {
return;
}
$request->getSession()->set(Security::LAST_USERNAME,$request->request->get('_username'));
return [
'username' => $request->request->get('_username'),
'password' => $request->request->get('_password'),
];
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$username = $credentials['username'];
return $this->em->getRepository('GMAOBundle:Employe')
->findOneBy(['EmailEmploye' => $username]);
}
/**
* #param mixed $credentials
* #param UserInterface $user
* #return bool
*/
public function checkCredentials($credentials, UserInterface $user)
{
$password=$credentials['password'];
if ($this->passwordEncoder->isPasswordValid($user, $password)) {
return true;
}
return false;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
$url = $this->router->generate('login');
return new RedirectResponse($url);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
$url = $this->router->generate('gmao_homepage');
return new RedirectResponse($url);
}
public function supportsRememberMe()
{
return true;
}
public function start(Request $request, AuthenticationException $authException = null)
{
$url = $this->router->generate('login');
return new RedirectResponse($url);
}
}
and this is the user class.
namespace GMAOBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Entity
* #ORM\Table(name="employe")
*/
class Employe implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/private $idEmploye;
/**
* #ORM\Column(type="string")
*/private $NomEmploye;
/**
* #ORM\Column(type="string")
*/private $PrenomEmploye;
/**
* #ORM\Column(type="date", nullable=true)
*/private $DateNaissanceEmploye;
/**
* #ORM\Column(type="string")
*/private $cinEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $AdresseEmploye;
/**
* #ORM\Column(type="string")
*/private $MatriculeEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $SituationFamiliale;
/**
* #ORM\Column(type="string", nullable=true)
*/private $SexeEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $CnssEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $FonctionEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $NumeroMutuelle;
/**
* #ORM\Column(type="date", nullable=true)
*/private $DateDebutEmploye;
/**
* #ORM\Column(type="date", nullable=true)
*/private $DateTitularisationEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $NumeroTelEmploye;
/**
* #ORM\Column(type="string", nullable=true)
*/private $NumeroLigneEmploye;
/**
* #ORM\Column(type="string")
*/private $EmailEmploye;
/**
* A non-persisted field that's used to create the encoded password.
* #var string
*/private $plainPassword;
/**
* #ORM\Column(type="string")
*/private $MdpEmploye;
/**
* #ORM\Column(type="string")
*/private $active;
/**
* #ORM\Column(type="json_array")
*/private $roles = [];
/**
* #ORM\ManyToOne(targetEntity="Departement")
* #ORM\JoinColumn(name="Departement",
referencedColumnName="id_departement")
*/private $Departement;
/**
* #ORM\ManyToOne(targetEntity="Equipe", cascade={"persist"})
* #ORM\JoinColumn(name="Equipe", referencedColumnName="id" ,nullable=true)
*/private $equipe;
/**
* #ORM\Column(type="string", nullable=true)
*/private $imgsrc;
/**
* #ORM\Column(type="string")
*private $responsable_projet;
/**
* #ORM\Column(type="string")
*private $m_GMAO_Projet;
/**
* #ORM\Column(type="string")
*public $m_PMP_Objectif;
/**
* #ORM\Column(type="string")
*public $m_Services;*/
/**
* User Interface Methode Override
*/
function __construct()
{
}
function __destruct()
{
}
public function getUsername()
{
return $this->EmailEmploye;
}
public function getRoles()
{
$roles = $this->roles;
if(!in_array('ROLE_USER',$roles))
{
$roles[]='ROLE_USER';
}
return $roles;
}
public function getPassword()
{
return$this->MdpEmploye;
}
public function getSalt()
{
}
public function eraseCredentials()
{
$this->plainPassword = null;
}
/**
* GETTERS AND SETTERS
**/
/**
* #return mixed
*/
public function getIdEmploye()
{
return $this->idEmploye;
}
/**
* #param mixed $idEmploye
*/
public function setIdEmploye($idEmploye)
{
$this->idEmploye = $idEmploye;
}
/**
* #return mixed
*/
public function getNomEmploye()
{
return $this->NomEmploye;
}
/**
* #param mixed $NomEmploye
*/
public function setNomEmploye($NomEmploye)
{
$this->NomEmploye = $NomEmploye;
}
/**
* #return mixed
*/
public function getPrenomEmploye()
{
return $this->PrenomEmploye;
}
/**
* #param mixed $PrenomEmploye
*/
public function setPrenomEmploye($PrenomEmploye)
{
$this->PrenomEmploye = $PrenomEmploye;
}
/**
* #return mixed
*/
public function getDateNaissanceEmploye()
{
return $this->DateNaissanceEmploye;
}
/**
* #param mixed $DateNaissanceEmploye
*/
public function setDateNaissanceEmploye($DateNaissanceEmploye)
{
$this->DateNaissanceEmploye = $DateNaissanceEmploye;
}
/**
* #return mixed
*/
public function getcinEmploye()
{
return $this->cinEmploye;
}
/**
* #param mixed $cinemploye
*/
public function setcinEmploye($Cinemploye)
{
$this->cinEmploye = $Cinemploye;
}
/**
* #return mixed
*/
public function getAdresseEmploye()
{
return $this->AdresseEmploye;
}
/**
* #param mixed $AdresseEmploye
*/
public function setAdresseEmploye($AdresseEmploye)
{
$this->AdresseEmploye = $AdresseEmploye;
}
/**
* #return mixed
*/
public function getMatriculeEmploye()
{
return $this->MatriculeEmploye;
}
/**
* #param mixed $MatriculeEmploye
*/
public function setMatriculeEmploye($MatriculeEmploye)
{
$this->MatriculeEmploye = $MatriculeEmploye;
}
/**
* #return mixed
*/
public function getSituationFamiliale()
{
return $this->SituationFamiliale;
}
/**
* #param mixed $SituationFamiliale
*/
public function setSituationFamiliale($SituationFamiliale)
{
$this->SituationFamiliale = $SituationFamiliale;
}
/**
* #return mixed
*/
public function getSexeEmploye()
{
return $this->SexeEmploye;
}
/**
* #param mixed $SexeEmploye
*/
public function setSexeEmploye($SexeEmploye)
{
$this->SexeEmploye = $SexeEmploye;
}
/**
* #return mixed
*/
public function getCnssEmploye()
{
return $this->CnssEmploye;
}
/**
* #param mixed $CnssEmploye
*/
public function setCnssEmploye($CnssEmploye)
{
$this->CnssEmploye = $CnssEmploye;
}
/**
* #return mixed
*/
public function getFonctionEmploye()
{
return $this->FonctionEmploye;
}
/**
* #param mixed $FonctionEmploye
*/
public function setFonctionEmploye($FonctionEmploye)
{
$this->FonctionEmploye = $FonctionEmploye;
}
/**
* #return mixed
*/
public function getNumeroMutuelle()
{
return $this->NumeroMutuelle;
}
/**
* #param mixed $NumeroMutuelle
*/
public function setNumeroMutuelle($NumeroMutuelle)
{
$this->NumeroMutuelle = $NumeroMutuelle;
}
/**
* #return mixed
*/
public function getDateDebutEmploye()
{
return $this->DateDebutEmploye;
}
/**
* #param mixed $DateDebutEmploye
*/
public function setDateDebutEmploye($DateDebutEmploye)
{
$this->DateDebutEmploye = $DateDebutEmploye;
}
/**
* #return mixed
*/
public function getDateTitularisationEmploye()
{
return $this->DateTitularisationEmploye;
}
/**
* #param mixed $DateTitularisationEmploye
*/
public function setDateTitularisationEmploye($DateTitularisationEmploye)
{
$this->DateTitularisationEmploye = $DateTitularisationEmploye;
}
/**
* #return mixed
*/
public function getNumeroTelEmploye()
{
return $this->NumeroTelEmploye;
}
/**
* #param mixed $NumeroTelTmploye
*/
public function setNumeroTelEmploye($NumeroTelEmploye)
{
$this->NumeroTelEmploye = $NumeroTelEmploye;
}
/**
* #return mixed
*/
public function getNumeroLigneEmploye()
{
return $this->NumeroLigneEmploye;
}
/**
* #param mixed $NumeroLigneEmploye
*/
public function setNumeroLigneEmploye($NumeroLigneEmploye)
{
$this->NumeroLigneEmploye = $NumeroLigneEmploye;
}
/**
* #return mixed
*/
public function getEmailEmploye()
{
return $this->EmailEmploye;
}
/**
* #param mixed $EmailEmploye
*/
public function setEmailEmploye($EmailEmploye)
{
$this->EmailEmploye = $EmailEmploye;
}
/**
* #return mixed
*/
public function getMdpEmploye()
{
return $this->MdpEmploye;
}
/**
* #param mixed $MdpEmploye
*/
public function setMdpEmploye($MdpEmploye)
{
$this->MdpEmploye = $MdpEmploye;
}
/**
* #return mixed
*/
public function getActive()
{
return $this->active;
}
/**
* #param mixed $active
*/
public function setActive($active)
{
$this->active = $active;
}
/**
* #return mixed
*/
public function getDepartement()
{
return $this->Departement;
}
/**
* #param mixed $Departement
*/
public function setDepartement($Departement)
{
$this->Departement = $Departement;
}
/**
* #return mixed
*/
public function getImgsrc()
{
return $this->imgsrc;
}
/**
* #param mixed $imgsrc
*/
public function setImgsrc($imgsrc)
{
$this->imgsrc = $imgsrc;
}
public function setRoles($roles)
{
$this->roles =$roles;
}
/**
* #return mixed
*/
public function getEquipe()
{
return $this->equipe;
}
/**
* #param mixed $Equipe
*/
public function setEquipe($Equipe)
{
$this->equipe = $Equipe;
}
/**
* #return string
*/
public function getPlainPassword()
{
return $this->plainPassword;
}
/**
* #param string $plainPassword
*/
public function setPlainPassword($plainPassword)
{
$this->plainPassword = $plainPassword;
$this->password = null;
}
}
i don't know what this error stand for.
If you are using dependency injection, you must send your password encoder in as your third argument.
Example:
services.yml
services:
app.loginform.authenticator:
class: GMAOBundle\Security\LoginFormAuthentificator
arguments:
- "#doctrine.orm.entity_manager"
- "#router"
- "#passwordencoder"
Alternatively you can "autowire".
services:
app.loginform.authenticator:
class: GMAOBundle\Security\LoginFormAuthentificator
autowire: true
Or however you're using your services.yml to inject dependencies.
If you're creating the loginFormAuthenticator as an object you have to instantiate it as:
$loginAuthenticator = new LoginFormAuthentificator($entitymanager, $router, $passwordEncoder);
You're missing the password encoder in some argument when you call the class.

Symfony ArrayCollection vs PersistentCollection

As I understood when you query database by repository you get PersistentCollection and when your working with your entities you get ArrayCollection.
so consider I have one to many self referencing relation for my user entity.
and in my user entity I have a setChildren method which get ArrayCollection of users as argument .
<?php
namespace UserBundle\Entity;
use Abstracts\Entity\BaseModel;
use CertificateBundle\Entity\Certificate;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use EducationBundle\Entity\Education;
use LanguageBundle\Entity\Language;
use PostBundle\Entity\Post;
use ProfileBundle\Entity\Company;
use RoleBundle\Entity\Role;
use SkillBundle\Entity\Skill;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* User
*
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="UserBundle\Repository\Entity\UserRepository")
* #UniqueEntity("email")
* #UniqueEntity("username")
*/
class User implements UserInterface
{
use BaseModel;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="type", type="string", columnDefinition="ENUM('merchant', 'company', 'customer') ")
*/
private $type;
/**
* #ORM\Column(type="string", unique=true)
* #Assert\NotBlank()
*/
private $username;
/**
* #var string
*
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank()
*/
private $email;
/**
* #var string
* #ORM\Column(type="string", nullable=true)
*/
private $avatar = null;
/**
* #var string
* #ORM\Column(type="string", nullable=true)
*/
private $cover = null;
/**
* #ORM\OneToMany(targetEntity="PostBundle\Entity\Post", mappedBy="user", orphanRemoval=true, cascade={"persist", "remove"})
*/
private $posts;
/**
* #ORM\OneToMany(targetEntity="EducationBundle\Entity\Education" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $educations;
/**
* #ORM\OneToMany(targetEntity="SkillBundle\Entity\SkillUser" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $skills;
/**
* #ORM\OneToMany(targetEntity="LanguageBundle\Entity\LanguageUser" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $languages;
/**
* #ORM\OneToMany(targetEntity="ResumeBundle\Entity\Resume" , mappedBy="user" , cascade={"all"})
*/
protected $resumes;
/**
* #ORM\OneToMany(targetEntity="CertificateBundle\Entity\CertificateUser" , mappedBy="user" , orphanRemoval=true, cascade={"persist", "remove"})
*/
protected $certificates;
/**
* #ORM\OneToOne(targetEntity="ProfileBundle\Entity\Company", mappedBy="user")
*/
protected $company;
/**
* #ORM\OneToOne(targetEntity="ProfileBundle\Entity\Customer", mappedBy="user")
*/
protected $customer;
/**
* #ORM\OneToOne(targetEntity="ProfileBundle\Entity\Merchant", mappedBy="user")
*/
protected $merchant;
/**
* #var string
* #Assert\NotBlank()
* #Assert\Length(min=4)
* #ORM\Column(name="password", type="string", length=255)
*
*/
private $password;
/**
* #ORM\ManyToMany(targetEntity="RoleBundle\Entity\Role", inversedBy="users", cascade={"persist"})
* #ORM\JoinTable(name="user_role", joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")}, inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")})
*/
private $roles;
/**
* #ORM\ManyToOne(targetEntity="UserBundle\Entity\User", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="SET NULL")
*/
protected $parent;
/**
* #ORM\OneToMany(targetEntity="UserBundle\Entity\User", mappedBy="parent", orphanRemoval=true, cascade={"persist", "remove"})
*
*/
protected $children;
/**
* #var array
*/
public static $fields = [ 'email', 'username', 'id', 'avatar', 'cover', 'type'];
/**
* User Entity constructor.
*/
public function __construct(/*EncoderFactoryInterface $encoderFactory*/)
{
//$this->encoderFactory = $encoderFactory;
$this->posts = new ArrayCollection();
$this->skills = new ArrayCollection();
$this->languages = new ArrayCollection();
$this->certificates = new ArrayCollection();
$this->educations = new ArrayCollection();
$this->children = new ArrayCollection();
dump($this->children);
die();
}
/**
* #param User $user
* #return $this
*/
public function setParent(User $user)
{
$this->parent = $user;
return $this;
}
/**
* #return $this
*/
public function removeParent()
{
$this->parent = null;
return $this;
}
/**
* #param User $user
* #return $this
*/
public function addChild(User $user)
{
if(!$this->children->contains($user)){
$this->children->add($user);
}
return $this;
}
/**
* #param User $user
* #return bool
*/
public function hasChild(User $user)
{
return $this->children->contains($user);
}
/**
* #param User $user
* #return bool
*/
public function isChildOf(User $user)
{
return $user->getChildren()->contains($this);
}
/**
* #return ArrayCollection
*/
public function getChildren()
{
return $this->children;
}
/**
* #param User $user
* #return $this
*/
public function removeChild(User $user)
{
if($this->children->contains($user)){
$this->children->removeElement($user);
}
return $this;
}
/**
* #param ArrayCollection $users
* #return $this
*/
public function setChildren(ArrayCollection $users)
{
$this->children = $users;
return $this;
}
/**
* #return $this
*/
public function removeChildren()
{
$this->children->clear();
return $this;
}
/**
* #param ArrayCollection $certificates
* #return $this
*/
public function setCertificates(ArrayCollection $certificates)
{
$this->certificates = $certificates;
return $this;
}
/**
* #param Certificate $certificate
* #return $this
*/
public function addCertificate(Certificate $certificate)
{
if(!$this->certificates->contains($certificate))
$this->certificates->add($certificate);
return $this;
}
/**
* #param Certificate $certificate
* #return $this
*/
public function removeCertificate(Certificate $certificate)
{
if($this->certificates->contains($certificate))
$this->certificates->removeElement($certificate);
return $this;
}
/**
* #return $this
*/
public function removeCertificates()
{
$this->certificates->clear();
return $this;
}
/**
* #param ArrayCollection $skills
* #return $this
*/
public function setSkills(ArrayCollection $skills)
{
$this->skills = $skills;
return $this;
}
/**
* #param Skill $skill
* #return $this
*/
public function addSkill(Skill $skill)
{
if(!$this->skills->contains($skill))
$this->skills->add($skill);
return $this;
}
/**
* #param Skill $skill
* #return $this
*/
public function removeSkill(Skill $skill)
{
if($this->skills->contains($skill))
$this->skills->removeElement($skill);
return $this;
}
/**
* #return $this
*/
public function removeSkills()
{
$this->skills->clear();
return $this;
}
/**
* #param ArrayCollection $languages
* #return $this
*/
public function setLanguages(ArrayCollection $languages)
{
$this->languages = $languages;
return $this;
}
/**
* #param Language $language
* #return $this
*/
public function addLanguage(Language $language)
{
if(!$this->languages->contains($language))
$this->languages->add($language);
return $this;
}
/**
* #param Language $language
* #return $this
*/
public function removeLanguage(Language $language)
{
if($this->languages->contains($language))
$this->languages->removeElement($language);
return $this;
}
/**
* #return $this
*/
public function removeLanguages()
{
$this->languages->clear();
return $this;
}
/**
* #param ArrayCollection $posts
* #return $this
*/
public function setPosts(ArrayCollection $posts)
{
$this->posts = $posts;
return $this;
}
/**
* #param Post $post
* #return $this
*/
public function addPost(Post $post)
{
$this->posts->add($post);
return $this;
}
/**
* #param Post $post
* #return $this
*/
public function removePost(Post $post)
{
$this->posts->removeElement($post);
return $this;
}
/**
* #return $this
*/
public function removePosts()
{
$this->posts->clear();
return $this;
}
/**
* #param ArrayCollection $educations
* #return $this
*/
public function setEducations(ArrayCollection $educations)
{
$this->educations = $educations;
return $this;
}
/**
* #param Education $education
* #return $this
*/
public function addEducation(Education $education)
{
$this->educations->add($education);
return $this;
}
/**
* #param Education $education
* #return $this
*/
public function removeEducation(Education $education)
{
$this->educations->removeElement($education);
return $this;
}
/**
* #return $this
*/
public function removeEducations()
{
$this->educations->clear();
return $this;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* #param integer $id
* #return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* #return mixed
*/
public function getType()
{
return $this->type;
}
/**
* #param mixed $type
* #return $this
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Set email
*
* #param string $email
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* #param $username
* #return $this
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* #return mixed
*/
public function getUsername()
{
return $this->username;
}
/**
* #return array
*/
public function getRoles()
{
return ['ROLE_USER', 'IS_AUTHENTICATED_ANONYMOUSLY'];
}
/**
* #param $password
* #return $this
*/
public function setPassword($password)
{
//$password =$this->encoderFactory->getEncoder($this)->encodePassword($password, $this->getSalt());
$this->password = $password;
return $this;
}
/**
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
*
*/
public function getSalt()
{
return md5(sha1('somesalt'));
}
/**
*
*/
public function eraseCredentials()
{
}
/**
* #param $cover
* #return $this
*/
public function setCover($cover)
{
$this->cover = $cover;
return $this;
}
/**
* #return string
*/
public function getCover()
{
return $this->cover;
}
/**
* #param $avatar
* #return $this
*/
public function setAvatar($avatar)
{
$this->avatar = $avatar;
return $this;
}
/**
* #return string
*/
public function getAvatar()
{
return $this->avatar;
}
/**
* #param Role $roles
*/
public function addRoles(Role $roles)
{
$this->roles[] = $roles;
}
/**
* #return mixed
*/
public function getRoles2()
{
return $this->roles;
}
/**
* #return array
*/
public function getRolesAsArray()
{
$rolesArray = [];
foreach ($this->getRoles2() as $role) {
$rolesArray[] = $role->getName();
}
return $rolesArray;
}
/**
* #return Company
*/
public function getCompany()
{
return $this->company;
}
/**
* #param Company $company
* #return $this
*/
public function setCompany(Company $company)
{
$this->company = $company;
return $this;
}
}
and this is what I want to do
$new_owner = $this->userRepository->findOneById($user_id, false);
$children = $old_owner->getChildren();
$old_owner->removeChildren();
$new_owner->setChildren($children);
and I get error which says :
Argument 1 passed to
Proxies__CG__\UserBundle\Entity\User::setChildren() must be an
instance of Doctrine\Common\Collections\ArrayCollection, instance of
Doctrine\ORM\PersistentCollection given
should I change my type hint in setChildren method to PersistentCollection ??
or I need to totally change my approach?
Short answer:
/**
* #param Doctrine\Common\Collections\Collection $users
* #return $this
*/
public function setChildren(Doctrine\Common\Collections\Collection $users)
{
$this->children = $users;
return $this;
}
Explanation:
If you look deep into Doctrine Classes you will see the following structure:
Array collection is class that implements interface Collection:
class ArrayCollection implements Collection, Selectable
PersistentCollection is class that extentds AbstractLazyCollection:
final class PersistentCollection extends AbstractLazyCollection implements Selectable
but AbstractLazyCollection implements Collection:
abstract class AbstractLazyCollection implements Collection
So:
Collection is interface, that you should use in method setChildren().
This is because of doctrine use lazy loading - mechanism that allow to load not all properties, but only these, that are needed.
Similar question:
Doctrine manyToMany return PersistentCollection instead of ArrayCollection
In your typing add Collection $children
use Doctrine\Common\Collections\Collection;
...
private ?Collection $children;
symfony: 5.3

Symfony Call to a member function getRole() on string

I am having troubles with user authorization.
This is my User
namespace AppBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="users")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*
* #var int id
*/
protected $id;
/**
* #ORM\Column(type="string", length=25)
*
* #var string username
*/
protected $username;
/**
* #ORM\Column(type="string", length=25)
*
* #var string password
*/
protected $password;
/**
* #ORM\Column(type="string", length=25)
*
* #var string firstName
*/
protected $firstName;
/**
* #ORM\Column(type="string", length=25)
*
* #var string lastName
*/
protected $lastName;
/**
* #ORM\Column(type="string", length=25)
*
* #var string email
*/
protected $email;
/**
* #ORM\Column(type="string", length=255)
*
* #var string salt
*/
protected $salt;
/**
* #ORM\ManyToMany(targetEntity="Role")
* #ORM\JoinTable(name="user_role",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*
* #var ArrayCollection $userRoles
*/
protected $userRoles;
public function __construct()
{
$this->posts = new ArrayCollection();
$this->userRoles = new ArrayCollection();
$this->createdAt = new \DateTime();
}
public function getId()
{
return $this->id;
}
public function getUsername()
{
return $this->username;
}
public function getPassword()
{
return $this->password;
}
public function getFirstName()
{
return $this->firstName;
}
public function getLastName()
{
return $this->lastName;
}
public function getEmail()
{
return $this->email;
}
public function getSalt()
{
return $this->salt;
}
public function getUserRoles()
{
return $this->userRoles;
}
public function getRoles()
{
return $this->getUserRoles()->toArray();
}
public function setUsername($username)
{
$this->username = $username;
}
public function setPassword($password)
{
$this->password = $password;
}
public function setFirstName($firstName)
{
$this->firstName = $firstName;
}
public function setLastName($lastName)
{
$this->lastName = $lastName;
}
public function setEmail($email)
{
$this->email = $email;
}
public function setSalt($value)
{
$this->salt = $value;
}
public function eraseCredentials()
{
}
public function equals(UserInterface $user)
{
return md5($this->getUsername()) == md5($user->getUsername());
}
}
And this is my Role
namespace AppBundle\Entity;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="role")
*/
class Role implements RoleInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*
* #var integer $id
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*
* #var string $name
*/
protected $name;
/**
* #ORM\Column(type="datetime", name="created_at")
*
* #var DateTime $createdAt
*/
protected $createdAt;
/**
* Геттер для id.
*
* #return integer The id.
*/
public function getId()
{
return $this->id;
}
/**
* Геттер для названия роли.
*
* #return string The name.
*/
public function getName()
{
return $this->name;
}
/**
* Сеттер для названия роли.
*
* #param string $value The name.
*/
public function setName($value)
{
$this->name = $value;
}
/**
* Геттер для даты создания роли.
*
* #return DateTime A DateTime object.
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Конструктор класса
*/
public function __construct()
{
$this->createdAt = new \DateTime();
}
/**
* Реализация метода, требуемого интерфейсом RoleInterface.
*
* #return string The role.
*/
public function getRole()
{
return $this->getName();
}
}
RoleHierarchy.php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Security\Core\Role;
/**
* RoleHierarchy defines a role hierarchy.
*
* #author Fabien Potencier <fabien#symfony.com>
*/
class RoleHierarchy implements RoleHierarchyInterface
{
private $hierarchy;
protected $map;
/**
* Constructor.
*
* #param array $hierarchy An array defining the hierarchy
*/
public function __construct(array $hierarchy)
{
$this->hierarchy = $hierarchy;
$this->buildRoleMap();
}
/**
* {#inheritdoc}
*/
public function getReachableRoles(array $roles)
{
$reachableRoles = $roles;
foreach ($roles as $role) {
if (!isset($this->map[$role->getRole()])) {
continue;
}
foreach ($this->map[$role->getRole()] as $r) {
$reachableRoles[] = new Role($r);
}
}
return $reachableRoles;
}
protected function buildRoleMap()
{
$this->map = array();
foreach ($this->hierarchy as $main => $roles) {
$this->map[$main] = $roles;
$visited = array();
$additionalRoles = $roles;
while ($role = array_shift($additionalRoles)) {
if (!isset($this->hierarchy[$role])) {
continue;
}
$visited[] = $role;
$this->map[$main] = array_unique(array_merge($this->map[$main], $this->hierarchy[$role]));
$additionalRoles = array_merge($additionalRoles, array_diff($this->hierarchy[$role], $visited));
}
}
}
}
I am getting next error - FatalErrorException in RoleHierarchy.php line 43: Error: Call to a member function getRole() on string
How should i solve the problem?

The Doctrine repository "Doctrine\ORM\EntityRepository" must implement UserProviderInterface in symfony2

I am getting above error when login. With property option in security.yml it is working. I have added the #ORM\Entity(repositoryClass="versionR\userBundle\Entity\UserRepository") line on my entity class, dobule checked path, cleared cache but no luck.
User entity class
<?php
namespace versionR\userBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
//use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* User
*
* #ORM\Table(name="user")
* #ORM\Entity(repositoryClass="versionR\userBundle\Entity\UserRepository")
*/
class User implements UserInterface, \Serializable
{
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=40, 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=255, nullable=false)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="address", type="string", length=255, nullable=false)
*/
private $address;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="versionR\userBundle\Entity\Role", inversedBy="user")
* #ORM\JoinTable(name="user_role",
* joinColumns={
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="role_id", referencedColumnName="id")
* }
* )
*/
private $role;
/**
* Constructor
*/
public function __construct()
{
$this->role = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* #param string $address
*/
public function setAddress($address)
{
$this->address = $address;
}
/**
* #return string
*/
public function getAddress()
{
return $this->address;
}
/**
* #param string $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* #param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param string $password
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* #param string $username
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* #param \Doctrine\Common\Collections\Collection $role
*/
public function setRole($role)
{
$this->role->add($role);
}
/**
* #return \Doctrine\Common\Collections\Collection
*/
public function getRole()
{
return $this->role;
}
/**
*/
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/**
*/
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
/**
* Returns the roles granted to the user.
*/
public function getRoles()
{
return $this->role->toArray();
}
/**
*/
public function getSalt()
{
return null;
}
/**
*/
public function eraseCredentials()
{
// TODO: Implement eraseCredentials() method.
}
}
User repository class
<?php
namespace versionR\userBundle\Entity;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
/**
* UserRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class UserRepository extends EntityRepository implements UserProviderInterface
{
/**
* #param string $username
* #return \versionR\userBundle\Entity\User
*/
public function loadUserByUsername($username)
{
return $this->findOneBy(array('username' => $username));
}
public function refreshUser(UserInterface $user)
{
$class = get_class($user);
if (!$this->supportsClass($class)) {
throw new UnsupportedUserException(
sprintf(
'Instances of "%s" are not supported.',
$class
)
);
}
return $this->find($user->getId());
}
public function supportsClass($class)
{
return $this->getEntityName() === $class
|| is_subclass_of($class, $this->getEntityName());
}
}
Both classes are in Entity directory. Any suggestions to solve this problem. I am using symfony 2.5.2

Categories