NewsApiController.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. /*
  15. * http://localhost/php-storm/internship-playground/src-php/public/api/news/news
  16. * http://localhost/php-storm/internship-playground/src-php/public/api/news/newslist/1
  17. */
  18. #[Inject]
  19. private NewsDao $newsDao;
  20. function getDoNews(): void {
  21. $this->sendJson($this->newsDao->getNews());
  22. }
  23. function getDoNewsList(int $newsId): void {
  24. $comment = $this->newsDao->getNewsById($newsId);
  25. if($comment === null) {
  26. throw new PageNotFoundException();
  27. } else {
  28. $this->sendJson($comment);
  29. }
  30. }
  31. /**
  32. * Speichere eine News.
  33. *
  34. * @return void
  35. * @throws StatusException
  36. */
  37. function postDoNews(ParamBody $body): void {
  38. $httpData = $body->parseJsonToHttpData();
  39. $title = $httpData->reqString('title');
  40. $description = $httpData->reqString('description');
  41. $text = $httpData->reqString('text');
  42. $intro = $httpData->reqString('intro');
  43. $newsToAdd = $this->createNews($title, $description, $text, $intro);
  44. $this->beginTransaction();
  45. $this->newsDao->saveNews($newsToAdd);
  46. $this->commit();
  47. $this->sendJson($newsToAdd);
  48. }
  49. function createNews($title, $description, $text, $intro): News {
  50. $news = new News();
  51. $news->title2 = $title;
  52. $news->description_finished = $description;
  53. $news->text_finished = $text;
  54. return $news;
  55. }
  56. }