Completed
Push — SWP-2331 ( 14ba03...598684 )
by
unknown
41s
created
src/SWP/Bundle/CoreBundle/Controller/ContentListItemController.php 1 patch
Indentation   +133 added lines, -133 removed lines patch added patch discarded remove patch
@@ -47,23 +47,23 @@  discard block
 block discarded – undo
47 47
 use Gos\Bundle\WebSocketBundle\Pusher\PusherRegistry;
48 48
 
49 49
 class ContentListItemController extends AbstractController {
50
-  private ContentListItemRepositoryInterface $contentListItemRepository;
51
-  private EntityManagerInterface $entityManager;
52
-  private ContentListServiceInterface $contentListService;
53
-  private EventDispatcherInterface $eventDispatcher;
54
-
55
-  /**
56
-   * @var PusherInterface
57
-   */
58
-  private $pusher;
59
-
60
-  /**
61
-   * @param ContentListItemRepositoryInterface $contentListItemRepository
62
-   * @param EntityManagerInterface $entityManager
63
-   * @param ContentListServiceInterface $contentListService
64
-   * @param EventDispatcherInterface $eventDispatcher
65
-   */
66
-  public function __construct(
50
+    private ContentListItemRepositoryInterface $contentListItemRepository;
51
+    private EntityManagerInterface $entityManager;
52
+    private ContentListServiceInterface $contentListService;
53
+    private EventDispatcherInterface $eventDispatcher;
54
+
55
+    /**
56
+     * @var PusherInterface
57
+     */
58
+    private $pusher;
59
+
60
+    /**
61
+     * @param ContentListItemRepositoryInterface $contentListItemRepository
62
+     * @param EntityManagerInterface $entityManager
63
+     * @param ContentListServiceInterface $contentListService
64
+     * @param EventDispatcherInterface $eventDispatcher
65
+     */
66
+    public function __construct(
67 67
     ContentListItemRepositoryInterface $contentListItemRepository,
68 68
     EntityManagerInterface $entityManager,
69 69
     ContentListServiceInterface $contentListService,
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
     string $invalidationCacheUrl,
72 72
     string $invalidationToken,
73 73
     PusherRegistry $pusher
74
-  ) {
74
+    ) {
75 75
     $this->contentListItemRepository = $contentListItemRepository;
76 76
     $this->entityManager = $entityManager;
77 77
     $this->contentListService = $contentListService;
@@ -79,31 +79,31 @@  discard block
 block discarded – undo
79 79
     $this->invalidationCacheUrl = $invalidationCacheUrl;
80 80
     $this->invalidationToken = $invalidationToken;
81 81
     $this->pusher = $pusher->getPusher('amqp');
82
-  }
82
+    }
83 83
 
84 84
 
85
-  /**
86
-   * @Route("/api/{version}/content/lists/{id}/items/", options={"expose"=true}, defaults={"version"="v2"}, methods={"GET"}, name="swp_api_core_list_items", requirements={"id"="\d+"})
87
-   */
88
-  public function listAction(Request $request, int $id): ResourcesListResponseInterface {
85
+    /**
86
+     * @Route("/api/{version}/content/lists/{id}/items/", options={"expose"=true}, defaults={"version"="v2"}, methods={"GET"}, name="swp_api_core_list_items", requirements={"id"="\d+"})
87
+     */
88
+    public function listAction(Request $request, int $id): ResourcesListResponseInterface {
89 89
     $sort = $request->query->all('sorting');
90 90
     if (empty($sort)) {
91
-      $sort = ['sticky' => 'desc'];
91
+        $sort = ['sticky' => 'desc'];
92 92
     }
93 93
 
94 94
     $items = $this->contentListItemRepository->getPaginatedByCriteria(
95
-      $this->eventDispatcher,
96
-      new Criteria([
95
+        $this->eventDispatcher,
96
+        new Criteria([
97 97
         'contentList' => $id,
98 98
         'sticky' => $request->query->get('sticky', ''),
99
-      ]),
100
-      $sort,
101
-      new PaginationData($request)
99
+        ]),
100
+        $sort,
101
+        new PaginationData($request)
102 102
     );
103 103
 
104 104
     $responseContext = new ResponseContext();
105 105
     $responseContext->setSerializationGroups(
106
-      [
106
+        [
107 107
         'Default',
108 108
         'api',
109 109
         'api_packages_list',
@@ -117,144 +117,144 @@  discard block
 block discarded – undo
117 117
         'api_image_details',
118 118
         'api_routes_list',
119 119
         'api_tenant_list',
120
-      ]
120
+        ]
121 121
     );
122 122
 
123 123
     return new ResourcesListResponse($items, $responseContext);
124
-  }
124
+    }
125 125
 
126
-  /**
127
-   * @Route("/api/{version}/content/lists/{listId}/items/{id}", options={"expose"=true}, defaults={"version"="v2"}, methods={"GET"}, name="swp_api_core_show_lists_item", requirements={"id"="\d+"})
128
-   */
129
-  public function getAction($listId, $id) {
126
+    /**
127
+     * @Route("/api/{version}/content/lists/{listId}/items/{id}", options={"expose"=true}, defaults={"version"="v2"}, methods={"GET"}, name="swp_api_core_show_lists_item", requirements={"id"="\d+"})
128
+     */
129
+    public function getAction($listId, $id) {
130 130
     return new SingleResourceResponse($this->findOr404($listId, $id));
131
-  }
131
+    }
132 132
 
133
-  /**
134
-   * @Route("/api/{version}/content/lists/{listId}/items/{id}", options={"expose"=true}, defaults={"version"="v2"}, methods={"PATCH"}, name="swp_api_core_update_lists_item", requirements={"id"="\d+", "listId"="\d+"})
135
-   */
136
-  public function updateAction(
133
+    /**
134
+     * @Route("/api/{version}/content/lists/{listId}/items/{id}", options={"expose"=true}, defaults={"version"="v2"}, methods={"PATCH"}, name="swp_api_core_update_lists_item", requirements={"id"="\d+", "listId"="\d+"})
135
+     */
136
+    public function updateAction(
137 137
     Request $request,
138 138
     FormFactoryInterface $formFactory,
139 139
     $listId,
140 140
     $id
141
-  ): SingleResourceResponseInterface {
141
+    ): SingleResourceResponseInterface {
142 142
     $contentListItem = $this->findOr404($listId, $id);
143 143
     $form = $formFactory->createNamed(
144
-      '',
145
-      ContentListItemType::class,
146
-      $contentListItem,
147
-      ['method' => $request->getMethod()]
144
+        '',
145
+        ContentListItemType::class,
146
+        $contentListItem,
147
+        ['method' => $request->getMethod()]
148 148
     );
149 149
 
150 150
     $form->handleRequest($request);
151 151
 
152 152
     if ($form->isSubmitted() && $form->isValid()) {
153
-      $contentListItem->getContentList()->setUpdatedAt(new DateTime());
153
+        $contentListItem->getContentList()->setUpdatedAt(new DateTime());
154 154
 
155
-      if (null !== $contentListItem->getStickyPosition()) {
155
+        if (null !== $contentListItem->getStickyPosition()) {
156 156
         $contentListItem->setPosition($contentListItem->getStickyPosition());
157
-      }
157
+        }
158 158
 
159
-      $this->entityManager->flush();
160
-      ContentListController::invalidateCache(
159
+        $this->entityManager->flush();
160
+        ContentListController::invalidateCache(
161 161
         $this->invalidationCacheUrl,
162 162
         $this->invalidationToken,
163 163
         [
164
-          'id' => $contentListItem->getContentList()->getId(),
165
-          'name' => $contentListItem->getContentList()->getName(),
166
-          'type' => $contentListItem->getContentList()->getType(),
167
-          'action' => 'CREATE'
164
+            'id' => $contentListItem->getContentList()->getId(),
165
+            'name' => $contentListItem->getContentList()->getName(),
166
+            'type' => $contentListItem->getContentList()->getType(),
167
+            'action' => 'CREATE'
168 168
         ]
169
-      );
169
+        );
170 170
 
171
-      return new SingleResourceResponse($contentListItem);
171
+        return new SingleResourceResponse($contentListItem);
172 172
     }
173 173
 
174 174
     return new SingleResourceResponse($form, new ResponseContext(400));
175
-  }
175
+    }
176 176
 
177
-  /**
178
-   * @Route("/api/{version}/content/lists/{listId}/items/", options={"expose"=true}, defaults={"version"="v2"}, methods={"PATCH"}, name="swp_api_core_batch_update_lists_item", requirements={"listId"="\d+"})
179
-   */
180
-  public function batchUpdateAction(
177
+    /**
178
+     * @Route("/api/{version}/content/lists/{listId}/items/", options={"expose"=true}, defaults={"version"="v2"}, methods={"PATCH"}, name="swp_api_core_batch_update_lists_item", requirements={"listId"="\d+"})
179
+     */
180
+    public function batchUpdateAction(
181 181
     Request                        $request,
182 182
     FormFactoryInterface           $formFactory,
183 183
     ContentListRepositoryInterface $contentListRepository,
184 184
     ArticleRepositoryInterface     $articleRepository,
185 185
     EventDispatcherInterface       $eventDispatcher,
186 186
     int                            $listId
187
-  ): SingleResourceResponseInterface {
187
+    ): SingleResourceResponseInterface {
188 188
     /** @var ContentListInterface $list */
189 189
     $list = $contentListRepository->findOneBy(['id' => $listId]);
190 190
     if (null === $list) {
191
-      throw new NotFoundHttpException(sprintf('Content list with id "%s" was not found.', $list));
191
+        throw new NotFoundHttpException(sprintf('Content list with id "%s" was not found.', $list));
192 192
     }
193 193
 
194 194
     $form = $formFactory->createNamed('', ContentListItemsType::class, [], ['method' => $request->getMethod()]);
195 195
 
196 196
     $form->handleRequest($request);
197 197
     if ($form->isSubmitted() && $form->isValid()) {
198
-      $data = $form->getData();
199
-      $updatedAt = DateTime::createFromFormat(DateTime::RFC3339, $data['updatedAt'], new DateTimeZone('UTC'));
200
-      $updatedAt->setTimezone(new DateTimeZone('UTC'));
201
-      $listUpdatedAt = $list->getUpdatedAt();
202
-      $listUpdatedAt->setTimezone(new DateTimeZone('UTC'));
203
-      if ($updatedAt < $listUpdatedAt) {
198
+        $data = $form->getData();
199
+        $updatedAt = DateTime::createFromFormat(DateTime::RFC3339, $data['updatedAt'], new DateTimeZone('UTC'));
200
+        $updatedAt->setTimezone(new DateTimeZone('UTC'));
201
+        $listUpdatedAt = $list->getUpdatedAt();
202
+        $listUpdatedAt->setTimezone(new DateTimeZone('UTC'));
203
+        if ($updatedAt < $listUpdatedAt) {
204 204
         throw new ConflictHttpException('List was already updated');
205
-      }
205
+        }
206 206
 
207
-      $updatedArticles = [];
208
-      $updatedItemsInvalidateCache = [];
209
-      /** @var ContentListAction $item */
210
-      foreach ($data['items'] as $item) {
207
+        $updatedArticles = [];
208
+        $updatedItemsInvalidateCache = [];
209
+        /** @var ContentListAction $item */
210
+        foreach ($data['items'] as $item) {
211 211
         $position = $item->getPosition();
212 212
         $isSticky = $item->isSticky();
213 213
         $contentId = $item->getContentId();
214 214
 
215 215
         $updatedItemsInvalidateCache[] = [
216
-          'id' => $contentId,
217
-          'action' => $item->getAction(),
218
-          'sticky' => $item->isSticky(),
219
-          'postition' => $item->getPosition()
216
+            'id' => $contentId,
217
+            'action' => $item->getAction(),
218
+            'sticky' => $item->isSticky(),
219
+            'postition' => $item->getPosition()
220 220
         ];
221 221
 
222 222
 
223 223
         switch ($item->getAction()) {
224
-          case ContentListAction::ACTION_MOVE:
224
+            case ContentListAction::ACTION_MOVE:
225 225
             $updated = false;
226 226
             $contentListItem = $this->findByContentOr404($list, $contentId);
227 227
 
228 228
             if ($position !== $contentListItem->getPosition()) {
229
-              $this->ensureThereIsNoItemOnPositionOrThrow409(
229
+                $this->ensureThereIsNoItemOnPositionOrThrow409(
230 230
                 $listId,
231 231
                 $position,
232 232
                 $isSticky,
233 233
                 ContentListAction::ACTION_MOVE
234
-              );
235
-              $contentListItem->setPosition($position);
236
-              $updated = true;
234
+                );
235
+                $contentListItem->setPosition($position);
236
+                $updated = true;
237 237
             }
238 238
 
239 239
             if ($isSticky !== $contentListItem->getStickyPosition()) {
240
-              $this->contentListService->toggleStickOnItemPosition($contentListItem, $isSticky, $position);
241
-              $updated = true;
240
+                $this->contentListService->toggleStickOnItemPosition($contentListItem, $isSticky, $position);
241
+                $updated = true;
242 242
             }
243 243
 
244 244
             if ($updated) {
245
-              $list->setUpdatedAt(new DateTime('now'));
246
-              $this->entityManager->flush();
245
+                $list->setUpdatedAt(new DateTime('now'));
246
+                $this->entityManager->flush();
247 247
             }
248 248
 
249 249
             $updatedArticles[$contentId] = $contentListItem->getContent();
250 250
 
251 251
             break;
252
-          case ContentListAction::ACTION_ADD:
252
+            case ContentListAction::ACTION_ADD:
253 253
             $this->ensureThereIsNoItemOnPositionOrThrow409(
254
-              $listId,
255
-              $position,
256
-              $isSticky,
257
-              ContentListAction::ACTION_ADD
254
+                $listId,
255
+                $position,
256
+                $isSticky,
257
+                ContentListAction::ACTION_ADD
258 258
             );
259 259
 
260 260
             $object = $articleRepository->findOneById($contentId);
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
             $updatedArticles[$contentId] = $contentListItem->getContent();
264 264
 
265 265
             break;
266
-          case ContentListAction::ACTION_DELETE:
266
+            case ContentListAction::ACTION_DELETE:
267 267
             $contentListItem = $this->findByContentOr404($list, $contentId);
268 268
             $this->entityManager->remove($contentListItem);
269 269
             $list->setUpdatedAt(new DateTime('now'));
@@ -272,94 +272,94 @@  discard block
 block discarded – undo
272 272
 
273 273
             break;
274 274
         }
275
-      }
275
+        }
276 276
 
277
-      $this->contentListService->repositionStickyItems($list);
277
+        $this->contentListService->repositionStickyItems($list);
278 278
 
279
-      foreach ($updatedArticles as $updatedArticle) {
279
+        foreach ($updatedArticles as $updatedArticle) {
280 280
         $eventDispatcher->dispatch(new ArticleEvent(
281
-          $updatedArticle,
282
-          $updatedArticle->getPackage(),
283
-          ArticleEvents::POST_UPDATE
281
+            $updatedArticle,
282
+            $updatedArticle->getPackage(),
283
+            ArticleEvents::POST_UPDATE
284 284
         ), ArticleEvents::POST_UPDATE);
285
-      }
286
-      ContentListController::invalidateCache(
285
+        }
286
+        ContentListController::invalidateCache(
287 287
         $this->invalidationCacheUrl,
288 288
         $this->invalidationToken,
289 289
         [
290
-          'id' => $list->getId(),
291
-          'name' => $list->getName(),
292
-          'type' => $list->getType(),
293
-          'action' => 'BATCH-UPDATE',
294
-          'items' => $updatedItemsInvalidateCache
290
+            'id' => $list->getId(),
291
+            'name' => $list->getName(),
292
+            'type' => $list->getType(),
293
+            'action' => 'BATCH-UPDATE',
294
+            'items' => $updatedItemsInvalidateCache
295 295
         ]
296
-      );
296
+        );
297 297
 
298
-      // Dispatch WebSocket update
299
-      $this->dispatchWebSocketUpdate('Manual list updated', 'BATCH-UPDATE');
298
+        // Dispatch WebSocket update
299
+        $this->dispatchWebSocketUpdate('Manual list updated', 'BATCH-UPDATE');
300 300
 
301
-      return new SingleResourceResponse($list, new ResponseContext(201));
301
+        return new SingleResourceResponse($list, new ResponseContext(201));
302 302
     }
303 303
 
304 304
     return new SingleResourceResponse($form, new ResponseContext(400));
305
-  }
305
+    }
306 306
 
307
-  private function findByContentOr404($listId, $contentId): ContentListItemInterface {
307
+    private function findByContentOr404($listId, $contentId): ContentListItemInterface {
308 308
     /** @var ContentListItemInterface $listItem */
309 309
     $listItem = $this->contentListItemRepository->findOneBy([
310
-      'contentList' => $listId,
311
-      'content' => $contentId,
310
+        'contentList' => $listId,
311
+        'content' => $contentId,
312 312
     ]);
313 313
 
314 314
     if (null === $listItem) {
315
-      throw new NotFoundHttpException(sprintf('Content list item with content_id "%s" was not found on that list. If You want to add new item - use action type "add".', $contentId));
315
+        throw new NotFoundHttpException(sprintf('Content list item with content_id "%s" was not found on that list. If You want to add new item - use action type "add".', $contentId));
316 316
     }
317 317
 
318 318
     return $listItem;
319
-  }
319
+    }
320 320
 
321
-  private function findOr404($listId, $id): ContentListItemInterface {
321
+    private function findOr404($listId, $id): ContentListItemInterface {
322 322
     /** @var ContentListItemInterface $listItem */
323 323
     $listItem = $this->contentListItemRepository->findOneBy([
324
-      'contentList' => $listId,
325
-      'id' => $id,
324
+        'contentList' => $listId,
325
+        'id' => $id,
326 326
     ]);
327 327
 
328 328
     if (null === $listItem) {
329
-      throw new NotFoundHttpException(sprintf('Content list item with id "%s" was not found.', $id));
329
+        throw new NotFoundHttpException(sprintf('Content list item with id "%s" was not found.', $id));
330 330
     }
331 331
 
332 332
     return $listItem;
333
-  }
333
+    }
334 334
 
335
-  private function ensureThereIsNoItemOnPositionOrThrow409(
335
+    private function ensureThereIsNoItemOnPositionOrThrow409(
336 336
     int $listId,
337 337
     int $position,
338 338
     bool $isSticky,
339 339
     string $action
340
-  ): void {
340
+    ): void {
341 341
     $existingContentListItem = $this->contentListService->isAnyItemPinnedOnPosition($listId, $position);
342 342
 
343 343
     if (!$existingContentListItem && !$isSticky) {
344
-      return;
344
+        return;
345 345
     }
346 346
 
347 347
     if ($existingContentListItem && $existingContentListItem->isSticky()) {
348
-      throw new ConflictHttpException('There is already an item pinned on that position. Unpin it first.');
348
+        throw new ConflictHttpException('There is already an item pinned on that position. Unpin it first.');
349 349
     }
350 350
 
351 351
     if ($action === ContentListAction::ACTION_MOVE && $isSticky) {
352
-      throw new ConflictHttpException('Cannot move pinned item. Unpin it first.');
352
+        throw new ConflictHttpException('Cannot move pinned item. Unpin it first.');
353
+    }
353 354
     }
354
-  }
355 355
 
356
-  private function dispatchWebSocketUpdate(string $message, string $action): void {
356
+    private function dispatchWebSocketUpdate(string $message, string $action): void {
357 357
     $pushData = [
358
-      'message' => $message,
359
-      'action' => $action,
360
-      'timestamp' => (new \DateTime())->format('c')
358
+        'message' => $message,
359
+        'action' => $action,
360
+        'timestamp' => (new \DateTime())->format('c')
361 361
     ];
362 362
 
363 363
     $this->pusher->push($pushData, 'content_list_topic');
364
-  }
364
+    }
365 365
 }
Please login to merge, or discard this patch.