ArticleController.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. <?php
  2. namespace internship\controller;
  3. use n2n\web\http\controller\ControllerAdapter;
  4. use internship\model\ArticleDao;
  5. use n2n\context\attribute\Inject;
  6. use n2n\web\http\controller\ParamBody;
  7. use internship\bo\Article;
  8. use n2n\web\http\PageNotFoundException;
  9. use n2n\web\http\BadRequestException;
  10. use n2n\web\http\StatusException;
  11. use internship\model\ArticleGroupDao;
  12. use function PHPUnit\Framework\throwException;
  13. use n2n\web\http\controller\impl\HttpData;
  14. use n2n\bind\build\impl\Bind;
  15. use n2n\bind\mapper\impl\Mappers;
  16. use n2n\validation\validator\impl\Validators;
  17. /**
  18. * REST Controller
  19. * https://dev.n2n.rocks/de/n2n/docs/rest
  20. */
  21. class ArticleController extends ControllerAdapter {
  22. #[Inject]
  23. private ArticleDao $articleDao;
  24. #[Inject]
  25. private ArticleGroupDao $articleGroupDao;
  26. function prepare(): void {
  27. if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
  28. header('Access-Control-Allow-Origin: *');
  29. header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
  30. header('Access-Control-Allow-Headers: Content-Type, Authorization');
  31. header('Access-Control-Max-Age: 86400'); // cache preflight
  32. http_response_code(204); // No Content
  33. exit;
  34. }
  35. $this->getResponse()->setHeader("Access-Control-Allow-Headers: X-Requested-With, Content-Type,Accept, Origin");
  36. $this->getResponse()->setHeader("Access-Control-Allow-Origin: http://localhost:4200");
  37. $this->getResponse()->setHeader('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, HEAD, OPTIONS');
  38. }
  39. /**
  40. * Gibt den {@see Article} mit der entsprechenden id im JSON Format zurück.
  41. *
  42. * <ul>
  43. * <li>
  44. * Gib "irgendöpis" mit dem {@code echo} command aus.
  45. * </li>
  46. * <li>
  47. * Ändere die Antwort nun zu einem gültigen json objekt {"hello" => "world"}. Übergebe dafür ein array der
  48. * Methode {@see $this->sendJson()}.
  49. * </li>
  50. * <li>
  51. * Implementiere und nutze die Methode {@see ArticleDao::getArticleById()}, um das entsprechende Artikel-Objekt
  52. * aus der Datenbank zu lesen und gebe diese anschliessend im JSON Format zurück.
  53. *
  54. * Das Article-Objekt kannst du einfach {@see $this->sendJson()} übergeben, um einen validen JSON-Response zu
  55. * generieren.
  56. * </li>
  57. * <li>
  58. * Kann der Artikel nicht gefunden werden, werfe eine {@link PageNotFoundException}.
  59. * </li>
  60. * </ul>
  61. *
  62. * @param int $articleId
  63. * @return void
  64. * @throws PageNotFoundException if Article could not be found.
  65. */
  66. function getDoArticle(int $articleId): void {
  67. // echo "hello";
  68. // echo $this->sendJson(["hello" => "world"]);
  69. $article = $this->articleDao->getArticleById($articleId);
  70. if ($article === null) {
  71. throw new PageNotFoundException();
  72. }
  73. $this->sendJson($article);
  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 string|null $categoryName
  92. * @return void
  93. */
  94. function getDoArticles(?string $categoryName = null): void {
  95. if ($categoryName === null) {
  96. $this->sendJson($this->articleDao->getArticles());
  97. } else {
  98. $this->sendJson($this->articleDao->getArticlesByCategoryName($categoryName));
  99. }
  100. }
  101. /**
  102. * Speichere einen Artikel.
  103. *
  104. * <ul>
  105. * <li>
  106. * Der Kategoriename darf nur 'international','national' oder 'sport' sein.
  107. * Validiere dies und schmeisse im Fehlerfall eine: {@see BadRequestException}
  108. * </li>
  109. * <li>
  110. * Mache eine neue Entity {@see Article} und befülle sie mit den übergebenen Daten.
  111. * </li>
  112. * <li>
  113. * Implementiere eine neue Methode im {@see ArticleDao} und bennene sie "saveArticle".
  114. * </li>
  115. * </ul>
  116. *
  117. * Nenne die Methode {@see saveArticle(Article $article)}
  118. *
  119. * @return void
  120. * @throws BadRequestException
  121. * @throws StatusException
  122. */
  123. function postDoArticle(ParamBody $body): void {
  124. // $article = new Article(["categoryName" => "sport", "title" => "All the Travel", "text" => "no 757576"]);
  125. // $article = new Article('sport', 'All the Travel', 'no 757576');
  126. $httpData = $body->parseJsonToHttpData();
  127. // $article = Article::fromHttpData($httpData);
  128. // $article = new Article($httpData);
  129. $newArticle = $this->updateArticle($body->parseJsonToHttpData(), new Article());
  130. $this->beginTransaction();
  131. $this->articleDao->saveArticle($newArticle);
  132. $this->commit();
  133. $this->sendJson($newArticle);
  134. }
  135. /**
  136. * Editiere einen Artikel.
  137. *
  138. * <ul>
  139. * <li>
  140. * Der Kategoriename darf nur 'international','national' oder 'sport' sein.
  141. * Validiere dies und schmeisse im Fehlerfall eine: {@see BadRequestException}
  142. * </li>
  143. * <li>
  144. * Finde den dazugehörigen {@see Article} und passe die Daten mit denjenigen Daten von gestern ab.
  145. * </li>
  146. * <li>
  147. * Implementiere eine neue Methode im {@see ArticleDao} und nenne die Methode {@see saveArticle(Article $article)}.
  148. * </li>
  149. * </ul>
  150. *
  151. * @return void
  152. * @throws PageNotFoundException if article id not found
  153. * @throws BadRequestException if categoryName is invalid
  154. * @throws StatusException
  155. */
  156. function putDoArticle(int $articleId, ParamBody $body): void {
  157. $existingArticle = $this->articleDao->getArticleById($articleId);
  158. if ($existingArticle === null) {
  159. throw new PageNotFoundException();
  160. }
  161. $existingArticle = $this->updateArticle($body->parseJsonToHttpData(), $existingArticle);
  162. $this->beginTransaction();
  163. $this->articleDao->saveArticle($existingArticle);
  164. $this->commit();
  165. $this->sendJson($existingArticle);
  166. }
  167. /**
  168. * Löscht den {@see Article} mit der dazugehörigen Id.
  169. *
  170. * <ul>
  171. * <li>Mache eine neue Methode im {@see ArticleDao} und benenne sie "removeArticle(int articleId) </li>
  172. * <ul>
  173. *
  174. * @return void
  175. */
  176. function deleteDoArticle(int $articleId): void {
  177. $this->beginTransaction();
  178. $this->articleDao->removeArticle($articleId);
  179. $this->commit();
  180. }
  181. /**
  182. * @param $httpData
  183. * @return Article
  184. * @throws PageNotFoundException
  185. * @throws StatusException
  186. */
  187. private function updateArticle(HttpData $httpData, Article $article): Article {
  188. $article->setCategoryName($httpData->reqEnum('categoryName', ['sport', 'international', 'national']));
  189. $article->setTitle($httpData->reqString('title'));
  190. $article->setText($httpData->reqString('text'));
  191. $existingArticleGroup = $this->articleGroupDao->getArticleGroupById($httpData->reqInt('articleGroupId'));
  192. if ($existingArticleGroup === null){
  193. throw new PageNotFoundException();
  194. }
  195. $article->setArticleGroup($existingArticleGroup);
  196. return $article;
  197. }
  198. }