em = $em; $this->pdo = $em->getPdo(); } /** * Gebe alle {@see Article}-Objekte, nach id absteigend sortiert, zurück. * * @return Article[] */ function getArticles(): array { $criteria = $this->em->createSimpleCriteria(Article::getClass(), order: ['id' => 'DESC']); return $criteria->toQuery()->fetchArray(); } /** * Gebe alle {@see Article} zurück, welche dem übergebenen Kategorienamen entsprechen. * * @return array */ function getArticlesByCategoryName(string $categoryName): array { $criteria = $this->em->createSimpleCriteria(Article::getClass(), ['categoryName' => $categoryName ], order: ['id' => 'DESC']); return $criteria->toQuery()->fetchArray(); } /** * Gebe den {@see Article} mit der enstprechenden ID zurück. * * @param int $id * @return Article|null */ function getArticleById(int $id): ?Article { return $this->em->find(Article::getClass(), $id); $criteria = $this->em->createSimpleCriteria(Article::getClass(),['id'=> $id]); return $criteria->toQuery()->fetchSingle(); } function saveArticle(Article $article) { $this->em->persist($article); } function removeArticle(int $id ) { $article = $this->em->find(Article::getClass(), $id); $this->em->remove($article); } //function getArticleRowById(int $id): array { // $this->pdo->prepare('SELECT...'), //} function BadRequestExceptionIfs(?ParamBody $body, ?int $articleId) { $bodyData = $body->parseJson(); if ($_SERVER['REQUEST_METHOD'] === 'POST') { if($body->getValue() === "") { throw new BadRequestException('Body cant be empty'); } $pattern = '/^{/'; $pattern2 = '/}$/'; if(preg_match($pattern2, $body) == 0 || preg_match($pattern, $body) == 0) { throw new BadRequestException('Json is invalid'); } if(!isset($bodyData['title'])) { throw new BadRequestException('Title must be set'); } if (strlen($bodyData['title']) > 255){ throw new BadRequestException('Title is too long'); } if (!isset($bodyData['categoryName'])) { throw new BadRequestException('The Category must be international, national or sport'); } if(!in_array($bodyData['categoryName'], ['sport','international','national'])) { throw new BadRequestException('The Category must be international, national or sport'); } if(!isset($bodyData['text'])) { throw new BadRequestException('Article must contain a text'); } if (strlen($bodyData['text']) > 12000){ throw new BadRequestException('Text is too long'); } } else if ($_SERVER['REQUEST_METHOD'] === 'PUT') { $article = $this->getArticleById($articleId); if($article === null) { throw new PageNotFoundException('Article not found'); } if(isset($bodyData['categoryName'])) { if(!in_array($bodyData['categoryName'],['sport','international','national'])) { throw new BadRequestException('The Category must be international, national or sport'); $article->setCategoryName($bodyData['categoryName']); } if(isset($bodyData['text'])) { $article->setText($bodyData['text']); } if(isset($bodyData['title'])) { $article->setTitle($bodyData['title']); } } } } }