Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like WopiController 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
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 WopiController, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
54 | class WopiController extends Controller { |
||
55 | /** @var IRootFolder */ |
||
56 | private $rootFolder; |
||
57 | /** @var IURLGenerator */ |
||
58 | private $urlGenerator; |
||
59 | /** @var IConfig */ |
||
60 | private $config; |
||
61 | /** @var AppConfig */ |
||
62 | private $appConfig; |
||
63 | /** @var TokenManager */ |
||
64 | private $tokenManager; |
||
65 | /** @var IUserManager */ |
||
66 | private $userManager; |
||
67 | /** @var WopiMapper */ |
||
68 | private $wopiMapper; |
||
69 | /** @var ILogger */ |
||
70 | private $logger; |
||
71 | /** @var TemplateManager */ |
||
72 | private $templateManager; |
||
73 | /** @var IManager */ |
||
74 | private $shareManager; |
||
75 | /** @var UserScopeService */ |
||
76 | private $userScopeService; |
||
77 | |||
78 | // Signifies LOOL that document has been changed externally in this storage |
||
79 | const LOOL_STATUS_DOC_CHANGED = 1010; |
||
80 | |||
81 | /** |
||
82 | * @param string $appName |
||
83 | * @param IRequest $request |
||
84 | * @param IRootFolder $rootFolder |
||
85 | * @param IURLGenerator $urlGenerator |
||
86 | * @param IConfig $config |
||
87 | * @param TokenManager $tokenManager |
||
88 | * @param IUserManager $userManager |
||
89 | * @param WopiMapper $wopiMapper |
||
90 | * @param ILogger $logger |
||
91 | * @param TemplateManager $templateManager |
||
92 | */ |
||
93 | View Code Duplication | public function __construct( |
|
|
|||
94 | $appName, |
||
95 | IRequest $request, |
||
96 | IRootFolder $rootFolder, |
||
97 | IURLGenerator $urlGenerator, |
||
98 | IConfig $config, |
||
99 | AppConfig $appConfig, |
||
100 | TokenManager $tokenManager, |
||
101 | IUserManager $userManager, |
||
102 | WopiMapper $wopiMapper, |
||
103 | ILogger $logger, |
||
104 | TemplateManager $templateManager, |
||
105 | IManager $shareManager, |
||
106 | UserScopeService $userScopeService |
||
107 | ) { |
||
108 | parent::__construct($appName, $request); |
||
109 | $this->rootFolder = $rootFolder; |
||
110 | $this->urlGenerator = $urlGenerator; |
||
111 | $this->config = $config; |
||
112 | $this->appConfig = $appConfig; |
||
113 | $this->tokenManager = $tokenManager; |
||
114 | $this->userManager = $userManager; |
||
115 | $this->wopiMapper = $wopiMapper; |
||
116 | $this->logger = $logger; |
||
117 | $this->templateManager = $templateManager; |
||
118 | $this->shareManager = $shareManager; |
||
119 | $this->userScopeService = $userScopeService; |
||
120 | } |
||
121 | |||
122 | /** |
||
123 | * Returns general info about a file. |
||
124 | * |
||
125 | * @NoAdminRequired |
||
126 | * @NoCSRFRequired |
||
127 | * @PublicPage |
||
128 | * |
||
129 | * @param string $fileId |
||
130 | * @param string $access_token |
||
131 | * @return JSONResponse |
||
132 | * @throws InvalidPathException |
||
133 | * @throws NotFoundException |
||
134 | */ |
||
135 | public function checkFileInfo($fileId, $access_token) { |
||
136 | try { |
||
137 | list($fileId, , $version) = Helper::parseFileId($fileId); |
||
138 | |||
139 | $wopi = $this->wopiMapper->getWopiForToken($access_token); |
||
140 | if ($wopi->isTemplateToken()) { |
||
141 | $this->templateManager->setUserId($wopi->getOwnerUid()); |
||
142 | $file = $this->templateManager->get($wopi->getFileid()); |
||
143 | } else { |
||
144 | $file = $this->getFileForWopiToken($wopi); |
||
145 | } |
||
146 | if(!($file instanceof File)) { |
||
147 | throw new NotFoundException('No valid file found for ' . $fileId); |
||
148 | } |
||
149 | } catch (NotFoundException $e) { |
||
150 | $this->logger->debug($e->getMessage(), ['app' => 'richdocuments', '']); |
||
151 | return new JSONResponse([], Http::STATUS_FORBIDDEN); |
||
152 | } catch (DoesNotExistException $e) { |
||
153 | $this->logger->debug($e->getMessage(), ['app' => 'richdocuments', '']); |
||
154 | return new JSONResponse([], Http::STATUS_FORBIDDEN); |
||
155 | } catch (\Exception $e) { |
||
156 | $this->logger->logException($e, ['app' => 'richdocuments']); |
||
157 | return new JSONResponse([], Http::STATUS_FORBIDDEN); |
||
158 | } |
||
159 | |||
160 | $isPublic = $wopi->getEditorUid() === null; |
||
161 | $guestUserId = 'Guest-' . \OC::$server->getSecureRandom()->generate(8); |
||
162 | $user = $this->userManager->get($wopi->getEditorUid()); |
||
163 | $userDisplayName = $user !== null && !$isPublic ? $user->getDisplayName() : $wopi->getGuestDisplayname(); |
||
164 | $response = [ |
||
165 | 'BaseFileName' => $file->getName(), |
||
166 | 'Size' => $file->getSize(), |
||
167 | 'Version' => $version, |
||
168 | 'UserId' => !$isPublic ? $wopi->getEditorUid() : $guestUserId, |
||
169 | 'OwnerId' => $wopi->getOwnerUid(), |
||
170 | 'UserFriendlyName' => $userDisplayName, |
||
171 | 'UserExtraInfo' => [ |
||
172 | ], |
||
173 | 'UserCanWrite' => $wopi->getCanwrite(), |
||
174 | 'UserCanNotWriteRelative' => \OC::$server->getEncryptionManager()->isEnabled() || $isPublic, |
||
175 | 'PostMessageOrigin' => $wopi->getServerHost(), |
||
176 | 'LastModifiedTime' => Helper::toISO8601($file->getMTime()), |
||
177 | 'SupportsRename' => true, |
||
178 | 'UserCanRename' => !$isPublic, |
||
179 | 'EnableInsertRemoteImage' => true, |
||
180 | 'EnableShare' => true, |
||
181 | 'HideUserList' => 'desktop', |
||
182 | 'DisablePrint' => $wopi->getHideDownload(), |
||
183 | 'DisableExport' => $wopi->getHideDownload(), |
||
184 | 'DisableCopy' => $wopi->getHideDownload(), |
||
185 | 'HideExportOption' => $wopi->getHideDownload(), |
||
186 | 'HidePrintOption' => $wopi->getHideDownload(), |
||
187 | 'DownloadAsPostMessage' => $wopi->getDirect(), |
||
188 | ]; |
||
189 | |||
190 | if ($wopi->isTemplateToken()) { |
||
191 | $userFolder = $this->rootFolder->getUserFolder($wopi->getOwnerUid()); |
||
192 | $file = $userFolder->getById($wopi->getTemplateDestination())[0]; |
||
193 | $response['TemplateSaveAs'] = $file->getName(); |
||
194 | } |
||
195 | |||
196 | if ($this->shouldWatermark($isPublic, $wopi->getEditorUid(), $fileId, $wopi)) { |
||
197 | $replacements = [ |
||
198 | 'userId' => $wopi->getEditorUid(), |
||
199 | 'date' => (new \DateTime())->format('Y-m-d H:i:s'), |
||
200 | 'themingName' => \OC::$server->getThemingDefaults()->getName(), |
||
201 | |||
202 | ]; |
||
203 | $watermarkTemplate = $this->appConfig->getAppValue('watermark_text'); |
||
204 | $response['WatermarkText'] = preg_replace_callback('/{(.+?)}/', function($matches) use ($replacements) |
||
205 | { |
||
206 | return $replacements[$matches[1]]; |
||
207 | }, $watermarkTemplate); |
||
208 | } |
||
209 | |||
210 | $user = $this->userManager->get($wopi->getEditorUid()); |
||
211 | if($user !== null && $user->getAvatarImage(32) !== null) { |
||
212 | $response['UserExtraInfo']['avatar'] = $this->urlGenerator->linkToRouteAbsolute('core.avatar.getAvatar', ['userId' => $wopi->getEditorUid(), 'size' => 32]); |
||
213 | } |
||
214 | |||
215 | if ($wopi->getRemoteServer() !== '') { |
||
216 | $response = $this->setFederationFileInfo($wopi, $response); |
||
217 | } |
||
218 | |||
219 | return new JSONResponse($response); |
||
220 | } |
||
221 | |||
222 | private function setFederationFileInfo($wopi, $response) { |
||
241 | |||
242 | private function shouldWatermark($isPublic, $userId, $fileId, Wopi $wopi) { |
||
297 | |||
298 | /** |
||
299 | * Given an access token and a fileId, returns the contents of the file. |
||
300 | * Expects a valid token in access_token parameter. |
||
301 | * |
||
302 | * @PublicPage |
||
303 | * @NoCSRFRequired |
||
304 | * |
||
305 | * @param string $fileId |
||
306 | * @param string $access_token |
||
307 | * @return Http\Response |
||
308 | * @throws DoesNotExistException |
||
309 | * @throws NotFoundException |
||
310 | * @throws NotPermittedException |
||
311 | */ |
||
312 | public function getFile($fileId, |
||
361 | |||
362 | /** |
||
363 | * Given an access token and a fileId, replaces the files with the request body. |
||
364 | * Expects a valid token in access_token parameter. |
||
365 | * |
||
366 | * @PublicPage |
||
367 | * @NoCSRFRequired |
||
368 | * |
||
369 | * @param string $fileId |
||
370 | * @param string $access_token |
||
371 | * @return JSONResponse |
||
372 | * @throws DoesNotExistException |
||
373 | */ |
||
374 | public function putFile($fileId, |
||
464 | |||
465 | /** |
||
466 | * Given an access token and a fileId, replaces the files with the request body. |
||
467 | * Expects a valid token in access_token parameter. |
||
468 | * Just actually routes to the PutFile, the implementation of PutFile |
||
469 | * handles both saving and saving as.* Given an access token and a fileId, replaces the files with the request body. |
||
470 | * |
||
471 | * @PublicPage |
||
472 | * @NoCSRFRequired |
||
473 | * |
||
474 | * @param string $fileId |
||
475 | * @param string $access_token |
||
476 | * @return JSONResponse |
||
477 | * @throws DoesNotExistException |
||
478 | */ |
||
479 | public function putRelativeFile($fileId, |
||
593 | |||
594 | /** |
||
595 | * Retry operation if a LockedException occurred |
||
596 | * Other exceptions will still be thrown |
||
597 | * @param callable $operation |
||
598 | * @throws LockedException |
||
599 | * @throws GenericFileException |
||
600 | */ |
||
601 | private function retryOperation(callable $operation) { |
||
616 | |||
617 | /** |
||
618 | * @param Wopi $wopi |
||
619 | * @return File|Folder|Node|null |
||
620 | * @throws NotFoundException |
||
621 | * @throws ShareNotFound |
||
622 | */ |
||
623 | private function getFileForWopiToken(Wopi $wopi) { |
||
654 | } |
||
655 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.