Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.30% covered (success)
91.30%
84 / 92
77.78% covered (warning)
77.78%
7 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
NewsEndpointTrait
91.30% covered (success)
91.30%
84 / 92
77.78% covered (warning)
77.78%
7 / 9
29.55
0.00% covered (danger)
0.00%
0 / 1
 getEntityData
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
5
 updateEntityWithData
95.00% covered (success)
95.00%
38 / 40
0.00% covered (danger)
0.00%
0 / 1
6
 persistUploads
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 editUploads
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getEntityById
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 getFormat
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 getFormatForApi
25.00% covered (danger)
25.00%
2 / 8
0.00% covered (danger)
0.00%
0 / 1
35.00
 getTagsForDb
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getTagsForApi
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3namespace Olz\News\Endpoints;
4
5use Olz\Common\Utils\WithUtilsTrait;
6use Olz\Entity\News\NewsEntry;
7use Olz\Entity\Roles\Role;
8use Olz\Entity\Termine\Termin;
9use Olz\Entity\Users\User;
10use PhpTypeScriptApi\HttpError;
11use PhpTypeScriptApi\PhpStan\IsoDateTime;
12
13/**
14 * @phpstan-type OlzNewsId int
15 * @phpstan-type OlzNewsData array{
16 *   format: OlzNewsFormat,
17 *   authorUserId?: ?int,
18 *   authorRoleId?: ?int,
19 *   authorName?: ?non-empty-string,
20 *   authorEmail?: ?non-empty-string,
21 *   publishAt?: ?IsoDateTime,
22 *   title: non-empty-string,
23 *   teaser: string,
24 *   content: string,
25 *   externalUrl?: ?non-empty-string,
26 *   tags: array<non-empty-string>,
27 *   terminId?: ?int,
28 *   imageIds?: ?array<non-empty-string>,
29 *   fileIds: array<non-empty-string>,
30 * }
31 * @phpstan-type OlzNewsFormat 'aktuell'|'kaderblog'|'forum'|'galerie'|'video'|'anonymous'
32 */
33trait NewsEndpointTrait {
34    use WithUtilsTrait;
35
36    /** @return OlzNewsData */
37    public function getEntityData(NewsEntry $entity): array {
38        $author_name = $entity->getAuthorName();
39        $author_email = $entity->getAuthorEmail();
40        $published_date = $entity->getPublishedDate()->format('Y-m-d');
41        $published_time = $entity->getPublishedTime()?->format('H:i:s') ?? '00:00:00';
42        $tags_for_api = $this->getTagsForApi($entity->getTags());
43        $external_url = $entity->getExternalUrl();
44
45        $valid_image_ids = $this->uploadUtils()->getValidUploadIds($entity->getImageIds());
46        $file_ids = $entity->getStoredFileUploadIds();
47
48        return [
49            'format' => $this->getFormatForApi($entity),
50            'authorUserId' => $entity->getAuthorUser()?->getId(),
51            'authorRoleId' => $entity->getAuthorRole()?->getId(),
52            'authorName' => $author_name ? $author_name : null,
53            'authorEmail' => $author_email ? $author_email : null,
54            'publishAt' => new IsoDateTime("{$published_date} {$published_time}"),
55            'title' => $entity->getTitle() ?: '-',
56            'teaser' => $entity->getTeaser() ?? '',
57            'content' => $entity->getContent() ?? '',
58            'externalUrl' => $external_url ? $external_url : null,
59            'tags' => $tags_for_api,
60            'terminId' => $entity->getTermin()?->getId(),
61            'imageIds' => $valid_image_ids,
62            'fileIds' => $file_ids,
63        ];
64    }
65
66    /** @param OlzNewsData $input_data */
67    public function updateEntityWithData(NewsEntry $entity, array $input_data): void {
68        $user_repo = $this->entityManager()->getRepository(User::class);
69        $role_repo = $this->entityManager()->getRepository(Role::class);
70        $termin_repo = $this->entityManager()->getRepository(Termin::class);
71        $current_user = $this->authUtils()->getCurrentUser();
72        $now = new \DateTime($this->dateUtils()->getIsoNow());
73
74        $author_user_id = $input_data['authorUserId'] ?? null;
75        $author_user = $current_user;
76        if ($author_user_id) {
77            $author_user = $user_repo->findOneBy(['id' => $author_user_id]);
78        }
79
80        $author_role_id = $input_data['authorRoleId'] ?? null;
81        $author_role = null;
82        if ($author_role_id) {
83            $is_admin = $this->authUtils()->hasPermission('all');
84            $is_authenticated_role = $this->authUtils()->isRoleIdAuthenticated($author_role_id);
85            if (!$is_authenticated_role && !$is_admin) {
86                throw new HttpError(403, "Kein Zugriff auf Autor-Rolle!");
87            }
88            $author_role = $role_repo->findOneBy(['id' => $author_role_id]);
89        }
90
91        $termin_id = $input_data['terminId'] ?? null;
92        $termin = $termin_id
93            ? $termin_repo->findOneBy(['id' => $termin_id])
94            : null;
95
96        $publish_at = $input_data['publishAt'] ?? $now;
97
98        $tags_for_db = $this->getTagsForDb($input_data['tags']);
99        $valid_image_ids = $this->uploadUtils()->getValidUploadIds($input_data['imageIds'] ?? null);
100
101        $entity->setAuthorUser($author_user);
102        $entity->setAuthorRole($author_role);
103        $entity->setAuthorName($input_data['authorName'] ?? null);
104        $entity->setAuthorEmail($input_data['authorEmail'] ?? null);
105        $entity->setPublishedDate($publish_at);
106        $entity->setPublishedTime($publish_at);
107        $entity->setTitle($input_data['title']);
108        $entity->setTeaser($input_data['teaser']);
109        $entity->setContent($input_data['content']);
110        $entity->setExternalUrl($input_data['externalUrl'] ?? null);
111        $entity->setTags($tags_for_db);
112        $entity->setImageIds($valid_image_ids);
113        $entity->setTermin($termin);
114        $entity->setCounter(0);
115        $entity->setFormat($this->getFormat($input_data['format']));
116        $entity->setNewsletter(true);
117    }
118
119    /** @param OlzNewsData $input_data */
120    public function persistUploads(NewsEntry $entity, array $input_data): void {
121        $this->persistOlzImages($entity, $entity->getImageIds());
122        $this->persistOlzFiles($entity, $input_data['fileIds']);
123    }
124
125    public function editUploads(NewsEntry $entity): void {
126        $this->editOlzImages($entity, $entity->getImageIds());
127        $this->editOlzFiles($entity);
128    }
129
130    protected function getEntityById(int $id): NewsEntry {
131        $news_repo = $this->entityManager()->getRepository(NewsEntry::class);
132        $entity = $news_repo->findOneBy(['id' => $id]);
133        if (!$entity) {
134            throw new HttpError(404, "Nicht gefunden.");
135        }
136        return $entity;
137    }
138
139    // ---
140
141    protected function getFormat(string $format): string {
142        if ($format === 'anonymous') {
143            return 'forum';
144        }
145        return $format;
146    }
147
148    /** @return OlzNewsFormat */
149    protected function getFormatForApi(NewsEntry $entity): string {
150        switch ($entity->getFormat()) {
151            case 'aktuell': return 'aktuell';
152            case 'anonymous': return 'anonymous';
153            case 'forum': return 'forum';
154            case 'galerie': return 'galerie';
155            case 'kaderblog': return 'kaderblog';
156            case 'video': return 'video';
157            default: throw new \Exception("Unknown news format: {$entity->getFormat()} ({$entity})");
158        }
159    }
160
161    /** @param array<string> $tags */
162    protected function getTagsForDb(?array $tags): string {
163        return ' '.implode(' ', $tags ?? []).' ';
164    }
165
166    /** @return array<non-empty-string> */
167    protected function getTagsForApi(?string $tags): array {
168        $tags_string = $tags ?? '';
169        $tags_for_api = [];
170        foreach (explode(' ', $tags_string) as $tag) {
171            $trimmed = trim($tag);
172            if ($trimmed) {
173                $tags_for_api[] = $trimmed;
174            }
175        }
176        return $tags_for_api;
177    }
178}