Article.php 1.6 KB

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