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: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ Changelog

## master

Imrprovements:
Features:

- Additive stubs #2968 @dantleech

Improvements:

- Restrict attribute completion using targets #2629 @przepompownia
- Use the Phan fork of the Tolerant Parser as a base #2946 @dantleech
Expand Down
17 changes: 15 additions & 2 deletions doc/reference/configuration.rst
Original file line number Diff line number Diff line change
Expand Up @@ -903,6 +903,19 @@ Location of the core PHP stubs - these will be scanned and cached on the first r
**Default**: ``"%application_root%\/vendor\/jetbrains\/phpstorm-stubs"``


.. _param_worse_reflection.additive_stubs:


``worse_reflection.additive_stubs``
"""""""""""""""""""""""""""""""""""


Additive stubs files relative to the project root. These stubs augment existing defininitions.


**Default**: ``[]``


.. _param_worse_reflection.diagnostics.undefined_variable.suggestion_levenshtein_disatance:


Expand Down Expand Up @@ -933,7 +946,7 @@ FilePathResolverExtension
"""""""""""""""""""""""""""""""""""


**Default**: ``"\/home\/arctgx\/dev\/arctgx\/php\/phpactor\/phpactor-dev"``
**Default**: ``"\/home\/daniel\/www\/phpactor\/phpactor"``


.. _param_file_path_resolver.app_name:
Expand Down Expand Up @@ -1426,7 +1439,7 @@ Amount of time (in milliseconds) to wait before responding to a shutdown notific
Internal use only - name path to Phpactor binary


**Default**: ``"\/home\/arctgx\/dev\/arctgx\/php\/phpactor\/phpactor-dev\/lib\/Extension\/LanguageServer\/..\/..\/..\/bin\/phpactor"``
**Default**: ``"\/home\/daniel\/www\/phpactor\/phpactor\/lib\/Extension\/LanguageServer\/..\/..\/..\/bin\/phpactor"``


.. _param_language_server.self_destruct_timeout:
Expand Down
34 changes: 34 additions & 0 deletions doc/reference/stubs.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
.. _stubs:

Stubs
=====

Phpactor has two types of "stubs":

PHP Core Stubs
--------------

These stubs fill in for definitions (classes, functions and constants) that are
defined in the PHP core or in PHP extensions. Phpactor expects the path to be a
single directory and that directory is configured by default to be the one
containing the `PHPStorm stubs <https://github.com/JetBrains/phpstorm-stubs/>`_
that are bundled with Phpactor.

You probably do **not** want to change this setting, but the directory *can* be
changed at as :ref:`param_worse_reflection.additive_stubs`.

Additive Stubs
--------------

These stubs **augment** existing classes. For example, in Laravel you may use the `Laravel IDE Helper <https://github.com/barryvdh/laravel-ide-helper>`_ package to provide missing "magic" methods and properties. New definitions cannot be provided with additive stubs.


You can specify these stub files with :ref:`param_worse_reflection.additive_stubs` and the stubs will merge onto the existing definitions.

.. note::

Additive stubs should *not* be indexed as Phpactor will be unable to
determine which definition is the canonical one. If you use additive stubs
ensure that you also manually specify which directories contain your project code (typically `src` and `tests`).

The indexer include patterns can be specified with :ref:`param_indexer.include_patterns`.
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@
use Phpactor\Extension\LanguageServerWorseReflection\InlayHint\InlayHintOptions;
use Phpactor\Extension\LanguageServerWorseReflection\InlayHint\InlayHintProvider;
use Phpactor\Extension\LanguageServerWorseReflection\Listener\InvalidateDocumentCacheListener;
use Phpactor\Extension\LanguageServerWorseReflection\Listener\StubValidationListener;
use Phpactor\Extension\LanguageServerWorseReflection\SourceLocator\WorkspaceSourceLocator;
use Phpactor\Extension\LanguageServerWorseReflection\Workspace\WorkspaceIndex;
use Phpactor\Extension\LanguageServerWorseReflection\Workspace\WorkspaceIndexListener;
use Phpactor\Extension\LanguageServer\Container\DiagnosticProviderTag;
use Phpactor\Extension\LanguageServer\LanguageServerExtension;
use Phpactor\Extension\WorseReflection\WorseReflectionExtension;
use Phpactor\LanguageServer\Core\Server\ClientApi;
use Phpactor\LanguageServer\Core\Workspace\Workspace;
use Phpactor\MapResolver\Resolver;
use Phpactor\WorseReflection\Core\CacheForDocument;
Expand All @@ -34,6 +36,13 @@ class LanguageServerWorseReflectionExtension implements Extension
public function load(ContainerBuilder $container): void
{
$this->registerSourceLocator($container);

$container->register(StubValidationListener::class, function (Container $container) {
return new StubValidationListener(
$container->get(ClientApi::class),
$container->parameter(WorseReflectionExtension::PARAM_ADDITIVE_STUBS)->listOfString(),
);
}, [ LanguageServerExtension::TAG_LISTENER_PROVIDER => [] ]);
}

public function configure(Resolver $schema): void
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

namespace Phpactor\Extension\LanguageServerWorseReflection\Listener;

use Phpactor\LanguageServer\Core\Server\ClientApi;
use Phpactor\LanguageServer\Event\Initialized;
use Psr\EventDispatcher\ListenerProviderInterface;

class StubValidationListener implements ListenerProviderInterface
{
/**
* @param list<string> $stubPaths
*/
public function __construct(private ClientApi $api, private array $stubPaths)
{
}

/**
* @return iterable<callable>
*/
public function getListenersForEvent($event): iterable
{
if (!$event instanceof Initialized) {
return;
}


yield function (): void {
$invalidPaths = [];
foreach ($this->stubPaths as $stubPath) {
if (file_exists($stubPath)) {
continue;
}

$invalidPaths[] = $stubPath;
}

if ([] === $invalidPaths) {
return;
}

$this->api->window()->showMessage()->warning(sprintf(
'The following stubs could not be found: "%s"',
implode('", "', $invalidPaths)
));
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,21 @@ public function testProvideReflectorWithStubs(): void
$this->assertEquals((string) $reflector->reflectClass(__CLASS__)->name(), __CLASS__);
}

public function testAdditiveStubPaths(): void
{
$reflector = $this->createReflector([
WorseReflectionExtension::PARAM_ADDITIVE_STUBS => [
'example/stub.stub',
],
FilePathResolverExtension::PARAM_APPLICATION_ROOT => __DIR__ . '/../../../../..',
FilePathResolverExtension::PARAM_PROJECT_ROOT => __DIR__
]);

$reflection = $reflector->reflectClass(__CLASS__);
$method = $reflection->methods()->byName('testAdditiveStubPaths')->first();
self::assertEquals('string', $method->inferredType()->__toString());
}

public function testProvideReflectorWithStubsAndCustomCacheDir(): void
{
$reflector = $this->createReflector([
Expand Down
14 changes: 14 additions & 0 deletions lib/Extension/WorseReflection/Tests/Unit/example/stub.stub
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Phpactor\Extension\WorseReflection\Tests\Unit;

class WorseReflectionExtensionTest extends TestCase
{
/**
* @return string
*/
public function testAdditiveStubPaths(): void
{
}
}

14 changes: 14 additions & 0 deletions lib/Extension/WorseReflection/WorseReflectionExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Phpactor\Extension\WorseReflection\Documentor\DiagnosticDocumentor;
use Phpactor\Extension\OpenTelemetry\OpenTelemetryExtension;
use Phpactor\Extension\WorseReflection\Telemetry\WorseTelemetry;
use Phpactor\FilePathResolver\PathResolver;
use Phpactor\WorseReflection\Bridge\Phpactor\MemberProvider\DocblockMemberProvider;
use Phpactor\WorseReflection\Bridge\TolerantParser\Diagnostics\AssignmentToMissingPropertyProvider;
use Phpactor\WorseReflection\Bridge\TolerantParser\Diagnostics\DeprecatedUsageDiagnosticProvider;
Expand All @@ -32,13 +33,15 @@
use Phpactor\WorseReflection\Core\SourceCodeLocator\NativeReflectionFunctionSourceLocator;
use Phpactor\WorseReflection\Core\SourceCodeLocator\StubSourceLocator;
use Phpactor\WorseReflection\Bridge\Phpactor\ClassToFileSourceLocator;
use Phpactor\WorseReflection\Core\Virtual\StubFileMemberProvider;
use Phpactor\WorseReflection\ReflectorBuilder;
use Phpactor\Container\Extension;
use Phpactor\MapResolver\Resolver;
use Phpactor\Container\ContainerBuilder;
use Phpactor\Container\Container;
use Phpactor\WorseReflection\Bridge\TolerantParser\Parser\CachedParser;
use Phpactor\WorseReflection\Bridge\TolerantParser\Reflector\TolerantFactory;
use Symfony\Component\Filesystem\Path;

class WorseReflectionExtension implements Extension
{
Expand All @@ -56,6 +59,7 @@ class WorseReflectionExtension implements Extension
const TAG_MEMBER_TYPE_RESOLVER = 'worse_reflection.member_type_resolver';
const PARAM_IMPORT_GLOBALS = 'language_server_code_transform.import_globals';
const PARAM_UNDEFINED_VAR_LEVENSHTEIN = 'worse_reflection.diagnostics.undefined_variable.suggestion_levenshtein_disatance';
const PARAM_ADDITIVE_STUBS = 'worse_reflection.additive_stubs';

public function configure(Resolver $schema): void
{
Expand All @@ -66,6 +70,7 @@ public function configure(Resolver $schema): void
self::PARAM_ENABLE_CONTEXT_LOCATION => true,
self::PARAM_STUB_CACHE_DIR => '%cache%/worse-reflection',
self::PARAM_STUB_DIR => '%application_root%/vendor/jetbrains/phpstorm-stubs',
self::PARAM_ADDITIVE_STUBS => [],
self::PARAM_UNDEFINED_VAR_LEVENSHTEIN => 4,
]);
$schema->setDescriptions([
Expand All @@ -79,6 +84,7 @@ public function configure(Resolver $schema): void
EOT
,
self::PARAM_STUB_DIR => 'Location of the core PHP stubs - these will be scanned and cached on the first request',
self::PARAM_ADDITIVE_STUBS => 'Additive stubs files relative to the project root. These stubs augment existing defininitions.',
self::PARAM_STUB_CACHE_DIR => 'Cache directory for stubs',
self::PARAM_IMPORT_GLOBALS => 'Show hints for non-imported global classes and functions',
]);
Expand All @@ -100,6 +106,7 @@ public function load(ContainerBuilder $container): void
private function registerReflection(ContainerBuilder $container): void
{
$container->register(self::SERVICE_REFLECTOR, function (Container $container) {
$resolver = $container->get(FilePathResolverExtension::SERVICE_FILE_PATH_RESOLVER);
$builder = ReflectorBuilder::create()
->withSourceReflectorFactory(new TolerantFactory($container->expect(self::SERVICE_PARSER, Parser::class)))
->cacheLifetime($container->parameter(self::PARAM_CACHE_LIFETIME)->float());
Expand Down Expand Up @@ -187,6 +194,13 @@ private function registerMemberProviders(ContainerBuilder $container): void
$container->register('worse_reflection.member_provider.docblock', function (Container $container) {
return new DocblockMemberProvider();
}, [ self::TAG_MEMBER_PROVIDER => []]);
$container->register('worse_reflection.member_provider.stubs', function (Container $container) {
$resolver = $container->expect(FilePathResolverExtension::SERVICE_FILE_PATH_RESOLVER, PathResolver::class);
return new StubFileMemberProvider(array_map(function (string $path) use ($resolver) {
$projectRoot = $resolver->resolve('%project_root%');
return Path::join($projectRoot, $resolver->resolve($path));
}, $container->parameter(self::PARAM_ADDITIVE_STUBS)->listOfString()));
}, [ self::TAG_MEMBER_PROVIDER => []]);
}

private function registerDiagnosticProviders(ContainerBuilder $container): void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,11 @@ public function members(): ReflectionMemberCollection
return $this->members;
}
$members = ClassLikeReflectionMemberCollection::empty();
$providedMembers = ClassLikeReflectionMemberCollection::empty();
foreach ($this->hierarchy() as $reflectionClassLike) {
$classLikeMembers = $reflectionClassLike->ownMembers();
$classLikeMembers = $classLikeMembers->merge($this->serviceLocator->methodProviders()->provideMembers(
/** @phpstan-ignore-next-line collection IS compatible */
$providedMembers = $providedMembers->merge($this->serviceLocator->methodProviders()->provideMembers(
$this->serviceLocator,
$reflectionClassLike
));
Expand Down Expand Up @@ -115,6 +117,7 @@ public function members(): ReflectionMemberCollection
continue;
}
}
$members = $members->merge($providedMembers);
$this->members = $members->map(fn (ReflectionMember $member) => $member->withClass($this));

return $this->members;
Expand Down
10 changes: 10 additions & 0 deletions lib/WorseReflection/Core/ServiceLocator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Phpactor\WorseReflection\Bridge\Phpactor\DocblockParser\CachedParserFactory;
use Phpactor\WorseReflection\Bridge\Phpactor\DocblockParser\DocblockParserFactory;
use Phpactor\WorseReflection\Bridge\Phpactor\MemberProvider\DocblockMemberProvider;
use Phpactor\WorseReflection\Core\Cache\NullCache;
use Phpactor\WorseReflection\Core\Cache\StaticCache;
use Phpactor\WorseReflection\Core\Inference\GenericMapResolver;
Expand All @@ -28,6 +29,7 @@
use Phpactor\WorseReflection\Core\SourceCodeLocator\TemporarySourceLocator;
use Phpactor\WorseReflection\Core\DocBlock\DocBlockFactory;
use Phpactor\WorseReflection\Core\Reflector\SourceCodeReflectorFactory;
use Phpactor\WorseReflection\ReflectorBuilder;
use Psr\Log\LoggerInterface;

class ServiceLocator
Expand Down Expand Up @@ -170,4 +172,12 @@ public function newDiagnosticsWalker(): DiagnosticsWalker
{
return new DiagnosticsWalker($this->diagnosticProviders);
}

public function stubReflector(): Reflector
{
return ReflectorBuilder::create()
->addLocator($this->sourceLocator)
->addMemberProvider(new DocblockMemberProvider())
->build();
}
}
64 changes: 64 additions & 0 deletions lib/WorseReflection/Core/Virtual/StubFileMemberProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

namespace Phpactor\WorseReflection\Core\Virtual;

use Phpactor\TextDocument\TextDocumentBuilder;
use Phpactor\WorseReflection\Core\Reflection\Collection\ChainReflectionMemberCollection;
use Phpactor\WorseReflection\Core\Reflection\Collection\ReflectionMemberCollection;
use Phpactor\WorseReflection\Core\Reflection\ReflectionClassLike;
use Phpactor\WorseReflection\Core\ServiceLocator;
use RuntimeException;

class StubFileMemberProvider implements ReflectionMemberProvider
{
/**
* @var array<string,ReflectionClassLike>
*/
private array $stubClasses = [];

private bool $initialized = false;

/**
* @param list<string> $stubFiles
*/
public function __construct(private array $stubFiles)
{
}

public function provideMembers(ServiceLocator $locator, ReflectionClassLike $class): ReflectionMemberCollection
{
$this->buildMap($locator);

if (!isset($this->stubClasses[$class->name()->__toString()])) {
return ChainReflectionMemberCollection::fromCollections([]);
}

$stubClass = $this->stubClasses[$class->name()->__toString()];
return $stubClass->members();
}

private function buildMap(ServiceLocator $locator): void
{
if ($this->initialized === true) {
return;
}

$classes = [];
foreach ($this->stubFiles as $stubFile) {
try {
$document = TextDocumentBuilder::fromUri($stubFile)->language('php')->build();
} catch (RuntimeException) {
// depend on validation on startup rather than break everything
continue;
}
foreach ($locator->stubReflector()->reflectClassesIn(
$document,
) as $class) {
$classes[$class->name()->__toString()] = $class;
}
}

$this->stubClasses = $classes;
$this->initialized = true;
}
}
Loading