Total Complexity | 91 |
Total Lines | 683 |
Duplicated Lines | 0 % |
Changes | 0 |
Complex classes like ResourceController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use ResourceController, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
55 | #[Route('/r')] |
||
56 | class ResourceController extends AbstractResourceController implements CourseControllerInterface |
||
57 | { |
||
58 | use ControllerTrait; |
||
59 | use CourseControllerTrait; |
||
60 | use GradebookControllerTrait; |
||
61 | use ResourceControllerTrait; |
||
62 | |||
63 | public function __construct( |
||
64 | private readonly UserHelper $userHelper, |
||
65 | private readonly ResourceNodeRepository $resourceNodeRepository, |
||
66 | private readonly ResourceFileRepository $resourceFileRepository |
||
67 | ) {} |
||
68 | |||
69 | #[Route(path: '/{tool}/{type}/{id}/disk_space', methods: ['GET', 'POST'], name: 'chamilo_core_resource_disk_space')] |
||
70 | public function diskSpace(Request $request): Response |
||
71 | { |
||
72 | $nodeId = $request->get('id'); |
||
73 | $repository = $this->getRepositoryFromRequest($request); |
||
74 | |||
75 | /** @var ResourceNode $resourceNode */ |
||
76 | $resourceNode = $repository->getResourceNodeRepository()->find($nodeId); |
||
77 | |||
78 | $this->denyAccessUnlessGranted( |
||
79 | ResourceNodeVoter::VIEW, |
||
80 | $resourceNode, |
||
81 | $this->trans('Unauthorised access to resource') |
||
82 | ); |
||
83 | |||
84 | $course = $this->getCourse(); |
||
85 | $totalSize = 0; |
||
86 | if (null !== $course) { |
||
87 | $totalSize = $course->getDiskQuota(); |
||
88 | } |
||
89 | |||
90 | $size = $repository->getResourceNodeRepository()->getSize( |
||
91 | $resourceNode, |
||
92 | $repository->getResourceType(), |
||
93 | $course |
||
94 | ); |
||
95 | |||
96 | $labels[] = $course->getTitle(); |
||
|
|||
97 | $data[] = $size; |
||
98 | $sessions = $course->getSessions(); |
||
99 | |||
100 | foreach ($sessions as $sessionRelCourse) { |
||
101 | $session = $sessionRelCourse->getSession(); |
||
102 | |||
103 | $labels[] = $course->getTitle().' - '.$session->getTitle(); |
||
104 | $size = $repository->getResourceNodeRepository()->getSize( |
||
105 | $resourceNode, |
||
106 | $repository->getResourceType(), |
||
107 | $course, |
||
108 | $session |
||
109 | ); |
||
110 | $data[] = $size; |
||
111 | } |
||
112 | |||
113 | /*$groups = $course->getGroups(); |
||
114 | foreach ($groups as $group) { |
||
115 | $labels[] = $course->getTitle().' - '.$group->getTitle(); |
||
116 | $size = $repository->getResourceNodeRepository()->getSize( |
||
117 | $resourceNode, |
||
118 | $repository->getResourceType(), |
||
119 | $course, |
||
120 | null, |
||
121 | $group |
||
122 | ); |
||
123 | $data[] = $size; |
||
124 | }*/ |
||
125 | |||
126 | $used = array_sum($data); |
||
127 | $labels[] = $this->trans('Free'); |
||
128 | $data[] = $totalSize - $used; |
||
129 | |||
130 | return $this->render( |
||
131 | '@ChamiloCore/Resource/disk_space.html.twig', |
||
132 | [ |
||
133 | 'resourceNode' => $resourceNode, |
||
134 | 'labels' => $labels, |
||
135 | 'data' => $data, |
||
136 | ] |
||
137 | ); |
||
138 | } |
||
139 | |||
140 | /** |
||
141 | * View file of a resource node. |
||
142 | */ |
||
143 | #[Route('/{tool}/{type}/{id}/view', name: 'chamilo_core_resource_view', methods: ['GET'])] |
||
209 | } |
||
210 | |||
211 | /** |
||
212 | * Redirect resource to link. |
||
213 | * |
||
214 | * @return RedirectResponse|void |
||
215 | */ |
||
216 | #[Route('/{tool}/{type}/{id}/link', name: 'chamilo_core_resource_link', methods: ['GET'])] |
||
217 | public function link(Request $request, RouterInterface $router, CLinkRepository $cLinkRepository): RedirectResponse |
||
218 | { |
||
219 | $tool = $request->get('tool'); |
||
220 | $type = $request->get('type'); |
||
221 | $id = $request->get('id'); |
||
222 | $resourceNode = $this->getResourceNodeRepository()->find($id); |
||
223 | |||
224 | if (null === $resourceNode) { |
||
225 | throw new FileNotFoundException('Resource not found'); |
||
226 | } |
||
227 | |||
228 | if ('course_tool' === $tool && 'links' === $type) { |
||
229 | $cLink = $cLinkRepository->findOneBy(['resourceNode' => $resourceNode]); |
||
230 | if ($cLink) { |
||
231 | $url = $cLink->getUrl(); |
||
232 | |||
233 | return $this->redirect($url); |
||
234 | } |
||
235 | |||
236 | throw new FileNotFoundException('CLink not found for the given resource node'); |
||
237 | } else { |
||
238 | $repo = $this->getRepositoryFromRequest($request); |
||
239 | if ($repo instanceof ResourceWithLinkInterface) { |
||
240 | $resource = $repo->getResourceFromResourceNode($resourceNode->getId()); |
||
241 | $url = $repo->getLink($resource, $router, $this->getCourseUrlQueryToArray()); |
||
242 | |||
243 | return $this->redirect($url); |
||
244 | } |
||
245 | |||
246 | $this->abort('No redirect'); |
||
247 | } |
||
248 | } |
||
249 | |||
250 | /** |
||
251 | * Download file of a resource node. |
||
252 | */ |
||
253 | #[Route('/{tool}/{type}/{id}/download', name: 'chamilo_core_resource_download', methods: ['GET'])] |
||
369 | } |
||
370 | |||
371 | #[Route('/{tool}/{type}/{id}/change_visibility', name: 'chamilo_core_resource_change_visibility', methods: ['POST'])] |
||
372 | public function changeVisibility( |
||
373 | Request $request, |
||
374 | EntityManagerInterface $entityManager, |
||
375 | SerializerInterface $serializer, |
||
376 | Security $security, |
||
377 | ): Response { |
||
378 | $user = $security->getUser(); |
||
379 | $isAdmin = ($user->hasRole('ROLE_SUPER_ADMIN') || $user->hasRole('ROLE_ADMIN')); |
||
380 | $isCourseTeacher = ($user->hasRole('ROLE_CURRENT_COURSE_TEACHER') || $user->hasRole('ROLE_CURRENT_COURSE_SESSION_TEACHER')); |
||
381 | |||
382 | if (!($isCourseTeacher || $isAdmin)) { |
||
383 | throw new AccessDeniedHttpException(); |
||
384 | } |
||
385 | |||
386 | $session = null; |
||
387 | if ($this->getSession()) { |
||
388 | $sessionId = $this->getSession()->getId(); |
||
389 | $session = $entityManager->getRepository(Session::class)->find($sessionId); |
||
390 | } |
||
391 | $courseId = $this->getCourse()->getId(); |
||
392 | $course = $entityManager->getRepository(Course::class)->find($courseId); |
||
393 | $id = $request->attributes->getInt('id'); |
||
394 | $resourceNode = $this->getResourceNodeRepository()->findOneBy(['id' => $id]); |
||
395 | |||
396 | if (null === $resourceNode) { |
||
397 | throw new NotFoundHttpException($this->trans('Resource not found')); |
||
398 | } |
||
399 | |||
400 | $link = null; |
||
401 | foreach ($resourceNode->getResourceLinks() as $resourceLink) { |
||
402 | if ($resourceLink->getSession() === $session) { |
||
403 | $link = $resourceLink; |
||
404 | |||
405 | break; |
||
406 | } |
||
407 | } |
||
408 | |||
409 | if (null === $link) { |
||
410 | $link = new ResourceLink(); |
||
411 | $link->setResourceNode($resourceNode) |
||
412 | ->setSession($session) |
||
413 | ->setCourse($course) |
||
414 | ->setVisibility(ResourceLink::VISIBILITY_DRAFT) |
||
415 | ; |
||
416 | $entityManager->persist($link); |
||
417 | } else { |
||
418 | if (ResourceLink::VISIBILITY_PUBLISHED === $link->getVisibility()) { |
||
419 | $link->setVisibility(ResourceLink::VISIBILITY_DRAFT); |
||
420 | } else { |
||
421 | $link->setVisibility(ResourceLink::VISIBILITY_PUBLISHED); |
||
422 | } |
||
423 | } |
||
424 | |||
425 | $entityManager->flush(); |
||
426 | |||
427 | $json = $serializer->serialize( |
||
428 | $link, |
||
429 | 'json', |
||
430 | [ |
||
431 | 'groups' => ['ctool:read'], |
||
432 | ] |
||
433 | ); |
||
434 | |||
435 | return JsonResponse::fromJsonString($json); |
||
436 | } |
||
437 | |||
438 | #[Route( |
||
439 | '/{tool}/{type}/change_visibility/{visibility}', |
||
440 | name: 'chamilo_core_resource_change_visibility_all', |
||
441 | methods: ['POST'] |
||
442 | )] |
||
443 | public function changeVisibilityAll( |
||
444 | Request $request, |
||
445 | CToolRepository $toolRepository, |
||
446 | CShortcutRepository $shortcutRepository, |
||
447 | ToolChain $toolChain, |
||
448 | EntityManagerInterface $entityManager, |
||
449 | Security $security |
||
450 | ): Response { |
||
451 | $user = $security->getUser(); |
||
452 | $isAdmin = ($user->hasRole('ROLE_SUPER_ADMIN') || $user->hasRole('ROLE_ADMIN')); |
||
453 | $isCourseTeacher = ($user->hasRole('ROLE_CURRENT_COURSE_TEACHER') || $user->hasRole('ROLE_CURRENT_COURSE_SESSION_TEACHER')); |
||
454 | |||
455 | if (!($isCourseTeacher || $isAdmin)) { |
||
456 | throw new AccessDeniedHttpException(); |
||
457 | } |
||
458 | |||
459 | $visibility = $request->attributes->get('visibility'); |
||
460 | |||
461 | $session = null; |
||
462 | if ($this->getSession()) { |
||
463 | $sessionId = $this->getSession()->getId(); |
||
464 | $session = $entityManager->getRepository(Session::class)->find($sessionId); |
||
465 | } |
||
466 | $courseId = $this->getCourse()->getId(); |
||
467 | $course = $entityManager->getRepository(Course::class)->find($courseId); |
||
468 | |||
469 | $result = $toolRepository->getResourcesByCourse($course, $session) |
||
470 | ->addSelect('tool') |
||
471 | ->innerJoin('resource.tool', 'tool') |
||
472 | ->getQuery() |
||
473 | ->getResult() |
||
474 | ; |
||
475 | |||
476 | $skipTools = ['course_tool', 'chat', 'notebook', 'wiki']; |
||
477 | |||
478 | /** @var CTool $item */ |
||
479 | foreach ($result as $item) { |
||
480 | if (\in_array($item->getTitle(), $skipTools, true)) { |
||
481 | continue; |
||
482 | } |
||
483 | $toolModel = $toolChain->getToolFromName($item->getTool()->getTitle()); |
||
484 | |||
485 | if (!\in_array($toolModel->getCategory(), ['authoring', 'interaction'], true)) { |
||
486 | continue; |
||
487 | } |
||
488 | |||
489 | $resourceNode = $item->getResourceNode(); |
||
490 | |||
491 | /** @var ResourceLink $link */ |
||
492 | $link = null; |
||
493 | foreach ($resourceNode->getResourceLinks() as $resourceLink) { |
||
494 | if ($resourceLink->getSession() === $session) { |
||
495 | $link = $resourceLink; |
||
496 | |||
497 | break; |
||
498 | } |
||
499 | } |
||
500 | |||
501 | if (null === $link) { |
||
502 | $link = new ResourceLink(); |
||
503 | $link->setResourceNode($resourceNode) |
||
504 | ->setSession($session) |
||
505 | ->setCourse($course) |
||
506 | ->setVisibility(ResourceLink::VISIBILITY_DRAFT) |
||
507 | ; |
||
508 | $entityManager->persist($link); |
||
509 | } |
||
510 | |||
511 | if ('show' === $visibility) { |
||
512 | $link->setVisibility(ResourceLink::VISIBILITY_PUBLISHED); |
||
513 | } elseif ('hide' === $visibility) { |
||
514 | $link->setVisibility(ResourceLink::VISIBILITY_DRAFT); |
||
515 | } |
||
516 | } |
||
517 | |||
518 | $entityManager->flush(); |
||
519 | |||
520 | return new Response(null, Response::HTTP_NO_CONTENT); |
||
521 | } |
||
522 | |||
523 | #[Route('/resource_files/{resourceNodeId}/variants', name: 'chamilo_core_resource_files_variants', methods: ['GET'])] |
||
552 | } |
||
553 | |||
554 | #[Route('/resource_files/{id}/delete_variant', methods: ['DELETE'], name: 'chamilo_core_resource_files_delete_variant')] |
||
555 | public function deleteVariant(int $id, EntityManagerInterface $em): JsonResponse |
||
556 | { |
||
566 | } |
||
567 | |||
568 | private function processFile(Request $request, ResourceNode $resourceNode, string $mode = 'show', string $filter = '', ?array $allUserInfo = null, ?ResourceFile $resourceFile = null): mixed |
||
569 | { |
||
570 | $this->denyAccessUnlessGranted( |
||
571 | ResourceNodeVoter::VIEW, |
||
572 | $resourceNode, |
||
573 | $this->trans('Unauthorised view access to resource') |
||
574 | ); |
||
575 | |||
576 | $resourceFile ??= $resourceNode->getResourceFiles()->first(); |
||
577 | |||
578 | if (!$resourceFile) { |
||
579 | throw $this->createNotFoundException($this->trans('File not found for resource')); |
||
580 | } |
||
581 | |||
582 | $fileName = $resourceFile->getOriginalName(); |
||
583 | $fileSize = $resourceFile->getSize(); |
||
584 | $mimeType = $resourceFile->getMimeType(); |
||
585 | [$start, $end, $length] = $this->getRange($request, $fileSize); |
||
586 | $resourceNodeRepo = $this->getResourceNodeRepository(); |
||
587 | |||
588 | // Convert the file name to ASCII using iconv |
||
589 | $fileName = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $fileName); |
||
590 | |||
591 | switch ($mode) { |
||
592 | case 'download': |
||
593 | $forceDownload = true; |
||
594 | |||
595 | break; |
||
596 | |||
597 | case 'show': |
||
598 | default: |
||
599 | $forceDownload = false; |
||
600 | // If it's an image then send it to Glide. |
||
601 | if (str_contains($mimeType, 'image')) { |
||
602 | $glide = $this->getGlide(); |
||
603 | $server = $glide->getServer(); |
||
604 | $params = $request->query->all(); |
||
605 | |||
606 | // The filter overwrites the params from GET. |
||
607 | if (!empty($filter)) { |
||
608 | $params = $glide->getFilters()[$filter] ?? []; |
||
609 | } |
||
610 | |||
611 | // The image was cropped manually by the user, so we force to render this version, |
||
612 | // no matter other crop parameters. |
||
613 | $crop = $resourceFile->getCrop(); |
||
614 | if (!empty($crop)) { |
||
615 | $params['crop'] = $crop; |
||
616 | } |
||
617 | |||
618 | $filePath = $resourceNodeRepo->getFilename($resourceFile); |
||
619 | |||
620 | $response = $server->getImageResponse($filePath, $params); |
||
621 | |||
622 | $disposition = $response->headers->makeDisposition( |
||
623 | ResponseHeaderBag::DISPOSITION_INLINE, |
||
624 | $fileName |
||
625 | ); |
||
626 | $response->headers->set('Content-Disposition', $disposition); |
||
627 | |||
628 | return $response; |
||
629 | } |
||
630 | |||
631 | // Modify the HTML content before displaying it. |
||
632 | if (str_contains($mimeType, 'html')) { |
||
633 | $content = $resourceNodeRepo->getResourceNodeFileContent($resourceNode, $resourceFile); |
||
634 | |||
635 | if (null !== $allUserInfo) { |
||
636 | $tagsToReplace = $allUserInfo[0]; |
||
637 | $replacementValues = $allUserInfo[1]; |
||
638 | $content = str_replace($tagsToReplace, $replacementValues, $content); |
||
639 | } |
||
640 | |||
641 | $response = new Response(); |
||
642 | $disposition = $response->headers->makeDisposition( |
||
643 | ResponseHeaderBag::DISPOSITION_INLINE, |
||
644 | $fileName |
||
645 | ); |
||
646 | $response->headers->set('Content-Disposition', $disposition); |
||
647 | $response->headers->set('Content-Type', 'text/html'); |
||
648 | |||
649 | // @todo move into a function/class |
||
650 | if ('true' === $this->getSettingsManager()->getSetting('editor.translate_html')) { |
||
651 | $user = $this->userHelper->getCurrent(); |
||
652 | if (null !== $user) { |
||
653 | // Overwrite user_json, otherwise it will be loaded by the TwigListener.php |
||
654 | $userJson = json_encode(['locale' => $user->getLocale()]); |
||
655 | $js = $this->renderView( |
||
656 | '@ChamiloCore/Layout/document.html.twig', |
||
657 | ['breadcrumb' => '', 'user_json' => $userJson] |
||
658 | ); |
||
659 | // Insert inside the head tag. |
||
660 | $content = str_replace('</head>', $js.'</head>', $content); |
||
661 | } |
||
662 | } |
||
663 | if ('true' === $this->getSettingsManager()->getSetting('course.enable_bootstrap_in_documents_html')) { |
||
664 | // It adds the bootstrap and awesome css |
||
665 | $links = '<link href="'.api_get_path(WEB_PATH).'libs/bootstrap/bootstrap.min.css" rel="stylesheet">'; |
||
666 | $links .= '<link href="'.api_get_path(WEB_PATH).'libs/bootstrap/font-awesome.min.css" rel="stylesheet">'; |
||
667 | // Insert inside the head tag. |
||
668 | $content = str_replace('</head>', $links.'</head>', $content); |
||
669 | } |
||
670 | $response->setContent($content); |
||
671 | |||
672 | return $response; |
||
673 | } |
||
674 | |||
675 | break; |
||
676 | } |
||
677 | |||
678 | $response = new StreamedResponse( |
||
679 | function () use ($resourceNodeRepo, $resourceFile, $start, $length): void { |
||
680 | $this->streamFileContent($resourceNodeRepo, $resourceFile, $start, $length); |
||
681 | } |
||
682 | ); |
||
683 | |||
684 | $disposition = $response->headers->makeDisposition( |
||
685 | $forceDownload ? ResponseHeaderBag::DISPOSITION_ATTACHMENT : ResponseHeaderBag::DISPOSITION_INLINE, |
||
686 | $fileName |
||
687 | ); |
||
688 | $response->headers->set('Content-Disposition', $disposition); |
||
689 | $response->headers->set('Content-Type', $mimeType ?: 'application/octet-stream'); |
||
690 | $response->headers->set('Content-Length', (string) $length); |
||
691 | $response->headers->set('Accept-Ranges', 'bytes'); |
||
692 | $response->headers->set('Content-Range', "bytes $start-$end/$fileSize"); |
||
693 | $response->setStatusCode( |
||
694 | $start > 0 || $end < $fileSize - 1 ? Response::HTTP_PARTIAL_CONTENT : Response::HTTP_OK |
||
695 | ); |
||
696 | |||
697 | return $response; |
||
698 | } |
||
699 | |||
700 | private function getRange(Request $request, int $fileSize): array |
||
719 | } |
||
720 | |||
721 | private function streamFileContent(ResourceNodeRepository $resourceNodeRepo, ResourceFile $resourceFile, int $start, int $length): void |
||
738 | } |
||
739 | } |
||
740 |