CategoryForm.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace internship\model;
  3. use n2n\web\dispatch\Dispatchable;
  4. use internship\bo\NewsCategory;
  5. use n2n\web\dispatch\map\bind\BindingDefinition;
  6. use n2n\impl\web\dispatch\map\val\ValNotEmpty;
  7. use n2n\impl\web\dispatch\map\val\ValImageFile;
  8. use n2n\io\managed\File;
  9. use n2n\web\dispatch\map\MappingResult;
  10. use n2n\util\io\IoUtils;
  11. use n2n\web\http\PageNotFoundException;
  12. class CategoryForm implements Dispatchable {
  13. private NewsCategory $category;
  14. protected string $title;
  15. protected string $content;
  16. protected $imageFile;
  17. public function __construct(NewsCategory $category = null) {
  18. $this->title = '';
  19. $this->content = '';
  20. if ($category) {
  21. $this->title = $category->getTitle();
  22. $this->id = $category->getId();
  23. $this->content = $category->getContent();
  24. $this->category = $category;
  25. }
  26. }
  27. public function getTitle() {
  28. return $this->title;
  29. }
  30. public function setTitle(string $title) {
  31. $this->title = $title;
  32. }
  33. public function getImageFile() {
  34. return $this->imageFile;
  35. }
  36. public function setImageFile(File $imageFile = null) {
  37. $this->imageFile = $imageFile;
  38. }
  39. public function getContent() {
  40. return $this->content;
  41. }
  42. public function setContent(string $content) {
  43. $this->content = $content;
  44. }
  45. private function _mapping(MappingResult $mr) {
  46. $mr->setLabel('title', 'Titel');
  47. $mr->setLabel('content', 'Beschreibung');
  48. $mr->setLabel('imageFile', 'Bild');
  49. }
  50. private function _validation(BindingDefinition $bd) {
  51. $bd->val(array('content', 'title'), new ValNotEmpty());
  52. $bd->val('imageFile', new ValImageFile(true));
  53. }
  54. public function save(NewsDao $newsDao) {
  55. $category = $this->category ?? new NewsCategory();
  56. $category->setTitle($this->title);
  57. $category->setLead(substr_replace($this->content, "...", 50));
  58. $category->setContent($this->content);
  59. $category->setImageFile($this->imageFile);
  60. $category->setUrlPart(strtolower(IoUtils::stripSpecialChars($this->title)));
  61. $newsDao->saveCategory($category);
  62. }
  63. public function delete(NewsDao $newsDao) {
  64. if (!$this->category) {
  65. throw new PageNotFoundException('no id set');
  66. }
  67. $category = $this->category;
  68. $newsDao->deleteCategory($category);
  69. }
  70. }