Symfony Call to a member function getRole() on string - php

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?

Related

Datas overwriting problem with EntityType (same problem with ChoiceType) in Symfony 5

So here is my concern. I have a "Child" entity that contains $services and $users linked in ManyToMany.
The goal in my application is to be able to assign a child to a user of my service.
So, depending on the service I'm in, I won't have the same choice of users to assign.
In my ChildType, in my "users" field, I added a key ''query_builder'' that will retrieve only the users concerned.
My ChildType.php
<?php
namespace App\Form;
use App\Entity\Child;
use App\Entity\Service;
use App\Entity\Sexe;
use App\Entity\User;
use App\Repository\ServiceRepository;
use App\Repository\UserRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Security;
class ChildType extends AbstractType
{
/** #var User $user */
private $user;
private $serviceRepository;
private $authorization;
public function __construct(Security $security, AuthorizationCheckerInterface $authorization, ServiceRepository $serviceRepository)
{
$this->user = $security->getUser();
$this->authorization = $authorization;
$this->serviceRepository = $serviceRepository;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
/** #var Service $service */
$service = $this->user->getService();
$builder
->add('nom', TextType::class)
->add('prenom', TextType::class)
->add('sexe', EntityType::class, [
'class' => Sexe::class,
])
->add('dateDeNaissance', DateType::class, [
'widget' => 'single_text'
])
->add('lieuDeNaissance', TextType::class)
->add('nationalite', TextType::class)
->add('dateElaborationPpe', DateType::class, [
'widget' => 'single_text'
]);
if ($this->authorization->isGranted('ROLE_ADMIN')) {
$builder->add('users', EntityType::class, [
'class' => User::class,
'label' => 'Affecter à un utilisateur',
'query_builder' => function (UserRepository $userRepository) use ($service) {
return $userRepository->findByCurrentService($service);
},
'multiple' => true,
'expanded' => true,
]);
$builder->add('services', EntityType::class, [
'class' => Service::class,
'label' => 'Affecter à un service',
'choices' => $this->serviceRepository->findByDepartement($service->getDepartement()),
'choice_attr' => function($key, $val, $index) use ($service) {
return([]);
return $key->getCategorie()->getId() === $service->getCategorie()->getId() ?
['disabled' => 'disabled'] :
[];
},
'multiple' => true,
'expanded' => true,
]);
}
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Child::class,
]);
}
}
The problem:
Let's assume that my Service #1 has several users from Service #1 to my child. When I assign in my Service #2 users from Service #2 to the child, I have my 2 new users from Service #2 in the database, but on the other hand, those from Service #1 have been deleted, which is not the desired behavior.
I've been looking for a topic for almost 2 hours, and I can't find an answer, so if it's a duplicate, really sorry.
edit method in my controller:
/**
* #Route("/{id}/edit", name="child_edit", methods={"GET","POST"})
*/
public function edit(Request $request, Child $child): Response
{
$this->denyAccessUnlessGranted("edit", $child);
$form = $this->createForm(ChildType::class, $child);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('child_show', ['id' => $child->getId()]);
}
return $this->render('child/edit.html.twig', [
'child' => $child,
'form' => $form->createView(),
]);
}
User.php:
<?php
namespace App\Entity;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use App\Entity\Service;
use App\Traits\BlameableEntity;
use App\Traits\TimestampableEntity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="App\Repository\UserRepository")
*
*/
class User implements UserInterface, \Serializable
{
use BlameableEntity;
use TimestampableEntity;
/**
* #var int
*
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #var string
*
* #ORM\Column(type="string")
* #Assert\NotBlank()
*/
private $fullName;
/**
* #var string
*
* #ORM\Column(type="string", unique=true)
* #Assert\NotBlank()
* #Assert\Length(min=2, max=50)
*/
private $username;
/**
* #var string
*
* #ORM\Column(type="string", unique=true)
* #Assert\Email()
*/
private $email;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $password;
/**
* #var array
*
* #ORM\Column(type="json")
*/
private $roles = [];
/**
* #var \DateTime
*
* #ORM\Column(type="datetime", nullable=true)
*/
private $lastLogin;
/**
* #var \DateTime
*
* #ORM\Column(type="datetime", nullable=true)
*/
private $secondToLastLogin;
/**
* #ORM\ManyToOne(targetEntity="Service", inversedBy="users")
*/
private $service;
/**
* #ORM\ManyToMany(targetEntity="Child", mappedBy="users")
*/
private $children;
public function __construct()
{
$this->children = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getFullName(): ?string
{
return $this->fullName;
}
public function setFullName(string $fullName): self
{
$this->fullName = $fullName;
return $this;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* Returns the roles or permissions granted to the user for security.
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantees that a user always has at least one role for security
if (empty($roles)) {
$roles[] = 'ROLE_USER';
}
return array_unique($roles);
}
public function setRoles(array $roles): void
{
$this->roles = $roles;
}
/**
* Get the value of lastLogin
*
* #return \DateTime
*/
public function getLastLogin()
{
return $this->lastLogin;
}
/**
* Set the value of lastLogin
*
* #param \DateTime $lastLogin
*
* #return self
*/
public function setLastLogin(\DateTime $lastLogin)
{
$this->lastLogin = $lastLogin;
return $this;
}
/**
* Get the value of secondToLastLogin
*
* #return \DateTime
*/
public function getSecondToLastLogin()
{
return $this->secondToLastLogin;
}
/**
* Set the value of secondToLastLogin
*
* #param \DateTime $secondToLastLogin
*
* #return self
*/
public function setSecondToLastLogin(\DateTime $secondToLastLogin)
{
$this->secondToLastLogin = $secondToLastLogin;
return $this;
}
/**
*
* {#inheritdoc}
*/
public function getSalt(): ?string
{
return null;
}
/**
* Removes sensitive data from the user.
*
* {#inheritdoc}
*/
public function eraseCredentials(): void
{
// if you had a plainPassword property, you'd nullify it here
// $this->plainPassword = null;
}
/**
* {#inheritdoc}
*/
public function serialize(): string
{
// add $this->salt too if you don't use Bcrypt or Argon2i
return serialize([$this->id, $this->username, $this->password]);
}
/**
* {#inheritdoc}
*/
public function unserialize($serialized): void
{
// add $this->salt too if you don't use Bcrypt or Argon2i
[$this->id, $this->username, $this->password] = unserialize($serialized, ['allowed_classes' => false]);
}
/**
* Get the value of service
*/
public function getService()
{
return $this->service;
}
/**
* Set the value of service
*
* #return self
*/
public function setService($service)
{
$this->service = $service;
return $this;
}
public function hasService(): bool
{
return !empty($this->getService());
}
/**
* #return Collection|Child[]
*/
public function getChildren(): Collection
{
return $this->children;
}
public function addChild(Child $child): self
{
if (!$this->children->contains($child)) {
$this->children[] = $child;
$child->addUser($this);
}
return $this;
}
public function removeChild(Child $child): self
{
if ($this->children->removeElement($child)) {
$child->removeUser($this);
}
return $this;
}
public function __toString()
{
return $this->getFullName();
}
}
Service.php :
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use App\Repository\ServiceRepository;
use App\Entity\Categorie;
use App\Entity\Departement;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
/**
* #ORM\Entity(repositoryClass=ServiceRepository::class)
*/
class Service
{
public const ASE = 'ASE';
public const MDPH = 'MDPH';
public const E_N = 'Éducation Nationale';
/**
* #var int
*
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $nom;
/**
* #var Departement
*
* #ORM\ManyToOne(targetEntity="Departement")
* #ORM\JoinColumn(nullable=false)
*/
private $departement;
/**
* #var Categorie
*
* #ORM\ManyToOne(targetEntity="Categorie")
* #ORM\JoinColumn(nullable=false)
*/
private $categorie;
/**
* #ORM\OneToMany(targetEntity="User", mappedBy="service")
*/
private $users;
/**
* #ORM\ManyToMany(targetEntity="Child", mappedBy="services")
*/
private $children;
/**
* #ORM\ManyToMany(targetEntity="Element", mappedBy="services")
*/
private $elements;
public function __construct()
{
$this->users = new ArrayCollection();
$this->children = new ArrayCollection();
$this->elements = new ArrayCollection();
}
/**
* Get the value of id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set the value of id
*
* #param int $id
*
* #return self
*/
public function setId(int $id)
{
$this->id = $id;
return $this;
}
/**
* Get the value of nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set the value of nom
*
* #param string $nom
*
* #return self
*/
public function setNom(string $nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get the value of departement
*
* #return Departement
*/
public function getDepartement()
{
return $this->departement;
}
/**
* Set the value of departement
*
* #param Departement $departement
*
* #return self
*/
public function setDepartement(Departement $departement)
{
$this->departement = $departement;
return $this;
}
/**
* Get the value of categorie
*
* #return Categorie
*/
public function getCategorie()
{
return $this->categorie;
}
/**
* Set the value of categorie
*
* #param Categorie $categorie
*
* #return self
*/
public function setCategorie(Categorie $categorie)
{
$this->categorie = $categorie;
return $this;
}
/**
* #return Collection|Users[]
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(User $user): self
{
if (!$this->users->contains($user)) {
$this->users[] = $user;
$user->setService($this);
}
return $this;
}
public function removeUser(User $user): self
{
if ($this->users->removeElement($user)) {
// set the owning side to null (unless already changed)
if ($user->getService() === $this) {
$user->setService(null);
}
}
return $this;
}
/**
* #return Collection|Children[]
*/
public function getChildren(): Collection
{
return $this->children;
}
public function addChild(Child $child): self
{
if (!$this->children->contains($child)) {
$this->children[] = $child;
$child->addService($this);
}
return $this;
}
public function removeChild(Child $child): self
{
if ($this->children->removeElement($child)) {
$child->removeService($this);
}
return $this;
}
/**
* #return Collection|Elements[]
*/
public function getElements(): Collection
{
return $this->elements;
}
public function addElements(Element $element): self
{
if (!$this->children->contains($element)) {
$this->elements[] = $element;
$element->addService($this);
}
return $this;
}
public function removeElement(Element $element): self
{
if ($this->elements->removeElement($element)) {
$element->removeService($this);
}
return $this;
}
public function __toString()
{
return $this->getNom();
}
}
Child.php :
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\Service;
use App\Entity\Sexe;
use App\Entity\User;
use DateTime;
use App\Repository\ChildRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use App\Traits\TimestampableEntity;
use App\Traits\BlameableEntity;
/**
* #ORM\Entity(repositoryClass=ChildRepository::class)
*/
class Child
{
use BlameableEntity;
use TimestampableEntity;
/**
* #var int
*
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $nom;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $prenom;
/**
* #var Sexe
*
* #ORM\ManyToOne(targetEntity="Sexe")
*/
private $sexe;
/**
* #var date
*
* #ORM\Column(type="date")
*/
private $dateDeNaissance;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $lieuDeNaissance;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $nationalite;
/**
* #var date
*
* #ORM\Column(type="datetime", nullable=true)
*/
private $dateElaborationPpe;
/**
* #var Service[]|Collection
*
* #ORM\ManyToMany(targetEntity="Service", inversedBy="children")
*/
private $services;
/**
* #var User[]|Collection
*
* #ORM\ManyToMany(targetEntity="User", inversedBy="children")
*/
private $users;
/**
* #var Element[]|Collection
*
* #ORM\OneToMany(targetEntity="Element", mappedBy="child")
*/
private $elements;
public function __construct()
{
$this->services = new ArrayCollection();
$this->users = new ArrayCollection();
$this->elements = new ArrayCollection();
}
/**
* Get the value of id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set the value of id
*
* #param int $id
*
* #return self
*/
public function setId(int $id)
{
$this->id = $id;
return $this;
}
/**
* Get id
*
* #return string
*/
public function getNumDossier()
{
return str_pad($this->id, 6, "0", STR_PAD_LEFT);
}
/**
* Get the value of nom
*/
public function getNom()
{
return $this->nom;
}
/**
* Set the value of nom
*
* #return self
*/
public function setNom(string $nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get the value of prenom
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set the value of prenom
*
* #return self
*/
public function setPrenom(string $prenom)
{
$this->prenom = $prenom;
return $this;
}
/**
* Get the value of sexe
*
* #return Sexe
*/
public function getSexe()
{
return $this->sexe;
}
/**
* Set the value of sexe
*
* #param Sexe $sexe
*
* #return self
*/
public function setSexe(Sexe $sexe)
{
$this->sexe = $sexe;
return $this;
}
/**
* Get the value of dateDeNaissance
*/
public function getDateDeNaissance()
{
return $this->dateDeNaissance;
}
/**
* Set the value of dateDeNaissance
*
* #return self
*/
public function setDateDeNaissance(datetime $dateDeNaissance)
{
$this->dateDeNaissance = $dateDeNaissance;
return $this;
}
/**
* Get the value of lieuDeNaissance
*/
public function getLieuDeNaissance()
{
return $this->lieuDeNaissance;
}
/**
* Set the value of lieuDeNaissance
*
* #return self
*/
public function setLieuDeNaissance(string $lieuDeNaissance)
{
$this->lieuDeNaissance = $lieuDeNaissance;
return $this;
}
/**
* Get the value of nationalite
*/
public function getNationalite()
{
return $this->nationalite;
}
/**
* Set the value of nationalite
*
* #return self
*/
public function setNationalite(string $nationalite)
{
$this->nationalite = $nationalite;
return $this;
}
/**
* Get the value of dateElaborationPpe
*/
public function getDateElaborationPpe()
{
return $this->dateElaborationPpe;
}
/**
* Set the value of dateElaborationPpe
*
* #return self
*/
public function setDateElaborationPpe(datetime $dateElaborationPpe)
{
$this->dateElaborationPpe = $dateElaborationPpe;
return $this;
}
/**
* #return Collection|Service[]
*/
public function getServices(): Collection
{
return $this->services;
}
public function addService(Service $service): self
{
if (!$this->services->contains($service)) {
$this->services[] = $service;
}
return $this;
}
public function removeService(Service $service): self
{
$this->services->removeElement($service);
return $this;
}
/**
* #return Collection|User[]
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(User $user): self
{
$test = 'test';
if (!$this->users->contains($user)) {
$this->users[] = $user;
}
return $this;
}
public function removeUser(User $user): self
{
$this->users->removeElement($user);
return $this;
}
public function getNbUsers()
{
return count($this->getUsers());
}
/**
* #return Collection|Element[]
*/
public function getElements(): Collection
{
return $this->elements;
}
public function addElement(Element $element): self
{
if (!$this->elements->contains($element)) {
$this->elements[] = $element;
}
return $this;
}
public function removeElement(Element $element): self
{
$this->elements->removeElement($element);
return $this;
}
public function isNotAssigned(): bool
{
return (!$this->getNbUsers());
}
public function __toString(): string
{
return $this->getNom() . ' ' . $this->getPrenom();
}
}
Thanks in advance for your help.

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;
}

Symfony 3 find closest date from now

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

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

Symfony2 Entity doctrine2 don't update field

I have this entity:
Profile.php
/**
* LoPati\BlogBundle\Entity\Profile
*
* #ORM\Table(name="profile")
* #ORM\Entity
* #Gedmo\TranslationEntity(class="LoPati\BlogBundle\Entity\ProfileTranslation")
*/
class Profile
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #Gedmo\Translatable
* #ORM\Column(name="name", type="string", length=255, nullable=true)
*/
protected $name=null;
/**
* #var text $description
* #Gedmo\Translatable
* #ORM\Column(name="description", type="text", nullable=true)
*/
protected $description=null;
/**
* #ORM\OneToMany(targetEntity="ProfileTranslation", mappedBy="object", cascade={"persist", "remove"})
*/
protected $translations;
/**
* Required for Translatable behaviour
* #Gedmo\Locale
*/
protected $locale;
public function __construct()
{
$this->translations = new ArrayCollection;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function getLocale()
{
return $this->locale;
}
public function setLocale($locale)
{
$this->locale = $locale;
}
public function setName($name)
{
$this->name=$name;
}
public function getName()
{
return $this->name;
}
public function setDescription($description)
{
}
public function getDescription()
{
return $this->description;
}
public function getTranslations()
{
return $this->translations;
}
public function addTranslation(ProfileTranslation $t)
{
$this->translations->add($t);
$t->setObject($this);
$this->name = $this->translations[0];
$this->description = $this->translations[1];
}
public function removeTranslation(ProfileTranslation $t)
{
$this->translations->removeElement($t);
}
public function setTranslations($translations)
{
$this->translations = $translations;
$this->name = $this->translations[0];
$this->description = $this->translations[1];
}
public function __toString()
{
return "hola";
}
}
And ProfileTranslation.php
/**
* #ORM\Entity
* #ORM\Table(name="profile_translations",
* uniqueConstraints={#ORM\UniqueConstraint(name="lookup_unique_idx", columns={
* "locale", "object_id", "field"
* })}
* )
*/
class ProfileTranslation extends AbstractPersonalTranslation
{
/**
* Convinient constructor
*
* #param string $locale
* #param string $field
* #param string $content
*/
public function __construct($locale = null, $field = null, $content = null)
{
$this->setLocale($locale);
$this->setField($field);
$this->setContent($content);
}
/**
* #ORM\ManyToOne(targetEntity="Profile", inversedBy="translations")
* #ORM\JoinColumn(name="object_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $object;
public function __toString()
{
return $this->getContent();
}
}
I want that when edit arraycollection that is a ProfileTranslation table, then also update the name and description field but form Profile Table, and it be the first element that collection.
It work when I create new Profile, but when I edit this profile, only update the ProfileTranslation Table and not Profile table.
How I can do it?
Your implementation turns away a little too classic Translatable use.
You could maybe have a look about TranslationFormBundle and its Demo if it right for you.

Categories