如何获取扩展类的ObjectManager

时间:2019-06-25 07:40:20

标签: symfony4

我想在网站的每个页面上获得一个用户的统计信息。 我有班级用户和班级统计信息。 用户扩展统计信息。 当我继续查看时,收到以下消息:呈现模板期间引发了异常(“注意:未定义的属性:App \ Entity \ User :: $ manager”)

我在用户构造函数中注入ObjectManager并在用户中调用统计信息的主要功能

统计类:

<?php
namespace App\Service;

use Doctrine\Common\Persistence\ObjectManager;


class StatsMailbox{

    public function __construct(ObjectManager $manager)
    {
        //initialisation du manager
        $this->manager = $manager;
    }

    public function getStatistics($id){
        //$user=$this->getUser();
        $messages=$this->getMessagesStats($id);
        $demands =$this->getDemandsStats($id);
        $offers =$this->getOffersStats($id);
        $invitations=$this->getInvitationsStats($id);
        return compact('messages','demands','offers','invitations');
    }

    //nombre de messages reçus avec le status "received"

    public function getMessagesStats($id){
        return $this->manager->createQuery( "SELECT COUNT (m) 
        FROM App\Entity\Message m
        JOIN m.receiver u
        WHERE m.receiver = ".$id."
        AND m.receiverStatus='received'"


         )
         ->getSingleScalarResult();
    }

    //nombre de demandes reçues avec le status received
    public function getDemandsStats($id)
    {
        return $this->manager->createQuery(
        "SELECT COUNT (d) 
        FROM App\Entity\Demand d
        JOIN d.receiver u
        WHERE d.receiver = " . $id . "
        AND d.type = 1
        AND d.receiverStatus='received'"


        )
            ->getSingleScalarResult();
    }

    //nombre d'offres reçues avec le status received
    public function getOffersStats($id)
    {
        return $this->manager->createQuery(
            "SELECT COUNT (d) 
        FROM App\Entity\Demand d
        JOIN d.receiver u
        WHERE d.receiver = " . $id . "
        AND d.type = 0
        AND d.receiverStatus='received'"


        )
            ->getSingleScalarResult();


    }
    //nombre d'invitations reçues avec le status received
    public function getInvitationsStats($id)
    {
        return $this->manager->createQuery(
            "SELECT COUNT (i) 
        FROM App\Entity\Invitation i
        JOIN i.receiver u
        WHERE i.receiver = " . $id . "

        AND i.receiverStatus='received'"


        )
            ->getSingleScalarResult();
    }


}

用户类:

    <?php

namespace App\Entity;

use App\Entity\Skill;
use App\Entity\SkillWant;
use Cocur\Slugify\Slugify;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping\HasLifecycleCallbacks;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

use App\Service\StatsMailbox;
use Doctrine\Common\Persistence\ObjectManager;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @HasLifecycleCallbacks
 * @UniqueEntity(
 * fields={"email"},
 * message="Cette adresse existe déjà dans notre base de données")
 * @UniqueEntity(
 * fields={"slug"},
 * message="Ce pseudo est déjà pris") 
 *  fields={"skills"},
 * message="Cette compétence existe déjà")
 */
class User extends StatsMailbox implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $slug;


    /** 
    * le token qui servira lors de l'oubli de mot de passe
    * @ORM\Column(type="string", length=255, nullable=true)
    */
    private $resetToken;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $firstname;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $lastname;

    /**
     * @ORM\Column(type="date", nullable=true)
     */
    private $birthDate;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $email;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Address")
     * @ORM\JoinColumn(nullable=false)
     */
    private $address;

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Skill", cascade={"persist"})
     */
    private $skills;

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\SkillWant", cascade={"persist"})
     */
    private $skillWants;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Activity", mappedBy="author", orphanRemoval=true)
     */
    private $activitys;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $description;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * 
     * @Assert\Type(
     *    type="File",
     *    message="The value {{ value }} is not a valid {{ type }}.")
     * @Assert\Image()
     */
    private $avatar;

    /**
     * @ORM\Column(type="string", length=255)
     *

     */
    private $hash;

    /**
     * Comparaison du champ avec le champ hash
     * @Assert\EqualTo(propertyPath="hash", message="Les 2 mots de passe ne correspondent pas")
     */
    public $passwordConfirm;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Book", mappedBy="booker")
     */
    private $books;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="author", orphanRemoval=true)
     */
    private $comments;


    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Message", mappedBy="sender")
     */
    private $messageSent;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Message", mappedBy="receiver")
     */
    private $messageReceived;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Demand", mappedBy="sender")
     */
    private $demandSent;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Demand", mappedBy="receiver")
     */
    private $demandReceived;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Invitation", mappedBy="sender")
     */
    private $invitationSent;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Invitation", mappedBy="receiver")
     */

    private $invitationReceived;

/** récupérer les stats du user */
    // public function box(){
    //     $id=$this->getId();

    //     $stats = $this->getStatistics($id);
    //     return $stats;
    // }


    public function stats()
    {


        $stats=$this->getStatistics($this->getId());
        return $stats;

    }

  //calcul de l'age                        
    public function age()
    {
        $date=$this->getBirthDate()->format('Y-m-d');

        $age = date('Y') - date('Y', strtotime($date));

        if (date('md') < date('md', strtotime($date))) {

            return $age - 1;
         }
               return $age;
          }

    /**
     * Initialiser le slug avant tout
     * @ORM\PrePersist
     * @ORM\PreUpdate
     * 
     */
    public function initializeSlug()
    {
        if (empty($this->slug)) {

            $slugify = new Slugify();
            $this->slug = $slugify->slugify($this->firstname.' '.$this->lastname);
        }
    }


    public function __construct()
    {

        $this->skills = new ArrayCollection();
        $this->skillWants = new ArrayCollection();
        $this->activitys = new ArrayCollection();
        $this->books = new ArrayCollection();
        $this->comments = new ArrayCollection();
        $this->messageSent = new ArrayCollection();
        $this->messageReceived = new ArrayCollection();
        $this->demandSent = new ArrayCollection();
        $this->demandReceived = new ArrayCollection();
        $this->invitationSent = new ArrayCollection();
        $this->invitationReceived = new ArrayCollection();


    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }

    public function getFirstname(): ?string
    {
        return $this->firstname;
    }

    public function setFirstname(string $firstname): self
    {
        $this->firstname = $firstname;

        return $this;
    }

    public function getLastname(): ?string
    {
        return $this->lastname;
    }

    public function setLastname(string $lastname): self
    {
        $this->lastname = $lastname;

        return $this;
    }

    public function getBirthDate(): ?\DateTimeInterface
    {
        return $this->birthDate;
    }

    public function setBirthDate(\DateTimeInterface $birthDate): self
    {
        $this->birthDate = $birthDate;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    public function getAddress(): ?Address
    {
        return $this->address;
    }

    public function setAddress(?Address $address): self
    {
        $this->address = $address;

        return $this;
    }
    public function getHash(): ?string
    {
        return $this->hash;
    }

    public function setHash(string $hash): self
    {
        $this->hash = $hash;

        return $this;
    }

    /**
     * @return Collection|Skill[]
     */
    public function getSkills(): Collection
    {
        return $this->skills;
    }

    public function addSkill(Skill $skill): self
    {
        if (!$this->skills->contains($skill)) {
            $this->skills[] = $skill;
        }

        return $this;
    }

    public function removeSkill(Skill $skill): self
    {
        if ($this->skills->contains($skill)) {
            $this->skills->removeElement($skill);
        }

        return $this;
    }

    /**
     * @return Collection|SkillWant[]
     */
    public function getSkillWants(): Collection
    {
        return $this->skillWants;
    }

    public function addSkillWant(SkillWant $skillWant): self
    {
        if (!$this->skillWants->contains($skillWant)) {
            $this->skillWants[] = $skillWant;
        }

        return $this;
    }

    public function removeSkillWant(SkillWant $skillWant): self
    {
        if ($this->skillWants->contains($skillWant)) {
            $this->skillWants->removeElement($skillWant);
        }

        return $this;
    }

    /**
     * @return Collection|Activity[]
     */
    public function getActivitys(): Collection
    {
        return $this->activitys;
    }

    public function addActivity(Activity $activity): self
    {
        if (!$this->activitys->contains( $activity)) {
            $this->activitys[] = $activity;
            $activity-> setAuthor($this);
        }

        return $this;
    }

    public function removeActivity(Activity $activity): self
    {
        if ($this->activitys->contains( $activity)) {
            $this->activitys->removeElement( $activity);
            // set the owning side to null (unless already changed)
            if ( $activity->getAuthor() === $this) {
                $activity->setAuthor(null);
            }
        }

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function getAvatar()
    {
        return $this->avatar;
    }

    public function setAvatar($avatar): self
    {
        $this->avatar = $avatar;

        return $this;
    }

    public function getRoles(){
        return ['ROLE_USER'];
    }
    public function getPassword(){
        return $this->hash;
    }
    public function getSalt(){}
    public function getUserName(){
        return $this->email;
    }
    public function eraseCredentials(){}

    /**
     * @return Collection|Book[]
     */
    public function getBooks(): Collection
    {
        return $this->books;
    }

    public function addBook(Book $book): self
    {
        if (!$this->books->contains($book)) {
            $this->books[] = $book;
            $book->addBooker($this);
        }

        return $this;
    }

    public function removeBook(Book $book): self
    {
        if ($this->books->contains($book)) {
            $this->books->removeElement($book);
            $book->removeBooker($this);
        }

        return $this;
    }

    /**
     * @return Collection|Comment[]
     */
    public function getComments(): Collection
    {
        return $this->comments;
    }

    public function addComment(Comment $comment): self
    {
        if (!$this->comments->contains($comment)) {
            $this->comments[] = $comment;
            $comment->setAuthor($this);
        }

        return $this;
    }

    public function removeComment(Comment $comment): self
    {
        if ($this->comments->contains($comment)) {
            $this->comments->removeElement($comment);
            // set the owning side to null (unless already changed)
            if ($comment->getAuthor() === $this) {
                $comment->setAuthor(null);
            }
        }

        return $this;
    }


    /**
     * @return string
     */
    public function getResetToken(): string
    {
        return $this->resetToken;
    }

    /**
     * @param string $resetToken
     */
    public function setResetToken(?string $resetToken): void
    {
        $this->resetToken = $resetToken;
    }

    /**
     * @return Collection|Message[]
     */
    public function getMessageSent(): Collection
    {
        return $this->messageSent;
    }

    public function addMessageSent(Message $messageSent): self
    {
        if (!$this->messageSent->contains($messageSent)) {
            $this->messageSent[] = $messageSent;
            $messageSent->setSender($this);
        }

        return $this;
    }

    public function removeMessageSent(Message $messageSent): self
    {
        if ($this->messageSent->contains($messageSent)) {
            $this->messageSent->removeElement($messageSent);
            // set the owning side to null (unless already changed)
            if ($messageSent->getSender() === $this) {
                $messageSent->setSender(null);
            }
        }

        return $this;
    }

    /**
     * @return Collection|Message[]
     */
    public function getMessageReceived(): Collection
    {
        return $this->messageReceived;
    }

    public function addMessageReceived(Message $messageReceived): self
    {
        if (!$this->messageReceived->contains($messageReceived)) {
            $this->messageReceived[] = $messageReceived;
            $messageReceived->setReceiver($this);
        }

        return $this;
    }

    public function removeMessageReceived(Message $messageReceived): self
    {
        if ($this->messageReceived->contains($messageReceived)) {
            $this->messageReceived->removeElement($messageReceived);
            // set the owning side to null (unless already changed)
            if ($messageReceived->getReceiver() === $this) {
                $messageReceived->setReceiver(null);
            }
        }

        return $this;
    }

    /**
     * @return Collection|Demand[]
     */
    public function getDemandSent(): Collection
    {
        return $this->demandSent;
    }

    public function addDemandSent(Demand $demandSent): self
    {
        if (!$this->demandSent->contains($demandSent)) {
            $this->demandSent[] = $demandSent;
            $demandSent->setSender($this);
        }

        return $this;
    }

    public function removeDemandSent(Demand $demandSent): self
    {
        if ($this->demandSent->contains($demandSent)) {
            $this->demandSent->removeElement($demandSent);
            // set the owning side to null (unless already changed)
            if ($demandSent->getSender() === $this) {
                $demandSent->setSender(null);
            }
        }

        return $this;
    }

    /**
     * @return Collection|Demand[]
     */
    public function getDemandReceived(): Collection
    {
        return $this->demandReceived;
    }

    public function addDemandReceived(Demand $demandReceived): self
    {
        if (!$this->demandReceived->contains($demandReceived)) {
            $this->demandReceived[] = $demandReceived;
            $demandReceived->setReceiver($this);
        }

        return $this;
    }

    public function removeDemandReceived(Demand $demandReceived): self
    {
        if ($this->demandReceived->contains($demandReceived)) {
            $this->demandReceived->removeElement($demandReceived);
            // set the owning side to null (unless already changed)
            if ($demandReceived->getReceiver() === $this) {
                $demandReceived->setReceiver(null);
            }
        }

        return $this;
    }

    /**
     * @return Collection|Invitation[]
     */
    public function getInvitationSent(): Collection
    {
        return $this->invitationSent;
    }

    public function addInvitationSent(Invitation $invitationSent): self
    {
        if (!$this->invitationSent->contains($invitationSent)) {
            $this->invitationSent[] = $invitationSent;
            $invitationSent->setSender($this);
        }

        return $this;
    }

    public function removeInvitationSent(Invitation $invitationSent): self
    {
        if ($this->invitationSent->contains($invitationSent)) {
            $this->invitationSent->removeElement($invitationSent);
            // set the owning side to null (unless already changed)
            if ($invitationSent->getSender() === $this) {
                $invitationSent->setSender(null);
            }
        }

        return $this;
    }

    /**
     * @return Collection|Invitation[]
     */
    public function getInvitationReceived(): Collection
    {
        return $this->invitationReceived;
    }

    public function addInvitationReceived(Invitation $invitationReceived): self
    {
        if (!$this->invitationReceived->contains($invitationReceived)) {
            $this->invitationReceived[] = $invitationReceived;
            $invitationReceived->setReceiver($this);
        }

        return $this;
    }

    public function removeInvitationReceived(Invitation $invitationReceived): self
    {
        if ($this->invitationReceived->contains($invitationReceived)) {
            $this->invitationReceived->removeElement($invitationReceived);
            // set the owning side to null (unless already changed)
            if ($invitationReceived->getReceiver() === $this) {
                $invitationReceived->setReceiver(null);
            }
        }

        return $this;
    }

}

视图:

<li class="list-group-item d-flex justify-content-between align-items-center "> <a href="{{path('account_mailBox')}}"> Boîte de réception</a>
    {% if app.user.stats.messages < 1 %}
    {% else %}
            <span class="badge badge-danger badge-pill ">{{app.user.stats.messages}}</span>
    {% endif %}
  </li>`

我想在每个页面上查看我的统计信息,但似乎ObjectManager存在问题

0 个答案:

没有答案