Article.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace internship\bo;
  3. use n2n\reflection\ObjectAdapter;
  4. use n2n\persistence\orm\attribute\ManyToMany;
  5. use n2n\persistence\orm\attribute\OneToMany;
  6. use n2n\persistence\orm\CascadeType;
  7. use n2n\persistence\orm\attribute\OrderBy;
  8. use n2n\persistence\orm\FetchType;
  9. class Article extends ObjectAdapter implements \JsonSerializable {
  10. public int $id;
  11. public string $categoryName;
  12. public string $text;
  13. public string $title;
  14. #[OrderBy(array('name' => 'ASC'))]
  15. #[ManyToMany(Category::class, 'articles', cascade: CascadeType::PERSIST)]
  16. public \ArrayObject $categories;
  17. #[OneToMany(Comment::class, 'article', cascade: CascadeType::PERSIST, fetch: FetchType::LAZY , orphanRemoval: true)]
  18. public \ArrayObject $comments;
  19. function __construct() {
  20. $this->categories = new \ArrayObject();
  21. $this->comments = new \ArrayObject();
  22. }
  23. private function getCategoryIds() {
  24. $categories = array();
  25. foreach($this->categories as $category) {
  26. $categories[] = $category->basicJsonSerialize();
  27. }
  28. return $categories;
  29. }
  30. private function getCommentIds() {
  31. $comments = array();
  32. foreach($this->comments as $comment) {
  33. $comments[] = $comment->basicJsonSerialize();
  34. }
  35. return $comments;
  36. }
  37. function basicJsonSerialize() {
  38. return [
  39. 'id' => $this->id,
  40. 'title' => $this->title,
  41. 'text' => $this->text
  42. ];
  43. }
  44. function jsonSerialize(): mixed {
  45. $basicJson = $this->basicJsonSerialize();
  46. $basicJson['categoryName'] = $this->categoryName;
  47. $basicJson['categories'] = $this->getCategoryIds();
  48. $basicJson['comments'] = $this->getCommentIds();
  49. return $basicJson;
  50. }
  51. }