| Conditions | 7 |
| Paths | 7 |
| Total Lines | 52 |
| Code Lines | 30 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 27 | public function __invoke( |
||
| 28 | CDocument $document, |
||
| 29 | Request $request, |
||
| 30 | ResourceNodeRepository $resourceNodeRepository, |
||
| 31 | EntityManagerInterface $em |
||
| 32 | ): Response { |
||
| 33 | $uploadedFile = $request->files->get('file'); |
||
| 34 | if (!$uploadedFile) { |
||
| 35 | throw new BadRequestHttpException('"file" is required.'); |
||
| 36 | } |
||
| 37 | |||
| 38 | $resourceNode = $document->getResourceNode(); |
||
| 39 | if (!$resourceNode) { |
||
| 40 | throw new BadRequestHttpException('ResourceNode not found.'); |
||
| 41 | } |
||
| 42 | |||
| 43 | $resourceFile = $resourceNode->getFirstResourceFile(); |
||
| 44 | if (!$resourceFile) { |
||
| 45 | throw new BadRequestHttpException('No file found in the resource node.'); |
||
| 46 | } |
||
| 47 | |||
| 48 | $filePath = $this->uploadBasePath . $resourceNodeRepository->getFilename($resourceFile); |
||
| 49 | if (!$filePath) { |
||
| 50 | throw new BadRequestHttpException('File path could not be resolved.'); |
||
| 51 | } |
||
| 52 | |||
| 53 | $this->prepareDirectory($filePath); |
||
| 54 | |||
| 55 | try { |
||
| 56 | $uploadedFile->move(dirname($filePath), basename($filePath)); |
||
| 57 | } catch (FileException $e) { |
||
| 58 | throw new BadRequestHttpException(sprintf('Failed to move the file: %s', $e->getMessage())); |
||
| 59 | } |
||
| 60 | |||
| 61 | $movedFilePath = $filePath; |
||
| 62 | if (!file_exists($movedFilePath)) { |
||
| 63 | throw new \RuntimeException('The moved file does not exist at the expected location.'); |
||
| 64 | } |
||
| 65 | $fileSize = filesize($movedFilePath); |
||
| 66 | $resourceFile->setSize($fileSize); |
||
| 67 | |||
| 68 | $newFileName = $uploadedFile->getClientOriginalName(); |
||
| 69 | $document->setTitle($newFileName); |
||
| 70 | $resourceFile->setOriginalName($newFileName); |
||
| 71 | |||
| 72 | $resourceNode->setUpdatedAt(new \DateTime()); |
||
| 73 | |||
| 74 | $em->persist($document); |
||
| 75 | $em->persist($resourceFile); |
||
| 76 | $em->flush(); |
||
| 77 | |||
| 78 | return new Response('Document replaced successfully.', Response::HTTP_OK); |
||
| 79 | } |
||
| 100 |