Article.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. class Article extends ObjectAdapter implements \JsonSerializable {
  9. public int $id;
  10. public string $categoryName;
  11. public string $text;
  12. public string $title;
  13. #[OrderBy(array('name' => 'ASC'))]
  14. #[ManyToMany(Category::class, 'articles', cascade: CascadeType::PERSIST)]
  15. public \ArrayObject $categories;
  16. #[OneToMany(Comment::class, 'article', cascade: CascadeType::PERSIST, orphanRemoval: true)]
  17. public \ArrayObject $comments;
  18. function __construct() {
  19. $this->categories = new \ArrayObject();
  20. $this->comments = new \ArrayObject();
  21. }
  22. private function getCategoryIds() {
  23. $categories = array();
  24. foreach($this->categories as $category) {
  25. $categories[] = $category->basicJsonSerialize();
  26. }
  27. return $categories;
  28. }
  29. private function getCommentIds() {
  30. $comments = array();
  31. foreach($this->comments as $comment) {
  32. $comments[] = $comment->basicJsonSerialize();
  33. }
  34. return $comments;
  35. }
  36. function basicJsonSerialize() {
  37. return [
  38. 'id' => $this->id,
  39. 'title' => $this->title,
  40. 'text' => $this->text
  41. ];
  42. }
  43. function jsonSerialize(): mixed {
  44. $basicJson = $this->basicJsonSerialize();
  45. $basicJson['categoryName'] = $this->categoryName;
  46. $basicJson['categories'] = $this->getCategoryIds();
  47. $basicJson['comments'] = $this->getCommentIds();
  48. return $basicJson;
  49. }
  50. }