src/Entity/Application/CategoryTranslation.php line 21

Open in your IDE?
  1. <?php
  2. namespace App\Entity\Application;
  3. use Doctrine\ORM\Mapping as ORM;
  4. use App\Entity\Behaviors\TranslationTrait;
  5. use App\Entity\Behaviors\SluggableTrait;
  6. use Knp\DoctrineBehaviors\Contract\Entity\TranslationInterface;
  7. use Knp\DoctrineBehaviors\Contract\Entity\SluggableInterface;
  8. use Doctrine\ORM\Event\LifecycleEventArgs;
  9. use JMS\Serializer\Annotation as Serializer;
  10. /**
  11. * @ORM\Table(name="app_category_translations",
  12. * uniqueConstraints={@ORM\UniqueConstraint(name="sluging", columns={"locale", "slug"})}
  13. * )
  14. * @ORM\Entity(repositoryClass="App\Repository\TranslationRepository")
  15. * @ORM\HasLifecycleCallbacks()
  16. */
  17. class CategoryTranslation implements TranslationInterface, SluggableInterface
  18. {
  19. use SluggableTrait;
  20. use TranslationTrait;
  21. protected $isEmptyOff = true;
  22. /**
  23. * @Serializer\Groups({"api"})
  24. * @Serializer\SerializedName("name")
  25. * @ORM\Column(type="string", length=199)
  26. */
  27. private $name;
  28. /**
  29. * @ORM\Column(type="string", length=2)
  30. */
  31. protected $locale;
  32. /**
  33. * @ORM\Column(type="string", length=190)
  34. */
  35. protected $slug;
  36. public function getName(): ?string
  37. {
  38. return trim($this->name);
  39. }
  40. public function setName(string $name): self
  41. {
  42. $this->name = $name;
  43. return $this;
  44. }
  45. /**
  46. * Returns an array of the fields used to generate the slug.
  47. *
  48. * @return array
  49. */
  50. public function getSluggableFields(): array
  51. {
  52. return [ 'name' ];
  53. }
  54. public function generateSlug(): void { }
  55. /**
  56. * @ORM\PreUpdate()
  57. * @ORM\PrePersist()
  58. */
  59. public function updateSlug( LifecycleEventArgs $eventArgs )
  60. {
  61. $translatable = $this->getTranslatable();
  62. $oldSlug = $translatable->getSlug();
  63. if ( $this->getRegenerateSlugOnUpdate() || empty( $this->slug ) ) {
  64. $fields = $this->getSluggableFields();
  65. $values = [];
  66. foreach ( $fields as $field ) {
  67. if ( property_exists( $this, $field ) ) {
  68. $val = $this->{$field};
  69. } else {
  70. $methodName = 'get' . ucfirst( $field );
  71. if ( method_exists( $this, $methodName ) ) {
  72. $val = $this->{$methodName}();
  73. } else {
  74. $val = null;
  75. }
  76. }
  77. $values[] = $val;
  78. }
  79. $this->slug = $this->generateSlugValue( $values );
  80. if ( $oldSlug !== $this->slug ) {
  81. $repo = $eventArgs->getEntityManager()->getRepository( get_class( $this ) );
  82. $repo->updateSlug( $this );
  83. }
  84. }
  85. }
  86. }