|
| 1 | +import { inject, injectable } from 'tsyringe'; |
| 2 | +import { Position, TextDocument, Uri, window } from 'vscode'; |
| 3 | +import { FileRenameHandler } from '@app/commands/FileRenameHandler'; |
| 4 | +import { RenameTypeDetector } from './RenameTypeDetector'; |
| 5 | +import { WorkspacePathResolver } from '@domain/workspace/WorkspacePathResolver'; |
| 6 | + |
| 7 | +interface Props { |
| 8 | + document: TextDocument |
| 9 | + position: Position |
| 10 | + newName: string |
| 11 | +} |
| 12 | + |
| 13 | +@injectable() |
| 14 | +export class FileRenameResolver { |
| 15 | + constructor( |
| 16 | + @inject(WorkspacePathResolver) private workspacePathResolver: WorkspacePathResolver, |
| 17 | + @inject(RenameTypeDetector) private renameTypeDetector: RenameTypeDetector, |
| 18 | + ) { |
| 19 | + } |
| 20 | + |
| 21 | + public async execute({ document, position, newName }: Props): Promise<void> { |
| 22 | + if (!newName.length) { |
| 23 | + throw new Error('New name cannot be empty'); |
| 24 | + } |
| 25 | + |
| 26 | + const type = this.renameTypeDetector.execute({ document, position }); |
| 27 | + |
| 28 | + const currentUri = document.uri; |
| 29 | + const oldPath = currentUri.fsPath; |
| 30 | + const fileName = this.workspacePathResolver.extractClassNameFromPath(oldPath); |
| 31 | + |
| 32 | + if (type === 'namespace') { |
| 33 | + try { |
| 34 | + const newDirectoryPath = await this.workspacePathResolver.getDirectoryFromNamespace(newName); |
| 35 | + |
| 36 | + FileRenameHandler.create({ |
| 37 | + oldUri: currentUri, |
| 38 | + newUri: Uri.file(`${newDirectoryPath}/${fileName}.php`), |
| 39 | + }); |
| 40 | + return; |
| 41 | + } catch (error) { |
| 42 | + window.showErrorMessage(`Error renaming namespace: ${error}`); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + const directory = oldPath.substring(0, oldPath.lastIndexOf('/')); |
| 47 | + const extension = oldPath.substring(oldPath.lastIndexOf('.')); |
| 48 | + |
| 49 | + FileRenameHandler.create({ |
| 50 | + oldUri: currentUri, |
| 51 | + newUri: Uri.file(`${directory}/${fileName}${extension}`), |
| 52 | + }); |
| 53 | + } |
| 54 | +} |
0 commit comments