src/Entity/Tag/BlogTag.php line 44

Open in your IDE?
  1. <?php
  2. namespace App\Entity\Tag;
  3. use ApiPlatform\Core\Annotation\ApiResource;
  4. use App\Entity\Blog;
  5. use App\Repository\Tag\BlogTagRepository;
  6. use Doctrine\Common\Collections\ArrayCollection;
  7. use Doctrine\Common\Collections\Collection;
  8. use Doctrine\ORM\Mapping as ORM;
  9. use Symfony\Component\Serializer\Annotation\Groups;
  10. use Symfony\Component\Serializer\Annotation\SerializedName;
  11. /**
  12.  * @ORM\Entity(repositoryClass=BlogTagRepository::class)
  13.  *
  14.  * @ApiResource(
  15.  *     attributes={
  16.  *          "order"={"title": "ASC"},
  17.  *          "normalization_context"={"groups"={
  18.  *              "BlogTag:output",
  19.  *              "BlogTag:io",
  20.  *              "Blog:output",
  21.  *          }},
  22.  *          "denormalization_context"={"groups"={
  23.  *              "BlogTag:input",
  24.  *              "BlogTag:io",
  25.  *          }}
  26.  *      },
  27.  *     collectionOperations={
  28.  *          "get"={
  29.  *              "method"="GET",
  30.  *              "path"="/public/blog-tags",
  31.  *          }
  32.  *     },
  33.  *     itemOperations={
  34.  *          "get"={
  35.  *              "method"="GET",
  36.  *              "path"="/public/blog-tag/{id}",
  37.  *          }
  38.  *     },
  39.  * )
  40.  */
  41. class BlogTag extends Tag
  42. {
  43.     /**
  44.      * @ORM\ManyToMany(targetEntity=Blog::class, mappedBy="tags")
  45.      * @SerializedName("blogs")
  46.      */
  47.     public Collection $blogs;
  48.     public function __construct()
  49.     {
  50.         $this->blogs = new ArrayCollection();
  51.     }
  52.     /**
  53.      * @return Collection|Blog[]
  54.      */
  55.     public function getBlogs(): ?Collection
  56.     {
  57.         return $this->blogs;
  58.     }
  59.     public function addBlog(Blog $blog): self
  60.     {
  61.         if (!$this->blogs->contains($blog)) {
  62.             $this->blogs[] = $blog;
  63.             $blog->addTag($this);
  64.         }
  65.         return $this;
  66.     }
  67.     public function removeBlog(Blog $blog): self
  68.     {
  69.         if ($this->blogs->contains($blog)) {
  70.             $this->blogs->removeElement($blog);
  71.             $blog->removeTag($this);
  72.         }
  73.         return $this;
  74.     }
  75.     public function __toString(): string
  76.     {
  77.         return $this->getTitle();
  78.     }
  79.     public function getBlogsListToHtml()
  80.     {
  81.         $html '';
  82.         /** @var Blog $blog */
  83.         foreach ($this->blogs->toArray() as $blog) {
  84.             $html .= '<li>'.$blog->getTitle().'</li>';
  85.         }
  86.         return '<ul>'.$html.'</ul>';
  87.     }
  88. }