Skip to content

0.7.0

Choose a tag to compare

@AJenbo AJenbo released this 08 Apr 04:34

Added

  • @psalm-return, @psalm-param, and @psalm-var tag support. Psalm-prefixed docblock tags are now recognized alongside their PHPStan equivalents for return types, parameter types, variable types, conditional return types, template parameter bindings, and semantic token highlighting.
  • Refactoring code actions. Extract function, extract method, extract variable, extract constant, inline variable, promote constructor parameter, generate constructor (traditional and promoted), generate getter/setter, and generate property hooks (PHP 8.4+). Deferred computation ensures the lightbulb menu appears instantly; edit generation only runs when the user picks an action.
  • PHPStan quickfixes. Automated fixes for a wide range of PHPStan diagnostics: update or remove mismatched @return/@param/@var tags, remove unused return type union members, fix unsafe new static() (add @phpstan-consistent-constructor, final class, or final constructor), add or remove #[Override], add #[\ReturnTypeWillChange], fix void return mismatches, add inferred iterable return types, remove unreachable statements, remove always-true assert() calls, fix overriding member visibility, fix vendor-prefixed class names, and simplify ternary expressions to ?? or ?->. All quickfixes eagerly clear their diagnostic on apply.
  • fix CLI subcommand. phpantom_lsp fix applies automated code fixes across a project. Specify rules with --rule (multiple allowed) or omit to run all preferred fixers. --dry-run reports what would change without writing files. The first shipped rule, unused_import, removes unused use statements project-wide, collapsing blank lines left behind by removals. Supports path filtering and single-file mode.
  • Keyword completions. Context-aware PHP keyword suggestions filtered by scope (e.g. return only inside functions, break only inside loops, member keywords inside class bodies, enum backing types after enum Name:). Contributed by @ryangjchandler in #43.
  • Attribute completion. Typing inside #[…] offers only classes decorated with #[\Attribute], filtered by the target declaration kind.
  • Eloquent model enhancements. Timestamp properties (created_at, updated_at) are automatically typed as Carbon with support for $timestamps = false and custom column constants. Legacy $dates arrays produce typed virtual properties. $appends entries produce virtual properties. where{PropertyName}() dynamic methods are synthesized from all known columns (including @property annotations) on both the model and the Builder. whereHas/whereDoesntHave closure parameters resolve to Builder<RelatedModel> by traversing relationship methods, with dot-notation chain support. Conditionable::when()/unless() chains preserve type information.
  • Type-guard narrowing. is_array(), is_string(), is_int(), is_float(), is_bool(), is_object(), is_numeric(), and is_callable() narrow union types inside if/else/elseif bodies and after guard clauses, preserving generic element types through narrowing.
  • Array value type tracking. Arrays built incrementally with variable keys inside loops now carry element types through foreach iteration, bracket access, and null-coalescing. Foreach over generic arrays with non-class element types (array shapes, scalars) now preserves the full element type.
  • Inherited docblock type propagation. When a child class overrides a method without providing its own @return or @param docblock, the ancestor's richer types flow through automatically. Applies to return types, parameter types (matched by position), property type hints, and descriptions.
  • Bidirectional template inference from closures. Templates appearing in callable parameter signatures are now inferred from both the closure's return type and its parameter types. Positional matching is supported, and return-type bindings take priority when the same template appears in both positions.
  • Drupal project support. Drupal projects are detected via composer.json. Drupal-specific directories and PHP extensions (.module, .install, .theme, .profile, .inc, .engine) are recognized and indexed. Contributed by @syntlyx in #52.
  • Completion and signature help for new self, new static, and new parent. Constructor parameter snippets and signature help inside the parentheses. Contributed by @RemcoSmitsDev in #51.
  • Hover on parameter variables at their definition site. Hovering on a function or method parameter now shows its resolved type, using the @param docblock type when it is richer than the native hint. Contributed by @RemcoSmitsDev in #68.
  • Array element type extraction from property generics. Bracket access on properties annotated with generic array or collection types (e.g. $this->cache[$key]->) now resolves the element type correctly through nested chains, string-literal keys, and method chains after the bracket.
  • @phpstan-assert-if-true $this narrowing. Instance methods annotated with @phpstan-assert-if-true or @phpstan-assert-if-false targeting $this now narrow the receiver variable in the corresponding branch. Contributed by @syntlyx in #52.
  • Namespace completion from file path. When creating a new PHP file, typing namespace suggests the correct namespace inferred from the file's location and the project's PSR-4 autoload mappings. The most specific mapping is preselected so you can accept it with a single keypress. When multiple PSR-4 roots match the same directory, all candidates appear ranked by specificity (longest match first).
  • Standalone @var docblock for untyped closure parameters. When a closure parameter lacks a type hint and no assignment follows, a @var block above the usage is now picked up as the variable's type.
  • --stdio CLI flag. Accepted (and ignored) for compatibility with LSP client wrappers that pass --stdio by default.
  • --tcp CLI flag. phpantom_lsp --tcp 9257 starts the server listening on a TCP port instead of stdin/stdout. Useful for debugging or connecting from IDE plugins that prefer a network transport over spawning a child process. Accepts a full address (127.0.0.1:9257) or just a port number. The server accepts one connection and exits when the client disconnects.
  • Method-level template parameters resolve inside method bodies. @template T of Builder with @param T $query now resolves $query to the template bound inside the method body, providing completions from the bound class.
  • Undefined variable diagnostic. Variable reads that have no prior definition (assignment, parameter, foreach binding, catch variable, global, static, use() clause, or destructuring) in the same scope are flagged as errors. Writes must appear before the read in source order, catching use-before-assign bugs, while assignments inside branches (if/else, switch, try/catch) still count to avoid false positives. Suppressed for superglobals, isset()/empty() guards, compact() references, extract() calls, variable variables ($$), @ error suppression, and @var annotations. Static property accesses (self::$prop, static::$prop, parent::$prop) are excluded. Variables passed to by-reference parameters are recognized as definitions: 40+ built-in PHP functions are covered (regex, cURL, OpenSSL, sockets, DNS, etc.), and user-defined functions, static methods, and constructors with &$param parameters are detected automatically from their signatures. Scoping is tracked through arbitrary nesting of closures, arrow functions, and catch blocks. Top-level code outside functions is skipped.
  • By-reference parameter type inference for method, static, and constructor calls. When a variable is passed to a by-reference parameter with a type hint (e.g. function foo(Baz &$bar)), the variable acquires that type after the call. Previously this only worked for standalone function calls. Now it also works for $this->method(), static method calls, and constructor calls.

Changed

  • Fewer false-positive diagnostics. Variable resolution now produces the same result across completions, hover, and diagnostics, eliminating cases where diagnostics disagreed about a variable's type.
  • @phpstan-ignore is never the preferred quickfix. The "Ignore PHPStan error" code action is explicitly non-preferred, so editor keyboard shortcuts no longer accidentally apply it when another fix is available.
  • Generate PHPDoc infers @return from the function body. Typing /** above a function that returns array now produces a specific element type (e.g. @return list<string>) instead of @return array<mixed>.
  • Faster startup. Stub loading during initialization is significantly faster.
  • More accurate generics resolution. Type substitution and resolution for complex nested generic types is more correct, particularly for unions, intersections, array shapes, and deeply nested generic arguments.
  • More accurate type predicates. NULL, Null, and case variants of null are now handled consistently throughout type checking, matching PHP's case-insensitive treatment of type keywords.
  • Go-to-definition at declaration sites returns the symbol's own location. Class, member, and variable declaration names now return their own location instead of nothing, so editors that detect "definition == cursor" can automatically fall back to Find References. Contributed by @lucasacoutinho in #76.

Fixed

  • Completion no longer triggers on the <?php open tag. Typing <?php and pressing enter no longer applies a spurious function suggestion like php_ini_loaded_file().
  • Case-insensitive parent handling in chained static calls. resolve_lhs_to_class now handles parent::method(...) in chained callable expressions and uses case-insensitive matching for self/static in the same context.
  • Intersection types preserved through resolution. Variables and parameters with intersection types (e.g. Countable&Serializable) now display correctly in hover, extract-function parameter hints, and generated docblocks. Previously intersection types were flattened to unions (Countable|Serializable).
  • Return types now carry class info through the resolution pipeline. Method and function return types that name a class (e.g. Collection<User>) now populate the resolved class info eagerly, so downstream consumers (hover, narrowing, completion) no longer need a second resolution pass.
  • Generic parameters preserved on resolved types. Catch clause variables, pass-by-reference parameters, closure parameters, and constructor calls now thread the original type hint (including generic parameters) through the resolution pipeline instead of discarding it.
  • Type-guard narrowing no longer drops class info on unions. Narrowing a union like Foobar|string|int with is_string()/is_int() in elseif chains now correctly preserves class info for the remaining class member.
  • False-positive undefined-variable diagnostic on static property access. self::$prop, static::$prop, and ClassName::$prop no longer trigger an undefined variable warning. Dynamic forms (self::$$prop, self::${expr}) still correctly flag undefined variables used in the expression. Contributed by @lucasacoutinho in #75.
  • Case-insensitive self, static, and parent resolution. SELF::method(), Static::create(), PARENT::foo(), and other non-lowercase spellings now resolve correctly. Previously only the exact lowercase forms were recognized.
  • Property type resolution in call arguments. When a method argument is $this->prop and the property has a generic, nullable, or union type, the full type structure is now preserved. Previously only the base class name was extracted, discarding generics and union components.
  • Update docblock enrichment comparison. The "Update docblock" code action now uses structural type comparison instead of string equality when deciding whether a @param type needs enrichment. Types that are semantically equivalent but formatted differently (e.g. \App\User vs App\User) no longer trigger spurious updates. Body-based @return enrichment now correctly detects when an existing @return tag already has type structure, instead of always proposing a replacement.
  • @phpstan-assert and @psalm-assert tags with generic types. Assertions like @phpstan-assert Collection<int, User> $param now parse the full generic type instead of truncating at the first space inside angle brackets.
  • parent::method() resolution in inline arguments. Passing parent::method() as an argument to a function now resolves the return type correctly, matching the existing handling for self:: and static::.
  • Laravel Eloquent Builder and Collection type resolution. Generic and nullable types on Eloquent models (e.g. Collection<int, User>, ?User) now resolve correctly when used for Builder scope injection, custom collection swapping, and relationship chain inference. Previously these types were stringified with their generic parameters or nullable prefix, causing lookups to fail silently.
  • Docblock generation no longer panics on lines with multibyte characters. Files containing non-ASCII characters (e.g. accented letters) could cause the /** docblock trigger to crash or produce misaligned edits due to a mismatch between UTF-16 column offsets and byte offsets.
  • Conditional return types showing mixed in hover. When a method with a conditional return type (e.g. @phpstan-return ($type is class-string<T> ? T : mixed)) resolved to a concrete class, hover still displayed the method's declared return type (mixed) instead of the resolved class. Affects methods like Symfony's SerializerInterface::deserialize().
  • Method-level @throws types now resolve short names to FQN. Exception types in @throws tags on class methods are now fully qualified using the file's use imports, matching the behaviour already in place for standalone functions. Cross-file throws propagation and the "Update docblock" code action produce correct results when the exception class is imported via a use statement.
  • Missing diagnostics and import actions in files without a namespace. When a namespaced class (e.g. Carbon\Carbon) had already been parsed, using its short name (Carbon) in a file without a namespace declaration incorrectly resolved against the namespaced class. This suppressed both the "class not found" diagnostic and the "Import" code action. Bare-name lookups now only match classes that are themselves in the global namespace.
  • Find-references false positives for global classes. Searching for references to a global-scope class (e.g. Helper with no namespace) could include references to unrelated namespaced classes with the same short name (e.g. App\Helper). Short-name fallback matching now only applies when the resolved name is unqualified.
  • Fluent chains only flag the first broken link. In a chain where the first method does not exist, only that method is flagged instead of every subsequent call receiving its own warning.
  • Null narrowing from !== null checks. Null-initialized variables guarded by $var !== null, !is_null(), or bare truthy checks now have null narrowed away inside the then-body and in subsequent && operands. Works in chained conditions, ternary expressions, and return statements.
  • Variables assigned inside if/while conditions now resolve in the body. if ($admin = AdminUser::first()) and while ($row = nextRow()) register the assignment so the variable has a type inside the branch or loop body.
  • Loop-body assignments not visible inside the same loop iteration. When a variable is initialized as null and reassigned later in a loop body, the assigned type is now visible at every point inside the loop. Combined with null narrowing, variables correctly resolve to the assigned class type.
  • @var docblock annotations no longer leak across class and method boundaries. A @var annotation for a same-named variable in a different class no longer bleeds into the current scope.
  • Inline @var cast no longer overrides the variable type on the RHS of the same assignment. /** @var array<string, mixed> */ $data = $data->toArray() no longer resolves the RHS $data using the cast type.
  • Foreach over union types containing arrays now resolves the element type. A parameter typed User|array<User> iterated with foreach now correctly yields User as the loop variable type. Previously the element type extraction did not look inside union members, producing no completions.
  • @param docblock overrides ignored when the native type hint resolves. When a parameter has both a native type hint and a more specific @param override, the docblock type now takes effect. Contributed by @calebdw in #55.
  • Variable reassignment inside try/catch/finally blocks now tracked. Subsequent accesses within the same block resolve against the reassigned type instead of the original.
  • Self-referential variable reassignments in nested loops no longer produce false "type could not be resolved" diagnostics. Recursive resolution that hits the depth limit no longer poisons the cache for later lookups.
  • instanceof narrowing with unresolvable target class. When the target class cannot be loaded, the variable's type is treated as unknown instead of keeping the un-narrowed type, eliminating false positives for members on the narrowed subclass.
  • stdClass and object types no longer produce false-positive diagnostics. Variables typed as object or stdClass now permit arbitrary property access. is_object() correctly narrows mixed to object and compound && conditions propagate the narrowing.
  • Docblock type refinement no longer matches class names containing type keywords. A class named PointOfInterest would incorrectly be treated as an int refinement because the refinement check used substring matching. Refinement compatibility now uses structural type predicates.
  • class-string<T> static method dispatch. Calling static methods on a class-string<Foo> variable now resolves return types correctly, including static substitution to the bound class.
  • self/static/$this in cross-file method return types now resolve correctly. When a method on a cross-file class returns a type referencing self (e.g. @return HasMany<self, $this>), the owning class was looked up by short name through the consuming file's import table, which failed when the consuming file did not import that class. The owning class is now looked up by its fully-qualified name.
  • in_array guard clause no longer wipes out variable type. When the haystack's element type matches the variable's type, the narrowing system no longer excludes the type entirely.
  • Method chains through __call no longer lose the return type. When __call returns $this, static, or self, the chain type is preserved through dynamic method calls.
  • Scope methods on Eloquent Builder no longer produce false-positive diagnostics. Bare Builder return types on scope methods are automatically wrapped as Builder<ConcreteModel> to preserve the chain.
  • Scope methods missing from completion on relationship results. Scope methods from related models now appear in completions, not just hover.
  • Closure and variable hover now preserves generic arguments. Closure parameters inferred from callable signatures, variables assigned from chained methods returning static/$this/self, and hovering on the $ sign of a variable at its assignment site all now show the correct generic type.
  • Callable parameter inference preserves generic arguments from the receiver. A closure typed as fn(Builder $q) inside a Builder<Product> chain now infers $q as Builder<Product>, so model-specific scope methods resolve correctly.
  • @see tags in floating docblocks now support go-to-definition. Docblock comments not directly attached to a class, function, or statement (e.g. inline /** @see SupervisorOptions::$balanceCooldown */ inside array literals or after expressions) are now parsed for symbol references. Previously these were silently ignored, particularly in files without a namespace.
  • Nullable static return types on inherited methods. Methods returning ?static or static|null now correctly resolve to the calling subclass across files.
  • Template binding with nested generics. Parameter types like Wrapper<Collection<T>, V> no longer break during template binding.
  • Single generic argument on collections bound to the wrong template parameter. Collection<User> now binds to the value parameter instead of the key parameter when key-like template parameters precede value parameters.
  • Nullable return types losing |null after template substitution. @return TValue|null now preserves |null through substitution, so calls like ::first() correctly show the nullable type.
  • @mixin referencing a template parameter now resolves. A class with @template T and @mixin T now pulls in methods from the concrete type passed via generic arguments.
  • @property and @method tags losing nullable types. Tags like @property int|null $foo no longer have |null stripped.
  • Callable types inside unions displayed ambiguously. (Closure(int): string)|Foo is now parenthesized correctly in hover and completions.
  • Hover and go-to-definition on attributes. Attributes on properties, class constants, parameters, and enum cases are now navigable.
  • Function-level @template with generic wrapper parameters. Template substitution at call sites now correctly handles array, iterable, and list as wrapper names.
  • Closure parameter inference from function-level @template bindings. Functions like array_any and array_all now infer concrete types for untyped closure arguments from the array parameter's element type.
  • Property chain arguments in template substitution. Expressions like $this->items passed to templated functions now resolve their type for template binding.
  • Variadic parameter element type lost in foreach. Iterating over a variadic parameter now resolves the loop variable to the element type.
  • Anonymous class variables now resolve their type. $model = new class extends Foo { ... } followed by $model->method() now resolves through the anonymous class's inherited members.
  • Namespaced functions imported via use function no longer flagged as unknown. Functions defined in one file and imported via use function in another now resolve correctly.
  • parent::method() return type resolution in variable analysis. Calling parent::method() and assigning the result now correctly resolves the parent method's return type.
  • Closure parameter inference inside switch cases and if conditions. Closure parameters that should be inferred from the enclosing callable context now resolve correctly when the closure appears inside a switch case or if-condition.
  • Generic arguments propagated through transitive @extends chains. When a class extends a parent that itself extends a generic grandparent, generic arguments now flow through the full chain.
  • Stack overflow when a foreach value variable shadows the iterator receiver. Patterns like foreach ($category->getBranch() as $category) no longer cause infinite recursion.
  • PHPStan * wildcard in generic type arguments. Type strings like Relation<TRelatedModel, *, *> now parse correctly.
  • Types with covariant or contravariant variance annotations in generic args now parse correctly. Annotations like BelongsTo<Category, covariant $this> no longer cause the entire type to become unresolvable.
  • Diagnostics now work for vendor files open in the editor. Projects using --prefer-source or monorepo setups no longer have diagnostics suppressed in vendor files.
  • PHPStan diagnostics no longer hidden by unrelated native diagnostics on the same line. Deduplication now only suppresses a full-line diagnostic when the precise diagnostic on the same line reports a related issue.
  • Nullable boolean properties now use is prefix for getters. Properties typed ?bool or ?boolean now generate isFoo() instead of getFoo() when using the "Generate getter" code action.
  • Aliased namespace imports used in attributes no longer flagged as unused. use Symfony\Component\Validator\Constraints as Assert; with #[Assert\Uuid(...)] no longer produces a false "Unused import" diagnostic.
  • DB::select() return type. DB::select() and related methods now return array<int, stdClass> instead of bare array, and DB::selectOne() returns ?stdClass.
  • Redis Connection method resolution. Redis commands on Illuminate\Redis\Connections\Connection now resolve through the phpredis stubs.
  • Array shape tracking from keyed assignments inside conditional branches. Shape types built incrementally with variable keys inside loops with if/else branching are now preserved through foreach iteration.
  • Deprecated class in implements renders with strikethrough. Deprecated classes referenced in implements clauses are correctly tagged.
  • Interleaved array access and property chains no longer produce false positives. Expressions like $results[$i]->activities[$id]->extras where array subscript and property access alternate were incorrectly parsed, causing the intermediate property chain to be dropped. This led to "Property not found on class" false positives when the element type was resolved but the subsequent property lookup was skipped.
  • FQN \assert() now narrows types. Writing \assert($var instanceof Foo) with a leading backslash was not recognized as an instanceof narrowing, causing false-positive "property not found" diagnostics after the assertion.
  • Generic template substitution producing invalid types. When a template parameter was the base of a generic type (e.g. T<int> where T maps to Collection<string>), the substitution produced malformed types like Collection<string><int>. The replacement's base name is now used correctly, yielding Collection<int>.

New Contributors

Full Changelog: 0.6.0...0.7.0