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
6 changes: 6 additions & 0 deletions autoload/phpactor/input/list.vim
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
function! phpactor#input#list#strategy()
" Hack to not use FZF in collections
" see https://github.com/phpactor/phpactor/pull/843
if g:_phpactorRpcActionIsCollection == v:true
return "phpactor#input#list#inputlist"
endif

if has_key(g:, 'phpactorInputListStrategy')
return g:phpactorInputListStrategy
endif
Expand Down
145 changes: 72 additions & 73 deletions composer.lock

Large diffs are not rendered by default.

16 changes: 16 additions & 0 deletions doc/refactorings.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Fixes:
- [Generate Method](#generate-method)
- [Implement Contracts](#implement-contracts)
- [Import Class](#import-class)
- [Import Missing Classes](#import-missing-classes)
- [Override Method](#override-method)

Generation:
Expand Down Expand Up @@ -892,6 +893,21 @@ class Hello
}
```

Import Missing Classes
----------------------

Import all missing classes in the current file.

- **Command**: **RPC Only**
- **VIM plugin**: _Class context menu > Import Missing_
- **VIM function**:`:call phpactor#ImportMissingClasses()`

### Motivation

You may copy and paste some code from one file to another and subsequently
need to import all the foreign classes into the current namespace. This
refactoring will identify all unresolvable classes and import them.

Override Method
---------------

Expand Down
10 changes: 4 additions & 6 deletions lib/Extension/ClassMover/Application/ClassMover.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ public function __construct(
public function getRelatedFiles(string $src): array
{
try {
return array_filter($this->pathFinder->destinationsFor($src), function (string $filePath) {
return (bool) file_exists($filePath);
});
return array_filter($this->pathFinder->destinationsFor($src), function (string $filePath) {
return (bool) file_exists($filePath);
});
} catch (NoMatchingSourceException $e) {
// TODO: Make pathfinder return it's own exception here, this is the class-to-file exception
return [];
Expand All @@ -70,8 +70,7 @@ public function move(
string $src,
string $dest,
bool $moveRelatedFiles
): void
{
): void {
$srcPath = $this->classFileNormalizer->normalizeToFile($src);
$destPath = $this->classFileNormalizer->normalizeToFile($dest);

Expand All @@ -93,7 +92,6 @@ public function moveFile(ClassMoverLogger $logger, string $filesystemName, strin
{
$srcPath = Phpactor::normalizePath($srcPath);
foreach (FilesystemHelper::globSourceDestination($srcPath, $destPath) as $globSrc => $globDest) {

foreach ($this->expandRelatedPaths($globSrc, $globDest, $moveRelatedFiles) as $oldPath => $newPath) {
try {
$this->doMoveFile($logger, $filesystemName, $oldPath, $newPath);
Expand Down
16 changes: 8 additions & 8 deletions lib/Extension/ClassMover/Rpc/ClassMoveHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

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 Down Expand Up @@ -71,7 +69,7 @@ public function handle(array $arguments)
));

if (
null !== $arguments[self::PARAM_DEST_PATH] &&
null !== $arguments[self::PARAM_DEST_PATH] &&
null === $arguments[self::PARAM_CONFIRMED]
) {
$this->requireInput(ConfirmInput::fromNameAndLabel(
Expand All @@ -83,15 +81,17 @@ public function handle(array $arguments)
}

if (
null === $arguments[self::PARAM_ADDITIONAL_MOVE_CONFIRM] &&
$arguments[self::PARAM_DEST_PATH] &&
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)
)));
sprintf(
"This class has the following related files:\n\n - %s\n\nMove these too? ",
implode("\n - ", $related)
)
));
}

if ($this->hasMissingArguments($arguments)) {
Expand Down
2 changes: 1 addition & 1 deletion lib/Extension/CodeTransformExtra/Application/ClassNew1.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@

class ClassNew1
{
}
}
18 changes: 15 additions & 3 deletions lib/Extension/CodeTransformExtra/CodeTransformExtraExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Phpactor\CodeTransform\Adapter\TolerantParser\Refactor\TolerantImportClass;
use Phpactor\CodeTransform\Adapter\TolerantParser\Refactor\TolerantRenameVariable;
use Phpactor\CodeTransform\Adapter\WorseReflection\GenerateFromExisting\InterfaceFromExistingGenerator;
use Phpactor\CodeTransform\Adapter\WorseReflection\Helper\WorseUnresolvableClassNameFinder;
use Phpactor\CodeTransform\Adapter\WorseReflection\Refactor\WorseExtractConstant;
use Phpactor\CodeTransform\Adapter\WorseReflection\Refactor\WorseExtractMethod;
use Phpactor\CodeTransform\Adapter\WorseReflection\Refactor\WorseGenerateAccessor;
Expand All @@ -22,12 +23,10 @@
use Phpactor\CodeTransform\Adapter\WorseReflection\Transformer\AddMissingProperties;
use Phpactor\CodeTransform\Adapter\WorseReflection\Transformer\CompleteConstructor;
use Phpactor\CodeTransform\Adapter\WorseReflection\Transformer\ImplementContracts;
use Phpactor\CodeTransform\CodeTransform;
use Phpactor\CodeTransform\Domain\Generators;
use Phpactor\CodeTransform\Domain\Transformers;
use Phpactor\Container\Container;
use Phpactor\Container\ContainerBuilder;
use Phpactor\Container\Extension;
use Phpactor\Extension\CodeTransformExtra\Rpc\ImportMissingClassesHandler;
use Phpactor\Extension\CodeTransform\CodeTransformExtension;
use Phpactor\Extension\Logger\LoggingExtension;
use Phpactor\Extension\Rpc\RpcExtension;
Expand Down Expand Up @@ -261,6 +260,12 @@ private function registerRefactorings(ContainerBuilder $container)
$container->register('code_transform.refactor.change_visiblity', function (Container $container) {
return new TolerantChangeVisiblity();
});

$container->register('code_transform.helper.unresolvable_class_name_finder', function (Container $container) {
return new WorseUnresolvableClassNameFinder(
$container->get(WorseReflectionExtension::SERVICE_REFLECTOR)
);
});
}

private function registerUpdater(ContainerBuilder $container)
Expand Down Expand Up @@ -335,6 +340,13 @@ private function registerRpc(ContainerBuilder $container)
$container->get('code_transform.refactor.extract_expression')
);
}, [ RpcExtension::TAG_RPC_HANDLER => ['name' => ExtractExpressionHandler::NAME] ]);

$container->register('code_transform.rpc.handler.import_unresolvable_classes', function (Container $container) {
return new ImportMissingClassesHandler(
$container->get(RpcExtension::SERVICE_REQUEST_HANDLER),
$container->get('code_transform.helper.unresolvable_class_name_finder')
);
}, [ RpcExtension::TAG_RPC_HANDLER => ['name' => ImportMissingClassesHandler::NAME] ]);
}

private function registerGenerators(ContainerBuilder $container)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

namespace Phpactor\Extension\CodeTransformExtra\Rpc;

use Phpactor\CodeTransform\Domain\Helper\UnresolvableClassNameFinder;
use Phpactor\CodeTransform\Domain\NameWithByteOffset;
use Phpactor\Extension\Rpc\Handler;
use Phpactor\Extension\Rpc\Request;
use Phpactor\Extension\Rpc\RequestHandler;
use Phpactor\Extension\Rpc\Response\CollectionResponse;
use Phpactor\Extension\Rpc\Response\EchoResponse;
use Phpactor\MapResolver\Resolver;
use Phpactor\Name\Name;
use Phpactor\TextDocument\TextDocumentBuilder;

class ImportMissingClassesHandler implements Handler
{
public const NAME = 'import_missing_classes';
public const PARAM_SOURCE = 'source';
public const PARAM_PATH = 'path';

/**
* @var UnresolvableClassNameFinder
*/
private $unresolvableClassNameFinder;

/**
* @var RequestHandler
*/
private $handler;

public function __construct(
RequestHandler $handler,
UnresolvableClassNameFinder $unresolvableClassNameFinder
) {
$this->unresolvableClassNameFinder = $unresolvableClassNameFinder;
$this->handler = $handler;
}

public function configure(Resolver $resolver)
{
$resolver->setRequired([
self::PARAM_PATH,
self::PARAM_SOURCE,
]);
}

public function handle(array $arguments)
{
$document = TextDocumentBuilder::create(
$arguments[self::PARAM_SOURCE]
)->language('php')->uri($arguments[self::PARAM_PATH])->build();

$unresolvedClasses = $this->unresolvableClassNameFinder->find($document);

$responses = [];
foreach ($unresolvedClasses as $unresolvedClass) {
assert($unresolvedClass instanceof NameWithByteOffset);
$responses[] = $this->handler->handle(Request::fromNameAndParameters(ImportClassHandler::NAME, [
ImportClassHandler::PARAM_PATH => $arguments[self::PARAM_PATH],
ImportClassHandler::PARAM_SOURCE => $arguments[self::PARAM_SOURCE],
ImportClassHandler::PARAM_OFFSET => $unresolvedClass->byteOffset()->toInt() + 1
]));
}

if (empty($responses)) {
return EchoResponse::fromMessage('No unresolved classes found');
}

return CollectionResponse::fromActions($responses);
}

public function name(): string
{
return self::NAME;
}
}
7 changes: 7 additions & 0 deletions lib/Extension/ContextMenu/menu.json
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,13 @@
"source": "%source%"
}
},
"import_missing_classes": {
"action": "import_missing_classes",
"parameters": {
"path": "%current_path%",
"source": "%source%"
}
},
"hover": {
"action": "hover",
"parameters": {
Expand Down
12 changes: 12 additions & 0 deletions plugin/phpactor.vim
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ let g:phpactorInitialCwd = getcwd()
let g:phpactorCompleteLabelTruncateLength=50
let g:_phpactorCompletionMeta = {}

" hack to avoid calling fzf strategy when using a collection
" see: https://github.com/phpactor/phpactor/pull/843
let g:_phpactorRpcActionIsCollection = v:false

if !exists('g:phpactorPhpBin')
let g:phpactorPhpBin = 'php'
endif
Expand Down Expand Up @@ -215,8 +219,14 @@ endfunction
" Insert a use statement
""""""""""""""""""""""""
function! phpactor#UseAdd()
call phpactor#ImportClass()
endfunction
function! phpactor#ImportClass()
call phpactor#rpc("import_class", {"offset": phpactor#_offset(), "source": phpactor#_source(), "path": expand('%:p')})
endfunction
function! phpactor#ImportMissingClasses()
call phpactor#rpc("import_missing_classes", {"source": phpactor#_source(), "path": expand('%:p')})
endfunction

"""""""""""""""""""""""""""
" RPC Proxy methods
Expand Down Expand Up @@ -536,7 +546,9 @@ function! phpactor#_rpc_dispatch(actionName, parameters)
" >> collection
if a:actionName == "collection"
for action in a:parameters["actions"]
let g:_phpactorRpcActionIsCollection = v:true
let result = phpactor#_rpc_dispatch(action["name"], action["parameters"])

@camilledejoye camilledejoye Nov 27, 2019 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So you call phpactor#_rpc_dispatch for each action received, before the user have filter them ?

Ok I finally understand, you want the classic fzf window to open ant let the user choose which FQCN to import, like if the user did it manually.

I don't see a way to make that work, since fzf is aynchronous.
Maybe with a chained list of action, so that:

  • you dispatch the first one
  • the user choose the right class to import
  • the sink is called
    • it dispatch the import action with the choosen class (added the use statement)
    • it dispatch the next action in the list (which will in turn open fzf and ask for which fqcn to use)

Does it make sense ?

@dantleech dantleech Nov 27, 2019 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes -- but this is where I'm confused - it think it does that already (it calls the callback handler when the items are selected?). But I confess to not fully understanding everything that's going on 👀

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For me what appen is:

  • We receive the collection of action
  • In the loop we dispatch each action
  • The rpc handler call fzf for each of them
    • The first fzf window is open
    • Once opened the second one is open (or not because already one windows exists but it doesn't matter)
    • and again until the end of the loop

So we must not use fzf in a loop, we need to treat it like the chain I mentioned.
So that the user choose the class for the first one, and only once he made a choice we call the next action

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I got a question, let's say that we are in a file with 3 classes not yet imported: A, B and C.
The classes A and C have multiple possible FQCN and need the user to choose, B on the other hand as only one possibility.

In the collection that the new handler returns, does all three actions are the same ?
Or do we have two actions to choose the right FQCN and one to import the only possibility for B ?

let g:_phpactorRpcActionIsCollection = v:false

if !empty(result)
return result
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ public function testOutdatedGitIndex()
public function testMovesRelatedFiles()
{
$this->workspace()->put('.phpactor.json', json_encode([
'navigator.destinations' => [
"source" => "lib/<kernel>.php",
'navigator.destinations' => [
"source" => "lib/<kernel>.php",
"test" => "lib/<kernel>Test.php"
]
]));
Expand Down
2 changes: 0 additions & 2 deletions tests/Unit/Extension/ClassMover/Rpc/ClassMoveHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,6 @@ public function testItShouldAskForConfirmation()
$action = array_shift($actions);
$this->assertInstanceOf(CloseFileResponse::class, $action);
$this->assertEquals(self::SOURCE_PATH, $action->path());

}

public function testItAskIfRelatedFilesShouldBeMoved()
Expand Down Expand Up @@ -168,6 +167,5 @@ public function testMovesRelatedFiles()
'confirmed' => true,
'move_related' => true,
]);

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

namespace Phpactor\Tests\Unit\Extension\CodeTransformExtra\Rpc;

use Phpactor\CodeTransform\Domain\Helper\UnresolvableClassNameFinder;
use Phpactor\CodeTransform\Domain\NameWithByteOffset;
use Phpactor\Extension\CodeTransformExtra\Rpc\ImportMissingClassesHandler;
use Phpactor\Extension\Rpc\Response\CollectionResponse;
use Phpactor\Extension\Rpc\Response\EchoResponse;
use Phpactor\Extension\Rpc\RpcExtension;
use Phpactor\Extension\Rpc\Test\HandlerTester;
use Phpactor\Name\QualifiedName;
use Phpactor\Tests\IntegrationTestCase;
use Phpactor\TextDocument\ByteOffset;
use Phpactor\TextDocument\TextDocument;
use Prophecy\Argument;

class ImportMissingClassesHandlerTest extends IntegrationTestCase
{
const EXAMPLE_PATH = '/example/path';
const EXAMPLE_SOURCE = 'example-source';


private $requestHandler;
/**
* @var ObjectProphecy
*/
private $finder;

/**
* @var HandlerTester
*/
private $tester;

protected function setUp(): void
{
$this->requestHandler = $this->container()->get(RpcExtension::SERVICE_REQUEST_HANDLER);
$this->finder = $this->prophesize(UnresolvableClassNameFinder::class);

$this->tester = new HandlerTester(new ImportMissingClassesHandler(
$this->requestHandler,
$this->finder->reveal()
));
}

public function testZeroUnresolvedClasses()
{
$this->finder->find(Argument::type(TextDocument::class))->willReturn([]);

$response = $this->tester->handle(ImportMissingClassesHandler::NAME, [
ImportMissingClassesHandler::PARAM_PATH => self::EXAMPLE_PATH,
ImportMissingClassesHandler::PARAM_SOURCE => self::EXAMPLE_SOURCE,
]);

$this->assertInstanceOf(EchoResponse::class, $response);
}

public function testImportsUnresolvedClasses()
{
$this->finder->find(Argument::type(TextDocument::class))->willReturn([
new NameWithByteOffset(
QualifiedName::fromString('Foobar'),
ByteOffset::fromInt(12)
)
]);

$response = $this->tester->handle(ImportMissingClassesHandler::NAME, [
ImportMissingClassesHandler::PARAM_PATH => self::EXAMPLE_PATH,
ImportMissingClassesHandler::PARAM_SOURCE => self::EXAMPLE_SOURCE,
]);

$this->assertInstanceOf(CollectionResponse::class, $response);
}
}