Completed
Push — SWP-2331 ( c6bc85...120e03 )
by
unknown
45s
created
src/SWP/Bundle/CoreBundle/Controller/ContentListItemController.php 1 patch
Indentation   +131 added lines, -131 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,78 +117,78 @@  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
     // Dispatch WebSocket update
@@ -198,66 +198,66 @@  discard block
 block discarded – undo
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,91 +275,91 @@  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
-      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_update');
364
-  }
364
+    }
365 365
 }
Please login to merge, or discard this patch.