<?php
namespace App\Entity;
use App\Repository\BlogTagRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\String\Slugger\SluggerInterface;
#[ORM\Entity(repositoryClass: BlogTagRepository::class)]
#[ORM\Table(name: 'blog_tag')]
#[ORM\HasLifecycleCallbacks]
#[UniqueEntity(fields: ['slug'], message: 'There is already a tag with this slug')]
class BlogTag
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
#[Assert\NotBlank]
private ?string $name = null;
#[ORM\Column(length: 255, unique: true)]
private ?string $slug = null;
#[ORM\Column]
private ?\DateTimeImmutable $createdAt = null;
#[ORM\ManyToMany(targetEntity: Blog::class, mappedBy: 'tags')]
private Collection $blogPosts;
public function __construct()
{
$this->blogPosts = new ArrayCollection();
$this->createdAt = new \DateTimeImmutable();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): static
{
$this->name = $name;
return $this;
}
public function getSlug(): ?string
{
return $this->slug;
}
public function setSlug(string $slug): static
{
$this->slug = $slug;
return $this;
}
public function computeSlug(SluggerInterface $slugger): void
{
if (!$this->slug || '-' === $this->slug) {
$this->slug = (string) $slugger->slug((string) $this->name)->lower();
}
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeImmutable $createdAt): static
{
$this->createdAt = $createdAt;
return $this;
}
/**
* @return Collection<int, Blog>
*/
public function getBlogPosts(): Collection
{
return $this->blogPosts;
}
public function addBlogPost(Blog $blogPost): static
{
if (!$this->blogPosts->contains($blogPost)) {
$this->blogPosts->add($blogPost);
$blogPost->addTag($this);
}
return $this;
}
public function removeBlogPost(Blog $blogPost): static
{
if ($this->blogPosts->removeElement($blogPost)) {
$blogPost->removeTag($this);
}
return $this;
}
public function __toString(): string
{
return $this->name ?? 'New Tag';
}
}