Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ Features:
- [import-class] Import declared classes (as long as they can be statically
resolved).
- [rpc] Class import uses offset to determine type to import
- [class-mover] Possiblity to move related any files whose relations are
defined in `navigator.destinations` (for both command and rpc)

Bug fixes:

Expand Down
3 changes: 3 additions & 0 deletions doc/refactorings.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,9 @@ new location, updating the classes namespace and all references to that class
where possible in a given _scope_ (i.e. files known by GIT: `git`, files known by Composer: `composer`, or all PHP files under
the current CWD: `simple`).

If you have defined file relationships with
[navigator.destinations](https://phpactor.github.io/phpactor/navigation.html#jump-to-or-generate-related-file), then you have the option to move the related files in addition to the specified file. If using the command then specify `--related`, or if using the RPC interface (f.e. VIM) you will be prompted.

<div class="alert alert-danger">
This is a dangerous refactoring! Ensure that you commit your work before
executing it and be aware that success is not guaranteed (e.g. class references
Expand Down
68 changes: 58 additions & 10 deletions lib/Extension/ClassMover/Application/ClassMover.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Phpactor\Extension\ClassMover\Application;

use Phpactor\ClassFileConverter\PathFinder;
use Phpactor\ClassMover\ClassMover as ClassMoverFacade;
use Phpactor\ClassMover\Domain\Name\FullyQualifiedName;
use Phpactor\Filesystem\Domain\FilePath;
Expand Down Expand Up @@ -29,45 +30,69 @@ class ClassMover
*/
private $filesystemRegistry;

/**
* @var PathFinder
*/
private $pathFinder;

public function __construct(
ClassFileNormalizer $classFileNormalizer,
ClassMoverFacade $classMover,
FilesystemRegistry $filesystemRegistry
FilesystemRegistry $filesystemRegistry,
PathFinder $pathFinder
) {
$this->classFileNormalizer = $classFileNormalizer;
$this->filesystemRegistry = $filesystemRegistry;
$this->classMover = $classMover;
$this->pathFinder = $pathFinder;
}

public function getRelatedFiles(string $src): array
{
return array_filter($this->pathFinder->destinationsFor($src), function (string $filePath) {
return (bool) file_exists($filePath);
});
}

/**
* Move - guess if moving by class name or file.
*/
public function move(ClassMoverLogger $logger, string $filesystemName, string $src, string $dest)
public function move(
ClassMoverLogger $logger,
string $filesystemName,
string $src,
string $dest,
bool $moveRelatedFiles
): void
{
$srcPath = $this->classFileNormalizer->normalizeToFile($src);
$destPath = $this->classFileNormalizer->normalizeToFile($dest);

return $this->moveFile($logger, $filesystemName, $srcPath, $destPath);
$this->moveFile($logger, $filesystemName, $srcPath, $destPath, $moveRelatedFiles);
}

public function moveClass(ClassMoverLogger $logger, string $filesystemName, string $srcName, string $destName)
public function moveClass(ClassMoverLogger $logger, string $filesystemName, string $srcName, string $destName, bool $moveRelatedFiles)
{
return $this->moveFile(
$logger,
$filesystemName,
$this->classFileNormalizer->classToFile($srcName),
$this->classFileNormalizer->classToFile($destName)
$this->classFileNormalizer->classToFile($destName),
$moveRelatedFiles
);
}

public function moveFile(ClassMoverLogger $logger, string $filesystemName, string $srcPath, string $destPath)
public function moveFile(ClassMoverLogger $logger, string $filesystemName, string $srcPath, string $destPath, bool $moveRelatedFiles)
{
$srcPath = Phpactor::normalizePath($srcPath);
foreach (FilesystemHelper::globSourceDestination($srcPath, $destPath) as $globSrc => $globDest) {
try {
$this->doMoveFile($logger, $filesystemName, $globSrc, $globDest);
} catch (\Exception $e) {
throw new \RuntimeException(sprintf('Could not move file "%s" to "%s"', $srcPath, $destPath), null, $e);

foreach ($this->expandRelatedPaths($globSrc, $globDest, $moveRelatedFiles) as $oldPath => $newPath) {
try {
$this->doMoveFile($logger, $filesystemName, $oldPath, $newPath);
} catch (\Exception $e) {
throw new \RuntimeException(sprintf('Could not move file "%s" to "%s"', $srcPath, $destPath), null, $e);
}
}
}
}
Expand Down Expand Up @@ -140,4 +165,27 @@ private function replaceReferences(ClassMoverLogger $logger, Filesystem $filesys
$filesystem->writeContents($filePath, (string) $source);
}
}

private function expandRelatedPaths($src, $dest, bool $moveRelatedFiles): array
{
$paths = [
$src => $dest
];

if ($moveRelatedFiles) {
$oldPaths = $this->getRelatedFiles($src);
$newPaths = $this->pathFinder->destinationsFor($dest);

foreach ($oldPaths as $oldType => $oldPath) {
if (!isset($newPaths[$oldType])) {
continue;
}

$newPath = $newPaths[$oldType];
$paths[$oldPath] = $newPath;
}
}

return $paths;
}
}
4 changes: 3 additions & 1 deletion lib/Extension/ClassMover/ClassMoverExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Phpactor\Extension\ClassMover\Rpc\ClassMoveHandler;
use Phpactor\Extension\ClassMover\Rpc\ReferencesHandler;
use Phpactor\Extension\Console\ConsoleExtension;
use Phpactor\Extension\Navigation\NavigationExtension;
use Phpactor\Extension\Rpc\RpcExtension;
use Phpactor\Extension\SourceCodeFilesystem\SourceCodeFilesystemExtension;
use Phpactor\Extension\WorseReflection\WorseReflectionExtension;
Expand Down Expand Up @@ -106,7 +107,8 @@ private function registerApplicationServices(ContainerBuilder $container)
return new ClassMoverApp(
$container->get('application.helper.class_file_normalizer'),
$container->get('class_mover.class_mover'),
$container->get('source_code_filesystem.registry')
$container->get('source_code_filesystem.registry'),
$container->get(NavigationExtension::SERVICE_PATH_FINDER)
);
});

Expand Down
8 changes: 5 additions & 3 deletions lib/Extension/ClassMover/Command/ClassMoveCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public function configure()
'Type of move: "%s"',
implode('", "', [self::TYPE_AUTO, self::TYPE_CLASS, self::TYPE_FILE])
), self::TYPE_AUTO);
$this->addOption('related', null, InputOption::VALUE_NONE, 'Move related files (as defined by the patterns in navigator.destinations');
FilesystemHandler::configure($this, SourceCodeFilesystemExtension::FILESYSTEM_GIT);
}

Expand All @@ -57,18 +58,19 @@ public function execute(InputInterface $input, OutputInterface $output)
$src = $input->getArgument('src');
$dest = $input->getArgument('dest');
$filesystem = $input->getOption('filesystem');
$related = (bool) $input->getOption('related');

if (null === $dest) {
$dest = $this->prompt->prompt('Move to: ', $src);
}

switch ($type) {
case 'auto':
return $this->mover->move($logger, $filesystem, $src, $dest);
return $this->mover->move($logger, $filesystem, $src, $dest, $related);
case 'file':
return $this->mover->moveFile($logger, $filesystem, $src, $dest);
return $this->mover->moveFile($logger, $filesystem, $src, $dest, $related);
case 'class':
return $this->mover->moveClass($logger, $filesystem, $src, $dest);
return $this->mover->moveClass($logger, $filesystem, $src, $dest, $related);
}

throw new \InvalidArgumentException(sprintf(
Expand Down
31 changes: 26 additions & 5 deletions lib/Extension/ClassMover/Rpc/ClassMoveHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Phpactor\Extension\ClassMover\Rpc;

use Phpactor\Extension\Rpc\Response\Input\ChoiceInput;
use Phpactor\Extension\Rpc\Response\Input\ListInput;
use Phpactor\MapResolver\Resolver;
use Phpactor\Extension\Rpc\Response\OpenFileResponse;
use Phpactor\Extension\Rpc\Response\Input\TextInput;
Expand All @@ -15,9 +17,11 @@

class ClassMoveHandler extends AbstractHandler
{
const PARAM_SOURCE_PATH = 'source_path';
const PARAM_DEST_PATH = 'dest_path';
const PARAM_CONFIRMED = 'confirmed';
private const PARAM_SOURCE_PATH = 'source_path';
private const PARAM_DEST_PATH = 'dest_path';
private const PARAM_CONFIRMED = 'confirmed';
private const PARAM_ADDITIONAL_MOVE_CONFIRM = 'move_related';

const NAME = 'move_class';

/**
Expand Down Expand Up @@ -46,6 +50,7 @@ public function configure(Resolver $resolver)
$resolver->setDefaults([
self::PARAM_DEST_PATH => null,
self::PARAM_CONFIRMED => null,
self::PARAM_ADDITIONAL_MOVE_CONFIRM => null,
]);
$resolver->setRequired([
self::PARAM_SOURCE_PATH
Expand All @@ -65,7 +70,10 @@ public function handle(array $arguments)
'file'
));

if (null !== $arguments[self::PARAM_DEST_PATH] && null === $arguments[self::PARAM_CONFIRMED]) {
if (
null !== $arguments[self::PARAM_DEST_PATH] &&
null === $arguments[self::PARAM_CONFIRMED]
) {
$this->requireInput(ConfirmInput::fromNameAndLabel(
self::PARAM_CONFIRMED,
'WARNING: This command will move the class and update ALL references in the git tree.' . PHP_EOL .
Expand All @@ -74,6 +82,18 @@ public function handle(array $arguments)
));
}

if (
null === $arguments[self::PARAM_ADDITIONAL_MOVE_CONFIRM] &&
$arguments[self::PARAM_DEST_PATH] &&
$related = $this->classMove->getRelatedFiles($arguments[self::PARAM_SOURCE_PATH])
) {
$this->requireInput(ConfirmInput::fromNameAndLabel(
self::PARAM_ADDITIONAL_MOVE_CONFIRM,
sprintf("This class has the following related files:\n\n - %s\n\nMove these too? ",
implode("\n - ", $related)
)));
}

if ($this->hasMissingArguments($arguments)) {
return $this->createInputCallback($arguments);
}
Expand All @@ -82,7 +102,8 @@ public function handle(array $arguments)
new NullLogger(),
$this->defaultFilesystem,
$arguments[self::PARAM_SOURCE_PATH],
$arguments[self::PARAM_DEST_PATH]
$arguments[self::PARAM_DEST_PATH],
$arguments[self::PARAM_ADDITIONAL_MOVE_CONFIRM] ?? false
);

return CollectionResponse::fromActions([
Expand Down
5 changes: 3 additions & 2 deletions lib/Extension/Navigation/NavigationExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class NavigationExtension implements Extension
{
const PATH_FINDER_DESTINATIONS = 'navigator.destinations';
const NAVIGATOR_AUTOCREATE = 'navigator.autocreate';
const SERVICE_PATH_FINDER = 'navigation.path_finder';

/**
* {@inheritDoc}
Expand All @@ -42,7 +43,7 @@ public function configure(Resolver $schema)

private function registerPathFinder(ContainerBuilder $container)
{
$container->register('navigation.path_finder', function (Container $container) {
$container->register(self::SERVICE_PATH_FINDER, function (Container $container) {
return PathFinder::fromDestinations($container->getParameter(self::PATH_FINDER_DESTINATIONS));
});

Expand Down Expand Up @@ -75,7 +76,7 @@ private function registerNavigators(ContainerBuilder $container)
return new ChainNavigator($navigators);
});
$container->register('navigation.navigator.path_finder', function (Container $container) {
return new PathFinderNavigator($container->get('navigation.path_finder'));
return new PathFinderNavigator($container->get(self::SERVICE_PATH_FINDER));
}, [ 'navigation.navigator' => [] ]);

$container->register('navigation.navigator.worse_reflection', function (Container $container) {
Expand Down
14 changes: 14 additions & 0 deletions tests/System/Extension/ClassMover/Command/ClassMoveCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,20 @@ public function testOutdatedGitIndex()
$this->assertSuccess($process);
}

public function testMovesRelatedFiles()
{
$this->workspace()->put('.phpactor.json', json_encode([
'navigator.destinations' => [
"source" => "lib/<kernel>.php",
"test" => "lib/<kernel>Test.php"
]
]));
$this->workspace()->put('lib/BadgerTest.php', '<?php namespace Animals; class BadgerTest {}');
$process = $this->phpactor('class:move lib/Badger.php lib/Fox.php --related');
$this->assertSuccess($process);
$this->assertFileExists($this->workspace()->path('/lib/FoxTest.php'));
}

/**
* Application level failures
*
Expand Down
66 changes: 55 additions & 11 deletions tests/Unit/Extension/ClassMover/Rpc/ClassMoveHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class ClassMoveHandlerTest extends HandlerTestCase
public function setUp()
{
$this->classMover = $this->prophesize(ClassMover::class);
$this->classMover->getRelatedFiles(self::SOURCE_PATH)->willReturn([]);
}

public function createHandler(): Handler
Expand Down Expand Up @@ -92,28 +93,27 @@ public function testNoDestPath()
'source_path' => self::SOURCE_PATH,
'dest_path' => null,
'confirmed' => null,
'move_related' => null
], $action->callbackAction()->parameters());
}

/**
* @testdox It should ask for confirmation
*/
public function testMoveClass()
public function testItShouldAskForConfirmation()
{
$this->classMover->move(
Argument::type(ClassMoverLogger::class),
SourceCodeFilesystemExtension::FILESYSTEM_GIT,
self::SOURCE_PATH,
self::DEST_PATH,
false
)->shouldBeCalled();

/** @var $action StackAction */
$action = $this->handle('move_class', [
'source_path' => self::SOURCE_PATH,
'dest_path' => self::DEST_PATH,
'confirmed' => true,
]);

$this->classMover->move(
Argument::type(ClassMoverLogger::class),
SourceCodeFilesystemExtension::FILESYSTEM_GIT,
self::SOURCE_PATH,
self::DEST_PATH
)->shouldBeCalled();

$this->assertInstanceOf(CollectionResponse::class, $action);
$actions = $action->actions();

Expand All @@ -125,4 +125,48 @@ public function testMoveClass()
$this->assertInstanceOf(OpenFileResponse::class, $secondAction);
$this->assertEquals(self::DEST_PATH, $secondAction->path());
}

public function testItAskIfRelatedFilesShouldBeMoved()
{
$this->classMover->getRelatedFiles(self::SOURCE_PATH)->willReturn([
'foobar.php',
]);

/** @var $action StackAction */
$action = $this->handle('move_class', [
'source_path' => self::SOURCE_PATH,
'dest_path' => self::DEST_PATH,
'confirmed' => true,
]);

$this->assertInstanceOf(InputCallbackResponse::class, $action);
$inputs = $action->inputs();
$input = reset($inputs);
$this->assertInstanceOf(ConfirmInput::class, $input);
$this->assertEquals('move_related', $input->name());
}

public function testMovesRelatedFiles()
{
$this->classMover->move(
Argument::type(ClassMoverLogger::class),
SourceCodeFilesystemExtension::FILESYSTEM_GIT,
self::SOURCE_PATH,
self::DEST_PATH,
true
)->shouldBeCalled();

$this->classMover->getRelatedFiles(self::SOURCE_PATH)->willReturn([
'foobar.php',
]);

/** @var $action StackAction */
$action = $this->handle('move_class', [
'source_path' => self::SOURCE_PATH,
'dest_path' => self::DEST_PATH,
'confirmed' => true,
'move_related' => true,
]);

}
}