ArticleController.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. <?php
  2. namespace internship\controller;
  3. use internship\model\CategoryDao;
  4. use n2n\web\http\BadRequestException;
  5. use n2n\web\http\controller\ControllerAdapter;
  6. use internship\model\ArticleDao;
  7. use n2n\context\attribute\Inject;
  8. use n2n\web\http\controller\ParamBody;
  9. use internship\bo\Article;
  10. use internship\bo\Category;
  11. use n2n\web\http\ForbiddenException;
  12. use n2n\web\http\PageNotFoundException;
  13. use n2n\web\http\StatusException;
  14. use n2n\web\http\annotation\AnnoPut;
  15. /**
  16. * REST Controller
  17. * https://dev.n2n.rocks/de/n2n/docs/rest
  18. */
  19. class ArticleController extends ControllerAdapter {
  20. // private static function _annos(AnnoInit $ai): void {
  21. // $ai->m('putDoArticle', new AnnoPut());
  22. // }
  23. #[Inject]
  24. private ArticleDao $articleDao;
  25. #[Inject]
  26. private CategoryDao $categoryDao;
  27. function prepare(): void {
  28. if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
  29. header('Access-Control-Allow-Origin: *');
  30. header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
  31. header('Access-Control-Allow-Headers: Content-Type, Authorization');
  32. header('Access-Control-Max-Age: 86400'); // cache preflight
  33. http_response_code(204); // No Content
  34. exit;
  35. }
  36. $this->getResponse()->setHeader("Access-Control-Allow-Headers: X-Requested-With, Content-Type,Accept, Origin");
  37. $this->getResponse()->setHeader("Access-Control-Allow-Origin: http://localhost:4200");
  38. $this->getResponse()->setHeader('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, HEAD, OPTIONS');
  39. }
  40. /**
  41. * Gibt den {@see Article} mit der entsprechenden id im JSON Format zurück.
  42. *
  43. * <ul>
  44. * <li>
  45. * Gib "irgendöpis" mit dem {@code echo} command aus.
  46. * </li>
  47. * <li>
  48. * Ändere die Antwort nun zu einem gültigen json objekt {"hello" => "world"}. Übergebe dafür ein array der
  49. * Methode {@see $this->sendJson()}.
  50. * </li>
  51. * <li>
  52. * Implementiere und nutze die Methode {@see ArticleDao::getArticleById()}, um das entsprechende Artikel-Objekt
  53. * aus der Datenbank zu lesen und gebe diese anschliessend im JSON Format zurück.
  54. *
  55. * Das Article-Objekt kannst du einfach {@see $this->sendJson()} übergeben, um einen validen JSON-Response zu
  56. * generieren.
  57. * </li>
  58. * <li>
  59. * Kann der Artikel nicht gefunden werden, werfe eine {@link PageNotFoundException}.
  60. * </li>
  61. * </ul>
  62. *
  63. * @param int $articleId
  64. * @return void
  65. * @throws ForbiddenException if article 1 is queried (for testing).
  66. * @throws PageNotFoundException if Article could not be found.
  67. */
  68. function getDoArticle(int $articleId): void {
  69. $article = $this->articleDao->getArticleById($articleId);
  70. if ($article === null) {
  71. throw new PageNotFoundException('Article does not exist');
  72. }
  73. $this->sendJson($article,true);
  74. }
  75. /**
  76. * Diese Methode kannst du im Browser testen. Pfad: localhost/[ordner name vom projekt]/src-php/public/api/articles
  77. *
  78. * <ul>
  79. * <li>
  80. * Implementiere und nutze die Methode {@see ArticleDao::getArticles()}, um Artikel aus der Datenbank zu lesen
  81. * und gebe diese anschliessend im JSON Format zurück.
  82. *
  83. * Article-Objekte kannst du einfach {@see $this->sendJson()} übergeben, um einen validen JSON-Response zu
  84. * generieren.
  85. * </li>
  86. * <li>
  87. * Wird ein $categoryName übergeben, gebe nur die Artikel aus, die über diesen Kategorienamen verfügen.
  88. * </li>
  89. * </ul>
  90. *
  91. * @param null | string $categoryName
  92. * @return void
  93. * @throws PageNotFoundException if category could not be found.
  94. */
  95. function getDoArticles(string $categoryName = null): void {
  96. if ($categoryName === null) {
  97. $articles = $this->articleDao->getArticles();
  98. $this->sendJson($articles);
  99. return;
  100. }
  101. $articles = $this->articleDao->getArticlesByCategoryName($categoryName);
  102. if (empty($articles)) {
  103. throw new PageNotFoundException('category name was not found!');
  104. }
  105. $this->sendJson($articles);
  106. }
  107. /**
  108. * Speichere einen Artikel. Es wird die id (fremdschlüssel) der kategorie übergeben.
  109. * Dieses wird in den namen der kategorie aufgelöst
  110. *
  111. * <ul>
  112. * <li>
  113. * Der Kategoriename darf nur 'international','national' oder 'sport' sein.
  114. * Validiere dies und schmeisse im Fehlerfall eine: {@see BadRequestException}
  115. * </li>
  116. * <li>
  117. * Mache eine neue Entity {@see Article} und befülle sie mit den übergebenen Daten.
  118. * </li>
  119. * <li>
  120. * Implementiere eine neue Methode im {@see ArticleDao} und bennene sie "saveArticle".
  121. * </li>
  122. * </ul>
  123. *
  124. * Nenne die Methode {@see saveArticle(Article $article)}
  125. *
  126. *
  127. * @param ParamBody $body
  128. * @return void
  129. * @throws BadRequestException if category is not 'Travel', 'Health' oder 'Finance'
  130. * @throws StatusException
  131. */
  132. function postDoArticle(ParamBody $body): void {
  133. $httpData = $body->parseJsonToHttpData();
  134. $title = $httpData->reqString('title');
  135. $text = $httpData->optString('text','',true);
  136. $categoryId = $httpData->reqInt('categoryId');
  137. $category = $this->categoryDao->getCategoryById($categoryId);
  138. if ($category === null) {
  139. throw new BadRequestException('category id has no corresponding category!');
  140. }
  141. $article = new Article();
  142. $article->setCategory($category);
  143. $article->setTitle($title);
  144. $article->setText($text );
  145. $this->beginTransaction();
  146. $this->articleDao->saveArticle($article);
  147. $this->commit();
  148. $this->sendJson($article);
  149. // echo 'article saved successfully.';
  150. }
  151. /**
  152. * Editiere einen Artikel.
  153. *
  154. * <ul>
  155. * <li>
  156. * Der Kategoriename darf nur 'international','national' oder 'sport' sein.
  157. * Validiere dies und schmeisse im Fehlerfall eine: {@see BadRequestException}
  158. * </li>
  159. * <li>
  160. * Finde den dazugehörigen {@see Article} und passe die Daten mit denjenigen Daten von gestern ab.
  161. * </li>
  162. * <li>
  163. * Implementiere eine neue Methode im {@see ArticleDao} und nenne die Methode {@see saveArticle(Article $article)}.
  164. * </li>
  165. * </ul>
  166. *
  167. * @param int $articleId
  168. * @param ParamBody $body
  169. * @return void
  170. * @throws BadRequestException if category is not 'Travel', 'Health' oder 'Finance'
  171. * @throws PageNotFoundException
  172. * @throws StatusException
  173. */
  174. function putDoArticle(int $articleId, ParamBody $body): void {
  175. $this->beginTransaction();
  176. $article = $this->articleDao->getArticleById($articleId);
  177. if ($article === null) {
  178. throw new PageNotFoundException('article does not exist');
  179. }
  180. $httpData = $body->parseJsonToHttpData();
  181. $title = $httpData->optString('title');
  182. $text = $httpData->optString('text');
  183. $categoryId = $httpData->reqInt('categoryId');
  184. $category = $this->categoryDao->getCategoryById($categoryId);
  185. if ($category === null) {
  186. throw new PageNotFoundException('category id has no corresponding category!');
  187. }
  188. if ($title !== null) {
  189. $article->setTitle($title);
  190. }
  191. if ($text !== null) {
  192. $article->setText($text );
  193. }
  194. $article->setCategory($category);
  195. // $this->articleDao->saveArticle($article);
  196. $this->commit();
  197. $this->sendJson($article);
  198. // echo 'article with id: '.$articleId.' edited successfully.';
  199. }
  200. /**
  201. * Löscht den {@see Article} mit der dazugehörigen Id.
  202. *
  203. * <ul>
  204. * <li>Mache eine neue Methode im {@see ArticleDao} und benenne sie "removeArticle(int articleId) </li>
  205. * <ul>
  206. *
  207. * @param int $articleId
  208. * @return void
  209. * @throws PageNotFoundException if the article does not exist
  210. */
  211. function deleteDoArticle(int $articleId): void {
  212. $this->beginTransaction();
  213. $article = $this->articleDao->getArticleById($articleId);
  214. if ($article === null) {
  215. throw new PageNotFoundException('The article you are trying to delete does not exist.');
  216. }
  217. $this->articleDao->removeArticle($article);
  218. $this->commit();
  219. $this->sendJson($article);
  220. // echo 'article with id ' .$articleId. ' was removed.';
  221. }
  222. }