Completed
Push — SWP-2331 ( f5a1b8...cfb7b7 )
by
unknown
49s
created
src/SWP/Bundle/CoreBundle/Controller/ContentListItemController.php 1 patch
Indentation   +136 added lines, -136 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,147 +117,147 @@  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
-      // Dispatch WebSocket update
172
-      $this->dispatchWebSocketUpdate('Content list item updated', 'UPDATE', $contentListItem->getContentList()->getId());
171
+        // Dispatch WebSocket update
172
+        $this->dispatchWebSocketUpdate('Content list item updated', 'UPDATE', $contentListItem->getContentList()->getId());
173 173
 
174
-      return new SingleResourceResponse($contentListItem);
174
+        return new SingleResourceResponse($contentListItem);
175 175
     }
176 176
 
177 177
     return new SingleResourceResponse($form, new ResponseContext(400));
178
-  }
178
+    }
179 179
 
180
-  /**
181
-   * @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+"})
182
-   */
183
-  public function batchUpdateAction(
180
+    /**
181
+     * @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+"})
182
+     */
183
+    public function batchUpdateAction(
184 184
     Request                        $request,
185 185
     FormFactoryInterface           $formFactory,
186 186
     ContentListRepositoryInterface $contentListRepository,
187 187
     ArticleRepositoryInterface     $articleRepository,
188 188
     EventDispatcherInterface       $eventDispatcher,
189 189
     int                            $listId
190
-  ): SingleResourceResponseInterface {
190
+    ): SingleResourceResponseInterface {
191 191
     /** @var ContentListInterface $list */
192 192
     $list = $contentListRepository->findOneBy(['id' => $listId]);
193 193
     if (null === $list) {
194
-      throw new NotFoundHttpException(sprintf('Content list with id "%s" was not found.', $list));
194
+        throw new NotFoundHttpException(sprintf('Content list with id "%s" was not found.', $list));
195 195
     }
196 196
 
197 197
     $form = $formFactory->createNamed('', ContentListItemsType::class, [], ['method' => $request->getMethod()]);
198 198
 
199 199
     $form->handleRequest($request);
200 200
     if ($form->isSubmitted() && $form->isValid()) {
201
-      $data = $form->getData();
202
-      $updatedAt = DateTime::createFromFormat(DateTime::RFC3339, $data['updatedAt'], new DateTimeZone('UTC'));
203
-      $updatedAt->setTimezone(new DateTimeZone('UTC'));
204
-      $listUpdatedAt = $list->getUpdatedAt();
205
-      $listUpdatedAt->setTimezone(new DateTimeZone('UTC'));
206
-      if ($updatedAt < $listUpdatedAt) {
201
+        $data = $form->getData();
202
+        $updatedAt = DateTime::createFromFormat(DateTime::RFC3339, $data['updatedAt'], new DateTimeZone('UTC'));
203
+        $updatedAt->setTimezone(new DateTimeZone('UTC'));
204
+        $listUpdatedAt = $list->getUpdatedAt();
205
+        $listUpdatedAt->setTimezone(new DateTimeZone('UTC'));
206
+        if ($updatedAt < $listUpdatedAt) {
207 207
         throw new ConflictHttpException('List was already updated');
208
-      }
208
+        }
209 209
 
210
-      $updatedArticles = [];
211
-      $updatedItemsInvalidateCache = [];
212
-      /** @var ContentListAction $item */
213
-      foreach ($data['items'] as $item) {
210
+        $updatedArticles = [];
211
+        $updatedItemsInvalidateCache = [];
212
+        /** @var ContentListAction $item */
213
+        foreach ($data['items'] as $item) {
214 214
         $position = $item->getPosition();
215 215
         $isSticky = $item->isSticky();
216 216
         $contentId = $item->getContentId();
217 217
 
218 218
         $updatedItemsInvalidateCache[] = [
219
-          'id' => $contentId,
220
-          'action' => $item->getAction(),
221
-          'sticky' => $item->isSticky(),
222
-          'postition' => $item->getPosition()
219
+            'id' => $contentId,
220
+            'action' => $item->getAction(),
221
+            'sticky' => $item->isSticky(),
222
+            'postition' => $item->getPosition()
223 223
         ];
224 224
 
225 225
 
226 226
         switch ($item->getAction()) {
227
-          case ContentListAction::ACTION_MOVE:
227
+            case ContentListAction::ACTION_MOVE:
228 228
             $updated = false;
229 229
             $contentListItem = $this->findByContentOr404($list, $contentId);
230 230
 
231 231
             if ($position !== $contentListItem->getPosition()) {
232
-              $this->ensureThereIsNoItemOnPositionOrThrow409(
232
+                $this->ensureThereIsNoItemOnPositionOrThrow409(
233 233
                 $listId,
234 234
                 $position,
235 235
                 $isSticky,
236 236
                 ContentListAction::ACTION_MOVE
237
-              );
238
-              $contentListItem->setPosition($position);
239
-              $updated = true;
237
+                );
238
+                $contentListItem->setPosition($position);
239
+                $updated = true;
240 240
             }
241 241
 
242 242
             if ($isSticky !== $contentListItem->getStickyPosition()) {
243
-              $this->contentListService->toggleStickOnItemPosition($contentListItem, $isSticky, $position);
244
-              $updated = true;
243
+                $this->contentListService->toggleStickOnItemPosition($contentListItem, $isSticky, $position);
244
+                $updated = true;
245 245
             }
246 246
 
247 247
             if ($updated) {
248
-              $list->setUpdatedAt(new DateTime('now'));
249
-              $this->entityManager->flush();
248
+                $list->setUpdatedAt(new DateTime('now'));
249
+                $this->entityManager->flush();
250 250
             }
251 251
 
252 252
             $updatedArticles[$contentId] = $contentListItem->getContent();
253 253
 
254 254
             break;
255
-          case ContentListAction::ACTION_ADD:
255
+            case ContentListAction::ACTION_ADD:
256 256
             $this->ensureThereIsNoItemOnPositionOrThrow409(
257
-              $listId,
258
-              $position,
259
-              $isSticky,
260
-              ContentListAction::ACTION_ADD
257
+                $listId,
258
+                $position,
259
+                $isSticky,
260
+                ContentListAction::ACTION_ADD
261 261
             );
262 262
 
263 263
             $object = $articleRepository->findOneById($contentId);
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
             $updatedArticles[$contentId] = $contentListItem->getContent();
267 267
 
268 268
             break;
269
-          case ContentListAction::ACTION_DELETE:
269
+            case ContentListAction::ACTION_DELETE:
270 270
             $contentListItem = $this->findByContentOr404($list, $contentId);
271 271
             $this->entityManager->remove($contentListItem);
272 272
             $list->setUpdatedAt(new DateTime('now'));
@@ -275,98 +275,98 @@  discard block
 block discarded – undo
275 275
 
276 276
             break;
277 277
         }
278
-      }
278
+        }
279 279
 
280
-      $this->contentListService->repositionStickyItems($list);
280
+        $this->contentListService->repositionStickyItems($list);
281 281
 
282
-      foreach ($updatedArticles as $updatedArticle) {
282
+        foreach ($updatedArticles as $updatedArticle) {
283 283
         $eventDispatcher->dispatch(new ArticleEvent(
284
-          $updatedArticle,
285
-          $updatedArticle->getPackage(),
286
-          ArticleEvents::POST_UPDATE
284
+            $updatedArticle,
285
+            $updatedArticle->getPackage(),
286
+            ArticleEvents::POST_UPDATE
287 287
         ), ArticleEvents::POST_UPDATE);
288
-      }
289
-      ContentListController::invalidateCache(
288
+        }
289
+        ContentListController::invalidateCache(
290 290
         $this->invalidationCacheUrl,
291 291
         $this->invalidationToken,
292 292
         [
293
-          'id' => $list->getId(),
294
-          'name' => $list->getName(),
295
-          'type' => $list->getType(),
296
-          'action' => 'BATCH-UPDATE',
297
-          'items' => $updatedItemsInvalidateCache
293
+            'id' => $list->getId(),
294
+            'name' => $list->getName(),
295
+            'type' => $list->getType(),
296
+            'action' => 'BATCH-UPDATE',
297
+            'items' => $updatedItemsInvalidateCache
298 298
         ]
299
-      );
299
+        );
300 300
 
301
-      // Dispatch WebSocket update
302
-      $this->dispatchWebSocketUpdate('Manual list updated', 'BATCH-UPDATE', $list->getId());
301
+        // Dispatch WebSocket update
302
+        $this->dispatchWebSocketUpdate('Manual list updated', 'BATCH-UPDATE', $list->getId());
303 303
 
304
-      return new SingleResourceResponse($list, new ResponseContext(201));
304
+        return new SingleResourceResponse($list, new ResponseContext(201));
305 305
     }
306 306
 
307 307
     return new SingleResourceResponse($form, new ResponseContext(400));
308
-  }
308
+    }
309 309
 
310
-  private function findByContentOr404($listId, $contentId): ContentListItemInterface {
310
+    private function findByContentOr404($listId, $contentId): ContentListItemInterface {
311 311
     /** @var ContentListItemInterface $listItem */
312 312
     $listItem = $this->contentListItemRepository->findOneBy([
313
-      'contentList' => $listId,
314
-      'content' => $contentId,
313
+        'contentList' => $listId,
314
+        'content' => $contentId,
315 315
     ]);
316 316
 
317 317
     if (null === $listItem) {
318
-      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));
318
+        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));
319 319
     }
320 320
 
321 321
     return $listItem;
322
-  }
322
+    }
323 323
 
324
-  private function findOr404($listId, $id): ContentListItemInterface {
324
+    private function findOr404($listId, $id): ContentListItemInterface {
325 325
     /** @var ContentListItemInterface $listItem */
326 326
     $listItem = $this->contentListItemRepository->findOneBy([
327
-      'contentList' => $listId,
328
-      'id' => $id,
327
+        'contentList' => $listId,
328
+        'id' => $id,
329 329
     ]);
330 330
 
331 331
     if (null === $listItem) {
332
-      throw new NotFoundHttpException(sprintf('Content list item with id "%s" was not found.', $id));
332
+        throw new NotFoundHttpException(sprintf('Content list item with id "%s" was not found.', $id));
333 333
     }
334 334
 
335 335
     return $listItem;
336
-  }
336
+    }
337 337
 
338
-  private function ensureThereIsNoItemOnPositionOrThrow409(
338
+    private function ensureThereIsNoItemOnPositionOrThrow409(
339 339
     int $listId,
340 340
     int $position,
341 341
     bool $isSticky,
342 342
     string $action
343
-  ): void {
343
+    ): void {
344 344
     $existingContentListItem = $this->contentListService->isAnyItemPinnedOnPosition($listId, $position);
345 345
 
346 346
     if (!$existingContentListItem && !$isSticky) {
347
-      return;
347
+        return;
348 348
     }
349 349
 
350 350
     if ($existingContentListItem && $existingContentListItem->isSticky()) {
351
-      throw new ConflictHttpException('There is already an item pinned on that position. Unpin it first.');
351
+        throw new ConflictHttpException('There is already an item pinned on that position. Unpin it first.');
352 352
     }
353 353
 
354 354
     if ($action === ContentListAction::ACTION_MOVE && $isSticky) {
355
-      throw new ConflictHttpException('Cannot move pinned item. Unpin it first.');
355
+        throw new ConflictHttpException('Cannot move pinned item. Unpin it first.');
356
+    }
356 357
     }
357
-  }
358 358
 
359
-  private function dispatchWebSocketUpdate(string $message, string $action, ?int $contentListId = null): void {
359
+    private function dispatchWebSocketUpdate(string $message, string $action, ?int $contentListId = null): void {
360 360
     $pushData = [
361
-      'message' => $message,
362
-      'action' => $action,
363
-      'timestamp' => (new \DateTime())->format('c')
361
+        'message' => $message,
362
+        'action' => $action,
363
+        'timestamp' => (new \DateTime())->format('c')
364 364
     ];
365 365
 
366 366
     if ($contentListId !== null) {
367
-      $pushData['content_list_id'] = $contentListId;
367
+        $pushData['content_list_id'] = $contentListId;
368 368
     }
369 369
 
370 370
     $this->pusher->push($pushData, 'content_list_update');
371
-  }
371
+    }
372 372
 }
Please login to merge, or discard this patch.