NewsApiController.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace internship\controller;
  3. use n2n\web\http\controller\ControllerAdapter;
  4. use n2n\context\attribute\Inject;
  5. use internship\model\CommentDao;
  6. use n2n\web\http\PageNotFoundException;
  7. use n2n\web\http\StatusException;
  8. use n2n\web\http\controller\ParamBody;
  9. use n2n\web\http\BadRequestException;
  10. use internship\bo\Article;
  11. use internship\bo\News;
  12. use internship\model\NewsDao;
  13. class NewsApiController extends ControllerAdapter {
  14. #[Inject]
  15. private NewsDao $newsDao;
  16. function getDoNews(): void {
  17. $this->sendJson($this->newsDao->getNews());
  18. }
  19. function getDoNewsList(int $newsId): void {
  20. $comment = $this->newsDao->getNewsById($newsId);
  21. if($comment === null) {
  22. throw new PageNotFoundException();
  23. } else {
  24. $this->sendJson($comment);
  25. }
  26. }
  27. /**
  28. * Speichere eine News.
  29. *
  30. * @return void
  31. * @throws StatusException
  32. */
  33. function postDoNews(ParamBody $body): void {
  34. $httpData = $body->parseJsonToHttpData();
  35. $title = $httpData->reqString('title');
  36. $description = $httpData->reqString('description');
  37. $text = $httpData->reqString('text');
  38. $newsToAdd = $this->createNews($title, $description, $text);
  39. $this->beginTransaction();
  40. $this->newsDao->saveNews($newsToAdd);
  41. $this->commit();
  42. $this->sendJson($newsToAdd);
  43. }
  44. function createNews($title, $description, $text): News {
  45. $news = new News();
  46. $news->title = $title;
  47. $news->description = $description;
  48. $news->text = $text;
  49. return $news;
  50. }
  51. }