Changelog¶
All notable changes to PHPantom will be documented in this file.
The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.
Unreleased¶
Added¶
Blade templates¶
- Flux and Filament components. Flux's
<flux:button>tags complete, offer the attributes the component declares, jump to its template in the package, and are reported when no component has the name. Components a package registers by directory, such as Flux's, now work under their<x-prefix::…>spelling too.
Fixed¶
- Livewire 4's view locations are view roots. Templates in the directories Livewire 4's
component_locationsandcomponent_namespacessettings name (by defaultresources/views/livewireandpages::) are views by those names, soview()and@includecalls naming them are no longer reported as unknown. A<livewire:…>tag is checked against the components in every location the config names. $appis defined in every Blade template. Laravel shares the application with all views, so{{ $app->getLocale() }}is no longer reported as an undefined variable and its members complete.-
No unknown-component report for a bare tag a package path answers.
<x-badge>reaches a template a package registered withBlade::anonymousComponentPath()under a prefix, as Laravel resolves it, so it is no longer reported as unknown. -
Claude Code no longer sees outdated diagnostics after an edit. Results from before an edit, at line numbers that no longer match the file, are not reported to the agent as new findings.
- Claude Code follows files changed by shell commands. A file rewritten or deleted by a command the agent runs, such as a formatter or
git checkout, is picked up within a second instead of keeping its old contents until the agent next edits it. - Missing properties on the left of
??are no longer reported.$this->label ?? ''and$this->cache ??= []read the property the wayisset()does, so a property the class does not declare is not an error there. A missing method on that side is still reported. - Undefined variables in a dynamic class constant fetch. An undefined
$nameinFoo::{$name}is reported like any other read of it. - Hover shows
readonlyproperties. A property declaredreadonly, promoted as one, or belonging to areadonlyclass shows the keyword in its hover. - DNF types are spelled as PHP writes them. A union holding an intersection shows as
(A&B)|nullin hover and anywhere else a type is written out, instead ofA&B|null, which is not valid PHP. clamp()returns its arguments' types. The result ofclamp($value, $min, $max)is typed from its arguments instead ofmixed.- More conditional return types are decided. A condition comparing a template with a class constant (
T is self::TYPE_STRING), counting the call's arguments withfunc_num_args(), or testingPHP_VERSION_IDnow picks the branch the call takes instead of the last branch or both.PHP_VERSION_IDis typed as the configured PHP version's range, such asint<80500, 80599>. - No unknown members on a class whose parent cannot be found. When a parent class, interface, or trait is missing, such as a test extending PHPUnit's
TestCasebeforecomposer install, the missing class is reported once instead of every member it would have supplied. - A guarded copy of a class no longer hides the real one. A fallback declared behind
if (! class_exists(Foo::class))orif (false)gives way to the class Composer would autoload, so members only the real class has are no longer reported unknown. - A class declared in more than one file reads its own members. Inside each declaration of a class that several files declare, such as a polyfill's variants,
$this,selfandstaticsee the members declared there, not another file's. - Looping over an intersection type.
foreachover a value typedCollection&iterable<User>gives each element asUser, and its key as the iterable says, instead ofmixed. - Values assigned before
continuereach the next iteration. Hovering or completing inside a loop body now sees what a variable was assigned on a path that ended incontinue. $i++forgets what was known about$items[$i]. Incrementing a variable, or updating it with+=and the like, drops a narrowing recorded for an expression that reads it, as a plain assignment already did.- An enum's
$this->valuefollows narrowing. Afterif ($this === self::None) { return; },$this->valueand$this->nameonly hold the remaining cases' values and names. - Omitted arguments bind templates to their defaults. Calling
@param T $test = 0without the argument typesTas0, the value PHP passes in its place. - Wildcard class constants open at both ends.
@param self::*OTHER* $xcovers every constant whose name containsOTHER. (string)on a generic object. Casting an object whose__toString()returns a template type, such asclass-string<T>, gives the type for that object's generic arguments.- Arithmetic with a float is a float.
$string * 1e-6, or any other arithmetic between a float and a string, bool, or null, is typedfloatinstead ofint|float. in_array()narrows an untyped needle. A parameter without a type, checked within_array($value, $strings, true), is astringinside the check.trigger_error()withE_USER_ERRORends the script. Code afterif ($s === null) { trigger_error('…', E_USER_ERROR); }sees$sas non-null, and the call itself isnever.- Calls on a union of classes return one flat union.
$fooOrBar->getParam(), where the two classes return?stringand?int, isstring|int|nullinstead of?string|?int. ??=with a literal fallback keeps the base type.$settings['name'] ??= 'unknown'on an optionalstringentry leaves astring, notstring|'unknown'.if ($x ?? false)narrows$x. Inside the branch$xis set and truthy, as inif ($x).staticin a final class is that class. A method returningstatic, called through$thisin afinalclass or an enum, returns the class itself instead ofstatic(Foo).fetchObject()returns the class it is given.PDOStatement::fetchObject(Foo::class),mysqli_result::fetch_object()andmysqli_fetch_object()no longer addstdClassto the class named in the call.- A type check on an array entry proves the key exists. After
is_int($a['key'])oris_int($a['key'] ?? null), an optionalkeyin$a's shape is required and typedint. - Writing under a template key keeps the template.
$array[$key] = $valuewith$keytypedTKey of array-keybuilds anarray<TKey, …>instead ofarray<int|string, …>. min()andmax()on a union of literal arrays. The result is the smallest or largest value of each array, rather than every value any of them holds.ReflectionClass::getName()returns a class string. For aReflectionClass<Foo>it isclass-string<Foo>, so it can be passed where a class name is expected.~on a value that may be a string or an int. The result isint|stringinstead ofint.- A loop body that always returns no longer feeds the next iteration. Inside
while,forandforeach, a value assigned just before areturnorthrowat the end of the body no longer shows up at the top of the loop, and after a loop over a non-empty array whose body always breaks out, a variable holds what the body assigned before breaking. unset()of an integer key.unset($a[1])removes that entry from an array shape, so[1, 2, 3]becomesarray{0: 1, 2: 3}, and a list loses its list promise.count()of a fixed-size array.count()andsizeof()of an array shape give its size, or the range its optional entries allow, also with aCOUNT_NORMALorCOUNT_RECURSIVEmode when no entry can hold an array.- Comparing with
nullby order narrows.$x <= nullnarrows the way$x == nulldoes, and$x > nullrules outnull. - Overriding a method a parent gets from a trait inherits its docblock. When a parent class takes a method from a trait, an override without its own
@paramor@returntypes uses the trait method's. preg_replace_callback()callbacks know their matches. The callback's$matchesparameter holds the groups the pattern captures, typed the waypreg_match()types them.?parentreturn types keepnull. A method declared: ?parentor: parent|nullreturns the parent class ornull, instead of always the parent class.- Closure parameters with a
nulldefault are nullable. Infunction (string $x = null),$xis?stringin the closure's signature and in what calling it returns. clonenever givesnull.clone $xon a?Foois aFoo, cloning a value of unknown type gives anobject, andclone new $thiskeeps the class.throwas an expression isnever.fn () => throw new Exception()returnsnever.base64_decode()returnsfalseonly in strict mode. Without$strictit is typedstring.pathinfo()may leave outdirname. The empty path has no directory part, so the array'sdirnamekey is optional.
1.1.0 - 2026-11-24¶
Added¶
Editing and navigation¶
- Named arguments follow the parameter they name. A label such as
name:innew SelectField(name: 'x')or$field->render(name: 'x')jumps to the parameter it fills, hovers as it, highlights with it, shows up in its references, and renames with it. When that parameter promotes a property, the label moves with the property as well. Contributed by @AbyssWaIker. - Signature help for invokable objects. Calling an object, as in
$action('x'),app(TestAction::class)('x')or(new TestAction())('x'), shows the parameters of its__invoke()method, and the arguments are checked against them. useimports fold. A file's block ofusestatements folds as one region, the same way a method body does. It is reported as an imports region, so"editor.foldingImportsByDefault": truein VS Code opens files with it already folded. Contributed by @tim-bezhashvyly.
Diagnostics¶
- Built-ins newer than the project's PHP version. A function, class, method, or constant the target PHP version does not have yet, such as
str_contains()on a project requiring PHP 7.4, is reported with the version it needs and left out of completion. A polyfill's declaration takes precedence, and code behindfunction_exists(),class_exists(),method_exists(),defined(), or aPHP_VERSION_IDcheck is not reported. - Named arguments to a class without a constructor.
new Point(x: 1), or an attribute written the same way, on a class that neither declares nor inherits a constructor is reported, the same error PHP throws. A class whose parent or trait cannot be found is left alone.
Laravel¶
-
Middleware names in Laravel controllers. In a controller's
$this->middleware('auth:admin')call, you can complete the guard, jump to its configuration, and see a diagnostic for a misspelling. This follows the controller's parent classes, including application-specific base controllers. Contributed by @shuvroroy. -
Authorization abilities on typed user models. In calls such as
$customer->can('update', $post), complete the ability, jump to its policy, or see why it does not apply to the model. Contributed by @shuvroroy. -
Laravel connection names follow the receiver's type. Connection names in instance calls and model or job properties now complete, navigate, show hover details and references, and report unknown names against the appropriate config file. Contributed by @shuvroroy.
Fixed¶
- Go to a global class's member from a file with a same-named class.
\Tag::make()written in a file that declaresApp\Tagnow jumps to the globalTag, not the class in the current file. - Linux binary crashing on older x86_64 CPUs. The 1.0.0 Linux x86_64 binary stopped at startup with "Illegal instruction" on processors without AVX2. Release binaries for x86_64 run on any 64-bit x86 CPU again.
- Completion after a heredoc or nowdoc closed mid-line. A heredoc or nowdoc whose closing label is followed by more code on the same line, as in
User::raw(<<<'SQL' … SQL);, no longer stops completion for the rest of the file. - Trailing comments no longer fold the code beside them. Comments at the end of consecutive lines of code, as in
$a = 1; // first, used to fold as a comment block that hid the code on the following lines. - Framework names passed to a nullable or union receiver. A template, service, route or other name passed to a call on a
?FactoryorFactory|Mailerreceiver now navigates, completes and is checked the same as one on a plainFactory.
Internal¶
- Faster CI builds and benchmarks. Test runners share a compiled suite and matching benchmark builds are reused. Performance checks keep the same thresholds and wait for background diagnostics before measuring memory. Contributed by @shuvroroy.
1.0.0 - 2026-11-23¶
Added¶
Command line¶
- Filter
analyzeby diagnostic code.--code unused_importreports only that code and--exclude-code unused_importleaves it out. Both are repeatable and work with--severityand every output format. Contributed by @stubbedev. fixreplaces deprecated calls. The newdeprecated_usagerule rewrites every call to a function or method whose#[Deprecated(replacement: "...")]names a replacement, across the whole project. An import the rewrite leaves unused is removed in the same run.
Editing and navigation¶
- Expected argument values. Inside an argument whose parameter declares
#[ExpectedValues], aspathinfo(),phpinfo(),extract()and many other built-in functions do, the values it expects are offered first. A flag argument keeps offering the flags it does not combine yet after each|, and a string argument offers its expected strings inside the quotes. - Make a parameter explicitly nullable. A typed parameter with a
nulldefault, which PHP 8.4 deprecates, gets a quick fix that writes thenullinto its type:?stringfor a single type,int|string|nullfor a union. It also fixes PHPStan'sparameter.implicitlyNullablereport from anywhere on the line. - Go to declaration. On a method call or a method's own declaration, go-to-declaration jumps to the interface or abstract method it implements. Where there is none, it lands where go-to-definition does.
- Go to an included file. Go-to-definition on the path of a
requireorinclude, such asrequire __DIR__ . '/db.php', opens the file, as do the other paths that are document links, for editors that do not follow document links. Paths required inside an array or a call's arguments are links too. - Format selection. Formatting a selection reformats only the lines it covers, with whichever formatter the project uses, in PHP files and Blade templates alike.
- Alias an import, or remove its alias. On a
usestatement, a code action imports the class under an alias, such asuse Illuminate\Database\Eloquent\Collection as EloquentCollection;, and switches every name in the file that reaches it through the import. On an aliased import, another removes the alias and switches them back. Renaming an alias, in theusestatement or anywhere the file writes it, renames it in that file only and leaves the class alone. None of these go ahead when the new name would clash with one the file already uses.
Diagnostics¶
- Objects used as strings. Echoing, concatenating, interpolating, or casting to
stringan object whose class has no__toString()is reported, since PHP throws anErrorthere. It is an error when the class is final or an enum, and a warning when a subclass could still add the method. - Private members nothing uses. A private method, constant, or property its class never uses is dimmed, with a quick fix that removes it. A private property the class writes but never reads is dimmed too, and one it reads but never writes, and that has no default, is reported since it always holds
null. Members a framework reads or writes by reflection, such as Doctrine's mapped fields, are left alone. - Unused parameters. With
unused-parameters = trueunder[diagnostics], a parameter a function, closure, or method never reads is dimmed, as long as it comes after the last one the body does read. Methods whose signature an interface, a parent class, or a possible override dictates are left alone, and so is any parameter whose name starts with$_. - Functions that can end without returning. A function, method, or closure whose return type does not accept
nullis reported as an error when it can reach its closing brace without returning a value, since PHP throws aTypeErrorthere. A body that always ends in athrow, anexit, or a call to anever-returning function is left alone, and so is aswitchwhose cases cover every value its subject can hold, or anifwhose condition always holds there. - Using the result of a
voidcall. Reading the result of a function or method declaredvoid, whether assigning it, passing it on, testing it in a condition, or returning it, is reported as a warning, since the value is alwaysnull. A call that is a statement of its own is left alone. - Unhandled exceptions. With
unhandled-exceptions = trueunder[diagnostics], athrow, or a call to something that declares@throws, is reported when notrycatches the exception and the function or method does not list it in@throws. An "Add @throws" quick fix adds the tag. Exceptions extendingRuntimeException,LogicExceptionorErrorare left alone, andunchecked-exceptionschanges that list. - Catches nothing can reach. A
catchfor an exception that nothing in itstrycan throw is reported as a warning. Each class of a multi-catch is judged on its own. Atrythat calls anything not declaring what it throws with@throwsis left alone, since that call could throw anything. - Values no enum case is backed by. A
from()call with a value no case of the enum is backed by, such asStatus::from('Active')when the case is backed by'active', is reported as an error, since it throws aValueError. The same value passed totryFrom()is a warning, since the call always returnsnull. - Unknown named arguments. A named argument no parameter of the function, method or constructor takes, as in
$mailer->send(subjct: 'Hi'),new Length(mni: 3)or an attribute such as#[Assert\Length(mni: 3)], is reported, the same error PHP throws. A call that reaches__callor__callStatic, which accepts any name, is left alone. - Docblock tags that drop a nullable hint's
null. A@param string $nameon a?string $nameparameter, or a@return stringon a?stringreturn type, gets a hint, and the "Update docblock" action adds the|null. A tag that refines the type, such as@param non-empty-string, is left alone. - Switch diagnostics off.
enabled = falseunder[diagnostics]turns off every diagnostic in the editor, external tools included, for projects where you only want completion and navigation.analyzestill reports everything.phpantom_lsp initasks about it first, along with every other diagnostic setting. - Leave out mismatches some members of a union fit. With
partial-union-mismatches = falseunder[diagnostics], an argument, return value or property assignment such as anarray|stringpassed to astringparameter is no longer reported. Only a value no member of which fits is. On by default. - Check type mismatches against native types only. With
docblock-type-mismatches = falseunder[diagnostics], an argument, return value or property assignment is only reported when it breaks the native type and would throw aTypeError. Mismatches against outdated docblocks in legacy code no longer bury the real errors. On by default. - Members only some classes of a union declare. With
partial-union-members = trueunder[diagnostics], a method or property that some classes of a union declare and others do not is reported, the way PHPStan reports it at level 7. Off by default. #[\Override]with nothing to override. A method or property marked#[\Override]that no parent class or interface declares is reported, the same fatal error PHP raises when it loads the class.- Conflicting trait properties. A class that gets the same property from two traits, or from a trait and its own body, with a different type, visibility, modifier or default is reported, the same fatal error PHP raises when it loads the class.
- Destructuring offsets an array cannot have.
[$a, $b] = $mapon a string-keyed array, or['email' => $email] = $rowon a shape without that key, is now reported, since the target ends upnullwith a warning at runtime. - Refinement types are enforced against their base type. A plain
stringpassed where anon-empty-stringis declared, anintwhere apositive-intorint<1, 100>is, or aboolwherefalseis, is now reported, the way PHPStan reports it. - Writes to
@readonlyproperties. A property marked@readonlyin its docblock (or with the Psalm or PHPStan spelling) is now held to the same rules as a nativereadonlyone: a write from outside its class, or after the constructor has initialized it, is reported. Psalm's allow-private-mutation tags are respected. - Typo fixes for unknown views and templates. A Laravel view or Twig template name that nothing declares now offers to change it to the closest declared names, ahead of the quick fix that creates the missing file.
- Discarded
#[\NoDiscard]results. Calling a function or method marked#[\NoDiscard]as a statement of its own, without using its result or casting it to(void), is now reported, the same warning PHP 8.5 raises. matchexpressions that miss a value. Amatchwithout adefaultarm whose arms leave an enum case,true,false,null, or one of a set of literal values unhandled is now reported, since that value throwsUnhandledMatchError. Cases an earlier check has already ruled out need no arm.- Dynamic member names that cannot name a member. A property name written as an expression that holds an array or an object without
__toString(), and a method name that is not a string, are now reported, since PHP throws anErrorfor them. AStringableobject still names a property, but never a method. - Properties
clone()writes are checked. The properties PHP 8.5'sclone($object, [...])sets on the copy are checked like an assignment: a property the class does not have, one the calling code cannot write, or a value of the wrong type is reported. The keys also jump to their property and follow it through find-references and rename. - Typed properties nothing initializes. A typed property with no default that only its own class can assign, and that the class never does, is now reported, since reading it throws. Properties a framework fills through an attribute count as initialized, and so do the generated identifiers and version fields of Doctrine entities. A public one is reported where it is read: on an object fresh from
new, before anything writes it. A readonly property the constructor assigns twice is reported too. - Arrays in variables that miss a required key. An array held in a variable that lacks a key the parameter's shape requires, such as one left by
$config = []or byunset($config['port']), is now reported, as an array written in the call already was.
Type inference¶
- Class constants as docblock types. A docblock type that names class constants, such as
@param Status::ACTIVE $status,@return self::STATUS_*, or@param Foo::class|Bar::class $name, now stands for the values those constants hold. Aswitchwith a case for each of them counts as covering every value, and passing anything else is reported. - Each enum case is a type of its own. Comparing an enum with one of its cases, or a backed enum's
valuewith a case's backing value, narrows it to that case, or to the cases left, inif/elseifchains, guard clauses,matcharms and strictin_array()checks, and a value known to be one case reads that case's ownnameandvalue. A case passed to avalue-of<T>template no longer reports every other case's value as a mismatch. - Array shapes are sealed. An array with a key that a shape like
array{foo: int}does not declare no longer satisfies it, whether the key is written at the call site or comes from the value's own declared shape. Writearray{foo: int, ...}to accept other keys. - Static file paths. Paths built from
__DIR__,__FILE__, anddirname()keep their known values across files and inherited constants. Contributed by @shuvroroy. - Properties a trait leaves to its users. Inside a trait, a property the trait reads but does not declare is typed from what the classes using the trait declare it as, when all of them do, so completion and type checks work on it as on the trait's own properties.
Testing¶
- Mocked method names. The method a mock is told to expect, in PHPUnit's
$mock->method('…'), Mockery'sshouldReceive('…')and its siblings, and a Laravel facade'sshouldReceive('…'), completes from the mocked class, navigates, shows up in find references, renames with the method, and is reported when the mocked class has no such method. - Prophecy doubles. A prophecy from
prophesize()completes the methods of the class it doubles, and a call to one jumps to that method and takes an argument token such asArgument::any()in place of any argument. setUp()andtearDown()that skip the parent. A test'ssetUp(),tearDown(),setUpBeforeClass()ortearDownAfterClass()that never calls the base test case's is reported, with a quick fix that adds the call.- Data providers PHPUnit cannot call. A PHPUnit test's data provider that is not public, or from PHPUnit 10 on not static, is reported, with a quick fix that adds the modifier. A provider a test names but nobody declared can be created with a quick fix.
- Create a test for a class. A code action on a class, or on one of its public methods, writes its test where the class's test CodeLens looks for it, in the test directory's namespace, extending the project's base test case, covering the class, with a test method for each public method or just the one under the cursor. A project with a
Pest.phpgets a Pest file instead. - Go to a class's tests, and back. The CodeLens on a class now also lists the tests named after it, mirrored under an
autoload-devroot (App\Billing\Invoiceandtests/Unit/Billing/InvoiceTest.php), Pest files included, not only the tests whose coverage metadata names it. A test gets a CodeLens that opens the class it tests.
Blade templates¶
- Code actions in Blade templates. Quick fixes and refactorings now work in Blade templates. An import is added as a
@usedirective, and an unused one is removed. An action that would have to change markup the template did not write as PHP, such as extracting a variable out of an{{ }}echo, is not offered. - Blade templates use the project's blade-formatter. A project that installs blade-formatter and configures it with a
.bladeformatterrc.jsonnow gets its Blade templates formatted by it, with the project's settings and.bladeignore, instead of by the built-in reindenter. Setblade-formatterunder[formatting]to choose the command or turn it off. - Unknown Blade and Livewire components. A
<x-…>or<livewire:…>tag that names no component class or template is reported. A quick fix changes it to the closest component name, or creates the component: an anonymous component's template, a component class with its template, or a Livewire component. Tags under a prefix PHPantom cannot list, or that a package registers under names only known at runtime, are not reported.
Laravel¶
- Go to a relation from its name. Go-to-definition on a relation name in
with(),load(),whereHas()and the other relation methods jumps to the relationship method. Each segment of a dotted path such as'posts.author'goes to the relation on the model the path has reached, including inside an eager-loading constraint closure. - Container call parameters. The parameter keys passed to
app()->call()complete from the callable's parameters and go to them. Contributed by @shuvroroy. - Laravel asset paths and Inertia pages. The paths
asset(),mix(),@viteandVite::asset()name, and the pagesInertia::render(),inertia()andRoute::inertia()render, complete from the files on disk, jump to the file, and are reported when nothing is there. An unknown Inertia page gets a quick fix that creates it. Page directories and extensions are read fromconfig/inertia.php. - Laravel related classes. Code lenses on an Eloquent model go to its factory, policy, observers, migrations, API resources, and custom collection, and a factory, policy, or observer gets one back to its model. An event lists the listeners that handle it, whether registered or discovered from their
handle()type hint, and a listener links to the events it handles. - Eloquent column attributes. Columns a model lists in class attributes such as
#[Fillable(['name'])]or#[Hidden([...])]now complete on the model and in queries like those in$fillableand$hidden, and#[Fillable]columns are offered first increate([...])andfill([...]). Attributes and properties combine and inherit the way Laravel applies them. Contributed by @shuvroroy. - Eloquent attribute-array completion. Complete model columns in calls such as
User::create(['name' => …]), with fillable attributes first and existing keys omitted. Column suggestions also cover more query methods and Laravel's column-name PHP attributes when available. Contributed by @shuvroroy. - Laravel validation strings. Validation rules and their referenced fields, database columns, and enum values now complete and navigate, with hover documentation and diagnostics for unknown rules and message keys. Suggestions follow the project's installed framework and custom rules. Contributed by @shuvroroy.
- Morph aliases and config keys complete as array keys. Registered aliases are suggested for the keys of
Relation::morphMap([...]), and config keys for the keys ofConfig::set([...])andconfig([...]). Contributed by @shuvroroy. - Plural and singleton resource routes in Laravel. Routes registered with
Route::resources(),Route::singleton()and their API and plural variants now complete, navigate, and are no longer reported as unknown. Resource names with stray slashes or empty segments get the same route names Laravel gives them. Contributed by @shuvroroy. - Morph aliases resolve in column comparisons. Comparing a model's polymorphic type column with a registered alias now offers completion, hover, go-to-definition, and find-references, and reports unknown aliases when the morph map is enforced. Query filters and property comparisons recognize the columns declared by the model's relationships, including custom names and inherited relations. Contributed by @shuvroroy.
- Routes on Laravel controller methods. A CodeLens above each controller action lists the routes that reach it, with their HTTP verb, URI and name, and jumps to where each is registered. Resource routes and routes inside a
Route::controller()group count too. - Laravel rate limiter names. Names registered with
RateLimiter::for()complete, navigate to their registrations, and report misspellings inthrottle:nameandnew RateLimited('name'). Contributed by @shuvroroy. - Laravel middleware names. The middleware aliases and groups a route names in
->middleware(),->withoutMiddleware(), or a controller's#[Middleware]attribute complete, navigate to where they are registered and to the middleware class, show up in find references, and are reported when nothing registers them. Hover shows the class an alias runs with the parameters it takes, or the middleware a group runs. The framework's own, thosebootstrap/app.phpor an HTTP kernel registers, and those a package adds are all known. - Create missing Laravel routes. An unknown route name now offers a quick fix that adds a named route stub to the project's routes file, ready for you to finish. A routes file loaded under a group's name prefix gets the name without it. Contributed by @shuvroroy.
- Config key hover shows the value. Hovering a key in
config('app.name')now shows what it holds: the value as written in the config file, or for anenv()read, the environment variable, its default, and what.envsets it to. Values of variables whose names look like credentials stay hidden. - Unknown methods on Eloquent models and builders. A method call that a model or its query builder does not answer, like
$order->getTotl()orOrder::query()->paidd(), is now reported, since Eloquent throws for it at runtime. Dynamicwhere{Column}()calls, scopes, and macros are still accepted. In an app that turns onModel::preventAccessingMissingAttributes()orModel::shouldBeStrict(), an unknown attribute on a model whose table the migrations declare is reported too.
Symfony¶
- Symfony form options. The keys of the options array a form builder's
add(), a form factory'screate(), or a controller'screateForm()passes complete from the options the form type accepts, its parent types and the installed type extensions included, and jump to where each is declared. An option the type does not accept, such as'requird', is reported. - Symfony constraint options in validation mappings. The options a YAML or XML validation mapping gives a constraint, such as
minin- Length: { min: 2 }or an XML<option name="min">, complete from the options the constraint takes. An option it does not take, such asmni, is reported. - Symfony serializer groups. A group named in the
groupsof a serialization context, fromserialize(),normalize(), and a controller'sjson()to#[Context]and#[MapRequestPayload], completes, jumps to every#[Groups]and serializer mapping that puts a member in it, and lists its references. - Rename reaches YAML and XML configuration. Renaming a class, a controller action, or a namespace rewrites its occurrences in Symfony and Doctrine configuration in the spelling each file uses, escaped backslashes included, and the rename can be started from the configuration file itself. When a namespace's directory moves with it, the
resource:andexclude:paths that point into it follow. Contributed by @sidux. - Symfony service IDs and container parameters. In a Symfony project, a service ID or parameter declared in YAML, XML, or a PHP configurator completes, jumps to its declaration, and lists its references wherever configuration or code names it, from
@app.mailerand%app.sender%to$container->get()and#[Autowire]. An application's ownapp.name that nothing declares is reported. Contributed by @sidux. - Symfony services that bundles and the container builder declare. The service IDs and parameters an installed bundle declares in its own configuration complete, jump to their declaration, and type
$container->get(), and so do the ones a kernel, an extension, or a compiler pass declares withregister(),setAlias(),setDefinition(),setParameter(), orgetKernelParameters(). A parameter set under a name built at runtime, like'app.' . $key, leaves the names it can produce unreported. A configurator'sparent()and the%name%placeholders in its arguments are read as the service and parameter they name. - Symfony route names. In a Symfony project, a route name declared by a
#[Route]attribute, the routing YAML or XML, or a PHP routing configurator completes, jumps to its declaration, and lists its references wherever a controller or a Twig template builds a URL to it, fromgenerateUrl()andredirectToRoute()topath()andurl(). Names are followed through the imports that load them, bundles' own routing files included, along with the ones Symfony derives from a route, such ascontact.enfor a localized one. A route name nothing declares is reported, unless the router is configured to load its routes some other way. Contributed by @sidux. - Symfony translations. In a Symfony project, a translation key declared in a YAML or XLIFF catalogue completes, jumps to its entry in every locale, and lists its references wherever PHP or a Twig template translates it, from
trans(),TranslatableMessage, andt()to thetransfilter. A key is looked up in the domain the call names, and a domain jumps to its catalogues. A key spelled like one (demo.title) that nothing declares is reported, in a domain the project's own catalogues hold and no installed bundle ships. Contributed by @sidux. - Symfony Twig templates. In a Symfony project, a template name completes, jumps to its file, and lists its references wherever a controller, an email, or another template names it, from
render()and#[Template]toextendsandinclude. A template the application'stemplates/directory does not hold is reported, with a quick fix that creates it, unless the project has a Twig loader of its own that could serve it. Contributed by @sidux. - Names a lookup is written to miss. A route, template, or container parameter looked up inside a
trythat catches the exception a missing name throws, or on a router or Twig environment the file builds itself as tests do, is not reported as unknown. - Symfony forms, validation, and bundle configuration. In a Symfony project, a form field and a property in a YAML or XML validation mapping jump to the data-class property they name and show up in its references and renames, and a form field completes from that class. A validation constraint jumps to its class. A bundle configuration key in
config/packages/completes, jumps to the key the bundle's own configuration schema declares, and lists its references. Contributed by @sidux. - Symfony events and Messenger. In a Symfony project, an event name dispatched by
dispatch()completes, jumps to every listener that subscribes to it, whether through#[AsEventListener],getSubscribedEvents(), or akernel.event_listenertag, and lists its references. The method a subscription names jumps to the method, and one that does not exist is reported. A Messenger bus name jumps to its declaration in the Messenger configuration and completes, and one the configuration does not declare is reported. A CodeLens on a message class opens the handlers that receive it, and one on a handler opens its message. Contributed by @sidux. - A kernel that moves the configuration directory. When the application's kernel overrides
getConfigDir()with a path under the project directory, services, parameters, routes, and bundle configuration are read from there instead ofconfig/. When it returns a path that cannot be worked out, the names that configuration would declare are no longer reported as unknown. - Symfony services and parameters are typed. In a Symfony project,
$container->get('app.mailer')is the class the service is declared with, through any aliases, andgetParameter('app.sender')has the type of the value the parameter is declared with. A query bus'sHandleTrait::handle()returns what the message's handler returns. - Decorated services. A service that decorates another, in a Symfony services file, a Drupal
*.services.yml, or a PHP configurator, takes over its ID, so a lookup of that ID is typed as the decorator's class as well as its own. The ID a YAMLdecorates:names jumps to its declaration and counts among its references. - Methods a service definition calls. A method named under a service's
calls:in a Symfony services file or a Drupal*.services.yml, or in XML's<call method="…">, jumps to its declaration, completes from the public methods of the service's class, and counts among the method's references. - Event subscriber maps built in code or keyed by constants. A subscriber's
getSubscribedEvents()is read when it builds its map by assignment ($events[KernelEvents::REQUEST][] = ['onRequest', 10];) as well as when it returns one, and a key written as a class constant declares the event name the constant holds, which makes the constant that event's definition for navigation and Find References. Contributed by @giuseppe-esposito-87.
Doctrine¶
- DQL variables. A variable a DQL join declares through an association, like
tinJOIN u.team tor->join('u.team', 't'), stands for the entity the association targets, so its fields complete, jump to their property, and are reported when the entity does not map them. A variable the query uses but nothing declares is reported, following the query builder through the methods that create, return, or receive it, and through branches that declare the variable on only some paths. - DQL in expression objects and builders from other methods. The DQL an expression object is built from, like
new Expr\OrderBy('u.name')ornew Expr\Andx([...]), is read like any other query builder fragment: its fields complete, jump to their property, and are reported when unmapped, and text Doctrine cannot parse is reported. A fragment added to a query builder that another method returns knows the variables that method declared on it. - DQL expressions typed by the database driver.
SUM(),AVG(), arithmetic, number and boolean literals, and the otherSELECTexpressions whose value differs between MySQL, PostgreSQL, and SQLite are typed the way the project's driver returns them, its PDO options and the PHP version included. The driver is read from theDriverManager::getConnection()parameters or a Symfony project's Doctrine configuration. - DQL syntax errors. A
createQuery()string, or a fragment a Doctrine query builder takes inwhere(),select()and the rest, that Doctrine cannot parse is reported where it goes wrong: a missing identification variable, a stray parenthesis, a condition without its comparison. - Doctrine entities and repositories link to each other. In a Doctrine project, a CodeLens on an entity opens its repository, and one on a repository opens its entity, found through the YAML or XML mapping or the usual naming convention. Contributed by @sidux.
- Doctrine
getRepository()returns the entity's own repository.$entityManager->getRepository(User::class)is typed as the repository the entity's#[ORM\Entity(repositoryClass: ...)]attribute or its YAML or XML mapping names, so the repository's own methods complete, navigate, and are checked. - Doctrine entity fields in repository calls. A repository answers
findBy<Field>(),findOneBy<Field>(), andcountBy<Field>()for each field its entity maps with attributes or an XML or YAML mapping, typed by the entity. The keys offindBy(),findOneBy(), andcount()complete the mapped fields, jump to their properties, and show up in find references, and a field or finder the entity does not map is reported. - Doctrine DQL. Entity classes and fields in a
createQuery()string or a query builder'sfrom(),join(),where()and the rest complete, jump to their classes and properties, and show up in find references and renames. An entity class that does not exist, or a field its entity does not map, is reported. - Doctrine query results typed by their DQL. A query from
createQuery()or a query builder is typed by what its DQL selects, sogetResult()and the other result methods return the selected entities or a shape of the selected fields, keyed by theINDEX BYfield when there is one. AnUPDATEorDELETEreturns the number of rows it affects. A query builder keeps its DQL when it is held in a variable, changed in a branch, or returned by a method that sets it up. - DQL aggregates, functions, and
NEWtyped. ACOUNT()in a query'sSELECTis anint<0, max>, a string function or aCASEof strings is astring, and aNEW Dto(...)row is aDto. An expression whose value depends on the database driver, likeSUM(), is typed for the driver the project connects with, and staysmixedwhen that is not known. When a query aggregates without aGROUP BY, its other columns may benull.
Twig templates¶
- Twig templates outside Symfony. In any project that uses Twig, from Drupal and Craft to an application that builds its own
Twig\Environment, a template name completes, jumps to its file, and lists its references wherever PHP renders it or another template extends or includes it, and a name no template holds is reported. The template directories are found from the names the templates reference, with no configuration, and.htmltemplates work as well as.twigones. A name that several themes hold jumps to each of them. - Unknown names in Twig templates. A template, route name, or translation key that nothing declares is now reported in the Twig template that names it, as it is in PHP, with the quick fixes that change a template name or create the missing template. Creating or deleting a template updates the warnings in the open files that name it.
- Twig blocks. In any project that uses Twig, a block jumps to the block it overrides, however many templates up, and a block that overrides nothing jumps to the templates that override it.
block()andparent()jump to the block they render, find references lists a block across the templates that extend, use, or embed each other, and the blocks a template can override complete after{% block. - Twig filters and functions. In any project that uses Twig, a filter or function jumps to the PHP method or function behind it, whether the project's own extension declares it or Twig and the packages it installs do, and its hover shows that signature. Filters complete after
|and functions where an expression starts, and a name no extension declares is reported. - Twig template variables. In any project that uses Twig, a variable a template reads completes where an expression starts, jumps to where it comes from, and says so on hover: the key a
render()passes it under, what a#[Template]action returns, the template that includes or extends this one, a global, or the template's ownset,for, ortypestag. The hover also shows what the variable holds, and an attribute read off it (post.title) completes, jumps to the property or getter Twig reads, and shows that member on hover.
Drupal¶
- Drupal services. In a Drupal project, the service IDs and container parameters that core, contributed, and custom modules declare in their
*.services.ymlcomplete, jump to their declaration, and list their references wherever a services file,$container->get(), or\Drupal::service()names them, and a lookup is typed by the class the service is built from, or by the class or interface a lookup names by::class. A service a module's service provider builds from a class of its own, as the language module does withlanguage_manager, is typed as either class. Rename leaves core and contributed extensions alone, as it does vendor code. Contributed by @giuseppe-esposito-87. - Drupal entity types. In a Drupal project, an entity type ID declared by an entity class's attribute or annotation completes, jumps to its declaration, and lists its references wherever the entity type manager is asked for it, and
getStorage()is typed as that entity type's storage, soload(),loadMultiple(),create(), and the other loads return the entity class. An entity query started by\Drupal::entityQuery()or a storage'sgetQuery()gives the IDs of that entity type, or their number aftercount(). Test code also sees the entity types its test modules declare. Contributed by @giuseppe-esposito-87. - Drupal hooks. In a Drupal project, a hook implementation, procedural or by
#[Hook], jumps to the hook's*.api.phpdocumentation and to the calls that fire it, core's computed hook names included, and an invocation jumps to the implementations it reaches. Hook names and implementations complete with their documented signature, and an implementation's untyped parameters take the documented types, narrowed to the entity class for a hook of one entity type. Hover on an implementation's name or#[Hook]shows the hook's documented signature and docblock. Contributed by @giuseppe-esposito-87. - Drupal sites in any layout. Modules and themes grouped in folders of their own, kept directly under
modules/orthemes/, or shipped inside an install profile are now indexed even when.gitignoreleaves them out, so they work like those incontrib/andcustom/. A site that keepscore/beside itscomposer.json, or a Drupal tree opened without anycomposer.json, is now recognized as a Drupal site. Contributed by @giuseppe-esposito-87. - Drupal route names. In a Drupal project, a route declared by a routing file, a
#[Route]attribute, or a route builder completes, jumps to its declaration, and lists its references wherever code, a links file, or a template names it, fromUrl::fromRoute(),$this->redirect(), and$form_state->setRedirect()toroute_name:andpath(). A route name nothing declares is reported. The parameter keys those calls, links files, and templates pass jump to the placeholder of the route's path and complete from it, and a controller's parameter is typed as the entity Drupal upcasts it to, with a warning when a controller's type hint unrelated to the entity keeps Drupal from upcasting it. Contributed by @giuseppe-esposito-87. - Drupal permissions and configuration. In a Drupal project, a permission name completes from every permissions file, jumps to its declaration, and shows its title and description on hover, wherever an access check, a route's
_permissionrequirement, or an entity type'sadmin_permissionnames it. A configuration name in\Drupal::config(), the config factory, a config form, or a#config_targetcompletes and jumps to the default configuration and the schema entry that declare it, and the keys a configuration object'sget(),set(), andclear()read complete from its schema one level at a time and jump to their schema line. Contributed by @giuseppe-esposito-87. - Drupal render arrays, theme hooks, and libraries. In a Drupal project, theme hook, render element, and library names complete, jump to their declaration, and show it on hover wherever render arrays, templates, and libraries or theme info files write them, and a theme hook also leads to its templates and each theme's override. A theme hook's templates receive its variables, typed by what the render arrays pass. A render element or library nothing declares is reported. Contributed by @giuseppe-esposito-87.
- Drupal plugin IDs. In a Drupal project, the plugin types plugin managers declare are read from the managers themselves, so blocks, field types, widgets, formatters, constraints, and every other plugin type, core's and contributed modules' included, work alike. A plugin ID completes, jumps to the plugin class, and shows its manager on hover wherever a plugin manager's
createInstance(),getDefinition(), orhasDefinition(),BaseFieldDefinition::create(), a field's display options, oraddConstraint()names it, and a derivative ID leads to its base plugin.createInstance()is typed as the plugin's class, and go to implementation and the implementation code lens on a plugin manager, or on an interface only one manager implements, list its plugins. - Unknown Drupal plugins. In a Drupal project, a plugin ID that
createInstance(),getDefinition(),BaseFieldDefinition::create(), a field's display options, oraddConstraint()names is reported when no plugin of its type declares it. A derivative of a declared plugin, a lookup the code checks withhasDefinition()first, a lookup in a file that may catch the exception a missing plugin throws, a plugin manager that finds plugins its own way, and test code are left alone. - Unknown Drupal services. In a Drupal project, a service ID that
\Drupal::service()or a container'sget()looks up is reported when no services file declares it and no service provider, compiler pass, or other PHP code could define it. A lookup the code checks withhas()first, one that runs only whenmoduleExists()finds a module the site lacks, or one in a file that may catch the exception a missing service throws, is left alone, and so is test code. - Drupal annotations without imports. In a Drupal project, an annotation on a plugin class that no
useimports, such as@Blockor@Translation, jumps to its class, shows it on hover, and is found by Find References, wherever Drupal's plugin discovery would find it. - Controller methods of a Drupal service. In a routing file, the method of a
_controlleror_title_callbackwritten asservice:methodjumps to the method of the service's class, completes from its public methods, and is listed among the method's references. - Drupal form and render callbacks. In a Drupal project, a callback named in a form or render array, such as a
#submit,#validate,#pre_render, or#ajaxcallback, jumps to its method or function, completes, shows it on hover, is renamed with it, and lists its references. A callback that names nothing, or that cannot be called, is reported. Contributed by @giuseppe-esposito-87. - Drupal event subscribers. In a Drupal project, event subscribers are read as they are in Symfony: the methods a subscriber's map names navigate and are checked, and an event name passed to the event dispatcher completes and leads to the constant that names it, if any, and to every subscription that listens to it. Contributed by @giuseppe-esposito-87.
- Drupal entity fields. In a Drupal project, a content entity's fields are typed properties of the entity and of its interfaces, down to the entity a reference field points to. Field names written in code complete, show their type on hover, and jump to where the field is declared. Contributed by @giuseppe-esposito-87.
- Precise return types for Drupal's URLs and query extenders. A URL built without asking for its bubbleable metadata is a plain string, and a query extended with an extender is typed as that extender, so its methods resolve. Contributed by @giuseppe-esposito-87.
WordPress¶
- WordPress hook names. A hook name in
add_action(),add_filter()and the rest of the listener API completes, jumps to everydo_action()orapply_filters()that fires it, lists its references, highlights, and renames. A hook fired under a name built at runtime, like"save_post_{$post->post_type}", matches the names it can produce, and completes as a snippet. Core's hooks, and those of plugins and themes installed with Composer, complete and navigate as well, and a project with only the stubs still completes core's. @globaltags type the globals a function imports. A@global wpdb $wpdbtag on a function or method docblock types$wpdbafterglobal $wpdb;, so WordPress code gets completion and diagnostics on$wpdb,$wp_queryand the rest. A function without a tag gets the type the@globaltags elsewhere give the global, in the stubs, in libraries, or in the project's own code, soglobal $wpdb;is typed wherever WordPress core orphp-stubs/wordpress-stubsis indexed.- WordPress return types that depend on the arguments. With the WordPress stubs installed,
get_post_meta($id, $key, true)returns the single value andget_post_meta($id, $key)a list of them,get_post_time('c')a string where'U'and'G'give anint, andwp_list_comments()a string only when'echo'isfalse.wp_parse_url()keepsfalsefor a URL it cannot parse, andesc_sql()returns an array for an array and a string for a scalar. - WordPress return types read from the arguments.
wp_parse_args()andshortcode_atts()return an array with the keys of their defaults, each holding the type of the value given or its default, andesc_sql()andwp_slash()keep the shape of the array they are handed. String helpers such astrailingslashit(),wp_slash()andwp_parse_url()called on a literal return the literal WordPress gives back.
Yii¶
- Yii Active Record. A query a record's
query()builds, or a relation'shasOne()orhasMany(), returns that record, soPost::query()->one()is aPost. An attribute named by a record'sget(),set()and the rest of its attribute API jumps to the property, completes, renames with it, and is reported when the record has no such property. On a record that declares no properties, the attributes are the columns the project's migrations give its table: a column name jumps to the migration that creates it, completes, shows its type on hover, and is reported when no migration creates it. A relation named byrelation(),with()orjoinWith(), a path like'author.profile'included, jumps to the arm ofrelationQuery()or the getter that declares it, completes, and is reported when the record does not declare it. - Yii query tables and columns. In a
yiisoft/dbquery, a table named byfrom()or a join, and a column named by a condition, an order, a grouping or a selection, jumps to the migration that creates it, completes, shows its type on hover, and is reported when no migration creates it. A column qualified by an alias the query gives a table, like'p.status', is read against that table, and a table may be named by a class constant that holds its name, in the query and in the migration alike. A query built up over several statements on a variable reads each statement's names against the tables the earlier ones named. - Yii asset bundle files. In a Yii asset bundle, a file listed in
$cssor$jsjumps to the file under the bundle's$sourcePath(or$basePath), completes from the files there, and is reported when no file is there. An entry that is a URL is left alone. - Yii aliases. In a Yii project, an alias such as
@runtimeat the start of any string jumps to the configuration that declares it, lists the strings that name it, and completes from the declared aliases. Hovering it shows the path it stands for, and the rest of the string links to the file or directory it names. Each declared alias is listed in workspace symbols, and in editors that show folded text, an aliased path folds to the path it resolves to. - Yii translation message IDs. In a Yii project, a message ID passed to the translator's
translate()jumps to its entry in each locale's message file, completes from the IDs of the category it is looked up in, and is reported when no message file declares it. Hovering it shows the message in the translator's locale. The category is the one the call names, or else the onewithDefaultCategory()or the configuration gives the translator. - Yii params. In a Yii configuration file, a key read from
$params, like'name'in$params['application']['name'], jumps to the params file that declares it, completes from the keys declared beside it, and is reported when no params file declares it. Hovering it shows the type of its value, and the read is typed as that value. The params are merged the wayyiisoft/configmerges them, the installed packages' included, and so are the files a key'sarray_merge()requires. - Yii config groups. In a Yii project, the
config-pluginof the project's or a package'scomposer.json, or of the PHP file itsconfig-plugin-filenames (config/configuration.phpinyiisoft/app), completes group names from the ones the project and its installed packages use, and file paths from its source directory. A path jumps to its file and a$groupentry to the group it names, and a path with no file is reported. - Yii DI definitions. In a Yii project, the
'setLogger()'and'$pageSize'keys of a DI definition jump to the method or property they name, complete, rename with it, and are reported when the class has no such member.'__construct()'jumps to the constructor the class declares or inherits. The arguments a definition passes by name, like'transport'in'__construct()' => [...], jump to the parameter, show its type and description on hover, complete, and are reported when the method takes no parameter of that name. Definitions are recognised wherever they are written, in thediandwidgetsconfiguration or inline in PHP. Go-to-implementation on a class, and a CodeLens above it, lead to the definitions that bind it, the installed packages' included. - Yii DI definitions are checked against their class. A definition key that is neither a method call like
'setLogger()'nor a property like'$pageSize'is reported, with a quick fix that adds the()or$the member it names needs. A method or property that is not public is reported, and so is a value or argument the member does not accept, with aReference::to()typed as the class it names. - Yii form fields and hydration maps. In a Yii project, the property a form field names, like
'title'inField::text($form, 'title'), jumps to the form model's property, completes from its properties, renames with it, and is reported when the model has no such property. The keys of the map a form hydrator or anArrayDatais given are treated the same way, as properties of the object being filled. - Yii key paths. In a project using
yiisoft/arrays, each key of a pathArrayHelperreads, like'city'ingetValueByPath($user, 'profile.address.city'), completes from the keys and properties of the value the keys before it reach, and a key that reads a property or calls a method jumps to it.getValue(),getValueByPath()andremove()return the type of the value the path reaches instead ofmixed. - Yii event listeners. In a Yii project's events configuration, the method of an
[Handler::class, 'method']listener is reported when the handler has no public method of that name, and a listener is reported when a parameter can be filled with neither the event nor a service. Go-to-implementation on an event class, and a CodeLens above it, lead to the listeners attached to it, the installed packages' included. - Yii views. In a Yii project, a view rendered by name, by a path built from
__DIR__, or from inside another template jumps to its template, completes from the template's directory, and lists its references, and a view no template matches is reported. A layout passed towithLayout()is treated the same way, and awithViewPath()directory that does not exist is reported. A name is resolved against the view path the class gives its renderer, through the aliases the configuration declares. A CodeLens at the top of a template lists the calls that render it. - Yii view parameters. In a Yii project, the keys of the parameters a render call passes its view complete from the
@varblock the template opens with, jump to the@varthat declares them, and show its type on hover. A value the declaration does not accept, a key the template has no use for, and a declared parameter the call does not pass are reported. A parameter every view is given, by the view's configured parameters, asetParameter()call, or the renderer's injections, is not one the call has to pass. - CSS class names in Yii HTML tags. In a Yii project, each class name given to a tag's
class()oraddClass()jumps to the selectors of the project's stylesheets that declare it, lists its references, and shows on hover where it is declared. Class names complete from the project's.css,.scssand.lessfiles, one name at a time. - Yii route names. In a Yii project, a route name declared by a
Routedefinition, under the name and path prefixes of the groups around it, completes, jumps to its declaration, and lists its references wherever a URL generator builds a URL to it, including through a class of the project's own that passes the name on. A key of the arguments array ofgenerate()completes from the placeholders of the route's path, jumps to the placeholder it fills, lists its references, and shows the route's path on hover. A handler's#[RouteArgument]jumps to the placeholder it reads and completes from it. A route name, or a#[RouteArgument]name, that nothing declares is reported.
Tempest¶
- Tempest View templates. In a Tempest project, PHP expressions in
.view.phptemplates use imports and@varannotations for completion, hover, navigation, and diagnostics, and infer the data that callers, components, custom View objects, and slots pass in. Component tags, their attributes, dynamic components, and view paths complete and navigate, following the project's discovery configuration, named data passed toview()completes from the template's inputs, and hover explains the built-in components and directives. Contributed by @shuvroroy. - Tempest routes. Route actions and URI placeholders complete and navigate, including custom route attributes, decorators that add a URI prefix, and paths without a leading slash. Renaming an action parameter updates its placeholders and the named arguments of
uri(). Contributed by @shuvroroy. - Tempest models and queries.
query(Book::class)keeps its results typed asBookthrough fluent calls, and model properties complete and navigate in typed query builders and model helpers, forwarded named arguments and array keys included. Contributed by @shuvroroy. - Container invocation arguments. The named arguments
Container::invoke()and theinvoke()helper forward complete from the callable's parameters and go to them. Contributed by @shuvroroy.
Configuration and indexing¶
- Unknown configuration keys are reported. A key in
.phpantom.tomlor the global config that PHPantom does not know, such as a typo, is reported with its file instead of silently doing nothing. The editor shows a warning when the config loads, andanalyze,fix,format, andmoveprint one per key. The rest of the config still applies. - Switch inlay hints off by kind.
parameter-names = falseorclosure-types = falseunder[inlay-hints]hides parameter name hints at call sites or inferred types on closures, without touching other extensions' hints. Editor extensions can pass the same toggles, and changes apply to open files right away. - Index files the workspace scan skips. List files and directories under
[indexing] includein.phpantom.tomlto index them even though they are hidden or gitignored, such as Castor's.castor/tasks and its generated.castor.stub.php. Their symbols then complete, resolve, and stop being reported as unknown. A path inside the workspace is treated as project code, and one outside it as a library, likevendor/. See configuration.md. Contributed by @joelwurtz. - Stubs that override. List stub files and directories under
[stubs] pathsin.phpantom.toml, and what they declare wins over every other declaration of the same name, PHP's own built-in stubs included. Use it for hand-written stubs of a PHP extension or to correct a signature you disagree with. Stub files are never analysed or edited, and an editor extension can pass a bundled stubs directory the same way. See configuration.md. - The other folders of a multi-root workspace resolve. Classes, functions, and constants declared in another folder of the editor's workspace now complete, resolve, and jump to their declaration from this one. That folder is treated as a library, like
vendor/, so its own diagnostics and renames stay with the folder itself. Adding or removing a folder takes effect without a restart. - Stub packages installed with Composer. A stub package such as
php-stubs/wordpress-stubsorphp-stubs/woocommerce-stubsworks like a[stubs]path with nothing to configure, so WordPress and WooCommerce functions and classes resolve in a theme or plugin that requires them. An installedjetbrains/phpstorm-stubstakes over PHP's own functions and classes, and go-to-definition on a built-in opens it there. Installing, updating, or removing a package takes effect without a restart. - Turn formatting off.
enabled = falseunder[formatting]in.phpantom.tomlstops PHPantom from formatting, built-in formatter included. Contributed by @enwi.
Changed¶
Behaviour¶
- The outline shows each declaration's modifiers. Every class, method, property and constant in the outline is described with its modifiers first, such as
private readonly Gatewayorfinal, so an editor can tell public members from private ones. Editors that label outline entries from the source, like Zed, showprivate function chargeinstead of a barecharge. - Completing a class whose name is already imported adds an aliased import. With
use Illuminate\Support\Collection;in place, completing Eloquent'sCollectionnow imports it asEloquentCollectionand inserts that, instead of writing out its fully qualified name. Classes under aContractsnamespace take aContractsuffix instead, likeJsonableContract. Renaming or moving a class into a name the file already imports picks its alias the same way. - A type mismatch that only a possible
nullorfalsecauses is no longer reported by default. Passing astring|falseto astringparameter, returning it from astringfunction or assigning it to astringproperty only fails if the value turns out empty. Setpossibly-empty-mismatches = trueunder[diagnostics]to report these as errors. It replacesdowngrade-nullable-argument-mismatch, which is gone. A mismatch where some other member fails is still reported. Contributed by @stubbedev. - Pull diagnostics are advertised to every client. Editors and tools that check the server's capabilities now see pull diagnostic support even when they don't declare it themselves, and a pull returns the diagnostics last published. Editors without pull support still receive pushed diagnostics as before.
- laravel-ide-helper files come back through
include. To index_ide_helper.phpor_ide_helper_models.php, list them under[indexing] include. A leading!in[indexing] excludeno longer does it, since!now only undoes your own exclude patterns. - Diagnostic messages read the same way across every check. Names are written the way PHP spells them, without quotes (
Class App\Models\User not found,Unused variable $total), members carry their class (Method App\Models\User::save() not found), string values stay quoted, and type mismatches readexpects X, got Y. An[[diagnostics.ignore]]rule that matches onmessagemay need updating; one that matches onidentifierkeeps working. - Diagnostic identifiers follow one naming scheme. Ahead of 1.0, these were renamed:
invalid_member_accessis nowinaccessible_member,invalid_laravel_transisinvalid_laravel_translation,invalid_command_parameterisinvalid_laravel_command_parameter,missing_view_variable,unused_view_variableandtype_mismatch_view_variablearemissing_blade_variable,unused_blade_variableandtype_mismatch_blade_variable, andblade_signature_widens_layoutisincompatible_blade_signature. The old names keep working in[[diagnostics.ignore]],@phpantom-ignoreandanalyze --code, and the config and command line warn when they meet one. The Diagnostics Reference lists every identifier. - Configuration names follow one spelling. Ahead of 1.0, every section and key in
.phpantom.tomlis kebab-case:[semantic_tokens]is now[semantic-tokens], andreport-magic-propertiesunder[diagnostics]ismagic-properties, to match the other diagnostic toggles. The old names keep working, with a warning that names the new one. - A member used on a class that cannot be found is reported as
unknown_class. "Cannot check method save(), because type App\Models\User could not be resolved" used to carryunknown_member. It now carriesunknown_class, so ignoring missing classes covers it too, andunknown_memberis left for members a class really lacks. - Disabling every external formatter keeps the built-in one. Setting
pint,php-cs-fixer, andphpcbfall to""under[formatting]now formats with the built-in formatter instead of turning formatting off. Useenabled = falseto turn it off. Contributed by @enwi. - Updated embedded phpstorm-stubs. Adds the
ps,proctitle, andyazextensions, updates Judy and Relay, and corrects many parameter and return types to match the PHP documentation, includingoci_fetch_object(),pg_loopen(), and nullable RdKafka message payloads.
Performance and memory¶
- Faster analysis of Laravel projects. Classes the project's Laravel setup adds to, such as the auth guard, the
Storagefacade, and classes with macros or pivot accessors, are no longer rebuilt every time they are looked up. Analysing a large Laravel application takes about an eighth less CPU time. - Faster diagnostics and completion after each edit. Diagnostics, completion, hover and every other request on an edited file reuse the parse the edit already made, instead of parsing the file again. Completing at the end of a file whose last statement is still unfinished takes about half as long.
- Faster diagnostics in Blade templates. A template is parsed once per diagnostic pass instead of once per check.
- Faster diagnostics while editing. After an edit inside a function or method, only that function is type-checked again, and the rest of the file keeps its diagnostics, moved along with the text. In a 1,500-line class the type checking after such an edit is around 70 times cheaper. Saving still checks the whole file.
- Faster analysis of methods that check many properties. Narrowing a property or a call's result no longer walks the method again from its first line.
- Memory is returned right after large files are read. Memory used while reading a large file, such as the single-file
php-stubs/wordpress-stubs, is returned as soon as the work is done instead of staying held for about ten seconds, or for as long as the server runs. Opening a file in a WordPress plugin settles around 80 MiB instead of 120 to 160 MiB. Contributed by @stubbedev. - Faster analysis of by-reference parameters. Working out what a function leaves in a variable passed by reference reads the function once, instead of once per
returnin it. Analysing WordPress takes about 6% less CPU time. - Faster analysis of loops. A loop body is no longer walked again once its types have settled.
- Faster analysis of
switchlookup tables. Aswitchthat assigns a different literal in each case, such as a table of country or currency names, no longer slows down out of proportion to its length. One with 8,000 cases is checked in about a tenth of a second. - Faster analysis of
if/elseiflookup tables. The same kind of table written as anif/elseifchain no longer slows down out of proportion to its length either. One with 1,000 arms is checked in a twentieth of a second instead of 20 seconds. - Faster analysis of long files. Checking a file of tens of thousands of lines, such as a legacy top-level script, no longer slows down out of proportion to its length. A 22,000-line script is checked in about a second instead of nearly five.
- Faster analysis of closures in long files. A long script full of closures with typed parameters, called through the variables that hold them, no longer slows down out of proportion to its length. A 22,000-line script of them is checked in under half a second instead of nearly six.
- Faster loading of vendor and stub files. Classes from a file loaded on demand are read with one parse of the file instead of three.
- Faster analysis of arrays filled under many
ifs. A function that adds one key at a time to an array, each under its ownif, no longer slows down out of proportion to its length. With 1,000 such writes it is checked in under two seconds instead of over two minutes. - Faster analysis of arrays given a different shape under each of many
ifs. Once the shapes an array can hold spell out more than 256 values between them, they are shown as one general array type such asnon-empty-array<string, int>, the way PHPStan does. A function with 2,000 such writes is checked in about a tenth of a second instead of over a second. - Faster analysis of long method chains. A fluent chain hundreds of calls long, as generated query builders and API clients produce, no longer slows down out of proportion to its length. A 600-call chain is checked in a fifth of a second instead of nearly seven, using a twentieth of the memory. Indexing a file of them no longer slows down either: one of Drupal core's database fixtures, with chains over a thousand calls long, is indexed in a third of the time.
- Faster indexing in projects that install PHPStan. The classes packed inside its
.pharare no longer parsed as if they were the project's own files. - Faster startup. Hiding the standard library functions, classes, and constants that the project's PHP version no longer has takes a few milliseconds instead of about 50.
- Lower memory use on large projects. Classes that inherit the same method or property now share one copy of it, and each method takes far less memory. On a large Laravel project this cuts peak memory by about 17%. What PHPantom keeps about each call in the project's files also takes much less memory, cutting a further 4%. Memory left behind by edited files is now reclaimed during a long editing session instead of accumulating.
- Less memory for indexed classes. The methods, properties and constants of every indexed class now take only the memory they need. On a large Laravel project this cuts memory after startup by about 5%. Contributed by @vishnub1626.
- Faster go-to-implementation on library classes. Finding the implementations of a class or interface from a Composer package now reads only the files that could hold one, instead of loading every class the project depends on.
Fixed¶
Type inference¶
array_reduce()with a named callback. A callback written as[static::class, 'method'],[$this, 'method'],'Foo::method'or'function'reduces to what that method or function returns, instead ofnull. Reducing an array that cannot be empty is nevernulleither.- Constraint closures passed to
load(). In$post->load(['comments' => fn ($query) => ...])andloadMissing(), on a model or a collection of models,$queryis the relation, as it already was forwith(), so its methods complete and are checked. - Reading an element of a union of arrays.
$trees[$key], where$treesmay be one of several array types, is whatever any of them holds there rather than what one of them does, so passing it to a function likearray_reduce()is no longer reported against the other. - Keys written into an untyped variable. After
$args['foo'] = $fooon an untyped parameter, the array still counts as holding whatever other keys it came with, so passing it to a function that takes an array shape no longer reports an undeclared key. - Variable variables replace what a local held. After
$$name = 1inside a function, the locals$namecould name no longer keep the types they held before, so passing one on is no longer reported against its old type. - Writes through a reference. After
$r = &$a;, a write to either$ror$achanges the other too, and after$e = &$items['key'];writes through$eland in$items, including thenullelement the reference creates.unset()and binding the reference somewhere else end the link. - Writes through a variable key keep an array's other keys. After
$element[$key]['#printed'] = true, reading$element['#attached']gives what that key held or what the write put there, no longer the values of every other key in the array, so passing it on is no longer reported against them. - Values whose type is a guess stay lenient when combined. The sum of two untyped values may be an
array,intorfloat, and is not checked against a parameter's type. That now still holds after it is merged with a value it already covers, such as an array written on another branch, the way PHPStan treats it. globalreplaces what a local held. After$a = 'text'; global $a;inside a function,$ano longer keeps the string it held before, so passing it on is no longer reported against that string.?->chains compared greater than a value. Insideif ($line->product?->stock > 0),$line->productis known to be non-null, since anullchain is never greater than anything.- Plain calls after a
?->check. Afterif ($m?->make(1) !== ''), a later$m->make(1)is what the method returns, without thenullonly the?->spelling can produce, so passing it on is no longer reported. selfparameters in traits. A parameter typedselfinside a trait now sees the members of the class its@phpstan-require-extendsor@phpstan-require-implementsnames, as$thisalready did, so a closure such asstatic function (self $model)in a model trait no longer reports the model's methods as unknown. Contributed by @pataar.selfeverywhere in traits. Return types, property types and@vartags writtenself,staticor$thisinside a trait with@phpstan-require-extendsor@phpstan-require-implementsnow see the required class's members too, so$this->fluent()->getTable()completes and is no longer reported as unknown.- Constants passed to calls. Namespaced and imported constants keep their values and types when used as arguments. Contributed by @shuvroroy.
- Constants defined from namespaced or imported constants. A class constant or namespaced constant such as
const MAX = LIMIT;now holds the value of the constant its own file means, whether imported withuse const, declared in its namespace, or global, when it is read from another file. A parameter default that names a constant is read the same way when the argument is left out. - Constants holding a class name or an enum case. A global or namespaced constant such as
const DEFAULT = Widget::class;orconst SUIT = Suit::Hearts;now has that type, including when it is passed to a templated function or used as a parameter default. - Property types on an annotated
$this. Reading a property through an explicitly typed$thisnow preserves its type in assignments and loops, including Tempest views. Contributed by @shuvroroy. (int)casts keep what the value says. Casting an integer range with(int)now keeps the range, and castingnull, abool, or an array gives0or1, instead of a plainint.- Untyped methods that return
new static(). Calling such a method through a subclass, or on a class that uses the trait declaring it, now gives that class instead of the one the method is declared in. - Variables passed to typed by-reference parameters. After a call to your own function or method that takes
array &$message, the variable now has the parameter's type instead of the shape it had before the call, so reads of keys the callee added are no longer reported. parent::calls that returnstatic. The result ofparent::create()called from a subclass is now the subclass, so its own methods and properties are no longer reported as unknown on the parent.- Members named by a variable in a chain.
$row->{$column}->equals($x)and$obj->$getter()->format()now resolve when the variable holds known strings. A variable that can hold several names reads every member they name. - Members read through a dynamic property name. A call like
$model->{$column}->equals($other)is no longer checked against the object the property is read from, which reported a method that the property's own value has. - Object casts keep the array's shape.
(object) ['key' => 'value']is typedobject{key: 'value'}&stdClasswhen written straight into a call's arguments too, so a template or conditional return type sees its properties, and the shape keeps the values the array was written with. voidreturns read asnull. A call whose conditional return type picksvoid, or whose return type is a union withvoidin it, now givesnullto the variable it is assigned to, so WordPress functions such asthe_title()andwp_list_pages()returnnullwhen they echo andstring|nullwhen it depends on the arguments.- Identity checks that can never hold are
false.$protocol === 'HTTP/1'isfalse, and!==istrue, when$protocolcan only be values other than'HTTP/1', such as'HTTP/1.0'|'HTTP/1.1', so a typo in the compared string no longer hides behind abool. - Variables an included file defines. After an
includeorrequire, the variables the included file assigns are no longer reported as undefined, and they have the types the included file gives them in hover, completion, and the type checks. The included file sees the variables of the scope that includes it, so a value it assigns from one of them keeps its type. The path is followed through__DIR__,dirname(), and constants such as WordPress'sABSPATH. When the path cannot be worked out, nothing after the include is reported as undefined, and a plaininclude $template;leaves every variable untyped, since the file may reassign any of them. A file whose value is used, such as$data = require $path;, or one loaded withrequire_once, keeps the variables' types. - A type beside its own refinement reads as one type. After an
ifthat narrowed astringto anon-falsy-string, the variable is astringagain rather thanstring|non-falsy-string, and an intersection such asstring&'foo'reads as'foo'. - Members of
new $classresolve.(new $class())->name()andnew $class()->name()now resolve against the class$classnames, whether it holds$obj::class,get_class(), a class name string or aclass-string<T>. Previously the method could be reported as unverifiable, or as a call on a string. - Untyped functions return what their body returns. A function with no return type now has it read from its
returnstatements, as a method already did, so members accessed on its result complete, show in hover, and are no longer reported as unresolved. newon a parenthesised expression resolves.new (User::class)(),new ('App\\User')()andnew ($factory->class)()now produce the class the expression names, so members accessed on the new instance complete and are no longer reported as unknown.- Same-named variables in different functions. A call through a variable no longer takes its type from a variable of the same name in another function of the file.
$box->get(0)on aBox<Post>was read as theBox<User>of an earlier function, and$f()lost its return type when another function's$fheld a plainClosure. - Integer ranges survive arithmetic and loops.
int<0, max> + 1isint<1, max>, and a loop counter that starts at0and grows on every pass isint<0, max>instead ofint, so handing either to anint<0, max>parameter is no longer reported. - String casts keep what they cast.
(string)on anintor afloatgives anumeric-string, on aboolornullthe strings PHP spells them as, and on an object whatever its__toString()declares, instead of a plainstring. - Concatenations keep a non-empty operand's guarantee.
'x' . $nameis anon-falsy-stringand$id . $nameanon-empty-string, instead of a plainstring. The same goes for.=. - Literal and numeric strings survive concatenation. Joining written-out strings, with
.,.=orimplode(), gives aliteral-string, and$id . '.95'is anumeric-string.array_fill(0, $n, 'x')is alist<'x'>instead of a barearray. - Inherited constants that read
parent::after an edit. A constant whose initializer readsparent::X, used through a subclass, no longer takes the subclass's parent's value once the file has been edited. - Variables imported with
global. A function that reads a top-level variable throughglobalnow sees the type the top-level code gave it in diagnostics too, as hover already did. - Variables shared between
namespace { }blocks. A variable assigned at the top of one bracednamespaceblock keeps its type in the blocks after it in diagnostics too, as it already did in hover, so its members and arguments are checked there. - Arrow functions that yield.
fn () => yield $xis now typed as aGenerator. - Method calls typed in more places. Some calls were only typed when assigned straight to a variable, and are now typed wherever they appear, such as in an argument, an array or a
return: calls on a$thisnarrowed byassert($this instanceof TestCase)in a test closure, static calls on a variable holding a class name such as$class = 'App\Stamp', and calls to an override without a docblock whose parent declares a conditional@return. - Variables holding a class name follow the code's branches. After
if (…) { $class = Apple::class; } else { $class = Pear::class; }, a call such as$class::make(),new $class, and completion after$class::now cover both classes, not only the one assigned last in the file. - Generators that use what
yieldreturns. A generator whoseyieldsits inside an expression, as in$sent = yield $value;, no longer has itsreturnstatements reported as incompatible with its declaredGeneratorreturn type. - Generators. In a method documented as returning
Generator<int, string, Task, void>, the result of$task = yield …is now aTaskfor diagnostics as well as for completion and hover, and the docblock is found even when an attribute sits between it and the method. A variable only takes the yielded type when the generator itself yields it, not when it yields a similarly named one such as$users. - Variables reassigned further down a
do-whilebody. Completion and hover inside ado { … } while (…)loop now see the type a variable is given further down the body, which is what it holds on every iteration after the first, the same as in the other loops. - Static calls through a variable holding one of several class names. In
$cls::make(), where$clsmay beApple::classorPear::class, the result now includes whatPearreturns when it only answers the call through__callStatic. - Integer literals too large for
int. A constant set to an integer pastPHP_INT_MAX, such asconst BIG = 99999999999999999999;, is now afloat, the way PHP reads it, instead of anint. - Untyped methods reached through long call chains. A method without a declared return type that was first reached at the end of a long chain of such methods no longer stays untyped everywhere else it is called, so members used on its result are checked again.
- Static properties holding non-class values.
Foo::$filesdeclared asstring[]is now read as that array everywhere, instead of as an instance ofFoo. - Inherited constants defined with
self::orparent::. A constant such asconst B = self::A;read through a subclass now holds the value from the class that declares it, as PHP does, instead of the subclass's override ofA. - Class constants set to
Foo::class. A constant such asconst SOURCE = Defaults::class;now holds the class's name, so$class = Settings::SOURCE;followed bynew $class()or$class::MODEresolves. A constant set to an enum's::classno longer reads as one of the enum's cases. - An override that narrows its return type keeps it. When an interface method documents
@return Factory<Meta>and an extending interface redeclares it as: OrmFactory, the override's result reads asOrmFactory, so returning it from a method declared: OrmFactoryis no longer reported. This fixes Doctrine'sEntityManagerInterface::getMetadataFactory(). - Iterating a constant that lists enum cases.
foreach (self::MARKETS as $market)over a constant such as[Country::DK, Country::SE]now gives$marketthe enum's type instead ofmixed, whether or not the constant declares a type. - A call nested in an expression writes through its reference parameters.
$found = [preg_match('/(\d+)/', $s, $m), …]now leaves$mtyped the same as apreg_match()call on its own line. ->valueand->nameon an enum read as its cases' values and names. Avalue-of<Enum>parameter or return, or a declared literal union, no longer reports a false type mismatch when fed an enum's->value.- A ternary whose arms are a class and that class or
null.$c ? new Foo() : $maybeFoonow keeps thenullinstead of reading as a plainFoo. - Variables passed by reference to any method or constructor. After
$service->fill($result),$this->repo->load($row),$class::fill($result)ornew $class($source, $errors), a variable the call writes through a by-reference parameter now has the type the parameter gives it, instead of keeping the value it held before the call. This includes calls on$thisinside a closure bound to another object, and an array unpacked into a by-reference variadic of a class type stays an array. ::CLASSin any letter case.Foo::CLASSnow means the class name, asFoo::classdoes, instead of being reported as a missing constant, andnew $name()on it resolves.- Superglobals inside functions and methods. Hover and completion now type
$_SERVER,$_GETand the other superglobals as arrays inside a function or method body, as they already did in top-level code. - Traits used by enums. An enum's
use Greets { hello as greet; }now gives the enum agreet()method,insteadofpicks the right trait, and/** @use Holds<Stamp> */binds the trait's templates, as they already did in classes. - Methods called through a variable name. When
$nameholds one known method name,$factory->$name()andFactory::$name()return what that method returns instead ofmixed. - Compound bitwise assignments on strings stay strings.
$payload ^= $mask(and|=,&=) on two strings, or on operands with no declared type, no longer makes$payloadanint, matching$payload ^ $mask. Contributed by @phcorp. - Repeated calls with a conditional return type. A call without arguments written a second time in the same method, or checked in a condition, now gets the branch its conditional return type picks instead of the method's wider declared type, so passing it on is no longer reported. Contributed by @giuseppe-esposito-87.
Narrowing and control flow¶
- Truthiness checks on untyped and
mixedvalues. Insideif ($x)orif (!empty($x['key'])), a value of unknown type is known to be truthy, so passing it to a function likearray_reduce(), whose result is onlynullfor an empty array, no longer reports thatnull. - Arrays filled by key in a loop with an inner loop. An array written at every value of a literal list, as in
foreach ([1, 2, 3] as $node) { $labels[$node] = 0; … }, now keeps every key required when the body also holds a nested loop orswitch, so reading$labels[1]afterwards no longer addsnull. Acontinuethat only skips the inner loop no longer counts as skipping the write. - Breaking out of two loops from a loop over a plain
array. Abreak 2inside aforeachover an untypedarraynow carries the values it set past the outer loop. On the outer loop's later passes the inner loop no longer judged that branch impossible from a stale value of its loop variable. - Integers cast from a
ctype_digit()-checked value. Afterctype_digit($delay)passes,(int) $delayandintval($delay)are known not to be negative, so passing them to a parameter such assleep()'sint<0, max>is no longer reported. ctype_digit()narrows what it checks. A string that passesctype_digit()is now anumeric-string, and an integer is narrowed to the values the check accepts in either branch.- Variables after a
trywhose body always returns. When atrybody always returns or throws, the code after the statement now sees only what thecatchblocks left behind, so a variable set in acatchhas that value afterwards instead of also keeping the one it had before thetry. - Ruling out a range's edge value. After a guard like
if (0 === $id) { throw ...; }, anint<0, max>variable or property is nowint<1, max>, so passing it where a positive integer is expected is no longer reported. - A
finallyblock sees the paths an uncaught exception takes. A variable thetryassigned before a call that may throw, and cleared after it, is no longer treated as never set inside thefinallyblock. The same goes for an exception acatchthrows partway through. isset()that fails on an array element. Whereisset($values[$key])was false,$values[$key]now reads asnull, the value a missing key gives. A guard likeif (isset($values[$key]) && !is_array($values[$key])) { return; }now leaves the element an array ornullpast it, the same as it does for a plain variable.- Type assertions on refined strings. A
@phpstan-assertthat refines a string the value already refines another way, such asnon-falsy-stringon alowercase-string, now narrows to both instead ofnever. A template the assertion names takes the type of the argument it was bound to, sowp_is_uuid('foo')keeps'foo', and the refinement is dropped again after theif. - Type guards on an impure call don't narrow the next call. After
if (is_wp_error(get_password_reset_key($user))), a second call to a function marked@phpstan-impurekeeps its full return type. !empty()on a property proves the property exists.!empty($x->prop), or returning early onempty($x->prop), now allows$x->propon every member of a union, the same wayisset($x->prop)does.- Calls whose conditional return type is
neverend the code path. A guard clause that calls a function likewp_die(), declared($args is array{exit: false, ...} ? void : never), now narrows the code after it when the arguments picknever. - Truthiness checks on
voidresults. A truthiness check such asmaybe() ?: nullorif (!$r)on a value typedvoid|stringnow drops thevoid, since it isnullat runtime, so returning the result where?stringis declared is no longer reported. array_key_exists()narrows the key. A key that passesarray_key_exists($k, $array)is now one of the array's keys, as it already was afterisset($array[$k]), so it can be returned as akey-of<...>. Both checks also narrow a key written as a cast, such as(string) $this->sort.- Integer comparisons narrow to a range. Inside
if ($n > 0)anint $nisint<1, max>, and afterassert($port >= 0)andassert($port <= 65535)it isint<0, 65535>.max(),min()andabs()keep the bounds of integer arguments too, somax(1, $n)isint<1, max>. - Checks on a string refine it. A string that passes
if ($s),!empty($s)or PHPUnit'sassertNotEmpty()is anon-falsy-string, a?stringcompared against''loses the empty string, and@phpstan-assert class-stringmakes astringaclass-string. instanceofon anobjectno longer sticks after theif. Once anif ($o instanceof Foo)with noelseends,$ois plainobjectagain, and calls on it are no longer reported as missing fromFoo.- Identity checks on values of unknown type.
assert($array[1] === null)orif ($x === 'a')now narrows the checked value even when its type could not be resolved, such as an offset on an object of a missing class. !== nullon a value that is one of several literals. After anif/elseifchain that assigns a different literal in each arm andnullin theelse, testing the variable againstnullnow narrows the types the arms tested, so passing$nodeto a parameter typedA|Bno longer reports a mismatch.- A
catchblock sees what thetrybody assigned before anything could throw. A variable set by an immediately invoked closure, or by any statement that cannot throw, now keeps that value in thecatchinstead of reverting to what it held before thetry. - A no-op emptiness check no longer breaks a
non-empty-stringargument. Afterif ($h !== '') { ... }, passing$hto anon-empty-stringparameter is no longer reported, since the variable is still a plainstring. - A value both branches could hold no longer says which branch ran. When one branch leaves
$xas1|2and the other as2|3, a laterif ($x === 2)no longer narrows variables to what only one of the branches assigned. The same goes for arrays whose elements could hold such a value. - A failed call with several
@phpstan-assert-if-truetags narrows none of its arguments. WhenbothDefined($start, $end)returns false,$startand$endare no longer both taken to benull, since only one of the promises has to have failed. - A passing strict
in_array()againstobjectelements keeps the needle's classes. AFoo|Bar|stringneedle checked against alist<object>still reads asFooorBarinside the branch. - An assignment is seen by the rest of the expression it sits in. In
if (($user = find($id)) && $user->isActive()), the right-hand side now knows what$userholds, and[$i++, $i]holds the old$iin its first item and the incremented one in its second. - Narrowing follows the order a condition is evaluated in. In
if ($x instanceof Foo && ($x = make()))the body sees whatmake()returned, and a call that changes an object between two checks drops what the first one proved. A check inside one argument no longer narrows the arguments after it. - Ternary and
matcharms see what was assigned earlier in the statement. In[$x = 1, $x > 0 ? needInt($x) : 0], the arm reads the1rather than what$xheld before the statement. - Completion after
&&knows what the left side proved about a property. Inif ($this->pet instanceof Cat && $this->pet->, completion offersCat's methods alone. is_subclass_of()narrows a class name. A string that passesis_subclass_of($class, Foo::class)is nowclass-string<Foo>, as withis_a($class, Foo::class, true).- A strict
in_array()on an unknown or nullable value.in_array($in, ['path', 'query'], true)now narrows amixedneedle to'path'|'query'and rules out itsnull, instead of leaving only thenull. - Comparing an object with a value that may be
null. An object is always greater thannull, so the branch where$obj > $maybeNullfails no longer sees anullthere, inside loops as well. - A value set by a ternary on an
instanceofcheck. After$problems = $x instanceof Sheet ? $x->problems() : [];, testing$problems !== []now narrows$xtoSheet, as theif/elseform already did. - Checking a union of classes, scalars and arrays against a subclass. An
instanceofor an asserted class on a value such asDateTimeInterface|array|int|nullnow leaves only the class, instead of keepingarrayandint. - The fallback of
??knows the left side wasnull. Insideif ($a || $b), the$bof$a ?? $bis no longer nullable. - A null check written through
?? nullnarrows the value.if (null !== ($row['name'] ?? null))makes$row['name']non-null the wayisset()does, and so does getting pastif (($row['name'] ?? null) === null). Contributed by @phcorp. - A
falsecheck written through?? falsenarrows the value.if (false !== ($row['flag'] ?? false))makes$row['flag']set and neithernullnorfalse, and so does getting pastif (($row['flag'] ?? false) === false). - Assertions of a nullable or union type. After a
@phpstan-assert ?Dog $x,$xisDog|nullinstead ofDog, and an assertion likeDog|intkeeps both halves. The same goes for a template bound to such a type, soassertSame($expected, $actual)with anint|string$expectedleaves$actualanint|string. - Assertions whose type is a template. A
@phpstan-assertnaming a@templatenow narrows to the type of the argument it is bound from, so after$this->assertSame(4, $width),$widthis4instead ofobject, and passing it on to anintparameter is no longer reported. Contributed by @phcorp. Closes #473. - A
finallyblock sees the paths that returned early. Afterif (null !== $tool) { return; }in thetry, anull !== $toolcheck in thefinallyblock is no longer treated as dead code. Areturnor rethrow inside acatchcounts too. Contributed by @phcorp. switchandmatchnarrow like the same comparison in anif. Acaseor arm narrows its subject the waysubject == label(or===formatch) does in anif, soswitch (get_class($x))andmatch (gettype($x))narrow$x, and an arm further down knows the conditions above it failed.gettype()comparisons narrow the value.gettype($x) === 'integer'narrows$xlikeis_int($x), and the same holds for the other type namesgettype()returns.- Loose
==against a non-numeric string rules out numbers. Insideif ($key == 'foo'), anintorfloatalternative of$keyis dropped, since PHP 8 never considers a number equal to a non-numeric string.
Generics and templates¶
foreachover aRecursiveIteratorIterator. Looping over aRecursiveIteratorIteratornow gives the keys and values of the iterator it wraps, rather than the wrapped iterator itself, sonew RecursiveIteratorIterator(new RecursiveArrayIterator($data))yields$data's elements.- Templates in the value type of an array parameter. A function taking
iterable<Tk, (Closure(): Tv)>orarray<Tk, TypeInterface<Tv>>now infersTvfrom each element of the array passed to it, closures and first-class callables included, instead of from the whole array. - Chained calls on conditional return types. A method whose return type depends on an argument's type, like
find(int|list<int> $id)returning a collection for a list, now picks the same branch when you call a method straight on its result as when you assign it to a variable first. - A template named twice in one parameter checks its bound. A parameter typed
T|class-string<T>, asnew ReflectionClass()takes, now reports a plainstringargument instead of accepting anything. - Conditional return types over templates. A condition on a template is judged by what the call bound it to, held to the template's bound, and the branch it picks narrows the template, so
absint(5)returns5andsanitize_sql_orderby($string)returnsnon-falsy-string|false. A condition onkey-of<T>orvalue-of<T>is judged on the keys or values of the array passed, so slashing an array of strings withwp_slash()gives strings. - Intersected conditional return types. A return type that intersects two conditionals now gives only the types both of them allow, so
get_category($term)returnsWP_Termandget_category($term, ARRAY_A)anarray<string, mixed>instead of the intersection as written. - Conditions over refined types. A conditional return type whose condition is a refined type, such as
int<min, 0>,non-falsy-string,array<int, mixed>orempty, now picks the branch the argument really takes. WordPress functions such asget_user(),absint(),has_shortcode(),size_format()andwp_unique_id()now return what their arguments ask for. - Conditional return types inside a union, an intersection or a generic. A return type such as
false|($output is 'ARRAY_A' ? array : WP_Term)or($display is true ? void : string)|nullis now decided by the call's arguments like one that is a conditional throughout, instead of showing its source text. WordPress functions such asget_term_by(),get_terms(),wp_get_post_terms()andedit_term_link()now return what their arguments ask for. - Defaults written
\true,\falseor\nulldecide conditional return types. An omitted argument whose parameter defaults to a fully qualified keyword, the way generated stubs write them, now picks its branch of a conditional return type, so WordPress functions such aswp_insert_post()andhas_filter()return what their defaults ask for. - Array-shape conditions compare the keys they name. A conditional return type like
($args is array{fields: 'ids', ...} ? int[] : WP_Post[])now checks the array the call passes: a missing required key, or a key holding another value, takes the other branch, and an array whose keys are unknown gets both. WordPress functions such asget_posts(),wp_list_pages()andwp_die()now return what their arguments ask for. - Variadic template parameters take every argument. A function declaring
@param T ...$valueswith@return Tnow returns the union of everything passed to it, not just the first argument's type. An array spread into it with...$itemspasses its elements. - Static calls with a conditional return type, passed as an argument.
wrap(Factory::make($x))now sees the branch ofmake()'s conditional@returnthat$xselects, instead of its native return type. - A typed closure decides a callback's template. A closure such as
fn(User $user) => …passed where acallable(T): stringis expected now bindsTtoUser, so it is no longer reported for accepting less than the template's bound. A closure whose parameter falls outside the bound is still reported. - Method templates through an override. A call through a class whose override declares only a native return type now resolves to the type the interface's
@templatepicks for the call, so members of the returned class are no longer reported as missing. staticas a type argument keeps the receiver's generics. A method returning something likeNodeBuilder<static>now carries the receiver's own type arguments into the rest of the chain, so a Symfony config tree's->children()->…->end()returns the parent node with its full type.- Class templates in
@returnbeat scalar and nullable return types. A method whose@returnnames a template of its class now returns what the class is instantiated with even when its native return type is a scalar union or nullable, so$request->query->get('page')isstring|nulland a Symfony tree builder's->end()returns the parent node without addingnull. - Nested conditional return types follow the argument through each branch. In
($key is Model ? TModel|null : ($key is Arrayable ? static : TModel|null)), an argument typed?Usernow reaches the inner condition as justnull, so the call returnsUser|nullinstead of also picking upstatic. - Callbacks that compare or combine values bind their generics. A closure returning a comparison or a logical expression, such as
fn ($carry, $item) => $carry && $item > 0, now counts toward the generic type it is passed for.array_reduce($items, …, true)with such a callback is aboolinstead oftrue. - Short template argument lists on interfaces, traits and mixins.
@implements Coll<User>on an interface with@template TKeyand@template TValuenow bindsUsertoTValuefor the@methodand@propertytags read through it, the same as@extendsalready did, and an omitted parameter takes its declared default. The same applies to@useand@mixin, and a parent is now matched by its full name, so two parents with the same short name no longer swap arguments. - Chained calls on container lookups keep their class.
$container->get(Foo::class)->bar()now resolves toFoowhen the method's return type also depends on an optional argument left out of the call, as Symfony'sContainerInterface::get()does. - Class names held in properties, constants, and return values. A function such as
app()or one taking@param class-string<T>and returningTnow resolves to the class when given a property, class constant, or method result that holds aclass-string, not only when givenFoo::class. - A class named like a template parameter. A class such as
trait T {}anywhere in the project no longer takes the place of every@template T, including the one onRecursiveIteratorIterator, in member access as well as argument and return type checks. - Literal constructor arguments bind literal templates.
new TreeBuilder('name', 'array')on a class declaring@template T of 'array'|'string'now keeps'array', so Symfony 8 config tree builders get the array node fromgetRootNode(). Closure(): Tconditional return types. A callback that never returnsnullnow takes the true branch of($callback is Closure(): T ? T : null|T), whether it is a closure, an arrow function, or a first-class callable such as$this->build(...).- Generic objects passed through a function keep their template defaults. Passing a plain
PendingRequestthrough a function that re-binds itsTAsynctemplate keeps the defaultfalse, soget()still returns aResponse. A template known only to be aboolnow gives both branches of a conditional return type instead of the second one. - Callbacks with a declared return type bind templates from their body. In a chain such as
$banners->flatMap(fn ($b): Collection => $b->items)->filter(...), the callback now sees the items' type instead of a bareCollection. A closure body counts everyreturn, including ones that return a local variable. - Templates bound from arrays with known keys. A parameter documented as
array<K, V>orarray{k: T}now binds its templates from an array whose keys are known, soarray_values($shape)keeps the element types instead of givinglist<mixed>. - A template next to other types in a parameter union binds only what they leave over. Passing
string|float|bool|nullvalues to a@param array<K, T|string|null>now bindsTtofloat|bool, so the call's return type no longer brings back thenullthe function filtered out. - Generic classes named without their type arguments. A variable assigned from a method of a bare
\Iterator(or any generic class named without arguments) is nowmixedinstead of the template parameter's name, as the same call already was when used directly. - Inner iterators keep their element type.
getInnerIterator()on anIteratorIteratororFilterIteratorsubclass now returnsIterator<TKey, TValue>, so$this->getInnerIterator()->current()has the element type the class's@extendstag gives. - Quotes and brackets inside call arguments. An argument such as
'a' === 'b', a string holding a|,]or->, or a nested index like$a[$b['x']]['y']is read as written when a call's generic or conditional return type is worked out. A call chained offnew Box(…)no longer takesBox's template types from its constructor. - Conditional return types decided by a default constant. A method whose conditional return type depends on an argument left out of the call is now decided when the parameter's default is a class constant imported in the declaring file, as Symfony's
ContainerBuilder::get()does.$this->container->get(EntityTypeManagerInterface::class)->getStorage('node')in a Drupal kernel test now resolves. - Methods returning
selfkeep the instance's type arguments. A method declared: selfin a trait that a generic class uses, or in a generic parent a class extends with@extends, now returns the class with the instance's type arguments, soBook::select()->where('title', $title)->all()in Tempest is still a list ofBooks. - Subclasses of generic classes that leave the templates unbound. A class extending
\ArrayObjectwith no@extendstag now keeps the return types its own overrides declare, so$list['key']and$list->offsetGet('key')give what itsoffsetGet()returns instead of an unresolvableTValue.
Closures and callables¶
- Generic array callable results. Calling a method through an array callable preserves the receiver's generic return type, so completion and type checks see the concrete result. Contributed by @shuvroroy.
- Closures declared to return
float. A closure or arrow function declared: floatis now shown returningfloateven when its body computes an integer, since PHP converts the value on return. - Closures that capture by reference the variable they are assigned to. In
$lock = new Lock(function () use (&$lock) { ... }),$lockinside the closure is now what the assignment stores,@varincluded, instead ofnull. - Union types in
@param-closure-this. A closure whose tag names several classes, such as@param-closure-this WebContext|ApiContext, now binds$this,self::, andstatic::to every one of them instead of falling back to the class around the closure, and aninstanceofcheck narrows$thisto the one it proves. Contributed by @ace-of-aces. - Closures that return a method call on their own parameter.
fn (User $u) => $u->label()now gets the method's return type, so calling the closure, or passing it where acallable(User): stringis expected, sees what it returns. - Closures and variables inside
<?= ?>echo tags. In a plain PHP template, a closure written inside an echo tag now knows the types of its parameters, so their members resolve instead of being reported as unverifiable. A variable assigned or read inside an echo tag counts as defined or used. - Callbacks passed by name.
call_user_func(callback: [$repo, 'find'])and\Closure::fromCallable(callback: …)()now return what the callback returns, instead of an unknown type or a false "method not found onClosure" error. Closure::fromCallable()keeps the callee's return type. Calling the closure it makes, such asClosure::fromCallable([$repo, 'find']), now returns what the callable does, whether it is an array callable, a callable string, an invokable object, or a closure.- Invoking an array callable. Calling
[$object, 'method']or[Foo::class, 'method']through a variable, or passing one tocall_user_func(), now returns what the method returns instead of an unknown type. - Calling a closure on the spot. Accessing a member on the result of a closure invoked where it is made, such as
$repo->find(...)(),$repo->find(?, 1)(5),(fn(): User => new User())()orClosure::fromCallable([$repo, 'find'])(), now resolves to what the closure returns. - Calling a partial application held in a variable. After
$make = $repo->make(1, ?), a call such as$make(User::class)is checked against the parameters the placeholders leave open, and returns what the wrapped call returns with the bound and passed arguments together. Signature help shows the same parameters. - First-class callables and partial applications carry their parameters. The closure made by
$repo->find(...)or$repo->make(1, ?)now has the parameters it takes, shown on hover and checked when it is passed where aClosure(…)signature is declared. A partial application's return type is decided by the arguments it binds. - Member access on a closure literal. Calling a method such as
call()orbindTo()directly on a parenthesised closure or arrow function, like(fn() => [])->call($obj), is now checked againstClosureinstead of being reported as an unresolved member access. - Callback parameters take what the call hands them. A closure passed to
array_map()or any other callable parameter sees the narrower type the call passes it, sofn (string $c)over alist<non-empty-string>gives$cthe typenon-empty-string. - The pipe operator with methods and closures.
$input |> $formatter->format(...),$input |> Stamp::fromString(...), and a closure or a variable holding one on the right of|>now give the callable's return type, as a function such astrim(...)already did. - Closure parameters keep refinement types. A closure parameter inferred as
positive-int,non-empty-lowercase-stringor another hyphenated type is no longer shown asmixed. - Generators written as closure arguments. A
yieldorreturninside a string or a comment no longer counts toward the generator type of a closure passed as an argument, andyield fn ($x) => $xis read as yielding an arrow function rather than a key and a value. Closure parameters with a default value containing a comma, such asstring $sep = ',', are no longer split in two. ($fn)()returns what$fn()does. Calling a closure through a parenthesized variable now gives the closure's return type, so passing the result straight to a function is checked like$fn()is.- Closure parameter hints keep their own class. A closure parameter hinted with a class that only shares its short name with the type the callback is declared to receive, such as
App\CollectionagainstIlluminate\Support\Collection<int, User>, keeps the class it names. Completion and diagnostics inside the closure no longer use the other class. array_map()over a call on a parenthesisednew.array_map(fn (Item $i) => …, (new Repo())->all())now checks the callback against the elementsall()returns instead of againstRepo.- A closure only reads
@paramfrom its own docblock. A closure whose docblock does not mention a parameter no longer picks up the type from a@paramwritten above an earlier closure. - Variables inside a closure keep their types when another method is chained onto the call. In
$obj->with(function (string $s) { … })->run(), hover and completion inside the closure again know the types of its parameters and locals. - Closures passed to a static call through a variable. A closure passed to
$class::each(…), where$classholds a class name or an object, now gets its parameter types and its@param-closure-thisbinding from the method, as it already did when the class name was written out. - Closure parameters follow the rules of function parameters. A closure's or arrow function's
@paramno longer replaces a native type it does not fit, so/** @param Foo $x */ function (int $x)reads$xas anint, the way a function's parameter is read. - By-reference captures follow the callee's invocation tags across files. After a closure with
use (&$x)is passed to a function or method declared anywhere, whatever the method is called on,$xreflects whether the callee's@param-immediately-invoked-callableor@param-later-invoked-callabletag, or one it inherits, says the closure has already run, and what a closure that has run changed on$thisis no longer taken as known. Without a tag, only a function parameter typed as a callable is taken to run the closure before returning, as in PHPStan. - Calling a closure stored in a variable applies its by-reference writes. After
$write = function () use (&$out) { $out = 'written'; };and$write();,$outholds'written'instead of possibly still its old value, so passing it on no longer raises a false argument type error. A closure that is only called on some paths, handed to another function, or replaced before the call, and a write the closure only makes on some paths, still leave both values possible. Contributed by @phcorp. Closes #474. - A closure with a signature keeps the
Closuremethods. Calling__invoke(),bindTo(),call(), or anotherClosuremethod on a value documented asClosure(): voidor\Closure(int): stringis no longer reported as member access on a scalar, and__invoke()andcall()return what the signature says. Contributed by @phcorp. Closes #465.
Arrays¶
- Constants written into an array in a loop. An array built in a loop from a constant, such as
$labels[$node] = self::WHITE, now keeps the constant's value as its element type instead of widening it toint, so passing it to a parameter that accepts only those values is no longer reported. - Keys written into a plain
array. After$args['foo'] = $fooon an untypedarray,$args['foo']is now known to be the value written, so it completes and is checked like any other entry. The array still counts as holding whatever other keys it came with, so passing it to a function that takes an array shape no longer reports an undeclared key. - Class-name keys written into an array. A key that is a class name, such as one checked with
class_exists(), added to an array whose keys areFoo::classconstants no longer turns every key into a plainstring, so passing them tonew ReflectionClass()is no longer reported. A constant array keyed byFoo::classkeeps its keys as class names. array_intersect_key()keeps the array's type. The result ofarray_intersect_key()now has the element type of the array it filters, likearray_diff_key()and the other intersect functions, instead of a barearray.- Conditional appends keep every path. After
if ($a) { $c[] = 1; } if ($b) { $c[] = 2; },$ccan now be[2]as well as[],[1]and[1, 2], so acount()check no longer narrows it to the wrong array.array_key_exists()on a union of array shapes now keeps only the shapes that can pass the check. - Writing a key into a
string[]keeps its keys open.$args['--admin'] = 1on an array declared asstring[]orarray<string>no longer pins its keys toint|string, so passing it on to anarray<string, …>parameter is no longer reported. - Reading a key from an intersection of array types. For a value typed
array<string, mixed>&array{at: Carbon},$entry['at']now resolves toCarboninstead of an unknown type. - Arrays filled by key in a loop keep their keys. Building an array with
$out[$key] = …while looping over a shape keeps the keys the shape requires, so reading one no longer addsnull. Looping over a non-empty array leaves a non-empty array. - Writing a literal key keeps a literal key type. Writing under a known key into an array typed
array<'a'|'b', V>orarray<value-of<Country>, V>keeps those keys, adding the written one if it is new, instead of widening them tostringorintand reporting the array where the original type is expected. - An array filled under repeated checks keeps every key. After
if ($flag) { $data['a'] = 1; }followed by moreif ($flag)blocks that each add a key,$datakeeps all of the keys instead of losing the ones added in between. The same holds for writes under a key only known at runtime ($data[$id]) and forarray_push(). - Array literals passed to a call inside another call. In
takesList(array_values(wrap(['k' => 'str']))), or an array passed as the starting value ofreduce(), the literal now keeps its keys and values, as it does when the inner call is assigned to a variable first. - A typed array no longer proves it holds the keys an open array shape requires. A parameter declared
array<string, int>orlist<int>is no longer taken to match anarray{foo: int, ...}orlist{int, ...}it says nothing about. - Shape keys spelled as class constants are read as the keys they hold. A docblock shape like
array{Slots::NAME: string, Slots::AGE: int}whose constants are0and1is now accepted where alistis expected. - Array literals with keyed arguments inside them.
collect([User::make(['name' => 'x'])])is now a collection ofUser, instead of reading the=>inside the call as the element's key.
Built-in functions and constants¶
JSON_THROW_ON_ERRORthrowsJsonException. Ajson_decode()orjson_encode()call whose flags includeJSON_THROW_ON_ERRORnow counts as throwingJsonException, so@throwscompletion and "Update docblock" suggest it, and what acatch (JsonException $e)block assigns is no longer lost after thetry.array_udiff()and its siblings accept their callback. Passing the comparison callback toarray_udiff(),array_diff_ukey(),array_uintersect()and the rest of the family is no longer reported as an argument that should be an array, and hover and signature help no longer list parameters PHP 8 removed from built-in functions.- Constants PHP has removed stay unknown. A built-in constant removed before the project's PHP version, such as
ASSERT_QUIET_EVALon PHP 8, no longer resolves once another constant from the same extension has been used. - Arithmetic on
GMPandBcMath\Number. An operation on aGMPor aBcMath\Number, such as$price * $qty, now produces the same class instead ofint|float, so passing the result on is no longer reported. - Refined results from string builtins.
strtolower(),sprintf(),number_format()and similar calls now return what their arguments decide, such as alowercase-string, anon-empty-stringor anumeric-string, instead of a plainstring. An array keyed bystrtolower()now matches anarray<lowercase-string, …>declaration. - Number strings from the standard library.
bcadd()and the other bcmath functions,(string)on aBcMath\Number, andsprintf()with a lone float conversion such as'%.2F'are anumeric-stringinstead of a plainstring. filter_var()andfilter_input()return types. The filter now decides the result, sofilter_var($v, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]])isint<1, max>|falseinstead ofmixed, andFILTER_NULL_ON_FAILUREturns thefalseintonull.class_implements(),class_parents()andclass_uses()on a class known to exist. Passing an object no longer gives a possiblefalse, and a class name checked withclass_exists()or written asFoo::classno longer reports thefalseas an argument mismatch.- Constants next to a removed one are no longer hidden.
ASSERT_EXCEPTION,MB_CASE_UPPER,MB_CASE_LOWER,MB_CASE_TITLE, andMCRYPT_BLOWFISH_COMPATresolve again on the PHP versions that have them, instead of being treated as removed along with the constant declared just before them. - APCu functions return only the form the call selects.
apcu_store(),apcu_add(),apcu_delete(), andapcu_exists()called with a single key return abool, so returning one from a function declared: boolis no longer reported.
PHPDoc and attributes¶
- Docblock types a native type rules out. A docblock member the native type cannot hold, such as the
resourcein@return resource|Socket|falseon a function declared: Socket|false, is now dropped, sosocket_import_stream()returnsSocket|falseinstead of being rejected where aSocketis expected. - The last of repeated
@phpstan-returnand@phpstan-paramtags wins. A docblock that repeats one of these tags now uses the one written last, as PHPStan does, so stubs that refine an older declaration below it, like the WordPress stubs forget_posts(), resolve through the newer one. - A
@varabove a reassignment replaces what calls on the old value returned. After/** @var Box<string> $box */ $box = make();, a call on$boxresolves with the new type even when the same call was passed as an argument before the reassignment. @usesnaming a global or a variable. A@usestag that names a global or a variable, as WordPress writes it, is no longer reported as an unknown function.- Escaped backslashes in attribute strings. A
#[Deprecated]replacement or reason, or another stub attribute's string, written with doubled backslashes ('\\Foo\\bar()') now reads as the single-backslash name PHP sees. - An override's own return type wins over its parent's docblock. A method declaring
: Viewwithout a docblock of its own no longer picks up the other classes and scalars a parent's@returnlists, so members ofVieware no longer reported as missing on them. @param-outdecides what a by-reference argument holds. After a call, the variable now has the type the callee's@param-outdeclares instead of keeping its old shape when the declared type is wider. The tag also carries over to a method that overrides or implements the one that declares it, with the class's template types filled in.@param trueand@param falseon aboolparameter. The docblock type is now used instead of the nativebool.- A docblock wider than the parameter's type.
@param object $moneyon aMoney $moneyparameter no longer turns$moneyinto a plainobject; the native type stands, as in PHPStan. @varabove code that sits behind other comments. A/** @var */block is still applied when a plain comment, an empty docblock or a Blade component tag stands between it and the code, or when a string above it contains/*.- Closure types in
@var.@var Closure(int $x): void $cbno longer counts$xas defined. - A plain comment above a method is not its docblock. A method with a
/* … */comment above it no longer reads the@param,@templateor@returntags of an earlier method's docblock, which could give its parameters the wrong type and report members as missing. Exception completion insidecatch (…)likewise no longer offers that docblock's@throws, and no longer mistakes a comment or a string that names a method for the method itself. - Inline
@varstays in its own function. An inline@varabove a one-line function no longer types a variable of the same name in the next function, and one written above a multi-line closure still applies below it. @not-deprecatedon an inherited method. Subclasses that inherit a method tagged@not-deprecatedno longer get the interface's deprecation back.@methodparameters defaulting tonull. A@methodtag such astag(string $disk = null)now acceptsnull, as the equivalent native signature does.- A method's
@paramno longer describes the method below it. When a documented method fits on one line, a parameter of the same name in the next method kept the type documented for the first one, which produced false type errors. It now keeps its own declared type. - Imported type aliases resolve in the file that imports them. A method typed with an alias from
@phpstan-import-typenow returns the full shape when it is called from the same file, not only from other files. @phpstan-self-outapplies wherever the call sits. A call whose result is assigned or tested, such as$ok = $box->replace('x'), now updates the type of$boxtoo, not only a call made on its own line.- A named
@varabove a destructuring./** @var array<string, string> $hashes */above[$ids, $hashes] = $cachednow types$hashesalone, and$idsstill gets its element of$cached. - Docblock classes that do not fit the declared type. A
@return,@paramor@varnaming a class that is neither the declared class nor one of its subclasses no longer replaces the declared type, which is what PHP enforces. A@return DateTimeImmutableinsidenamespace Appon a: \DateTimeImmutablemethod no longer reports its ownreturn new \DateTimeImmutable()as a mismatch.
Name resolution¶
- Method bodies in files not yet opened. A method with no return type, or one that returns a Doctrine query builder, declared in a file the editor has not opened now reads the class names in its body through that file's imports, so
return new User();gives the importedUserrather than a class of that name in the method's own namespace. - Property types inferred from
newwith an imported class. A property assignednew Logger()in a class loaded from disk, whereLoggeris imported into a namespaced file, now gets the imported class as its type instead of one under the file's namespace. Contributed by @shuvroroy. - Imported functions that share a name with a global one. After
use function Lib\greet;, signature help and the other features that look the function up showLib\greet, not a globalgreet(). - Classes with the same short name in different namespaces. Protected members and constructors are offered only for the class itself and its real ancestors, not for a same-named class in another namespace, and semantic highlighting colours each class by its own kind and deprecation.
- Imports match
newin any case. A property typed fromnew user()in a constructor, or from a promoted parameter's default, now names the importedApp\Models\Userinstead of a class in the current namespace. - Function and constant imports no longer stand in for a class. A
use functionoruse constimport spelled like a class, such asuse function Laravel\Prompts\table;next to a classTable, no longer makes that class name resolve to the function or constant. A type hint that spells an imported class in a different case, such asmoneyforMoney, now names the imported class. - A template no longer reaches other classes in its file. A docblock name such as
@var Node $ninsidenamespace Appnow meansApp\Nodeeven when another class in the same file declares@template Node, instead of the globalNodeclass. key-ofandvalue-ofread in the function's own file. Akey-of<Foo::BAR>orvalue-of<Suit>in a function's docblock now names the class the function's file imports or declares, rather than one the caller happens to have under the same short name.- Functions in a global
namespace { }block. A function declared in an unnamednamespace { }block after a named one is now global, instead of being placed in the earlier block's namespace. - Global classes next to an import of the same short name. With
use App\Facades\Redis;, both\Redisand an alias such asuse Redis as PhpRedis;now mean the globalRedisclass instead of the facade, while a bareRedisstill means the facade. A class that extends or implements a global class is no longer checked against the imported one either, so diagnostics, hover, and go-to-implementation see its real parents. - Narrowing to a global class next to an import of the same short name. An
@phpstan-assert, anin_array()check, or$x instanceof $ythat narrows to the global\Nodenow keeps it as the global class in a file that imports anotherNode, instead of switching to the imported one. Type checks insidearray_filter()callbacks andmatch ($x::class)arms also follow the file's imports. - Unqualified class constants inside a namespace. In
namespace App,Foo::BARpassed to a generic function, and areturn Foo::BAR;read when generating or updating a function's@return, now meanApp\Foowithout an import, instead of a globalFoo. - Class constants defined in terms of another class. A constant such as
const MODE = Defaults::MODE;now holds the value of theDefaultsits own file imports or declares, instead of whichever class the file reading it, or a subclass in another namespace, callsDefaults. Hovering such a constant shows that class fully qualified. - Imported class names in a different letter case. With
use Lib\Money;, writingnew money()now meansLib\Money, as PHP's case-insensitive class names do, instead of a class of the current namespace. - Unqualified parent classes and traits inside a namespace. In
namespace App,extends Baseanduse T;now meanApp\BaseandApp\T, as in PHP, instead of a global class or trait of the same name. @throwswith a fully qualified exception. A@throws \LogicExceptiontag inside a namespace now names the global exception, so acatchblock the call can never reach no longer affects the types of variables after it.- An override that names a different class than its ancestor keeps its own. A
take(Box $b)that names its ownBoxno longer inherits the ancestor's@param Box&Countablefor aBoxin another namespace. - Class names in code no longer fall back to a global class. Inside a namespace, a class named without an import, anywhere in code, now means the namespace's own
Foo, as PHP does, instead of silently reaching a globalFoo. Hover and docblock types such as@varfollow the same rule, even when the namespace has noFoo. - Class names in docblock tags follow the declaring file's imports. A class a function's or method's docblock names, such as an
@phpstan-asserttype or a@templatebound, now means the class its own file imports, wherever it is called from. A declared global class the project does not have is no longer read as an imported class of the same short name. - Class-name parameter defaults called from another namespace. A method such as
make(string $class = Svc::class)that returns the class it is given now resolves to theSvcits own file names when the argument is left out, wherever the call is written. Aself::classorparent::classdefault means the declaring class or its parent, not the class the call is written in. - A
@returnnaming a subclass that shares the native type's short name. A method declared: \ReflectionPropertywith@return ReflectionPropertynaming an imported subclass now returns the subclass, so passing its result where the subclass is expected is no longer reported. - Global classes named inside a namespace with a class of the same name. In a namespace that declares its own
Node, a type hint,instanceof,catchor docblock naming\Nodenow means the global class rather than the namespace's. Completion also stops offering the private members of a same-named class from another namespace. - By-reference parameters of namespaced functions. A variable passed to a by-reference parameter of
App\fill()from insidenamespace Appis no longer reported as undefined when a globalfill()also exists. - Functions called through an imported namespace. With
use Lib\Helpers;, a call such asHelpers\greet()now reachesLib\Helpers\greet()in signature help and the other features that look the function up, instead of being looked for in the current namespace. use functionanduse conststay in their ownnamespaceblock. In a file with severalnamespace { }blocks, an import in one block no longer changes which function or constant the same name means in another.- The same call in two classes or
namespaceblocks of one file. Eachself::make()now returns its own class, and eachmake()orFoo::make()follows its own block's imports, instead of every copy taking the result of the first. Members called on the result are checked against the right class.
Type checking¶
- Generic iterator parameters check their class. Passing an iterator to a parameter typed with a generic iterator interface, such as
RecursiveIterator<int, string>, is now reported when the iterator does not implement that interface. - Methods
__calltakes because the caller cannot see them. A call to a private or protected method from where it is out of reach, on a class with__callor__callStatic, is no longer checked against that method's parameters, since the magic handler takes it. A call that can see the method now has its named arguments checked. - Trait methods imported under another name. A class whose
useblock renames a trait method (isLocal as isSafe) is no longer told it must implement the abstract method that name already implements. #[\AllowDynamicProperties]classes. Reading or writing a property such a class, or a subclass of one, does not declare is no longer reported as unknown.- Arguments to a variadic parameter are type-checked. Each argument collected by a
...$restparameter is now checked against the type the parameter declares, the same as any other argument. Mockery'sMockery::mock(Foo::class, [...])andspy()accept the mocked class's constructor arguments. preg_replace()on a value of unknown type. Passing the result ofpreg_replace(),str_replace()or a related function on an untyped value straight totrim()or another function that takes a string is no longer reported, since the result has whatever shape the value had. Astringsubject still reports thenullthatpreg_replace()returns on a regex error. Contributed by @stubbedev.- Bare
return;with a@return void|…docblock. A function whose docblock return type includesvoid, such as@return void|string, may now return without a value. - Scalar coercion outside
strict_types. In a file withoutdeclare(strict_types=1), aboolpassed to astring,intorfloatparameter, an integer range passed tostring, and any scalar passed toboolare no longer reported, since PHP converts them. The same holds for return values and property assignments. A callback's return value is still checked strictly, because nothing converts it. - Subclasses may initialize a parent's readonly property on PHP 8.4. Assigning an inherited readonly property in a subclass is no longer reported as a write from outside the declaring class when the project targets PHP 8.4 or later, which allows it.
enum-stringandtrait-stringaccept enum and trait names.SomeEnum::classpassed or returned where anenum-stringis declared, andSomeTrait::classwhere atrait-stringis, is no longer reported, while the name of a different kind of class still is.enum-string<SomeEnum>andtrait-string<SomeTrait>check the bound too.newon a class name held in a string is checked.$class = 'Countable'; new $class()now reports the interface, abstract class, trait or enum it would fail to instantiate, and a constructor given the wrong number of arguments, the same as when the class is written out. A leading backslash in the string names the same class.- Property type checks on every write. Assigning a value of the wrong type to a typed property is now reported wherever the write happens, such as
$user->age = 'ten'from outside the class,Config::$timeout = '30', or a static write through a class-string, not only through$thisinside the class. trait-stringandenum-stringparameters are checked. Passing anintor a plainstringto one is now reported.- Existence checks and attributes written in strings. A
function_exists(),class_exists()ormethod_exists()check, or a#[, that appears inside a string or comment no longer silences unknown-function, unknown-class or unknown-member diagnostics. A check in anelseifcondition now covers its branch. - A namespace declared on the
<?phpline.<?php namespace App\Models;is no longer reported as a namespace mismatch, and the fix no longer offers to add a second declaration. - Enum backing types after a comment.
enum Ratio /* exact */ : floatnow reports the invalid backing type. - Functions declared in
elsebranches are checked. A function declared in theelseiforelsebranch of anif, or in anifnested inside another, now gets the same diagnostics as any other function. Before, only the first branch was checked. ?->method calls on anullvalue.$x?->save()where$xis known to benullis no longer reported as a call onnull, the same as$x?->namealready was. Laravel strings passed through?->, such as the ability inauth()->user()?->can('edit-post'), are now checked and navigable like those passed through->.- Functions that read
func_get_args(). Calls such as$query->select('id', 'name')or$request->only('a', 'b')no longer report extra arguments when the method collects its arguments withfunc_get_args(). object|nullreturn types. A call documented as returningobject|nullno longer gets a "could not be resolved" hint on member access, matching a native?object.- A broken chain in one method no longer hides problems in another. When
$x->foo()cannot be checked in one method, the same$x->foo()->bar()in a different method, where$xis a known class, is still checked for a missingbar(). - Writing to a
globalvariable is no longer reported as unused. The same goes for a write through a reference, such as$first = &$items[0]; $first = 5;. - A class with
__toString()is accepted asStringable. Passing one whereStringableorstring|Stringableis expected no longer reports a false type mismatch, whether the method is declared on the class, a parent, or a trait. - Abstract methods a parent gets from a trait. A class extending an abstract class whose trait declares an abstract method is now reported when it does not implement it, and "Implement missing methods" adds a stub for it. The diagnostic also names the interface a method comes from when that interface extends another with the same short name.
- Objects of a missing class are no longer reported as type mismatches. Passing, returning or assigning an object whose class cannot be found, such as one from a package that is not installed, no longer reports a mismatch beside the missing class itself, since whether it extends or implements the expected type cannot be known. A final class or a scalar type is still reported.
- Member chains from
$thisinside traits are checked.$this->manager->missing()in a trait is now reported when the classes using the trait type$manager, the same as it is through a variable. A member read directly on$this,selforstaticis still left to the classes using the trait.
Laravel¶
- Singular relationships can be
null. Reading ahasOne,belongsTo,morphOne, orhasOneThroughrelationship as a property, such as$post->author, now gives?Author, since the related row may not exist. A relationship declared withwithDefault()keeps the plainAuthor. Contributed by @pataar. - Scopes keep custom Eloquent builders. Chaining a local scope preserves the custom builder and its model type, including with ide-helper docblocks, so its methods remain available and valid returns are no longer reported as type mismatches. Contributed by @shuvroroy.
- Route groups in
bootstrap/app.php. Routes registered from thethen:orusing:callback ofwithRouting(), including route files grouped there under a name prefix, are now known by their full names and are no longer reported as unknown routes. - Unsaved edits to included route files. Routes in a file another route file or
bootstrap/app.phploads, or that a service provider registers, are now read from the editor, so a route added there, by hand or with the "Create missing route" quick fix, is known before the file is saved. - Imported
#[Table]and#[Connection]attributes. A model's table and connection attributes are now read when the attribute is imported withuse, not only when written fully qualified, in files open in the editor and inanalyze. Contributed by @shuvroroy. - Nullable columns stay nullable through a cast. A model attribute cast to
boolean,integer, a date, an enum or another cast that handsnullback untouched is now nullable when its column is, and so is a nullableupdated_ator other timestamp column. A null check on a nullable date column, the soft-delete column included, leaves the date class with all its members. - Relations whose model comes from config. A relation that reads its related class from
config(), like therolesandpermissionsrelations of spatie/laravel-permission, now loads the model the config file names instead of the baseModel. analyzereads the database schema. Model columns are typed from the schema dumps and migrations on the command line too, soanalyzeandfixagree with the editor about a column's type.$pivotright after startup. A model reached through a many-to-many relationship no longer misses its$pivotproperty in completion or diagnostics when the editor asks for both at once while the relationship index is still being built.- Comments inside a call no longer stop Laravel name completion. A comment among a call's arguments, such as
whereHasMorph('commentable', ['video', /* note */ '|']), no longer stops route, config, morph alias and other Laravel names from completing, even when it holds a quote or a bracket. selfin a scope called on a query. A scope parameter typedselfnow accepts the model when the scope is called through a query, such asPost::query()->relatedTo($post), instead of reporting that it expects aBuilder.- Config keys with no config file are reported. In a Laravel application,
config('gate.missing')is now reported as an unknown config key when no config file declaresgate, not only when the key is a typo inside a file that exists. Keys under a config file a package registers in a way that can't be read are still left alone. response()with content is a response.response($content)now resolves to aResponseeven when$contentmay benull, so returning it from a method declared to returnResponseis no longer reported. Onlyresponse()with no arguments is the response factory.- Hover on
model-propertyarguments passed by name.where(column: 'email')now hovers as the model property, like the positional form. - Laravel name completion in facade calls. Completion now offers view names, morph aliases, and the other Laravel names in every static call that go-to-definition and diagnostics already recognise, such as
View::first()andResponse::view(). A class that only shares a facade's short name, such asAcme\View, no longer gets them. - Relation callbacks follow their argument types. Closures passed to
whereHas()and similar methods are now typed when the relation is a variable, one of several names, or a relation object. Callbacks fororWhereRelation(),whereDoesntHaveRelation(), andwith('relation', fn)are typed too. Contributed by @shuvroroy. - Relation callbacks keep their full context. Completion, navigation, and diagnostics retain generic model alternatives through custom relationships and eager-loading arrays. Application-defined callback signatures take precedence, and relation query methods work regardless of letter case. Contributed by @shuvroroy.
- Relation callbacks on a relation.
$team->stocks()->whereHas('warehouse', fn ($q) => ...)and->with('warehouse', fn ($r) => ...)now type the closure from the relation's related model instead of a generic builder or relation. - Custom builder methods on relations. Methods of a model's custom Eloquent builder can be called through a relation to that model, and keep the relation as their result when they return the builder, as
Relation::__calldoes at runtime. - Eager relation constraints keep both callback types.
withWhereHas()andwithWhereRelation()now retain the related builder and relation through fluent calls, including dotted paths and explicit union hints. Contributed by @shuvroroy. - Polymorphic relation callbacks know their candidate models. Closures passed to
whereHasMorph()and related methods are now typed from the listed model classes, including their custom builders. Unknown candidates and'*'use the relation's declared model. Contributed by @shuvroroy. - Named relation callbacks keep their model types. Completion and diagnostics now resolve relationship constraints when named arguments are reordered or optional arguments are omitted. Contributed by @shuvroroy.
- Relation callbacks keep custom builders. Constraints on related models now offer their custom builder methods, including through custom-builder query chains and bare
Builderparameter hints. Contributed by @shuvroroy. - Model instance queries keep custom builders. Starting a query with
newQuery(),newModelQuery(), ornewQueryWithoutScopes()now keeps the model's custom builder and its model type through later calls. Contributed by @shuvroroy. groupBy()followed by a callback.$items->groupBy('id')->map(fn ($group) => ...)now gives$groupthe grouped collection's type instead of unevaluated conditional types.- View namespaces registered with
View::addNamespace(). A namespace a service provider adds through theViewfacade or the container's view factory, includingprependNamespace(), now resolves inview('webshop::…')and@include('webshop::…')instead of being reported as an unknown view. - Facade calls keep the concrete method's generics. When a facade's
@methodtag drops the type arguments of the method it forwards to, such asHttp::recorded()returning a bareCollection, the call now takes the concrete method'sCollection<int, array{…}>. when()andunless()callbacks see the value they are called with.$query->when($nullableString, fn (Builder $q, string $value) => …)is no longer reported as a type mismatch, sincewhen()only calls its callback with a truthy value. The$defaultcallback gets the other half and is checked against it, andunless()works the other way round.keyBy()andgroupBy()on an Eloquent collection keep the model type.Member::all()->keyBy('id')now reads as a collection ofMemberinstead ofmixed. This also holds for any generic class that names its parent or interface by a fully qualified name in@extends,@implements, or@use.- Path helpers in service providers. A config file, or a view, translation or route directory, that a service provider names with any of Laravel's path helpers, such as
config_path(), is now found. One named withlang_path()is looked for inresources/langwhen the project still keeps its translations there, as Laravel does. - Config key completion in
Config::string(),integer()andfloat(). The typed getters on theConfigfacade now offer config keys, asConfig::get()andConfig::boolean()already did. - Escaped quotes in
#[Config]and#[RedirectToRoute]keys. A key such as#[Config('app.it\'s')]now namesapp.it's, the way PHP reads it, as aconfig()call already did. #[Scope]applies to its own method only. A method written near a#[Scope]method, or in a model with#[ScopedBy], no longer has itsBuilderparameter read as a builder of that model, so diagnostics agree with hover.- Laravel name completion beyond the first argument. Completion now offers a name wherever the finished call names one: the view in
View::renderWhen($ok, '…')orRoute::view('/about', '…'), the ability in$this->authorizeForUser($user, '…'), the morph types inwhereHasMorph('commentable', ['…']), and every entry of a list such asGate::any([…]). View names are also offered inview()->make('…')and a mailable's$this->view('…'), and route names are no longer offered in$request->route('…'), which reads a route parameter. - Service providers in a
config/app.phpwritten witharray(). Only the classes listed underprovidersare now read as service providers, as they already were for the[…]spelling. - Route files nothing visibly loads. A route file in a subdirectory of
routes/that no route file or service provider loads, as whenweb.phprequires a whole directory throughglob(), now has its routes completed and checked under their own names instead of reported as unknown. - Routes of
laravel-package-toolspackages. Route files a package registers with$package->hasRoutes(), as Filament does, are now read, so their routes complete and are no longer reported as unknown. - Edits to route files outside
routes/. Editing a route file loaded from elsewhere, such as a module's route file that a service provider loads, now updates route completion, diagnostics and go-to-definition right away. - Collection keys and values follow literal property paths.
keyBy(),groupBy(), andpluck()infer their result from the selected properties, including dotted paths and higher-order calls. Nested grouping respectspreserveKeys. Contributed by @shuvroroy. - Computed Eloquent attributes stay out of column suggestions. Read-only accessors and appended values no longer appear as query columns or assignment keys unless another source declares a backing column. Attributes with setters still complete in
create()andfill(), and computed properties remain available on models and in serialization settings. Contributed by @shuvroroy.
Blade templates¶
- Component tags spelled differently from their class.
<livewire:last-24-hours-orders>and<x-forms.datePicker>now navigate and complete and type their attributes like the spelling derived from the class name, since Laravel and Livewire reach the same class from either. - Nested
@includes inherit their includer's data. A partial included without data no longer reports a variable as not passed when the template including it receives that variable from everywhere it is rendered or included, even if that template never declares it. Contributed by @zerone0x. - Blade component props that default to
null. A prop declared as'type' => nullin@propsnow accepts whatever the caller passes, instead of being treated as alwaysnull, which reported everymatcharm on it as unreachable. - Dead branches in Blade templates. A mistake inside a branch the template can never take, such as
@if (false), is no longer reported, and diagnostics in live code are no longer dropped by mistake. - Template variables passed from constants and config values. A namespaced constant, a
config()value or a translation that a controller passes to a Blade view now types the template's variable the same way it is typed in the controller, and so does aconfig()value or a translation that a service provider shares with its templates. - Values passed to Blade templates are checked the way they are where they come from. A value the controller or service provider passing it could echo without being reported, such as a translation whose key is only known at runtime, is no longer reported when the template echoes it.
@componentno longer shares the surrounding template's variables. A variable the including template holds no longer counts as passed to a@componentview, and a name only that view reads is no longer accepted from the template's callers.- Blade
{{!!$flag}}. A double negation written without a space is an escaped echo again, instead of a raw echo that broke the rest of the template. - A Blade component's template sees its class wherever the class lives. The template a class component or Livewire component returns from
render()now has the class's public properties and methods in scope, even when the class sits outsideApp\View\Componentsor the view name doesn't follow Laravel's naming convention. - A component's
render()view is no longer short of$attributes. A template that declares$attributesor$componentNameis no longer reported as missing them when a class component renders it, since Laravel passes them itself. - A variable set for a Blade
@includeis no longer reported as unused. The@includefamily and@extendshand the child template every variable in scope, so a variable only the child reads now counts as used.
Testing¶
$thisin a Pest test is the configured test case. Insideit(),test(),beforeEach(), andafterEach()closures,$thisis now the test case and traits bound to the file withpest()->extends()oruses(), whether in the test directory'sPest.phpor in the test file itself, falling back to PHPUnit'sTestCase. Helpers defined on them now resolve, and so do their return types.- PHPUnit's
assertSame(),assertCount()andassertArrayHasKey()narrow. These and their negated forms now narrow the way the check they stand for does, soself::assertArrayHasKey('id', $row)makes$row['id']no longer possiblynull, andself::assertNotSame(null, $x)removesnullfrom$x. - Guards that end in
$this->fail()inside a Pest test. A guard ending in anevercall on the object a closure is bound to, or on a class named by a variable ($class::fail()), now narrows the code after it, so$xis no longer reported as possiblynullbelowif ($x === null) { $this->fail(); }.
Other frameworks¶
- WordPress core's translation and hook functions. Calls to
__(),add_filter(),home_url()and the other functions WordPress core also declares as no-ops for its script loader now use their real declarations, so they are no longer reported as passing too many arguments, and hover and signature help describe the right function. - Find References in Drupal hook files. Calls in a Drupal site's
.module,.install,.theme,.profile,.incand.enginefiles are now found by Find References and rename, andanalyzechecks those files, without listing the extensions under[indexing] extensions. - WordPress's
__()returns a string. Outside a Laravel project,__()andtrans()keep the return type their own declaration gives, instead of Laravel'sstring|array, so passing a translated string to WordPress functions is no longer reported. - WordPress output constants. In a project with the WordPress stubs installed,
OBJECT,OBJECT_K,ARRAY_AandARRAY_Nare known constants, soget_post($id)is aWP_Post|nullandget_post($id, ARRAY_A)an array, instead of every possible result at once.
Completion, hover, and editor features¶
- Global class member navigation. Following a member of a global class goes to its declaration even when another namespace contains a class with the same short name. Contributed by @shuvroroy.
- Classes that share a short name in one type. Hover, completion, and signature help now show each class by its full name when a type names two classes with the same short name, such as
class-string<\App\C>|class-string<\Other\C>, instead of printing them as one. - Code examples in hover. A multi-line
<code>or<pre>example in a docblock, as in Doctrine's query builder, now shows as a code block instead of running together on one line. - Hover on a
globalstatement's variable. Hovering the variable inglobal $x;now shows the type it imports, instead of nothing. - Escaped dollar signs stay literal during completion. A
\$inside a double-quoted string no longer offers variable names, so string-value suggestions remain available. Contributed by @shuvroroy. - No highlighting flicker while typing. Semantic highlighting, CodeLens, and document highlights no longer blank out or land a few characters away from their symbol when a request arrives before an edit has been parsed. The editor keeps what it shows until the update is ready.
- Class constants beside a same-named property. Go-to-definition and hover on
Config::pathorself::pathnow land on the constant, not on a$pathproperty the class also declares. - Go-to-definition on a class name written in a different case.
new myclass()now jumps toclass MyClass, as PHP treats the two as the same name. - Type hierarchy in editors without dynamic registration. Type hierarchy is now announced at startup to editors that cannot register it later, so they offer it too.
- Deprecated classes are marked in type hierarchy. The deprecation tag on a type hierarchy item is now sent as the list the protocol specifies, so editors that strike through deprecated entries do so.
- Parameter-name hints no longer double up while typing. Editing a call could leave a hint in the wrong place, such as
myFunc(var1: var1: $something), until the file was reopened. - Parameter-name hints no longer blink off while typing. The editor keeps the hints it is showing until the file has been re-read, then refreshes them. Contributed by @SuperFes.
- Same answers in the browser build. Go-to-definition, rename, hover, signature help, and highlights in the WebAssembly build now resolve types as thoroughly as the language server does.
@seelinks in hover. A@seereference now links to the class it names, through the declaring file'suseimports, rather than to another class with the same short name. Go-to-definition and type hierarchy no longer land in the wrong file in the same situation.- Stale diagnostics after a quick edit. An editor that pulls diagnostics no longer occasionally keeps showing the previous set when it asks for them just as a new set finishes.
- Diagnostics catch up after an edit in Neovim and Emacs. Fixing an error, such as closing a class's brace, now clears its diagnostic once the edit has been checked, where these editors used to keep the diagnostics from the edit before. A file opened while the project is still being indexed now shows its diagnostics once indexing finishes, without needing an edit first. Contributed by @stubbedev.
- Completion after an emoji. Member, variable, array-key, class-name and PHPDoc tag completion now work on a line that has an emoji or other character outside the Basic Multilingual Plane before the cursor.
- A call still missing its
). While you type a call or array whose closing bracket is not there yet, the rest of the class or function it is in keeps working: its imports are no longer reported as unused, and its members still complete, hover and resolve. The same goes for a statement being typed at the end of a file, such as the newest route in a routes file, from the moment its(is typed. - Constants in
switchcases. Hover, go-to-definition, find references and rename now work on a constant or class constant written in acaselabel, and an import used only there is no longer reported as unused. - Go-to-definition on
@propertyand@methodmembers. Jumps to the tag in the docblock of the class that declares the member, not to the first tag of that name in the file, and to the key of an Eloquent$castsentry rather than a cast type spelled the same. - Deleted files in workspace diagnostics. A file deleted while workspace diagnostics are on no longer keeps reporting its problems.
- Method names in array callables held in a variable. Completion inside
[$handler, '…']now offers the handler's methods when the variable was assigned the result of a function call. - Hover on inherited members shows the class that declares them. A parent's own method now wins over the same method in a trait it uses, and members from a trait used by a trait or declared only on an interface show where they come from.
parentin namespaced classes. The type hierarchy now opens onparent, and semantic highlighting coloursparentand the members called through it by the parent class.- Completion documentation for classes the file does not import. Selecting a completion for a member of a class the file neither imports nor shares a namespace with now shows the member's documentation.
- Saving a method body refreshes the files whose types depend on it. When another open file's types are worked out from a method's body, such as the element type of a collection the method returns, editing only that body and saving now re-checks that file too.
- Diagnostics appear in editors that do not answer a file-watcher registration. An editor that never replied to the server's request to watch files, such as CodeLite, showed no diagnostics at all. The request is now only sent to editors that support it, and a missing reply no longer holds anything up.
- Named arguments after an array, closure or
matchargument. Named-argument completion now works after an earlier argument such as[1, 2], a closure, or amatchexpression, and commas inside such an argument or a comment no longer move signature help to the next parameter. - Signature help for callables in enum methods. After
$fn = makePen(...);inside an enum method,$fn(now showsmakePen's signature, as it does in classes and traits. - Completion below a
#comment with an apostrophe. A comment such as# Don't call this twiceno longer stops completion in the code that follows it. - Typing in a
namespace { }block. While a call in a bracednamespaceblock is still missing its), or the block its closing}, signature help and completion use the block's own namespace and imports instead of an earlier block's, and the classes and functions it declares stay available to other files. - Completion shows member types next to the name. Method and property suggestions show their return or property type right after the name (e.g.
findOneByEmail($email): ?User) in editors such as PhpStorm and VS Code, where previously only the class name was visible. Contributed by @EranNL. - Progress no longer gets stuck when searches overlap. When the editor sends several Go to Implementation, Find References, or Type Hierarchy requests at once, as an implementation gutter does for the declarations in view, each one's progress now finishes in the editor's task list. Contributed by @lleviathe.
Code actions¶
- "Replace with" no longer leaves a stray parenthesis. Replacing a call to a deprecated function or method now replaces its closing parenthesis too, instead of leaving an extra
)behind. - Filtered code action menus. When the editor asks for one kind of code action, such as only quick fixes or only the organize-imports action run on save, only actions of that kind are returned instead of every action mixed together. Every kind of action PHPantom offers is now listed among the kinds it advertises.
- Generated property hooks follow the file's indentation. "Generate get hook" and "Generate set hook" indent the new hooks by two spaces in a file indented with two spaces, instead of always using four.
@phpstan-ignorereasons with commas. Adding an identifier to an ignore comment, or removing one from it, keeps each reason with its own identifier, even when the reason contains commas or parentheses.- Edits and jumps after non-ASCII text. "Remove assert" and go-to-definition on an object shape key no longer land too far right on a line with non-ASCII characters before them, and go-to-definition on a shape whose keys contain them no longer fails.
- Removing a
returnfrom a bracelessifor loop. The quick fix for a value returned from avoidfunction now puts braces around the kept statement and itsreturn;when thereturnwas the whole body of anif,elseor loop, so the function no longer returns there unconditionally. Inside a loop, thereturn;is also kept when nothing follows the loop. - Inferred
@returnin docblocks that mention "function". "Update docblock" now adds the@returntype inferred from the body when the docblock's summary contains the word "function", and docblock generation infers it for a function whose parameter list runs over several lines, or one documented by a/**the editor has not closed yet. - Line endings of generated code. Imports, generated methods and docblocks, extracted code and other edits now end their lines with
\r\nin a file saved that way, instead of leaving it with mixed line endings. - "Generate promoted constructor" removes property docblocks. The
@vardocblock above each promoted property is now removed with it, instead of being left to document the next member, and properties declared together (private int $a, $b;) no longer make editors reject the action. - "Remove assert" with a parenthesis in a comment. The quick fix is now offered for an
assert()call with a)inside a comment. - A
;in a comment inside a statement. The quick fix that removes a returned value now edits the wholereturnstatement, and the outline covers the whole property or constant declaration, when a comment inside it holds a;. new staticquick fixes edit the right class. The fixes for PHPStan'snew staticerrors no longer act on the wrong class when the word "class" appears in a comment or string inside the method, or when the call sits in a trait.- Files with Windows line endings. In a file saved with
\r\nline endings, PHPStan quick fixes now edit the line they were offered for, and the lines they write into a docblock or method end in\r\nlike the rest of the file. An inline@varannotation applies where it is written instead of in an earlier function. - Removing an unneeded
@phpstan-ignoreon a line with non-ASCII text. When an accented letter or other non-ASCII character comes before the comment, the quick fix now removes exactly the identifier or comment it was offered for instead of garbling the line. - "Add @throws" finds the method it was offered for. The quick fix is now offered when a string earlier in the method holds a
}, adds the tag to the method rather than to a closure inside it, and no longer doubles the indentation when it spreads a one-line docblock over several lines. #comments no longer suggest@throwstags. Athrowinside a# …comment is now ignored by@throwscompletion and docblock generation, the same as one inside a//or/* */comment.- Quick fixes that add a docblock to a method with attributes. The
@throwsand@returnquick fixes now put a new docblock above the method's attributes, where PHPantom reads it, instead of between the attributes and the method. - Removing an unused type from a generic
@return. The quick fix for PHPStan'sreturn.unusedTypenow rewrites a tag such as@return array<int, string>|nullas a whole instead of cutting it at the first space. - Element types for a returned array literal. The quick fix for PHPStan's missing iterable value type now writes
@return array<1|2>for a method that returns[1, 2], instead of nesting the whole literal asarray<array{1, 2}>. - Generated docblocks name the right class. "Update docblock" and docblock generation now write a class the file neither imports nor shares a namespace with fully qualified in
@throwsand inferred@returntags, instead of a short name that reads as a different class. - Convert to instance variable no longer redeclares an inherited property. The action is not offered when a parent class or trait already declares the property.
- Convert to instance variable handles closures and arrow functions. A closure's
use ($x)capture is dropped and its body converted, and arrow-function bodies are converted too. The action is no longer offered when the variable appears in acatch,static, orglobaldeclaration, or is reached by name throughcompact(),extract(), or$$name, where the rewrite would have broken the code. - Code actions work in editors that cannot resolve them lazily. Quick fixes and refactorings such as extract function now apply in clients that do not support
codeAction/resolve. - Refactoring actions wherever the code is written. "Convert to arrow function", "Convert to closure", "Convert to match expression", "Inline variable" and the
??and?->simplifications now also work inelseifandelsebranches,matcharms, and closure bodies. "Convert to closure" captures what a nested closure'suseclause or a spread such as...$itemsreads, and leaves$_GETand the other auto-globals out ofuse, which PHP rejects. - Extracting code with early returns leaves other
returns alone. "Extract method" and "Extract function" rewrite only the selection's own guard returns. Areturninside a closure in the selection, or a string or comment that reads like one, is no longer changed toreturn false;. - Docblock generation after an attribute on the same line. Typing
/**above#[\Override] public function save(array $rows): voidnow generates the method's docblock instead of skipping the line. - PHPStan quick fixes read the code they edit. Removing unreachable code stops at the end of the
switchcase it is in instead of deleting the cases after it, and works in top-level code. Adding or removing#[\Override]and#[\ReturnTypeWillChange]finds the method however its attributes and modifiers are laid out, and an attribute mentioned in a comment no longer counts as written. @throwssuggestions follow the code's types.@throwscompletion, docblock generation and "Update docblock" now pick up the exceptions declared by methods called on a property, on a variable assigned from a factory, or on anything else hover can type. Acatchnow takes exactly what PHP would hand it, subclasses of the class it names included, and athrowinside a closure that is never called no longer counts.@return voidfor functions whose closures return.@return voidis now suggested for an untyped function whose onlyreturnwith a value is inside a closure or a string.- "Replace deprecated call" on names in other scripts. On a call such as
$ユーザー[0]->legacy()the quick fix is now offered, and it replaces the whole call instead of leaving part of the subject's name in front of the replacement. - Return-type quick fixes edit the closure they were offered for. On a PHPStan error inside a closure or arrow function, "Update return type" and the other return-type fixes now change that function's own return type, instead of writing the enclosing method's type onto it and adding a docblock above it. "Remove return statement" also no longer adds a
return;at the end of a method that another method follows.
Imports¶
- Class constants in docblock types name their class. The class in a docblock type such as
@param E::class $sor@return Status::ACTIVEnow counts as a use of its import, so that import is no longer reported as unused or removed, and go-to-definition, hover, and references reach the class. - Docblock annotations name their class. A Doctrine-style annotation such as
@ORM\Entityor@Route("/users"), including one nested in another's arguments, now counts as a use of the import it goes through, so that import is no longer reported as unused or removed by the quick fix andphpantom_lsp fix. Go-to-definition, hover, references, and rename reach the annotation's class. - Imports only fully qualified names refer to.
use DateTime;is now reported as unused when the file only ever writes\DateTime, and the same goes for function and constant imports. @seein a plain comment. A// @see Foo::bar()inside a method body now counts as a use of theFooimport, so it is no longer reported unused or deleted by "Remove unused imports", and go-to-definition, find-references and rename follow it like a docblock@see.- Imports used by an unfinished
::access. An import named only by aMailer::still waiting for its member at the end of the file is no longer reported unused. - Unused imports named only in text. An import whose name appears only in a string, a comment or as a property name is now reported as unused.
- Organize imports on save. "Remove all unused imports" and "Sort use statements" now run through
editor.codeActionsOnSave, and applying both in one go leaves a correctly sorted import block. "Import all missing classes" no longer runs as part of organizing imports, since it may have to pick between candidates. @throwsand function imports land in the namespace block you are in. In a file with severalnamespaceblocks, theuseline added by these completions no longer goes into another block, and in Blade templates it is no longer dropped.- A new import inside a braced
namespace { }block is indented to match the block. Imports added by completion, code actions and class moves no longer land flush left. - Removing two unused members at the end of a group import keeps the statement intact.
use App\Models\{User, Post, Comment};no longer loses its closing};when "Remove all unused imports" orfixdrops the last two members. - Imports and
namespacestatements go ahead of code written on the<?phpline. In a file with nonamespacewhose code starts on the same line as the opening tag, or adeclareafter it, a new import ornamespacestatement is now written right after the tag or thedeclareinstead of on the next line, below the code it was meant to cover. - "Import all missing classes" with the cursor at the start of a name. The bulk import is now offered there too, wherever "Import class" is.
Rename, references, and move¶
- Named arguments in attributes. In
#[Foo(bar: 'hello')], thebar:label is now a reference to the property a promoted$barconstructor parameter declares, so find references, rename, go-to-definition and hover reach it from both sides. moveon Windows. Themovecommand no longer refuses every file as being outside the project on Windows, and a namespace such asTests\Unitis no longer mistaken for the directory of the same name.- Static members reached through a differently cased class name are references. Find References and rename on a static property, method, or constant now include
WIDGET::$countand{@see widget::$count}when the class is declaredWidget, as PHP's case-insensitive class names allow. - A property and a method of the same name are told apart. Find References, rename, document highlight, and the reference count lens on a property like
$emailno longer pick up anemail()method on the same class, and the method's no longer pick up the property. - Renaming one implementation of an interface method no longer breaks the interface. Renaming
greet()on a class that implementsGreetingrenamed only that class and its calls, leaving the interface and the other implementations behind. The editor now refuses the rename before asking for a new name, and points atGreeting::greet(), where renaming it updates every implementation and call. The same goes for a method an abstract parent or trait requires. Contributed by @Deadsquirrel93. - A class constant and a property of the same name are told apart. Find References, rename, document highlight, and the reference count lens on
const pathno longer pick up a$pathorstatic $pathproperty on the same class, and the property's no longer pick up the constant. Contributed by @Deadsquirrel93. - Moving a class out of a braced global
namespace { }block keeps the file valid. The new namespace is written into the block'snamespacekeyword instead of a separatenamespacestatement above it.
Indexing and configuration¶
- Tools installed with the Composer bin plugin. In a project using
bamarni/composer-bin-plugin, classes from the tools undervendor-bin/(PHPUnit'sTestCase, say) resolve again without un-ignoring their vendor directories, and stay out of analysis like any other vendor code. PHPUnit's version is read from there too. [indexing] excludecovers Composer's class lists. A class Composer's classmap or PSR-0 map names no longer resolves from a path you excluded, so excluding a path mid-session and restarting give the same result.- Each Composer project of a workspace sees only its own dependencies. In a monorepo, or a workspace with Composer projects nested below its root, a class that only another project installed or declares is now reported as unknown and no longer completes, and when two projects install different versions of a package, each file resolves the version its own project installed.
- Composer projects in subdirectories resolve their dependencies. A Composer project with its own
vendor/inside a workspace that has a rootcomposer.jsonnow has its installed packages indexed, including ones installed mid-session.analyzeandfixfind the Composer projects of a workspace without a rootcomposer.jsonthe same way the editor does, instead of treating it as plain PHP. - Helper functions behind a
function_exists()check. A function declared insideif (! function_exists(...))in a file that Composer does not autoload directly, such as the Laravel helpers Roots' Acorn loads for Sage themes (app(),config(),public_path()), now resolves instead of being reported as unknown. - Classes in files that are not UTF-8. A class, function or constant declared in a Latin-1 or Windows-1252 file now resolves, instead of showing up in workspace symbols but being reported as unknown wherever it is used.
- Monorepo subprojects are indexed like standalone projects. In a workspace without a root
composer.json, each subproject's local path-repository modules now resolve, its vendor classes rank below project code in completion, and acomposer updatein it is picked up without a restart. - Warnings for files PHPantom could not read. A
composer.jsonwith a syntax error, a.phpantom.tomledit that no longer parses, a broken phar, and a Laravel schema dump or migration that fails to load are now reported in the PHPantom output log instead of being silently skipped. - Non-ASCII variable names before
->can(). Such a variable no longer stops the file from being indexed. - A class declared in more than one file keeps what it inherits. When a second declaration of a class (such as a stand-in defined behind
class_exists()) was read first, members the real class inherits are no longer reported as unknown once its own file is indexed. Contributed by @Deadsquirrel93.
Command line and external tools¶
- Errors in coc.nvim from external tool diagnostics. Diagnostics from PHPStan, PHPCS and PHPMD no longer make clients that validate positions, such as coc.nvim, raise an error on every edit above the reported line. Contributed by @stubbedev.
- Builds without network access keep the PHP standard library. A build that cannot download the PHP stubs now fails instead of producing a binary that reports every built-in function and class as unknown, which is what happened to the Homebrew package. Packagers can supply the stubs with
PHPANTOM_STUBS_DIR(see BUILDING.md), and a binary built without stubs warns about it on startup. - phpcbf fixes against the
[phpcs]standard. Withstandardset in.phpantom.toml, formatting now applies the rules PHPCS reports instead of PHP_CodeSniffer's default standard. - A
[phpcs]standard now selects phpcbf too. A project that setsstandardwithout a ruleset file orrequire-deventry gets its fixes from phpcbf instead of the built-in formatter.
Performance and stability¶
analyzeno longer stalls on large projects. Analyzing a large framework codebase, such aslaravel/frameworkitself, could sit idle for 10 to 30 seconds before reporting anything. It now takes about a second there. Contributed by @stubbedev.analyzereports the same errors on every run of a Laravel project. A file callinguser()on a request or guard could occasionally lose a type error between two runs of the same code. Contributed by @stubbedev.- Classes inside a phar no longer go missing on a busy machine. Classes shipped in a
.phar, such as PHPStan's, could sometimes be reported as not found when the machine was under load. - No more busy core after indexing large legacy scripts. Preparing find-references data in the background could keep one CPU core busy indefinitely on a long file full of methods without return types.
- Find References no longer hangs on constructors or Laravel macros. Finding the references of a
__constructmethod could leave the server unresponsive until it was restarted, and so could finding or renaming a macro while a file that registers macros was being edited. - No more crash on generated files with long operator chains. A file that joins thousands of values with
.,+,&&or a similar operator, as generated code often does, no longer crashes the server while indexing, in plain PHP and framework projects alike, and is analyzed and edited without delay. Expanding the selection from one operand of such a chain now selects the whole chain.
Internal¶
- Tempest performance checks. CI measures template editing, completion, navigation, and memory use against the Tempest playground. Contributed by @shuvroroy.
- Pull request benchmarks no longer fail on a slow runner. Each benchmark runner measures both the PR and its base, so the 30% regression check reflects the change rather than which machine ran it. Contributed by @shuvroroy. Closes #489.
- Faster benchmark checks on pull requests. Latency benchmarks now run split across four runners, and benchmark alerts on fork pull requests show up in the job summary instead of failing on a permission error. Contributed by @shuvroroy.
- A Drupal playground.
examples/drupal/is a Drupal 11 site with one custom module and one theme, for trying PHPantom on Drupal code, with runtime checks of what its comments claim. Contributed by @giuseppe-esposito-87.
0.11.1 - 2026-10-07¶
Added¶
- Laravel translations are understood across locales. JSON and PHP language files under
lang/andresources/lang/share navigation, locale and replacement-key completion, and hover with links to each locale's value. Missing keys offer an insertion quick fix when their PHP group file already exists. Contributed by @shuvroroy. - Code that cannot be reached is dimmed. Statements after a
return,throw,exit,continue,break, or anifwhose every branch leaves the block are greyed out the way an unused import is. Contributed by @petrovo-as.
Changed¶
Performance and memory¶
- Indexing Blade templates with no DocBlock is now much faster. Templates without a DocBlock declaring their variables have those variables inferred from the controllers that render them, and that is now much faster. The work is also spread across every core.
- Faster reference counts and hover in untyped code. Code lenses, hover and diagnostics are faster in projects where untyped methods call other untyped methods.
- Code that calls undefined functions is analyzed much faster. Files full of calls to missing helpers or functions from uninstalled packages no longer take minutes to analyze.
- Files with many diagnostics are reported much faster. Large files that produce thousands of diagnostics no longer spend most of their time locating each one.
- Long scripts are analyzed much faster and in far less memory. A long file of top-level code, such as a legacy procedural script or a generated configuration file, no longer takes minutes and gigabytes of memory to analyze.
- Untyped methods in large classes are inferred much faster. Code that calls methods without a declared return type from a large class, such as a generated one, is no longer slowed down in proportion to the size of the file that declares them.
Fixed¶
- Moving a class is refused when other declarations share its
namespace. In the editor or withphpantom_lsp move, a class that sits beside other classes, functions, or constants under onenamespaceis no longer moved on its own, which put those in the new namespace while every reference to them kept the old one. - Moving a class into the global namespace is refused in a file with several
namespacestatements. In the editor or withphpantom_lsp move, the move no longer deletes the class'snamespaceline, which left the class in another namespace or the file invalid. - Moving a class imports what its own
namespaceblock used. In a file with severalnamespaceblocks, moving a class, in the editor or withphpantom_lsp move, now imports the names its block reached through the old namespace, and no longer imports names another block wrote. - Moving a class changes the right
namespaceblock. When severalnamespaceblocks in one file each declare a class with the same short name, moving one of them, in the editor or withphpantom_lsp move, no longer rewrites another block'snamespace. - A function added by a watched file is found right away. A function declared in a file created or changed on disk no longer keeps being reported as undefined while a diagnostic pass or hover is running.
- Global Laravel translation paths are recognised. Translations registered with
loadTranslationsFrom($path)now support completion, navigation, hover, and key diagnostics, including when the namespace is explicitlynull. Analysis also finds translation files when--project-rootis a relative path. Contributed by @shuvroroy. - Alpine and Vue
:attrbindings in Blade. A:name="…"attribute on a plain HTML tag is no longer parsed as PHP, so it stops producing syntax errors. Only<x-…>component tags evaluate bound attributes. - laravel-ide-helper files are skipped.
_ide_helper.phpand_ide_helper_models.phpare no longer indexed, since PHPantom resolves facades and models natively and their stand-in classes only competed with the real ones. List them with a leading!in[indexing] excludeto index them anyway. - Invoking a property's closure is no longer checked against a same-named method.
($this->onClose)()is checked against the closure the property holds, not against anonClose()method. Contributed by @phcorp. Closes #463. - PHP_CodeSniffer only runs on projects that use it. A
vendor/bin/phpcsinstalled by some other package no longer produces coding-standard warnings. PHPCS diagnostics now needsquizlabs/php_codesnifferinrequire-dev, a PHPCS ruleset file, or a[phpcs] standardin.phpantom.toml. - Import edits and unused-import hints respect each
namespaceblock. In a file with severalnamespaceblocks, an import in one block no longer hides the "Import class" action in another, and an import only another block uses is now dimmed as unused. New imports from code actions, completion, PHPStan quick-fixes and class moves go into the block that needs them, and renaming or moving a class updates each block's own import. analyzereports the same Blade diagnostics on every run. In Laravel projects, the diagnostics reported for Blade templates no longer vary between runs, and they now match what the editor shows.- Blade only recognizes the directives your Laravel version has. A directive newer than the installed Laravel is plain text, the way Blade itself treats it. A
"@context"key in a JSON-LD block no longer produces a cascade of syntax errors on Laravel versions before 11. - A container binding removed from a service provider stops resolving. Deleting the last
$this->app->bind(...)from your providers no longer leaves the old key resolving to its class until restart. - Member actions appear when the selection starts in the indentation. Getter/setter, property hooks, visibility and other actions on a property or method are now offered with the cursor at column 0, on a whole-line selection, or when the selection begins on the line above.
- A
match (true)arm knows the arms above it did not match.match (true) { $name === null => 'none', default => strtoupper($name) }no longer reports$nameas possiblynullin thedefaultarm. Hover, completion, and the value of thematchsee the same narrowing, whereverdefaultis written. Contributed by @phcorp. - Imports of non-ASCII class names no longer break a file. An import such as
use App\Models\Øl;no longer stops the file's diagnostics and code actions. - Files outside the project no longer break indexing. A PHP file opened from elsewhere, or a file change in another folder of the editor's workspace, no longer stops the server when the configuration changes or drops the other file changes reported with it.
- Blade
@breakand@continuekeep their condition.@break($done)and@continue($skip)in a loop now only leave the iteration when the condition holds, instead of being read as an unconditional jump. - An integer
range()passed straight into a call is a list of integers.array_map(fn (int $i) => …, range(0, $n - 1))no longer reports that the callback is passedint|float. Contributed by @phcorp. - Type checks narrow properties the way they narrow variables.
if (\is_resource($this->stream)) { fclose($this->stream); }on aresource|nullproperty no longer reports "expects resource, got resource|null". Every type-check function now narrows a property, with or without a leading backslash. Contributed by @phcorp. \extract()and\compact()are recognised with a leading backslash. Variables they define or read are no longer reported as undefined or unused.- A Blade template's first import no longer breaks the view. When a template's first line opens a block, such as
@ifor a component tag, completing a class adds its@useabove that line instead of inside the block, where the view would no longer compile. A template that opens with@phpgets the import as ausestatement inside that block. - Unused
@useimports in Blade templates are dimmed. A@usedirective that nothing in the template uses is now shown as unused, the way an unused PHP import is, andphpantom_lsp fixremoves it. - A
@usegroup import wrapped over several lines no longer shifts a Blade template. Hover, diagnostics and go-to-definition no longer land on the wrong line for the rest of a template that wraps a@use('App\Models\{...}')list over several lines. - An unsealed array shape is held to the entries it lists. A parameter or return type such as
array{foo: int, ...}orlist{string, int, ...}no longer accepts any non-empty array: an argument that leaves outfooor gives an entry the wrong type is reported, and so is an extra entry that does not fit the...<K, V>tail. - An unsealed array shape passed to a typed array is held to the entries it lists. A value typed
array{foo: string, ...}is no longer accepted wherearray<string, int>is expected: the entries it lists, and what its...tail holds, have to fit the parameter's key and value types. - A shape keyed by a class constant is no longer reported against a typed array. A docblock type such as
array{Slots::FIRST: string}passed wherearray<int, string>is expected no longer reports that its key is a string. - Type checks narrow in any letter case.
Is_String($x)andIS_RESOURCE($this->stream)now narrow exactly asis_string()andis_resource()do, since PHP function names are case-insensitive. - Comparing an array to an array literal narrows it. After
if ($arr === [null]) { return; }, anarray{?string}is known to hold astring, so passing it where alist{string}is expected is no longer reported. Inside theif, the array is the literal'sarray{null}. matcharms narrow the way the equivalentifdoes. An arm with several conditions sees what any one of them proves, not what all of them would together. An&&in amatch (true)arm condition narrows the operands after it, and amatchpassed straight into a call narrows its arms the same as one assigned to a variable first.- A ternary or
matchto the right of&&or||knows what the left side proved.$x !== null && ($x->ready ? process($x) : null)no longer reports$xas possiblynullinside the ternary. - Hovering a Blade component tag's name or a directive's keyword shows nothing unrelated. On
<x-panel :author="$post->author">or@if($cond), hovering the tag name or@ifno longer describes code the template never wrote or the expression after it. - Hovering a raw Blade echo's
{!!or!!}describes the echo. On{!!$html!!}, hovering either delimiter no longer shows the hover of$html, and go-to-definition on it no longer jumps to the variable. The hover now says the output is not escaped. - Config keys a package sets from its service provider are known.
auth('sanctum')is no longer reported as an unknown guard, and neither is any other key a package's provider sets withconfig([...])orConfig::set()instead of shipping it in a config file. in_array()only narrows by what the list proves. Whenin_array($x, $list, true)is false for alist<string>orlist<User>,$xcan still be a string or aUser, since the list may not hold that one, and when it is true for a list ofmixedvalues,$xkeeps its classes. A literal list such as[null, '']narrows both ways, now also when it is stored in a variable first.- A raw Blade echo written inside literal braces is read as a raw echo. In
{{!!$html!!}}, the braces around the echo are plain text, so hovering one no longer showse()or leads to its declaration, and the echo's own{!!and!!}are described and coloured as a raw echo's. - An import added to a
namespacewritten on one line goes inside it. Ausefrom a code action, completion, or class move is no longer written after the closing}ofnamespace B { class Foo {} }, outside the block, where PHP refuses the file. Anamespacewhose{is on the next line no longer gets theusebetween its name and the brace. - A caller's imports no longer change the types of a function it calls. Calling a global
function is_enrolled(context $context)from a file that imports or declares its owncontextclass no longer reports a valid\contextargument as the wrong type, and passing the file's owncontextthere is now reported. Contributed by @arcticfulmar. - An integer
range()passed straight into a call is a list of integers.array_map(fn (int $i) => …, range(0, $n - 1))no longer reports that the callback is passedint|float. Contributed by @phcorp. Closes #467. - Callbacks returning arrays keep their PHPDoc return type. A parameter such as
(callable(string): string[])|nullnow accepts an array-returning closure without a false type mismatch, including Symfony Console's autocompleter callback. Contributed by @shuvroroy. Closes #456. - A closure created in a narrowed ternary,
&&,||ormatchbranch sees the narrowed variable.$c ? fn () => $this->take($c) : nullno longer reports$cas nullable inside the closure. Contributed by @phcorp. Closes #459. - A closure capturing a variable by reference sees later reassignments. Inside
function () use (&$c) { … },$cnow also has the types the code after the closure assigns to it, so a$c = nullthat follows the closure is no longer missed.
0.11.0 - 2026-10-05¶
Added¶
Command line¶
phpantom_lsp format. Formats every PHP file and Blade template in a project using the same formatter the editor runs on save: the project's Laravel Pint, php-cs-fixer, or PHP_CodeSniffer if it uses one, and the built-in formatter otherwise.--checklists unformatted files and exits non-zero without changing anything, so CI can enforce formatting. Paths can be named to limit the run, and--format githuband--format jsonare supported.phpantom_lsp move. Moves a class or a whole namespace and updates declarations, imports, references, and PSR-4 paths across the project. Both sides can be class names or PSR-4 paths, and--dry-runchecks a move without writing anything. Moves that would overwrite an existing class, or that target a Composer-installed class, are refused. Mentions the move cannot rewrite (in Blade templates, YAML, baselines, or path strings) are listed with file and line. Supportstable,json, andgithuboutput. Contributed by @calebdw.analyzeaccepts multiple paths.phpantom_lsp analyze app/ lib/Helper.php tests/checks everything named, so a pre-commit hook or CI step can pass only the changed files.phpantom_lsp initasks what to set. On an interactive terminal,init(andinit --global) asks about the most commonly changed settings and writes only the answers that differ from the defaults.--yesor piped input skips the questions.
Editing and navigation¶
- Call hierarchy. See which functions and methods call a given one, and what it calls in turn. Call sites are grouped by the function containing them, and callees resolve across files, including the constructor a
newruns. Contributed by @sidux. - Reference CodeLens. A clickable reference count above classes, functions, methods, properties, and constants opens the Find References list. It replaces the read-only count at the end of the line. Counts are computed in the background, update only what an edit could have changed, and keep their line while loading so the file does not jump around. Contributed by @sidux.
- Implementation CodeLens. Interfaces, abstract classes, and their methods show a clickable implementation count. Contributed by @sidux.
- Convert qualified names to imports. A code action adds the matching
use,use function, oruse constand shortens every matching name in the file, adding an alias if the short name is already taken. A second action imports everything from a whole namespace at once. Contributed by @calebdw. - Navigate to PHP classes from YAML and XML. Ctrl+Click a fully-qualified class name or
Class::memberin any YAML or XML file to open it. These also count in Find References and CodeLens. Contributed by @sidux. - PHPUnit data providers and dependencies are navigable. Ctrl+Click the method named in
#[DataProvider],#[DataProviderExternal],#[Depends],@dataProvider, or@dependsto jump to it. Renaming the method updates these references, and a name that matches no method is reported.
Diagnostics¶
- PHPMD support. Projects using PHP Mess Detector 3 see its findings in the editor on save, or across the project when workspace diagnostics are on. The project's PHPMD config and
vendor/bin/phpmdare found automatically, and each finding links to the rule's documentation. Configure or disable it with[phpmd]in.phpantom.toml. - Nullable argument mismatches can be warnings. With
[diagnostics] downgrade-nullable-argument-mismatch = true, an argument that only fails its parameter type because it might benullis reported as a warning instead of an error. Off by default. Contributed by @iz-ahmad.
Blade templates¶
- Blade formatting. Formatting a
.blade.phpfile fixes its indentation, following directives, HTML and component tags, and attribute lists, without changing line contents.<script>,<style>,<pre>,<textarea>,@php,@verbatim, andblade-formatter-disableregions keep their layout, and templates where indentation is part of the output (Envoy, Markdown mail) are left alone. Projects that format Blade with Pint keep using Pint. Setblade-php = trueunder[formatting]to also format the PHP inside templates and normalise Blade spacing (@if($a&&$b)becomes@if ($a && $b)). - Document outline. The outline, breadcrumbs, and go-to-symbol show a template's sections, stacks, and components, nested the way the template is, and jump to the right place in the template.
- Folding ranges. Blade block directives, component tags, and the PHP inside a template fold on the correct lines.
- Custom directives. Directives a project registers with
Blade::directive()orBlade::if()are completed, and the PHP passed to them is type-checked like any built-in directive. - "Create missing view" quick fix. A
view('name')call naming a template that does not exist offers to create it where Laravel will look for it, including a package's own view directory. - Unbalanced component tags are reported. An unclosed
<x-alert>, a mismatched closing tag, or a stray closing tag is flagged, including<livewire:…>tags. - Named slots belong to the component.
<x-slot:title>now defines$titleas aComponentSlotinside the component's template rather than in the caller's. - Attribute completion for components without
@props. An anonymous component that reads variables like$titlewithout declaring them now offers those variables as attributes. Templates with@props()keep their declared list, with any undeclared reads added after it.
Laravel¶
- Model PHPDoc types resolve to real Eloquent classes.
builder-of<Model>,collection-of<Model>,factory-of<Model>, andrelation-of<Model, 'relation'>resolve to the builder, collection, factory, or relation the model actually uses, including custom ones. Dotted paths such asrelation-of<User, 'posts.comments'>follow relations, unions are supported, and anything unresolvable falls back to the framework's base class. Contributed by @calebdw. - Model operators work inside
Closure(…)parameter types. A parameter likeClosure(builder-of<static>): mixednow types the closure's argument, so the closure body gets completion, hover, and navigation. Contributed by @calebdw. view-stringparameters. A parameter typedview-stringcompletes template names, and a literal that names no template is reported as an unknown view. Variables, concatenations, and unregistered package namespaces are not flagged. Contributed by @calebdw.- Storage disk names. Disk names passed to
Storage::disk(),fake(),persistentFake(),forgetDisk(), and#[Storage]complete fromconfig/filesystems.php, with hover, go-to-definition, Find References, and typo diagnostics where Laravel requires a configured disk. Contributed by @shuvroroy. - More configured service names. Names passed to framework facades, container attributes, and auth middleware get the same completion, hover, navigation, references, and diagnostics from their config files.
Log::stack()channel arrays are understood too. Contributed by @shuvroroy. - UUID and ULID keys are strings. Models using
HasUuidsorHasUlids, directly or through a parent or trait, type their primary key asstring. Contributed by @shuvroroy. - Custom pivot accessors. A relationship renamed with
->as('participation')exposes$participationinstead of$pivot, keeping the configured pivot model. Contributed by @shuvroroy (#381).
Configuration and indexing¶
- Exclude paths and add PHP extensions.
[indexing] excludein.phpantom.tomltakes gitignore-style patterns to skip during indexing andanalyze, and[indexing] extensionsadds file types to treat as PHP (e.g.["module", "inc", "theme"]for Drupal). Open files are always served. Contributed by @syntlyx. - Editor file settings reach the index. The
[indexing]lists can also come from the editor. VS Code and Cursor sendfiles.excludeandfiles.associationsautomatically, and other editors can pass them as initialization options (see Editor Setup). Editor and project settings are combined, and changes from either apply mid-session without a restart. - Symlinked directories are indexed. Code linked into the project from elsewhere resolves like any other project code, and paths keep their symlinked spelling. Contributed by @liudashuang.
Tooling and platform¶
- Semantic export library feature. The optional
semantic-exportfeature lets other tools pass in PHP documents and get back declarations, references, calls, and diagnostics without running an LSP. A separateoffline-stubsfeature prevents build-time stub downloads. Contributed by @aaaaaandrew.
Changed¶
Behaviour¶
- Extract interface is only offered to editors that can create files. Editors that do not support creating files no longer see an action they cannot apply.
- Updated the bundled mago toolchain to 1.47.5. Contributed by @nguyentranchung.
Performance and memory¶
- Find References and reference CodeLens are much faster. Searches now run in parallel, skip files whose calls clearly target a different class (such as
$this->save()orInvoice::save()), and only type-check the function bodies that contain the accesses being searched for. Results are kept and reused by later searches, including searches for other names. On a large Laravel app, opening 250 classes in turn went from 3.0 to 1.7 seconds of searching. - Repeated reference searches no longer re-read files. Positions are stored with each result, so a second search for the same declaration takes milliseconds instead of seconds.
- Editing a signature no longer throws away all reference results. Only files that depended on the changed class or function are re-checked. Previously one edit made the next search start from scratch (about 120 CPU-seconds on a large Laravel app).
- Reference searches reuse resolved classes. Searches used to rebuild the same Laravel models over and over (one model 767 times in a single search). Opening a class with 26 members went from 1.2 to 0.4 seconds. Go-to-definition, hover, signature help, rename, and code actions now share the same cache.
- Faster hover and completion in long functions. Functions with many local variables and calls no longer slow down every request: hovering 315 expressions in one file went from 4.3 to 0.8 seconds.
- Faster analysis of large files. Looking up
/** @var */annotations no longer scans back to the top of the file. Analysing php-parser's generatedPhp7.phpwent from 2.1 to 0.7 seconds. - Faster workspace symbol search. Files are only read when they contain a match, instead of every file on every keystroke.
- Faster edits. Editing a file no longer scans the inheritance of the whole workspace.
- Less copying of Laravel config data.
config()lookups and config, view, and translation key checks share data instead of copying it. - Faster interface member lookup. Searching an interface chain for a member no longer visits each parent twice per level.
Fixed¶
Type inference¶
- Constants defined from other constants have a type. A namespaced
const TWO = ONE * 2;, and class constants that divide, concatenate, or spread other constants, now resolve.self::ONE / self::THREEis afloat(or the exact integer when it divides evenly), and[...parent::KEYS, 'c' => 'c']is the full array shape. - Constants built from enum cases resolve.
const DEFAULT = Suit::Hearts;holds the enum, including on the enum itself or when typedstatic.Suit::Hearts->valueand->namegive the literal behind the case. - Expressions over known values resolve to the exact value.
'1' . 'a'is'1a',(int) '1'is1,"$id"is'42'when$idholds42, and arithmetic,%,~,<=>, unary signs, and casts on literal operands fold to what PHP computes (including inexact float results). A numeric string counts as its number ('1' + 1is2),PHP_INT_MINhas its value, a comparison of two known numbers istrueorfalse, and adding two untyped values givesarray|int|floatrather thanmixed. - Magic constants resolve to their value.
__LINE__,__NAMESPACE__,__FUNCTION__,__METHOD__, and__TRAIT__give what PHP substitutes, naming{closure}inside a closure. Inside a property hook,__FUNCTION__/__METHOD__give the hook's name ('$name::get') and__PROPERTY__the property's name. - PHP version constants follow the configured PHP version.
PHP_MAJOR_VERSIONandPHP_MINOR_VERSIONno longer show the stubs' values, and the patch-dependent constants are typed without claiming a value. $value::classand$value::CONSTresolve.$foo::classisclass-string<Foo>, and$pen::LIMITreads the constant from the value's class.isset()andempty()are booleans when used as a value.- A variable assigned from a
voidcall isnull, notvoid. ??on a never-assigned or always-nullleft side no longer widens tomixed.$x = $a ?? 1;with$anever assigned is1.- Assignments used as values resolve everywhere.
$x = ($y = 1), an assignment inside a??chain, amatcharm, a ternary branch, a constructor argument, or as a call receiver (($cache[$key] ??= $this->compute($key))->isValid()) now gives both the target and the surrounding expression the assigned type.??=in a condition also leaves its target non-null in the branch. ??=leaves a value behind and makes its target non-null.$this->regexp ??= $this->generate();no longer leaves the property nullable, and$x = $cache[$key] ??= expensive();gives$xa type.- A reference assignment used as a value reads as its target.
($a =& $var) ?? 'hello'leaves$aas$var's type. - An assignment whose right side cannot be typed forgets the old type.
$acc = $acc->merge($x)no longer keeps the variable's previousnull, which caused false "method call on null" reports in loops. - By-reference parameters read back correctly after a call. The caller's variable now takes what the callee writes on every path, including paths that return early (
4|5rather than4), with a declared nullable type kept only where some path does not write. This works for functions, methods, static calls, constructors, andself::/static::/parent::/new selfcalls. What the variable held before the call is no longer checked against the parameter type, and unpacking an array into a by-reference variadic keeps it an array. - Same-named functions in different namespaces no longer share by-reference results.
A\fill($x)could report whatB\fill()writes. - Files with several
namespaceblocks resolve names per block. Class names,useimports,self/static,key-of<A::FOO>operands, and by-reference results now resolve against the block they appear in rather than the first block or another block's imports. This fixes false type mismatches, wrong members and hover, missed "unknown class" reports, and empty Find References. A comment directly above anamespaceno longer hides it. - Class names resolve the way PHP resolves them. Inside
namespace App\Models,Event::classnames the sibling model rather than a loaded globalEvent.new self(...)in a namespacedErrororExceptionbuilds that class, not the built-in. A namespacedException extends \Exceptionkeeps its inherited members even in files that import it. newof an unloadable class keeps its type, andnew parent(...)resolves to the class being extended.- A static call on an object resolves through its class.
$foo::doStaticFoo()and$this->prop::doStaticFoo()resolve like the matching->call, including on unions, intersections, and properties holding aclass-string. - Calls on intersections keep every part. A method both members of
A&Bdeclare returns the intersection of their return types, and a@return staticcall onScope&Invoker&Emitterkeeps all three. - Override return types are respected. An override's narrower return type is no longer replaced by an interface's
: selfhigher up, and a method declared: neverstaysneverwhen it overrides an interface method. selfandstaticmembers resolve against the right class. A property typedstaticresolves to the class it is read from, a member typed?selfresolves against the class it is read off rather than the calling code's class, andself::$items[$key]is treated as an element of the static property.$thisin a trait. A trait with@phpstan-require-extends/-implementssees the required class's properties, andreturn $thisin a trait method is checked against what the classes using it have in common rather than the trait itself.- An untyped property assigned an array literal is an
array. - A nullsafe access on a nullable value can be
null.$e?->getMessage()on?Exceptionisstring|null, as is every link after it in a chain. A check likeif (!$tier?->journey instanceof Journey) { return; }proves$tiernon-null afterwards. - Variable types follow control flow more accurately. A
catchsees what thetrybody assigned,finallysees every path throughtryandcatch, acatchthetrybody provably cannot reach no longer leaks its assignments, aswitcharm that exits no longer contributes,continueinsideswitchacts asbreak, and aforloop known to run is no longer joined with the pre-loop value. - Loops settle on the right types. A read in nested loops sees the settled loop types, a
forcounter isintin the body (also in Blade@for), aforeachover a known-empty array no longer checks its body with a stale loop variable, and a loop inside a provably dead guard keeps its own assignments. - The seed-or-merge accumulator idiom keeps its type.
$acc = null;followed by a loop that seeds$acconce and merges into it afterwards no longer loses the type at the merge. - A
static $var;local carries values from earlier calls. It is typed from its initialiser plus every assignment in the body. extract()defines the right variables. Shape keys become variables with their value types (optional keys widen), unions of shapes write every key, theEXTR_*flags and prefixes are honoured, and an array of unknown keys makes the affected localsmixed.- Values that are genuinely open are
mixed.mixedbeside a class in a union no longer absorbs the class at a later join,int|floatno longer collapses tofloator duplicates members across branches, and(A&I)|Asimplifies toA. - A call whose argument can never be reached is
never. - A
@return mixedbody with disagreeing returns keepsmixed. A body whose returns all agree still narrows the declaration. - Standard-library return types follow the arguments.
var_export($v, true),mb_internal_encoding(),version_compare(), andsscanf()return only the form the call selects.range(1, 10)is a list ofint, a seededarray_reduce()is nevernull,pow()only includesobjectfor an operand that is one, andini_get()on a core directive is notfalse. - String builtins handed literals return literals.
strtolower()and the other case-changing, trimming, and repeating functions compute their result per literal alternative. Values from platform constants likePHP_OSare left alone. get_class()andReflectionClass::getInterfaceNames()return class names.func_get_args()is alist<mixed>, and(bool) preg_match(…)narrows the matches array.new ReflectionProperty(Foo::class, 'bar')remembers what it reflects, likegetProperty()already did.- DOM stubs.
DOMElement::$attributesis never null (hasAttributes()proves it onDOMNode), andDOMNamedNodeMap::item()returnsDOMAttr|null. - Casting a non-empty array to
objectkeepsstdClass.(object) ['foo' => 1]isobject{foo: int}&stdClass. - Project files that redeclare PHP builtins no longer override them. Signature-reference packages such as
phpstan/php-8-stubsused to replace the built-in signatures and lose precision (for examplearray_keys()key types). - A class named
ScalarorNumericis a class. Only the lowercase spellings are PHPDoc pseudo-types, soPhpParser\Node\Scalarresolves. - Two anonymous classes at the same position in different files no longer share one resolution. Laravel migrations, which all open
new class extends Migration {at the same offset, now each describe themselves. - Binding a template from
$map[']']keeps its type.
Closures and callables¶
- First-class callables resolve.
$test->$name(...),Test::$name(...), and$invokable(...)return the right type, and$closure(...)has the wrapped closure's signature. - Calling a closure or callable held in a variable resolves.
$c(),[$this, 'doFoo'](),($this->factory)()on acallable(): Scopeproperty, a closure returned by another closure ($a()()), and a closure declared: staticall return the right type.(fn () => $this)->call($obj)binds$thisto$obj. - A closure's return type comes from its body. A narrower body wins over the declared hint (
Box<stdClass>overBox,class-stringoverstring), and an untypedfn ($b) => $breceives the element type the call hands it. - Closure parameters are inferred from context.
usort/uasort/uksortcallbacks get the element (or key) type, a@phpstan-typealias for acallable/Closuretypes the closure passed to it (including aliases on traits and parents),callable(static)binds to the receiver's class, and a docblock above the statement a closure is assigned in (or inline between=andfunction) types its parameters. - Closure parameters are typed like function parameters. A variadic is
array<int|string, T>rather than a list, an untyped one isarray<int|string, mixed>, and anulldefault acceptsnullhowever it is capitalised. $thisinside a@param-closure-thisclosure is the bound object for diagnostics too, not only for completion.- Variables assigned inside arrow functions have a type, and an arrow function passed to
Closure::call()reads the bound$this. - Variables inside an immediately invoked closure resolve for hover, completion, and the other position-based features.
- By-reference captures behave like PHP. A closure capturing itself by reference sees the closure, not
null.use (&$x)on an undefined variable makes itnulland is no longer reported as undefined. Reads inside and after the closure see every value the closure assigns, including assignments on early-return paths and inside closures passed to a constructor. - Closures in an immediately indexed array literal keep their parameter types.
['isNull' => static fn (Type $t) => …][$name]. - A self-referencing first-class callable no longer crashes the server.
$callback = $callback(...)(found inleague/csv) used to recurse until the process aborted.
PHPDoc¶
- Type aliases work outside the file that declares them. Members typed with a
@phpstan-type/@psalm-typealias resolve wherever the class is used, including imported, inherited, and trait-provided aliases, and hover shows the aliased type. Imported aliases built from other aliases expand fully (cycles stop atmixed), parameters typed with an alias narrow correctly, and iterating an aliased array keeps its key type. - Class names in
@phpstan-typeand@phpstan-import-typeare references. They are now highlighted, navigable, found by Find References, and updated by rename. - Inline
@varannotations are read more completely.@phpstan-varand@psalm-varare honoured (and win over@var),@varabove an array-element assignment applies ($GLOBALS['x']), stacked docblocks all apply,@varaboveglobalonly types the imported variable, an inline@vardescribes the variable after the assignment rather than its right-hand side, and short class names resolve from the current namespace first (solist<Error>means the localError). - Vendor-prefixed tags win wherever they appear.
@phpstan-method/@psalm-methodbeat@method, and@psalm-param/@phpstan-paramtype the parameter inside the function body. @param-outis read, including conditional@param-outtypes.@paramhandling in methods. Unnamed@paramtags match by position and their descriptions appear in hover. A union continued on the next line keeps its full type. A trait method inherits the@paramof the interface method it implements.- Docblock types combine correctly with native types.
@param array<int, string>onarray|falsekeeps thefalse,@return neveris honoured, and a@returntag no longer adds a value the native return type rules out (such asfalseon a method declared: DateTimeImmutable). selfin a docblock names the class that wrote it. This covers inherited@var string|selfproperties,object{foo: self}, andlist<self>, and a parameter typedselfhovers as the class name.@mixinon a trait applies to the classes using it, withstaticin its type arguments bound to the receiving class.key-of<…>reads more.key-of<array<V>>andkey-of<V[]>areint|string, method@return key-of<self::TABLE>resolves at the call site, list constants contribute integer keys, numeric keys areint, andkey-of<A|B>covers both.- Duplicate shape keys are one key.
array{a?: string, b?: string, a?: string}listsaonce. - A PHPDoc type that does not parse is ignored instead of being shown as the type.
Generics and templates¶
- More templates bind from the call. Templates now bind from omitted arguments with defaults, promoted
@var Tproperties, array literals passed to a constructor, objects built inline in a chain ((new Proxy(new Engine()))->), templates reached through another template's bound, aclass-stringargument's@extends/@implements, an argument's own ancestors (IntTypeimplementingType<int>), and every argument that names a template (new Pair(new Cat(), new Dog())isPair<Cat|Dog>).new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir))yields what it really yields. - Templates keep literals where they should.
id('hello')is'hello', a bounded template on a native hint binds the literal passed, array literal elements all contribute (1|2), and an empty literal bindsnever. Objects built withnewstill generalise unless the bound is a scalar. - Bounded templates behave correctly. Inside its function a bounded template stays
Tfor hover and when passed on, while its bound still supplies members. An argument outside the bound falls back to the bound, and inherited bounds follow@extendsarguments. - Template defaults apply.
@template U = stringfills in arguments an@extendsleaves out, unbound method templates use their default rather than their bound, a default can name another template (including a class template), and declared generic types spell out defaulted arguments (Test<false, true>). - A
nulldefault no longer makes a template parameter nullable. - A method template with the same name as a class template binds from the call.
$reflection->getAttributes(Ref::class)isReflectionAttribute<Ref>. - Callables and closures bind templates. A callable held in a variable binds the templates its return type names, a closure's parameter is typed from the generic the call binds (including through fluent chains), and a call argument the text-based resolver cannot read (
array_keys($a + $b)) still binds. - Templates from arrays.
@param array<T, mixed>handedFoo[]bindsint|string, and empty arrays bindnever. - Inheritance carries generics.
parent::method()in a subclass ofFoo<Dog>returnsDog, a generic trait used by another generic trait receives its arguments, an override without a docblock keeps the parent's method templates, andstaticinside a generic collapses to the named class on aFoo::access. - A new object stored in a generic property takes the property's type arguments.
- Iterable generics. A single type argument to
Iterator,Traversable,IteratorAggregate, orGeneratornames the value,foreachover an object that names only a value givesmixedkeys,SplObjectStorage<Order, int>no longer swaps keys and values, andnew ArrayIterator($items)keepsint|stringkeys. - More conditional return types are decided. Literal subjects, constant comparisons (
$flag is PREG_SPLIT_NO_EMPTY), conditions inside generics, offsets of templates (T[0] is string),$thisagainst the receiver's template arguments,is non-empty-array, overrides that rename parameters, andis true/is falseon non-boolean arguments now pick the right branch. A condition on an undeclared name gives both branches, aneverbranch staysnever, and an intersection branch (T&MockInterface) is no longer turned into a union. - Offset access types are evaluated.
@return Bob[TKey]on a type alias andData[value-of<T>]through an enum case give the selected entry. - Assertions on generic types keep their arguments.
@phpstan-assert-if-true Ok<TOk> $thisgivesOk<int>, and an assertion written against an interface's template narrows to the implementation's binding. - Template names are not mistaken for classes. A return typed
T1is checked against the template's bound rather than a class namedT1, and hover and go-to-definition onTin@param Treach the template declaration.
Arrays¶
- Array shapes survive spreads and writes. Spreads follow PHP 8.1 rules (string keys overwrite, integer keys renumber), entries written beside a spread keep their own types (
array{admin: AdminUser, ...<int, User>}, also spellable in PHPDoc), literal and known-variable keys build shapes, and loops writing a list of known keys givearray{a: true, b: true}(optional when the write can be skipped).Foo::classkeys name the entry, including in class constants (const MAP = [Foo::class => 'x']), and writing through aclass-stringkey keepsclass-stringkeys. - Writes keep the shape. Writing to an integer key, a new offset, a nested offset, a union of shapes, a property's array offset, or through
ArrayAccessnow updates the right entry. Compound assignments (+=,%=) update the element, overwriting a key keeps its position, and literal values are kept outside loops ($data['status'] = 'draft'). Reads of an offset see writes made below it. - Appends outside a loop keep exact values.
$a = []; $a[] = 'one';isarray{'one'}.array_push()andarray_unshift()update the array like an append, and appending toarray<int, T>no longer claims a list. - Lists stay lists. Writing back through a
foreachkey keeps a list,unset($list[$k])makes itarray<int, …>, a plainarray<int>is no longer treated as alistor non-empty, and the key of aforeachover a list isint<0, max>(as arearray_keys()andarray_search()on a list). - Loops build arrays correctly. A
foreachthat rewrites every element no longer keeps the pre-loop shape, a value written under a dynamic key keeps its literal type across iterations, tuples written in one loop and destructured in another keep their element types, a by-referenceforeachupdates the array it walks, and writing through a key of unknown type no longer produces strictint|stringkeys. - Joins and unions of arrays are cleaner. Joined array types drop alternatives a sibling covers, and a union of shapes folds when one covers another (including positional against keyed spellings).
array{…}|nulland?array{…}are the same nullable shape. Branches writing either spelling now fold into one shape instead of listing each separately. Contributed by @sidux.- Offset reads see every alternative. Reading an offset of a union of shapes answers with every alternative, a
count()check on an entry no longer leaves itnever, and??=on an offset stores the element whatever the key. - Array functions keep shapes and literals.
array_keys(),array_key_first()/last(),array_shift()/pop(),array_filter(),array_merge()(including the accumulate-in-a-loop idiom),min()/max(),preg_replace(), andstrlen()of a literal all keep what the input says.reset()/end()/next()/prev()no longer change the array's type, and the key-reading builtins read keys from literals, nested elements, andarray_fill_keys(). - Element functions include the empty-array result.
reset(),end(),current()includefalseandarray_pop(),array_shift(),array_first(),array_last()includenullunless the array is provably non-empty.next(),prev(), andarray_find()always include it,explode()returns anon-empty-list<string>, and array functions see what a guard proved about their argument. array_map()is more precise. It keeps the input's shape and keys (no longer inventingintkeys), maps avoidcallback tonull, returns what a callable-typed, first-class, or parameterless callback returns, reads the shape the callback body actually builds, and types the callback parameter as one element of a union of shapes.- Sorting keeps the values.
sort(),rsort(),usort(), andshuffle()give a list of the same values, and key-preserving sorts leave the type alone. - Destructuring assigns every target correctly. Nullable sources add
null, unknown sources givemixed, unions of shapes contribute every alternative, and a skipped position ([, $second]) no longer shifts the later targets. - A constant array of
Foo::classentries keeps the class names.private const FOOS = [Foo::class];islist{'Foo'}, so iterating it and making static calls on the entries works. (array)on a union casts each member.- Key spellings follow PHP.
'+15'and'015'stay string keys, single-quoted escapes stay strings, and double-quoted escapes decode ("\x38"is8). isset()on a shape read through a variable key keeps the element type.
Narrowing¶
instanceofnarrows more accurately. On a union, it keeps the half a subclass could satisfy (Model&HasName|HasName), a failed check rules out subclasses of the checked class, a passing check keeps a subclass as itself, and a template-typed value becomesA&Tinside the branch. It also narrows against an unloadable class, against a value holding a class name (instanceof $stmtClass), and withselfin a trait meaning the using classes. A failed check against aclass-stringvariable rules nothing out.- An
instanceofguard rules out a template bounded by the checked class. A@template TFactory of Factoryalternative no longer survives! $x instanceof Factory, which caused false return-type mismatches (most visible on model traits). Contributed by @calebdw. $this instanceof Subclassresolves the subclass's members, even after other$thisproperties have been read.- Negated and combined conditions narrow correctly.
if (!($a instanceof X || $a instanceof Y)) { return; }leavesX|Y, aninstanceofbeside an unrelated||operand no longer narrows the branch, a disjunction narrows each leg on its own, an&&operand that pins a class outranks a later disjunction, and an assignment on the right of&&/||sees what the left proved. elseifand fall-through conditions narrow. Anelseifcondition narrows its own&&operands, and falling out of anif/elseifchain whose branches all exit knows every condition was false.- Guards on properties, calls, and array elements hold. A
!== nullcheck on a getter returning an array, an{@inheritDoc}override, a second accessor on the same object,&&chains over elements and getter chains, array elements with variable or computed offsets ($types[$i],$statements[$count - 2]), and repeated reads of a guarded getter all keep their narrowing. A ternary re-checking a call ($p->getDocComment() !== false ? $p->getDocComment() : null) narrows the arm. - A guard's proof is recovered where it is read. Re-testing the same condition re-applies what its branch proved (including on calls and property paths), a boolean assigned from a condition (including
||chains) narrows wherever it is tested, a variable filled inside a guarded branch stands for the guard, the failing side of aninstanceofrecords what it ruled out, variables set together in one branch keep their correlated nullability, a copy of a property carries its null check back to the property, and closures see the narrowing of what they capture. - Comparisons narrow more values.
===against a variable already narrowed to one value narrows the other side,$a === $bremovesnullfrom the nullable side, strict comparisons against0,0.0,'', and[]narrow both branches, and<,<=,>,>=narrow unions of number literals. Loose==narrowsmixedand strings (tonumeric-string) under PHP 8 rules, andget_class($x) === Foo::classnarrows properties, elements, and call results. - More conditions narrow.
=== true/=== falseon a check, loosein_array()over literals,isset()/array_key_exists()narrowing the key,is_a()with class-string variables orallow_string,ReflectionClass::isSubclassOf(),enum_exists()(toclass-string<UnitEnum>),strlen()/mb_strlen()comparisons (tonon-empty-stringor''), and type checks on array offsets. Global functions written with a leading backslash (\get_class,\class_exists) narrow like the unqualified spelling, and a guarded class name written with escaped backslashes matches. A failed strictin_array($x, [null, ''], true)drops those values. - Falsy branches hold the falsy values. In the else of
if ($count), underif (!$name)orempty($x), or after$id == null, anintis0, astringis''|'0', an array isarray{}, and objects and class-strings drop out. Anon-empty-stringis no longer always truthy, a(bool)cast narrows like its operand, and the skipped branch of a truthy test keeps exactly the members the test rules out. count()narrows arrays.count()sizes shapes with optional entries, rules out impossible sizes, pins lists to a length (also withCOUNT_NORMALand, for lists of scalars,COUNT_RECURSIVE), andcount($xs) > 0or writing an element proves the array is non-empty, so a loop over it is known to run.isset()narrows more. A named offset rules out astring,isset($arr[$key])types the offset it guards (also on static properties),isset($var)proves the variable exists for the whole branch, and a seed-if-absent write (if (!isset($t[$k])) { $t[$k] = 0; }) is no longer undone by the guard.array_key_exists()narrows. It narrows an optional shape key, accepts a variable key, drops the key when it fails, and with an unknown key proves the array non-empty.- Union and tag narrowing. Tagged unions of shapes narrow on their tag (also in
switch), aforeachkey over a shape is the shape's keys and comparing it narrows the matching value, an offset read through a variable holding one literal key reads just that entry, aswitcharm sees whichcaseit came in by,is_callable()keeps classes that may be invokable (and calling a union of callables gives the union of their results),is_resource()keepsresourcein the else branch, and type checks oniterablesplit into array andTraversablehalves. - A value every check has ruled out is
never, and its branch no longer widens the types after it. Code in a branch a!== nulltest rules out is no longer checked againstnull. - Narrowing ends where it should. A ternary's or
match's narrowing ends with it, a branch narrowing to an intersection no longer erases the other path's type at the join, and a write the resolver cannot type drops a stale property narrowing. - Calls that change state forget what was proved. Methods returning nothing or
$this,@impure/@phpstan-impure/@psalm-impuremethods, objects passed to them,parent::__construct(),clearstatcache()/unlink(), and stateful built-ins (SplFileObject,DateTimesetters) invalidate earlier narrowing, including static properties.@pureand value-returning methods no longer invalidate. Closures run inline, called immediately, or called later through a variable apply the same invalidation to$thisand their captures. - The arguments of a
?->call see the receiver as not null, and a guard likeif ($queue?->pop() === null) { return; }no longer re-proves an impure call. - Assertions narrow more. A class assertion drops
nullfrom a union of classes,-if-true/-if-falseassertions narrow untyped parameters, assertions on variadics narrow every argument,@phpstan-assertcan narrow$this->prop, assertion types resolve in the declaring file's namespace, and predicates apply through properties, intersections,&&chains, and interfaces. - Readonly properties remember the constructor. What the constructor assigns or proves (including on early-return paths and nested readonly properties) holds in every other method when it is narrower than the declaration.
is_a($name, Foo::class, true)on a string stays a string, and an array literal built from an@var-annotated variable respects the guard around it.- Loops prove what they check. A
do/whilecondition narrows the body after the first pass, awhilecondition that assigns narrows, a loop that doesbreak 2on a bad entry proves every entry passed, and a ternary in aforeachheader narrows its arms.
Diagnostics¶
- Fewer false positives on loosely typed code. Arithmetic on untyped values,
foreachkeys of undescribed arrays, keys collected from them, and values with lenient failure branches (tempnam(),curl_init()) only need one branch to fit, even past anif. Declared types are still enforced.int<0, max>passed tofloat,class-stringtonon-empty-string,array-keytointorstring, and$a & $bon untyped closure parameters are accepted. - Unverifiable members name the cause. A member read on a value PHP leaves open now reports
mixed, and a value guards can refine, instead of "type could not be resolved". A missing method in a loop accumulator is reported once at the call instead of blaming the variable. - Nothing is reported in code that cannot run.
if (false)branches and the negated arm of a satisfiedmethod_exists()are skipped, while the guard and imports in the branch still count. A dead branch in one file no longer hides diagnostics in another, and a}in a comment no longer cuts an existence guard short. - Arrays are checked without scalar coercion. Keys and values of an array are checked strictly in every file, since PHP never converts them.
- New checks on generics and shapes. Closures passed to a
callable(…)with incompatible parameters, wrong shape keys or values, string keys passed to a list,[]passed to a non-empty type, subclasses binding a template differently (IntBoxforBox<string>), and arguments outside a template's bound are now reported.array_filter()callbacks work in every mode, andchunk()callbacks receive the model's custom collection. deprecated_usageis more precise. Imports, trait methods implementing a deprecated method, overrides delegating to the deprecated method, and usages inside deprecated code are no longer flagged. Overrides inherit@deprecated.- Undefined and unused variables. A
use (&$total)capture and anisset($var)guard no longer report the variable as undefined, and a variable in a scope thatrequires a file is not reported as unused. - Docblock and type checks. A
@param Closureabove?Closureis no longer flagged, while a docblock admittingnullon a non-nullable signature is. Constants insideint-mask<…>are no longer reported as missing classes, andComposer\Autoload\ClassLoaderresolves. - Unused group imports are found. Multi-line group imports are checked member by member (including aliases and sub-namespaces), and removing every member removes the whole statement instead of leaving
use App\Models\{. - Saving a class refreshes diagnostics in grandchildren, not only in direct children.
Laravel¶
- Class-based casts resolve to their value.
AsEnumCollection::of(Status::class)isCollection<array-key, Status>, and the other built-in cast classes (AsCollection,AsArrayObject,AsStringable,AsFluent,AsUri, and the rest) resolve to what they return. Contributed by @calebdw. - Relationships without docblocks know their related model.
posts(): HasMany { return $this->hasMany(Post::class); }types$user->postsas a collection ofPost. - A base model's Eloquent settings apply to its subclasses.
$fillable,$casts,$hidden,$primaryKey,$connection, andCREATED_ATare inherited from the nearest declaring class, and a child'scasts()is merged over an inherited$casts. - Model columns and finders.
SoftDeletesmodels havedeleted_atandwhereDeletedAt(), every model haswhereId(), a single-linecasts()keeps its last entry, the base model's settings are no longer offered as columns, and migrations' index and constraint calls no longer create or retype columns. - Column names complete after a relationship.
$user->posts()->where('offersPostcolumns, andwith('offers its relations. $pivotis known without opening the relationship's file, andmorphedByMany()relationships take effect as soon as they are edited.- Custom collections only where Eloquent provides them. A
@param Collection<int, Product>no longer offers the model's custom collection methods, andinstanceofupdates the tracked type. - Scopes and accessors in Find References, lenses, and rename.
scopeActive()used asactive()and accessors used as->full_nameare found, counted, and renamed with their declaration. Invalid new names are refused. Hover on them shows their docblock, and go-to-definition on a scope named like a column finder lands on the scope. - Go-to-definition on a facade opens the forwarded method, including methods reached through the target's
@mixin. - A class name inside a namespace no longer falls back to a facade alias.
Cache::forget()without an import is no longer treated as the facade. - Container keys resolve reliably. Requests arriving during startup wait for the binding tables instead of seeing them empty.
- Routes. Only calls on the router register route names,
Route::as()prefixes likeRoute::name(), names written before the registration count, Find References works from->name(), and group names compose the way Laravel does. - Views. Published package views in
resources/views/vendor/<ns>take precedence, aresources/viewsdirectory created later is found, view roots follow unsaved edits toconfig/view.php, a variable passed twice keeps the last value, Find References on a view name includes@includeand@each, and the fully qualifiedView::share()reaches templates. - Config. Config groups replace the package's copy the way Laravel merges them, go-to-definition lands in the package file for unpublished keys, lists of classes hover correctly, an empty string types as
string, completion and type resolution read the same files, and keys set at runtime (Config::set(),config([...]),Storage::fake()) count as declared. Package code is no longer checked against the application's config. - Translations. Subdirectory groups complete,
lang/vendor/<package>overrides apply, keys require the package namespace, hover quotes the configured locale, resolution no longer waits for the workspace index, and translation directories refresh when a provider changes them. - Escaped quotes in keys. Config and translation keys declared or used with an escaped quote (
'it\'s') are known by the name PHP reads. - Package resource paths.
dirname(__DIR__)paths andlang_path()are followed in service provider loaders, andspatie/laravel-package-toolsproviders' translations, views, and config are known. .envfiles..env.<environment>files count as declarations, and a variable declared twice hovers with its last value.- Deleted files stop contributing. A deleted service provider's macros, gates, commands, morph aliases, storage drivers, bindings, and paths are removed, and so are runtime config keys from deleted files.
- Completing a string key after a non-ASCII named argument no longer fails.
- PHPStan runs for projects using
calebdw/phpstan-laravel. Either Laravel extension (or a fork) now enables PHPStan diagnostics. Contributed by @calebdw.
Blade templates¶
- Blade parsing follows the compiler. An
@inside a word is not a directive,)or]inside PHP comments no longer closes directive arguments, a directive ends a multi-line echo that contains it, quotes in@verbatimno longer leak into PHP, and a commented-out@useis not an import. - Escaped frontend interpolations are left alone.
@{{ name }}and@{!! name !!}are not parsed as PHP, including across lines. Contributed by @shuvroroy. - Highlighting and hover agree with the compiler.
@@if,@{{ … }}, and@verbatim/@phpcontent are no longer coloured as Blade, and echo-delimiter lookalikes no longer trigger hover or go-to-definition. - Unbalanced-directive and slot checks. Two-argument
@push,@prepend, and@slotare not unclosed blocks,<x-slot:title>is closed by</x-slot>, and<x-slot name="footer">shows asx-slot:footerin the outline. - Component attributes are typed from the right expression even when
@class,@style, or@jsonappear earlier. - Components in every PSR-4 directory are found, and
$loop->parentoffers the outer loop's members. @langand@choiceare translation keys.- Class completion offers classes that need importing, inserting
@use('…'). - Template types stay current. Variable types no longer go stale after saving a controller, Find References lands on the right line, and Laravel macros called from templates are found.
- Internal Blade declarations stay hidden from workspace symbols and completion.
- Deleted templates are released from memory, and section and stack pairing no longer rescans every template for each layout.
Editor features¶
- Go-to-definition on a subclass name no longer jumps to its parent. At its own declaration it answers with itself, so "Declaration or Usages" in PhpStorm and Zed can show usages. The
extendsclause still navigates to the parent. - Go-to-definition on a member declaration no longer jumps to the prototype. Methods, constants, and enum cases answer with their own location, and Go to Implementation and the
implements/extendsclauses still reach the prototype. Contributed by @EranNL. - Methods implementing an interface keep their reference-count lens alongside the prototype lens.
- Go to Implementation finds trait methods. Methods a class takes from a trait are listed, as are classes using a trait's abstract method. Contributed by @sidux.
- Find References is more reliable. It finds implementations inside dependencies, no longer mixes up cached results between files, and shows progress for constants.
- The reference-count lens stays accurate when files are closed or changed on disk, and new files are counted.
- Hover works on an unfinished
$user->orModel::. - Array key completion works for type aliases named on
@varor@param, including chained aliases. - Code actions. Import-class fixes are available with the cursor on the first character, "Extract variable/constant (all occurrences)" no longer produces overlapping edits or fails on multibyte names, and PHPDoc quick fixes work on files with Windows line endings.
- Columns with emoji. Go-to-definition on an
@methodtag and override completion land on the right column on lines with characters outside the Basic Multilingual Plane. - The document outline no longer goes blank when a multibyte character in a comment precedes a symbol's name.
Rename and move¶
- Variable renames respect scope. Closures that do not capture the variable and functions in the same file are left alone,
global $namelinks are followed, and invalid names (1bad,$this) are refused. - Renames and moves reach Blade templates, including
@phpblocks,@vardocblocks, directive arguments, and@use. Find References includes templates without opening them. - Imports are rewritten correctly. Wrapped
usestatements, group imports (use App\Models\{User, Post};), and comma lists are updated, rewritten imports keep their indentation, and moving a class out of a group's prefix gives it its ownuse. - References keep their meaning after a namespace move. Fully qualified and relative names are rewritten so they still resolve to the moved class, including
::classstrings in Laravel config. - Moves keep code working. Files that reached the class by short name gain an import (aliased if needed), and the moved class gains imports for its former namespace siblings, functions, and constants.
- Moving to and from the global namespace. The
namespaceline is removed when moving to global, and a class leaving the global namespace is no longer reported as left behind. - Namespace renames put files in the right place. Files follow the destination's PSR-4 mapping, merging into an existing namespace moves files one by one,
App\Internalno longer claimsApp\InternalTools, and a namespace served by two PSR-4 roots is refused with both named. - Moves onto taken names are refused with a reason instead of being half-applied.
- Moving a class no longer writes the namespace above
declare(strict_types=1). - Directory walks no longer loop on symlinks when moving onto an existing directory or scanning PSR-0 packages.
Formatting and command line¶
- phpcbf works on projects without a
phpcs.xml. - phpcbf exit codes 2 and 4 no longer fail formatting. These report remaining or conflicting issues, not errors.
- Pint uses the project's
pint.json. External formatters now run from the workspace root. - Pint no longer stalls on large files.
- An external formatter that prints nothing no longer empties the file.
- Whole-document formatting edits measure the last line correctly when it contains multibyte text.
phpantom_lsp fixno longer silently skips files. Blade templates crashed workers, which looked like a clean result.fixnow also sharesanalyze's stack size, parsing, and Laravel discovery.analyzeoutput is stable between runs, sorting same-line diagnostics by column and code.
Performance and stability¶
- Deeply chained and guarded code no longer stalls analysis. Methods with many chained calls in branches, or property guards mixed with chained calls, used to take exponentially longer (some never finished). Long methods are no longer re-read for every question.
- The editor stays responsive during slow requests. PHPDoc generation, symbol pickers, selection ranges, quick-fix resolution, inlay hints, type hierarchy, and Laravel startup indexing no longer block other messages.
- A slow editor response no longer crashes the server. Diagnostic refresh, progress, and navigation requests now wait for late answers.
- A running Laravel app no longer slows the editor. Changes under
storage/framework/viewsandbootstrap/cacheare ignored, and file changes that add or remove no class keep the type caches. - Find References is faster on widely used names. Positions are computed without rescanning files, and member searches share resolved receivers with the reference-count lens.
- Reference lenses reuse the completed workspace index instead of walking the filesystem for every declaration. Contributed by @sidux.
- The reference-count worker no longer reruns workspace searches while you type.
- Renaming a local variable no longer re-indexes the project. Contributed by @calebdw.
- Requests parse the document once. Hover, completion, go-to-definition, signature help, and inlay hints share one parse, and code lenses and inlay hints no longer slow down further down a file.
- Closing a file and workspace symbol search no longer block editing.
- Laravel projects read the installed-package list once per indexing pass and per edit.
- Symlinked dependencies are treated as dependencies. Completion ranking and removed functions after
composer updateare correct with symlinked paths. Contributed by @sidux. analyzeand the indexer skipvendor/however it is reached, including through symlinks or aliased paths.- New
[indexing] extensionsare watched without a restart. analyzeno longer intermittently misses members due to a race between workers.- Crashes no longer degrade later analysis, and Find References on
new self()no longer risks a crash on a shrunken file.
0.10.0 - 2026-08-20¶
Added¶
Whole-project analysis¶
- Full workspace indexing. PHPantom now parses every PHP file in the project in the background after startup, so Find References, Rename, Go to Implementation, and Type Hierarchy cover the whole project instead of only the files you have opened. Lighter modes remain available for projects that prefer a smaller footprint. Contributed by @sidux in https://github.com/PHPantom-dev/phpantom_lsp/pull/186.
- Workspace-wide diagnostics. Set
workspace = trueunder[diagnostics]in.phpantom.tomlto see problems in every file, not just open ones. Results stream into the problems panel once startup and indexing finish, and configured external tools (PHPStan, PHPCS, Mago) run once over the whole project afterwards. Off by default.
Blade templates¶
- Template variables come from a clear priority chain. A template's variables are resolved from, in order: a
@bladestan-signaturedocblock,@propsand@aware, the component class (or Livewire's$this),View::share()andView::composer()registrations, the layout it extends, and finally the data passed at its render sites. Completion, hover, go-to-definition, and undefined-variable diagnostics all use the same set, alongside the variables Blade injects itself. - Every way of rendering a template is recognised.
view(),View::make(),Route::view(),Response::view(), the view factory's render helpers, mailable views, and Blade's@includefamily,@extends, and@eachall navigate, hover, complete, and pass their data to the template. This works however the view factory or mailable is obtained, and data passed as a typed array is read from its type. Contributed by @shuvroroy (#337). - Render calls are checked against the template's contract. When a template declares what it needs, a missing variable, a variable of the wrong type, or a key the template never reads is reported at the render call, matching what Bladestan reports in CI. Templates that declare nothing are not checked, so this is opt-in.
- Blade components are first-class.
<x-alert>,<x-forms.date-picker>, and<livewire:counter>navigate to their class or template, complete after<x-or<livewire:, and complete attributes from the constructor,mount(), or@props. Wrong attribute types and missing required attributes are reported on the tag, and$componentworks inside the tag body. - Sections and stacks are linked. Ctrl+Click, completion, and hover connect
@yieldwith@sectionand@stackwith@pushacross files. A@sectionor@pushthat no layout in its chain ever renders is reported. - Directive completion and block checks. Typing
@completes every known directive and inserts the matching@end…for block directives. A block closed by the wrong directive, or never closed, is reported in the template itself instead of as a parse error in a compiled cache file.
Laravel¶
- Route, config, view, and translation keys are real symbols. Strings passed to
route(),config(),view(),__(), and related helpers complete, hover, navigate to their definition, and report typos such asroute('dashbaord'). Keys registered by installed packages and service providers are included, as are container attributes and facade methods that take a config sub-key (DB::connection(),Cache::store(),Log::channel()). Contributed by @calebdw. - More places that name a Laravel key are recognised. Route names in signed URLs, the
Redirect,URL, andResponsefacades and helpers,#[RedirectToRoute], andRoute::is()/routeIs()patterns all get the same support. Notification mail views,Lang::hasForLocale(), andConfig::getMany()are covered too. - Environment variables.
env('APP_NAME')andEnv::get()complete from.envand.env.example, hover to show the value and file, and appear in Find References. Values of names that look like secrets (STRIPE_SECRET,APP_KEY) are not shown. Unknown names are never reported, since the real runtime environment is not on disk. - Route parameters complete from the route's URI. The keys of
route('users.show', ['user' => $user])complete from the route's{parameters}, including group prefixes and the URIsRoute::resource()andapiResource()generate. Contributed by @shuvroroy (#301, #308). - Artisan commands. Command names complete, navigate, hover with their arguments and options, and are checked, including aliases. Inside a command,
$this->argument()and$this->option()complete and are typed from the command's own$signature, andArtisan::call()parameters complete the target command's keys. Contributed by @shuvroroy (#274) and @krist7599555. - Config values are typed from your
config/files.config('database.default'),Config::get(), and repositoryget()calls resolve to the type the config file actually holds, including nested array shapes andenv()fallbacks. Framework defaults fill in keys a published config leaves out. Contributed by @calebdw. - Path helpers link to files. The argument of
base_path(),app_path(),config_path(),resource_path(), and the other path helpers is a clickable link and completes one directory segment at a time. Contributed by @shuvroroy (#334). - Authorization abilities and policies. Abilities in
Gate::allows(),$user->can(),$this->authorize(),can:middleware, and Blade's@canfamily complete, hover, navigate, and are checked againstGate::define()registrations and model policies. An ability that belongs to a different model's policy is reported as such. Contributed by @shuvroroy (#330). - Container bindings and facades resolve to the bound class. String keys bound in a service provider make
app('sentry')andresolve('sentry')resolve to the bound class, with hover, navigation, and Find References on the key. Facades whose accessor names such a key, including hand-written facades with no@methoddocblock, now get their members from the class behind it. Contributed by @shuvroroy (#335). - Eloquent models know their database columns. Columns from schema dumps in
database/schemaand from migrations become typed model properties with nullability and defaults. Custom connections, table names, andBlueprint::macro()helpers are respected, and editing one migration does not re-read the rest. Configure with[laravel.migrations]in.phpantom.toml. Contributed by @calebdw. - Model factories build the right thing.
has{Relationship}(),for{Relationship}(), andtrashed()complete and chain on factories, andcount(3),times(3), orfactory(3)makecreate()andmake()return the model's collection instead of a single model. Contributed by @shuvroroy (#260, #315). - Request input and
validated()are typed from validation rules. Field names complete wherever request input is read, with the rule shown and a link to where it is declared.validated()returns an array shape typed from the rules (nullable, optional, nesteditems.*, files, and enums included). Contributed by @shuvroroy (#292, #294, #307). - Higher-order collection proxies.
$users->map->emailis typed like$users->map(fn ($u) => $u->email), with completion and hover through the proxy and chaining afterwards. Contributed by @shuvroroy (#314). $pivoton many-to-many related models. Models reached throughbelongsToManyormorphToManyexpose a typed$pivot, using the relationship's pivot model or->using()class, and hover lists the->withPivot()columns. Contributed by @shuvroroy (#266).- Morph map aliases. Aliases registered with
Relation::morphMap()orenforceMorphMap()hover to their model, navigate to both the registration and the model, and appear in Find References. Unknown aliases are only reported when the map is enforced. Storage::disk()resolves to the real adapter. Disks are typed fromconfig/filesystems.php(andStorage::extend()for custom drivers), so adapter-only methods likeassertExists()anddownload()are no longer reported missing.- Macros registered with
mixin().Str::mixin(),Collection::mixin(), and Carbon's trait-basedmixin()add their methods to the target class, with completion, hover, and type checking. Contributed by @shuvroroy (#256) and @calebdw. - Larastan's
model-property<Model>is checked and completed. String literals that name no property on the model are flagged, and the model's property names complete inside such arguments. Contributed by @calebdw.
Diagnostics¶
- Access to
privateandprotectedmembers is reported. Reading or calling a member you cannot reach from the current scope is now flagged, checked against the class that declares it. Classes with magic methods, trait members, and@seereferences are left alone. Contributed by @petrovo-as. - Illegal
readonlywrites and contradicting docblocks. Writes to areadonlyproperty from places PHP forbids (includingunset(),foreachtargets, and references), and@paramor@returntags whose nullability contradicts the declaration, are now reported. - Four new declaration diagnostics. Enum cases that do not match the enum's backing type, overrides that drop an inherited
staticreturn type, abstract trait methods nothing implements (with "Implement missing methods" stubbing them), andmatcharms that can never match. Contributed by @calebdw.
Type inference¶
preg_match()gives$matchesthe right keys. With a literal pattern,$matchesbecomes an array shape with the whole match, each group, and named groups, honouringPREG_OFFSET_CAPTURE,PREG_UNMATCHED_AS_NULL, andpreg_match_all()modes. The shape also depends on whether the match succeeded in the current branch.- By-reference closure captures update the outer variable. A closure capturing
use (&$var)that is passed to an immediately invoked callable can update the outer variable's type, following PHPStan's defaults. Contributed by @calebdw. @psalm-this-outand@phpstan-self-out. A method call can now retype the object it was called on, as mutable generic containers describe.@phpstan-require-implementsin traits.$thisinside the trait sees the required interface's members, matching@phpstan-require-extends. Contributed by @calebdw.
Editing and navigation¶
- Override completion. Completion in a class body, or after
function,$, orconst, offers every parent, interface, and trait member the class can still override or implement, inserting the full declaration with#[\Override]where supported. Contributed by @calebdw. - Reference and implementation counts. Classes, members, and functions show how many times they are used, as an inlay hint and above the declaration, with implementation counts on interfaces and abstract classes. Following a count lists exactly what it counted. Contributed by @calebdw and @petrovo-as.
- PHPUnit coverage metadata navigates both ways. Ctrl+Click a target in
#[CoversClass],#[CoversMethod],#[CoversFunction], theirUsesvariants, or@covers/@uses/@coversDefaultClassto open it, and rename keeps them in step. Covered classes show a lens naming the tests that cover them. - Two new code actions. "Sort use statements" sorts imports like PhpStorm's Optimize Imports. "Convert to string interpolation" turns
'Hello ' . $name . '!'into"Hello {$name}!"where that is safe. - Semantic token modes.
[semantic_tokens] mode = "contextual" | "full" | "off"in.phpantom.toml. The defaultcontextualmode only adds highlighting the editor's grammar cannot provide,fullkeeps the previous behaviour, andoffdisables it. Contributed by @calebdw. @phpstan-ignoreidentifiers are highlighted and completed. Identifiers are highlighted in docblocks and//comments, and complete from the diagnostic codes already seen in the file. Contributed by @calebdw.
Tooling and platform¶
- Global settings.
phpantom_lsp init --globalcreates a config in your platform's config directory (~/.config/phpantom_lsp/.phpantom.tomlon Linux) that every project inherits. A project's own.phpantom.tomlis merged over it key by key, and errors in the global file are reported against that file. - Config changes apply without a restart. Editing the global config or a project's
.phpantom.tomlreloads settings within a couple of seconds. Previously only Laravel projects reloaded, and the global config never did. - Analyze verbosity flags.
phpantom_lsp analyzesupports--debug(prints each file as it is analysed, so hangs are easy to pin down) and-v/-vv/-vvvfor timings, worker details, and memory usage. - PHPantom runs in the browser. The type engine compiles to WebAssembly, giving web editors completion, hover, go-to-definition, highlighting, and rename without a server. Every release ships a prebuilt module. See wasm.md for the host interface. Contributed by @ondrejmirtes.
Changed¶
Behaviour¶
- One parser for all PHPDoc.
@psalm-and@phpstan-prefixed tags are treated as the same tag as their plain form everywhere, with the prefixed version taking precedence. Multi-line types, variance annotations, tags indented with extra spaces, and half-written docblocks are all handled more reliably, and prose after a type no longer leaks into it. - Property hover shows the effective type on a
varline. Like method hover, the resolved type is shown above the code, and the code itself shows only the native declaration. Contributed by @calebdw. - Live progress counts. Indexing progress advances file by file with live counts (e.g. "Scanning vendor packages (3201/8544 files)"). Go to Implementation, Find References, and Type Hierarchy show the same live progress.
- One slow file no longer stops workspace diagnostics. Previously a single file the analyser could not finish froze the progress bar and left the rest of the project undiagnosed. Now the other files keep going, a file still running after two seconds is named in the progress message, and one that takes more than ten is skipped and logged so it can be reported. Opening the file still diagnoses it normally.
- External tool re-runs only refresh files that changed. A project-wide PHPStan, PHPCS, or Mago run no longer re-sends diagnostics for every file, only for files whose results differ.
- Updated the bundled mago toolchain to 1.46.0. Contributed by @enwi in https://github.com/PHPantom-dev/phpantom_lsp/pull/234.
- Updated embedded phpstorm-stubs. Adds PHP 8.6 coverage and corrects several signatures, including Redis, FFI, enchant, xmlreader,
openssl_x509_parse(), andhtmlspecialchars().
Performance and memory¶
- Saving no longer re-analyses every open tab. Only open files that use something the save changed are re-checked, keeping completion and hover responsive after a save. Saving a Laravel config, translation, or route file still refreshes every open file.
- Classes are pre-resolved after startup. Once indexing finishes, every class is resolved across multiple workers, so the first completion, hover, or go-to-definition reads a warm cache. This also shortens the pause before diagnostics on large Laravel projects.
- Lower memory use for types and class hierarchies. Identical types are stored once and shared, and inherited members are shared with their source instead of copied. On large Laravel projects this roughly halves the memory held by resolved classes and also speeds up analysis.
- Lower memory use in the reference index and member lookups. The data behind Find References, method lookups, and member access positions is stored more compactly, removing many short-lived allocations.
- Faster startup. File discovery and indexing use all CPU cores and no longer get held up by one very large dependency. On a large Laravel project indexing is about a quarter faster and peak memory is about 25 MB lower. When two files declare the same class, the same one now wins on every run.
- Faster class-name lookups. Lookups are cached, making whole-project analysis 8-12% faster on large Laravel projects, with the same gain for hover, completion, and go-to-definition.
- Faster vendor scanning. Vendor files are read once instead of twice, and package origin for completion ranking is worked out during the same parallel scan.
- Argument checks no longer slow down on large files. On a 370 KB file with 2200 calls, the argument checks went from 13.7 seconds to 0.2, and the whole file from 16.7 seconds to 3.4.
- Faster diagnostics on long method chains. Files built from long fluent chains report diagnostics around a quarter faster, and the deprecated-usage check roughly halves.
- Faster diagnostics in general. Several checks reuse already-resolved class data instead of recomputing it (and now also see interface-declared members), and calls that resolve to no class are no longer resolved twice, roughly halving diagnostics time on files with many unresolved chains.
- Faster narrowing, docblock, and Eloquent scope handling.
assert()and type-guard checks skip statements that cannot be assertions,@methodand@propertytags are parsed once per class, and Eloquent scopes are resolved once per model. - Faster workspace symbol search. Matching no longer allocates a copy of every symbol name on each keystroke.
analyzeandfixskip the reference index. The CLI commands do not need it, so whole-project runs do less work.- The first reference search of a session is fast. Files are pre-walked in the background after indexing, so the first Find References or reference CodeLens is as fast as later ones. On a large Laravel app, reference counts for 250 files went from 1.4 seconds to 0.14. The background pass uses a quarter of the CPU cores and stops after 30 seconds on very large projects.
Removed¶
- Bundled Zed extension. PHPantom's support has merged into Zed's official PHP extension. See Editor Setup for the updated Zed configuration.
- Linked editing. Editors could mirror ordinary edits into a linked range and corrupt the line being edited. Use rename (explicit, cross-file, previewable, one undo step) or your editor's multi-cursor instead.
Fixed¶
Narrowing¶
instanceofnarrows to exactly what it proves. A successful check keeps a generic's type arguments (Collection<User>staysCollection<User>), replaces a wider type such asobject|nullinstead of adding the class beside it, and drops the array half of a union likeUploadedFile|array<UploadedFile>|null. Ruling a class out of a class-and-scalar union such asDecimal|floatnow leaves the scalar instead of dropping the whole union, and theif (!$x instanceof Foo) { throw … }guard narrows the same way asassert().- An
instanceofcheck on anobject|stringvalue narrows it to the class.if ($server instanceof Server)on a route parameter typedobject|stringused to giveobject|string|Server, so passing it on was reported as a type error. The check's result is now the whole answer, including in guards likeif (! $server instanceof Server || ! canManage($server)). instanceofon a nested property keeps the declared class.$this->holder->service instanceof MockInterfacenow gives both the declared class and the interface, as the one-level form already did.- A value proven to be two types at once is an intersection.
$x instanceof Reader && $x instanceof Writer, orassertInstanceOf()andassert()on a mock, now giveReader&Writer(orMethodNode&MockObject) instead of a union that satisfies neither. An existing intersection narrows within itself, and an||check still only proves one of its alternatives. is_a($x, Foo::class, true)keeps the class-string case. On anobject|stringvalue the check now narrows toFoo|class-string<Foo>, so a followingis_string()check is no longer reported as always false.get_class($v) !== Foo::classkeeps subclasses. A subclass'sget_class()names the subclass, so it now survives the check instead of being ruled out withFoo.match ($value::class)narrows its subject in each arm. Each arm narrows the subject to the classes it names, so handlers typed for those classes no longer report a mismatch.- Negated
nullchecks are read correctly.!($v != null)no longer narrows tonull(loose equality also matches'',0, and[]), and!($v === null)now proves the value is not null. filled()andblank()narrow their argument.if (filled($search))now removesnullfrom a?string. Assertions written as unions (!=null|'') work, and equality-form assertion tags no longer narrow the opposite branch to a wrong type.- Laravel's bail-out helpers narrow the code after them. After
abort_if($user === null, 404),abort_unless(),throw_if(), orthrow_unless(), the value is narrowed with every guard form anifunderstands. More generally, any function whose conditional return type has aneverbranch now narrows the argument that would select it, for variables, properties, and array elements. - Calling a
neverfunction or method ends the branch. Guards likeif (!$x instanceof Foo) { abort(); }narrow what follows whenabort()returnsnever, for functions, static calls, and methods (declared, inherited, or from a trait), whatever the call is written on (app()->abort(422),$this->responder->abort(422), …). Assignments in such a branch are treated as dead code. - Guards written with
if: … endif;narrow. The colon syntax now exits the same way the brace form does. &&and||guards narrow the next operand wherever they are written. Assignments, arguments, array entries, ternary conditions,matcharms, anddo/whileandforconditions now narrow like anifcondition does, so$ok = is_string($v) && strlen($v) > 0no longer reports anything.- A negated compound guard narrows by every part. After
if (!is_string($payload) || $payload === '') { return; }each operand's inverse applies, for any exit (return,throw,continue,abort()) and in theelsebranch.is_resource()is now a type guard, and!== ''/!== []givenon-empty-string/non-empty-array. - Checks against
falsenarrow both ways.if ($handle !== false)rulesfalseout inside the branch,if ($value === false) { … } else { … }and!empty($value)rule it out in theelse, andif ($x === false) { throw …; }narrows what follows. AT|false|nullvalue keeps itsnull. - A truthy check rules out every always-falsy value.
if ($value)and!empty($value)now remove[],'','0',0, and0.0as well asnullandfalse, so$markets = $this->option('markets') ?? []followed byif ($markets)leaves a string.'0'is also treated as falsy in@phpstan-assertchecks. - A doubly negated guard narrows like the bare one.
if (!(!$user))now narrows, so Blade's@unless (!$user)does too. - A check written beside an assignment narrows the variable.
while (($line = fgets($handle)) !== false),while ($parent = $parent->getParent()),if (!$row = $query->first()) { throw … }, and} elseif ($token = $request->bearerToken()) {all narrow the assigned variable in the body. - Read loops keep the narrowing their condition established. In
while ($line !== false) { useString($line); $line = readLine(); }the read at the top of the body is no longer judged against the reassigned type.forconditions now narrow the body and the code after the loop the same waywhileconditions do. forloop details are tracked. Aninstanceofin aforcondition narrows the rest of the condition, and the update clause ($node = $node->next) now feeds its type into the next iteration and the code after the loop.- A loop over a non-empty array runs at least once. After
if (!$qtys) { return 0; }, aforeachover$qtysreplaces the$max = null;sentinel, and variables first assigned inside the loop are defined after it. Arrays proven non-empty by guards,non-empty-arrayannotations, required shape keys, or literals all count. - Null-initialized variables reassigned in an untyped
foreachare not stuck asnull. When the iterable has no known element type, the loop value ismixed, so later merges andis_nullearly returns work. Contributed by @calebdw. - Writes to a
foreachvalue variable stay in their iteration. The value and key variables are reset to the element type on every pass, so a write at the end of the body no longer leaks into the next iteration's guards. breakcarries its state out of the loop. Variables assigned before abreak(including inswitcharms and inner loops) now contribute to the type after the loop.- An assignment inside
trysurvives acatchthat rethrows. Acatchthat throws or returns no longer puts back the type the variable had before thetry. - Branch merges use what each branch ends with. After an
if, a variable's type is the union of what its branches end with. A guard that repairs a value (if (!$value) { $value = 'fallback'; },if (!is_array($s)) { $s = [$s]; }) keeps the repaired type, a branch that only narrowed no longer leaks its narrower type, and a property assigned inside a guardedifkeeps that type after the block. - Ternaries and
matcharms see what their condition proved. Each arm of a ternary is resolved under its own side of the condition, wherever the ternary appears (assignments, arguments, returns,throw,new Foo(…)), for every kind of check, including the explicit$x ? $x : ''form and repeated properties like$article->alt ? $article->alt : $article->title.match (true)arms narrow their results the same way, and later arms know the earlier ones failed. - A guard inside an
echonarrows. Ternaries,&&chains, andmatch (true)in an echoed expression now narrow, which fixes Blade{{ … }}echoes as well as plain PHP. - Checks on a function or static call carry to the same call written again.
if (currentUser()) { render(currentUser()); },Session::current(), and guards likeif (mb_strpos($slug, $m) !== false) { … mb_strpos($slug, $m) … }now narrow the repeated call. Arguments are part of the match, and the proof ends when anything the call reads is written, at the end of the branch, or on the next loop iteration. Calls that return something different each time (fgets(),array_shift(),time(),rand()) are never remembered. - A check on a method call narrows the same call.
if ($this->getHttpKernel() instanceof TerminableInterface) { $this->getHttpKernel()->terminate(...); }and scalar checks like$this->value() !== falsenow narrow the repeated argument-less call, throughinstanceof,assert(),is_a(), and truthy or null tests, including where the call is passed as an argument. Completion, hover, and go-to-definition see it too. - Remembered checks expire when their state may have changed. A call on a receiver drops what was proven about other calls, properties, and elements read through it (unless the callee is
@pure), and assigning a new object to$aends earlier checks on$a->value. Properties checked before a method call on the same object keep their narrowing. ?->chains narrow their receivers. Insideif ($image?->file_id !== null), after$period = $agreement?->latestPeriod(); if (!$period instanceof Period) { return; }, and when a?->chain is compared with a non-null value, every receiver along the chain is known to be non-null.- Static properties remember writes and checks. The lazy-initialisation idiom
if (self::$repo === null) { self::$repo = new Repo(); } return self::$repo;now returnsRepo, not?Repo. - Guard clauses on properties narrow them.
if ($this->handle === false) { return; },!$this->handle, andempty($this->handle)now narrow the property for the rest of the method, at any depth. A check on an indexed entry like$category->translations[0]keeps the collection's element type instead of turning it intomixed. - Checks on a property can narrow a union of objects. Testing a property that tells classes apart (
is_string($b->v),$r->tag === 'ok') now narrows the object itself to the matching classes. - Checks on array elements narrow those elements.
isset($m[0]),$m[0] !== null,!empty($row['name']), andisset($state['files'][$path]['violations'])with a variable index all narrow the element they name, without claiming anything about other keys. assert()proves whatever the same condition proves in anif.assert($handle !== false),assert(is_string($v)),&&chains, checks on properties and array elements (assert($items[0] instanceof Foo)), and the fully-qualified\assert()all narrow now.assert($this instanceof …)narrows$thisin Pest closures. A@param-closure-thisbinding is now a starting point that assertions can refine, so members of your real test base class resolve.- More assertion tags narrow.
@phpstan-assert-if-truetags about the receiver's own members (as on PHPStan'sScope::isInTrait()),!nullassertions on parameters, and pseudo-types likeresourceandnull(assertIsResource(),assertNull()) are now applied. iterableis a type guard.is_iterable($x)andassertIsIterable()keep arrays andTraversableobjects and remove everything else.- A strict
in_array()narrows the needle.if (!in_array($email, self::APPROVED, true)) { abort(403); }now proves the value is one of the listed values, for lists, inline arrays, and constants. Constant lists of literals also keep their values. - Fully-qualified type guards narrow.
\is_array($x),\is_a(),\class_exists(),\property_exists(), and\method_exists()now work like their unqualified spellings. - A type guard types a value that had no type.
assert(is_string($version))andif (!is_string($v)) { return; }now establish the type even when nothing else said what the value was. - A check stored in a variable still narrows.
$isHtml = $raw instanceof HtmlString;followed byif ($isHtml), a ternary, or a guard clause now narrows$raw, until either variable is written. - Guards reach reads derived from the narrowed value. Array reads (
$violationMessage['args']), array functions (array_slice($cached, …)), and reads after assertions likeassertNotNull()now use the guarded type instead of the declaration. - Comparing with an enum case rules out
null.$land === Land::Be && $this->takes($land)no longer reports?Land. Other class constants work the same way, based on the constant's own type. - Inline
@varannotations no longer block narrowing. An annotated assignment no longer skips narrowing for the rest of its statement, and the annotated type now flows normally, so later guards narrow it and reassignments replace it.
Type inference¶
- Reflection-style accessors are typed at each call site. A method with an untyped parameter that returns whatever its arguments name (
Sudo::fetchProperty($config, 'shell')) now resolves to the named property's type, with completion and references. - Property reads through reflection are typed.
(new ReflectionObject($config))->getProperty('shell')->getValue($config)now resolves to the property's declared type when the name is a literal, andnew ReflectionObject($x)keeps the class it reflects. - A class's own
offsetGet()beats theArrayAccessdocblock.$pens[0]on a class withoffsetGet(): Pennow resolves toPeninstead of an unknownTValue. - Magic constants have types.
__LINE__is anintand__FILE__,__DIR__,__CLASS__, and the rest are strings, so__LINE__ + 3stays anint.__CLASS__keeps the class it names. - Constants keep their values. Class constants with a scalar initializer resolve to that value (
'foo',1,3.14) wherever they are used, typed class constants (private const int FLAGS = …) keep their initializer, and constants built from other constants are folded through bitwise operators, sojson_encode($v, self::FLAGS)knows aboutJSON_THROW_ON_ERROR. Flag masks stored in variables keep their value too. - More constant references resolve.
parent::SOME_CONSTANTand members read off a constant (self::TYPED->valueon an enum case) now resolve, and a variable holding a global constant ($mode = PHP_ROUND_HALF_UP;) is typed during diagnostics as it already was on hover. - Conditional return types pick the right branch. Conditions are decided by the argument's resolved type and class hierarchy (so
Order::find(7)isOrder|nulland a list of ids gives a collection), by named constants and literal values, and by a parameter's default when the argument is left out (as instr_word_count()). A default likeself::EXCEPTION_ON_INVALID_REFERENCEresolves against the declaring class. Conditions that cannot be decided still report every branch. - Conditional return types recognize interpolated strings as strings.
config("{$prefix}.host")now takes thestringbranch. Contributed by @calebdw. - A standalone
@varcast abovereturnis honoured./** @var int */written abovereturn giveString();now casts the returned value, as PHPStan does. @return mixedno longer hides a method's real return type. Such a method now gets its return type from its body, as an undeclared method does.- An untyped property takes its type from its assignments.
private $context;assigned from a typed parameter ornewin the constructor or setters now has that type. - Overrides inherit what they should. An override without its own docblock uses the parent's
@paramtypes inside its body, its native return type limits the@returnunion it inherits, and aparentorselfparameter type on an inherited method refers to the classes the declaration meant. @methodand@propertytags follow PHP's rules. A@methodtag no longer replaces a method that really exists, a@propertytag wins over an inherited property that is not accessible (such as Eloquent's protected$connection), and tags on implemented interfaces are always applied.@methodand@propertytags on a parent's trait are inherited. Subclasses now see them, with the trait's template parameters resolved. Contributed by @shuvroroy (#314).- A
@methodtag's own template parameter is understood.@method TVal get<TVal of mixed>(TVal $default)no longer reportsTValas an unknown class. - Docblock reading is more robust. A tag written on the
/**line itself is now read, a one-line function no longer picks up the previous function's@param, a/* … */comment between two annotated assignments no longer brings back the earlier annotation, and/** @var \Closure(User $user): string $callback */annotates$callbackrather than$user. - A standalone
@varblock keeps its variable in scope. A/** @var Model $model */that does not sit directly above an assignment (as at the top of a Blade template) now survives comments and blocks written after it. - A docblock can refine one member of a native union.
/** @return false|string */on abool|stringreturn now givesfalse|string. - Literal types are kept precisely. Exact string, integer, and float values survive parentheses, signs,
match, ternaries, and??, and are widened only where PHP requires. Contributed by @snowyukitty. - A ternary with a constant condition only uses the live branch.
true ? 1 : 2is1, not1|2. trueandfalsekeep their own type.$time = false; … if ($time) { … }now narrows to the non-false value, and$found = false; … if ($found)reportstrueinside the branch. Generated return types still usebool.?:drops the value it replaces.$response->getContent() ?: ''is now astring, notstring|false.- Casts are typed everywhere.
(int) $ain a ternary branch,(string) $valueas an argument, and!and~now resolve to their result type. - Integer arithmetic stays integer. Refined ints like
int<0,max>(fromstrlen()orcount()) add up toint, and-$counton anintstays anint. - Arrow functions keep their parameters in their type.
fn (BrandView $view) => …is nowClosure(BrandView): …, so it satisfies a matchingClosure(…)parameter. - Union types are cleaner. Repeated alternatives are dropped, a class and its generic form are not listed twice,
true|falsebecomesbool, and(A|B)&Ckeeps its parentheses in hover and messages. Two classes with the same short name in different namespaces are no longer collapsed into one. - An untypeable branch widens the result instead of vanishing.
array_key_exists('k', $s) ? $s['k'] : 'exception'onarray|string|nullno longer resolves to just'exception', and reading an offset from a string givesstring. - Writes through
__setno longer change what__getreturns.$bag->a = 9on a class with a magic setter no longer makes the next read9. - Assignments through a by-reference closure capture are kept. A closure with
use (&$var)now widens the outer variable even when PHPantom cannot prove when it runs, as PHPStan does. $thisin nested@param-closure-thisclosures resolves to the innermost binding. Nested route groups and macros resolve$this,self::, andstatic::correctly, including when the outer closure is stored in a variable or returned. The tag's class is now looked up in the file that declares it, not the calling file.- Static calls resolve as accurately as instance calls.
Foo::bar()now handles@phpstan-typealiases, inherited generic return types, and the__callStatic()fallback. $string::method()is not reported as scalar access. A static call on astringis valid PHP and is now left unchecked, and on aclass-string<T>it resolves againstT($job->class_name::dispatch()).- Every feature resolves types as well as hover does. Return types inferred from method bodies, Laravel auth guard models, and validation rule shapes were only used by hover, completion, and diagnostics. Go-to-definition, references, signature help, code actions, rename, and inlay hints now use them too.
- PHP 8.4 property hook bodies are analysed. Navigation, hover, and completion now work inside
getandsethooks, including hooks on promoted constructor properties, with$thisand$valuetyped. - Parent property hook calls are understood.
parent::$label::get()is no longer reported as two missing members, and an ordinaryRegistry::$instance::get('service')is no longer mistaken for a hook call.
Generics and templates¶
- A missing generic argument uses the
@templatedefault.@template TAsync of bool = falsenow applies when no argument is given, soHttp::get()returns aResponse(withjson()and the rest) andasync()still returns aPromiseInterface. Contributed by @shuvroroy (#377). - Changing a
@templatedefault takes effect immediately. Editing= falseto= truenow updates dependent return types. - A generic class named without type arguments uses the template bounds.
@var ItemCollection $itemsfollowed by$items->first()now gives the declared bound (ormixed) instead of a nonexistentTModelclass. - Short
@implementsargument lists bind the value parameter.@implements Bag<User>now bindsUsertoTValue, notTKey, when merging interface members. - Templates bind from every place they appear. A template used by several parameters (
@param T[] $first, @param T[] $second) is the union of all of them, a template in one alternative of a union@param(Collection<TKey, TValue>|array<TKey, TValue>,iterable<…>|TWrapValue) binds from the alternative the argument matches, and a property argument ($this->items) binds as well as a local does. - Templates keep the full type of an argument.
passthrough(Carbon::create(2024))now binds?Carbonrather thanCarbon, the same as when the call is assigned to a variable first. - An argument is not checked against a template only it bound.
assertSame(url('/login'), $x)and$this->travelTo(Carbon::create(2024))no longer report circular mismatches. - Callback return types bind templates correctly. Every template in a callback's declared return shape now binds (so
Collection::flatMap()gives the right key and value types), and the body is used when the closure's annotation says less. - A callback whose body is a call binds the template it returns.
->keyBy(fn (Review $r) => $r->getRating())now bindsintas the key. - Closure parameters typed
arraytake the element type from the call.array_map(static fn (array $case) => $case[0]->name, …)now types$casefrom the array, including when the array is an inline call likeiterator_to_array(self::cases()). - Named arguments bind to the right parameters. Reordered or skipped named arguments no longer break template bindings or closure parameter types.
- Static factory templates survive chaining.
Wrapper::make(names())->push([1])now reports the same as the two-line form. - Constant tables work with
key-of,value-of, and lookups.@param key-of<ID_TABLE>and@return value-of<ID_TABLE>hold plain functions to the table's keys and values, and@return ID_TABLE[T]resolves each call to its own entry, including when the argument is omitted and its default names the key.Class::TABLEandself::TABLEwork too. key-ofandvalue-ofkeep a literal's precision.firstValue(['low' => 1, 'high' => 10])is1|10, and a key not in a literal passed to akey-of<T>function is now reported.- Conditionals inside generic return types are resolved.
$collection->groupBy('key')no longer leaks a raw$groupBy is array|string ? …type into later calls. - A generic class is no longer rejected by a parameter of the same class.
new Decimal('0.00')now satisfies aDecimal $amountparameter.
Arrays and built-in functions¶
array_filter()narrows what survives. A callback that tests values (fn ($v) => $v !== null,'is_int',instanceof) narrows the element type, one that tests keys narrows the key type, and both narrow together withARRAY_FILTER_USE_BOTH. This also works forarray<T>andT[].array_filter()without a callback removes falsy values. Anarray<string, string|null>comes back withoutnull. This also improvesif ($x)and$x ?:on unions.- A filtered list is no longer a
list.array_filter()keeps keys, so its result isarray<int, T>.array_values()still gives a list. - Array builtins answer in terms of the array they were given.
array_keys(),array_values(),array_search(),array_key_first(),array_key_last(), andkey()use the array's real key and value types.array_pop(),array_slice(),array_merge(),current(), and the rest now keep scalar element types (alist<string>pops astring) and unwrap nested arrays by one level. array_key_first(),array_key_last(), andkey()dropnullfor non-empty arrays.array_sum()andarray_product()over ints returnint.array_chunk()returns chunks. Each chunk is an array of the input's elements, not a single element.array_map()handles string callbacks and keeps keys.array_map('intval', $ids)usesintval()'s return type, and single-array calls keep the input's keys.max()andmin()return the type of the values compared.- Fully-qualified builtins work like unqualified ones.
\array_sum(),\array_pop(), and the rest of the family now get the same precise return types. - Replace functions return the shape of their subject.
preg_replace(),preg_replace_callback(),preg_filter(),str_replace(),str_ireplace(), andsubstr_replace()return a string for a string subject and an array for an array subject, instead ofarray|string. - More builtins return what their arguments select.
pathinfo($p, PATHINFO_FILENAME),print_r($v, true),hrtime(true),microtime(true),getenv('HOME'),mb_convert_encoding()on a string,abs()on anint, andSimpleXMLElement::asXML()now return the single type they produce, including through constants and parameter defaults. json_encode()withJSON_THROW_ON_ERRORis neverfalse. The flag is recognized on its own, combined with other flags, as a number, or held in a constant.- Builtins whose failure branch is rarely checked are not reported. Functions like
tempnam()that PHPStan exempts no longer triggerstring|falseerrors. Hover still showsstring|false, and functions wherefalseis meaningful, likestrpos(), are still checked. - Out-parameters are typed after the call. A by-reference parameter that defaults to
null(preg_match()'s$matches,parse_str(),exec(), and your own functions) is no longer nullable afterwards. A stored result ($ok = preg_match($p, $s, $m); if ($ok)) narrows the matches the same way testing the call directly does. - Builtin arguments are read in more forms.
$error ?? '',$data['message'], global constants likePHP_VERSION, concatenation, and?:now decide a builtin's return type like a variable does. - Stubs that were too strict or too loose are fixed.
ctype_digit()and thectype_*family acceptmixed,define()accepts any value,ReflectionClass::newInstanceArgs()no longer returnsnull, and the closure passed tospl_autoload_register()gets astringparameter. - Array literals record exactly what they hold.
[$violation, $file, $line]keeps each position's type for destructuring and indexing, literal values like[1, 1.5, '123']keep their values (so they satisfynumeric), and mixed literals like['first', 'b' => 1]keep their positional entries. Each entry is still checked against alist<int>or similar parameter. - Array literals with runtime keys are typed by keys and values.
[$name => 1]isarray<K, int>instead ofarray{mixed: 1},[Event::class => $handler]satisfiesarray<class-string, …>, andnull,true, andfalsekeys map to the keys PHP uses. (object) []is astdClass.- Element writes update the array's type.
$row[] = $penand$row[$key] = 1add to a tracked shape,$grouped[$id][] = $rowbuildsarray<int, list<Row>>, and writing into anarray<string, int>keeps its key and value types instead of turning it into a one-key shape. - Array keys keep their type. Non-literal
stringkeys staystring(only literal numeric strings become ints), computed indices like$mapping[$line + 1]and$result[max($a - 1 - $b, 0)]areint, and++$iworks as a key. - Arrays built across several branches read as one array.
$rows = []followed by writes in severalifs is now a singlearray<int, A|B|C>, and an empty[]no longer trails along beside what is written into it. - Accumulators that start as
[]stay integers.$totals[$k] = ($totals[$k] ?? 0) + $nnow givesint, and arrays filled by a loop or by-reference closure no longer carry the empty-array alternative. - Appending keeps
false.$files[] = realpath($path)storesstring|false, notstring|bool, soassertNotFalse()on an element works. unset()on an array element updates the array.unset($config['driver'])removes a shape key and the non-empty guarantee, so a later loop may not run.- Reading an optional shape key may give
null.type?: stringnow reads asstring|null. - Array union keeps both sides' keys.
$config += ['slot' => $default]and$defaults + $overridesnow keep their shape instead of becomingarray. list<T>andarray<int, T>are the same type. Array types written with different numbers of type arguments are now compared properly, and shapes satisfylistandnon-empty-arrayaccording to their actual keys.foreachkeys are typed from the subject. AlistorT[]gives anintkey, and a shape gives the key types it has.- Inline array function calls keep their element types.
iterator_to_array($it)[0]->nameand nestedarray_map()/array_filter()calls now resolve the same as when assigned to a variable, andarray_keys($this->templates())uses the method's return type. - Array literals missing required shape keys are reported.
takesConfig(['host' => 'localhost'])andtakesConfig([])againstarray{host: string, port: int}now name the missing keys.
Name resolution¶
- Names resolve against the current namespace like PHP does. Unqualified and qualified class names (
B::x(),new View\Event()) in a namespace now resolve to the same-namespace class before a global one, and imports of the first segment take precedence. This applies inside plain functions, file-scope closures, and top-level code as well as classes. - Files with several
namespaceblocks are analysed correctly. Code after the secondnamespaceline is resolved against that namespace, calls to functions in another block of the same file have their return type, and classes in a globalnamespace { }block keep their global name (PDOis no longerPdo\PDO). - Functions called through an imported namespace are found.
use Core\Ip;followed byIp\isIpAllowed()is no longer reported as undefined. Contributed by @petrovo-as. - Namespaced constants are found however they are written.
Config\GRADES,\App\Config\GRADES,use constimports, and fully-qualified globals like\PHP_EOLnow resolve. - Whole-namespace imports resolve to the right class.
use App\Support;withSupport\Pennow always meansApp\Support\Pen, including in::classstrings passed to other files. - A leading backslash in a
useimport is ignored.use \Foo\Bar;resolves the same asuse Foo\Bar;. - Built-in classes win over vendor polyfills. Built-in classes like
RoundingModealways resolve to PHP's own definition, so enum cases no longer become int constants. Results no longer vary between runs.
Type checking¶
- Nullable values are checked consistently.
?stringandstring|nullare now treated the same, so passing a?stringto astringparameter is reported either way. - Union arguments must fit completely. An argument typed
1|99passed where1|10is expected, orint|stringwhereintis expected, is now reported, and the message names the member that does not fit. - Passing a base type where a subclass is expected is reported. Returning an
Animalfrom a method declared to returnCatis now a type mismatch, unless the code proves the narrower type first. - Wrong generic type arguments are reported.
Box<string>whereBox<int>is expected is now reported for arguments, returns, and properties. - Closures passed to
callable(...)have their return type checked.static fn (int $v): int => $vfor acallable(int): stringparameter is now reported.array_filter()callbacks no longer have to returnbool. - Passing the result of a
voidcall is reported.takesString(logRequest($request))now says the expression returns no value. - A plain function's
@returndocblock is checked. Returns that satisfy the native type but not the docblock (such asarray<string, int>) are now reported, as they already were for methods. - Unsupported native type hints are reported.
resource,integer,boolean,double,real,number,scalar, andlistin a native type hint are now reported as unknown classes. Docblocks can still use them. - Classes named like scalar aliases are classes.
Integer,Boolean,Double,Resource, andRealclasses are no longer read asint,bool,float, orresource. Only the lowercase spelling is the alias. - More string refinements are understood.
non-empty-literal-string,uppercase-string,non-empty-lowercase-string,non-empty-uppercase-string,trait-string, andenum-stringare recognized, string literals satisfylowercase-string,uppercase-string, andcallable-stringwhen they should, andnon-falsy-string(andtruthy-string) is accepted wherenon-empty-stringis expected. interface-stringrequires an interface.SomeClass::classis reported andSomeInterface::classaccepted.- Escaped backslashes in class names are understood.
'App\\Model'matchesApp\Modelforclass-string<T>,interface-string, andmodel-property<Model>. object{prop: Type}shapes accept matching objects. Classes and(object) [...]literals are checked property by property instead of always being rejected.- Unknown PHPDoc pseudo-types are not enforced as classes. Spellings like
pure-callableorliteral-intwiden to the type they refine (ormixed) instead of being reported as missing classes, andkey-of<…>/value-of<…>over a concrete array are evaluated. array-keyis treated asint|string. It is now accepted whereverint|stringis.- Out-of-order array literals are not lists.
[1 => 'x', 0 => 'y']passed wherelist<string>is expected is reported with a message about key order, and hover shows list parameters as written. Stringablerespectsstrict_types. AStringableobject passed to astringparameter is reported underdeclare(strict_types=1).staticand$thistypes of aStringableclass (such asSimpleXMLElement) are accepted otherwise.int / intandint ** intfitintpositions. Theirint|floatresult is accepted where one branch fits, and afloatreaching anintoutsidestrict_typesis accepted as PHP does.self,static, andparentin parameter types resolve to real classes.canChangeTo(self $next)no longer reports "expects self, got State", andparentparameters are now checked.class-string<static>is checked correctly. Sibling subclasses'::classconstants are accepted, unrelated classes are reported, andstaticand$thisnow keep the class they are bound to, shown in hover asstatic(App\Foo). Contributed by @calebdw.- The
objectanditerablerules apply everywhere. Completion filtering and hover know a class is anobjectand aTraversableisiterable, and a nullable value no longer satisfies anobjectoriterableparameter. ?->on anullsubject is not reported. Only a plain->onnullis a crash.isset()in a short-circuit marks the variable defined.isset($x) && $x == 1(common in Blade@if) no longer reports$xas undefined.- By-reference method out-parameters define the variable. Passing an undeclared variable to a by-ref method parameter no longer reports it as undefined. Contributed by @calebdw.
- Diagnostics run inside property hooks. Misspelled variables in
get/sethooks are reported, closures in one-line hooks have their members checked, and extract/inline code actions use the hook's scope. - Deprecation warnings use each variable's own type. Two methods with a same-named parameter of different types no longer share a deprecation result (such as
Request::getreported on an HTTP client call). - Calls with the same text are resolved separately.
self::make()in two classes, or$var->method()with different$vartypes, no longer share argument-count or argument-type results. - Unquoted keys in interpolated strings are keys.
"$data[code]"no longer reportsunknown_class, and"${data}"resolves as the variable. Contributed by @HelgeSverre (#352). @seetags with prose are not reported as missing symbols. A@seetarget that resolves to nothing is now ignored, while PHPUnit's@coversand@usesare still checked. Contributed by @HelgeSverre (#353).@phpstan-typealiases on traits and enums work. They are no longer reported as unknown classes. Contributed by @calebdw.
Laravel¶
- Custom Eloquent builders keep their model.
SiteCertificate::query()->whereKey($id)->firstOrFail()now returnsSiteCertificatewhen the model uses a custom builder, with or without generics and at any depth of builder inheritance. - Custom builders are no longer cached half-built. A builder could get stuck without its virtual members and mixin methods until the file was edited.
- Query chains keep the model through
Query\Buildermethods. Methods reached through@mixin(such aslockForUpdate()) keepBuilder<TModel>, including on relations. Contributed by @calebdw. - Eloquent inference works for aliased models.
use App\Models\Channel as ChannelModelnow typesChannelModel::whereName(...)->firstOrFail()correctly. Contributed by @calebdw. - Builder methods chained on a relation stay on the relation.
$this->belongsTo(Author::class)->withTrashed()returns aBelongsTo, so methods declared: BelongsToare no longer reported. - Queries return the model's own collection class.
get(), relation properties, and relation queries now return the collection set by#[CollectedBy],HasCollection, ornewCollection(). - Models always have a primary key.
$model->idresolves without a migration, honouring$primaryKeyand$keyType. - Framework internals no longer appear as model properties. Methods like
hasManyandbelongsToare no longer offered as relationship properties. - Factories use their declared
$model. A factory's$modelproperty now decides the model formake(),create(), and the rest, through shared base factories too, and a nullablecount()keeps the model-or-collection union. Contributed by @shuvroroy (#364). - Factories keep their model through a shared base factory. Naming conventions now apply to the concrete factory, not the base. Contributed by @shuvroroy (#356).
- Collection re-keying methods rebind keys correctly.
keyBy(),groupBy(), andmapWithKeys()work on collection subclasses that only use@extends,mapWithKeys()binds the array's key rather than the whole array, andstatic fnand unannotated callbacks bind the key from their body. auth()->user()andAuth::user()return the configured model. Completion, hover, navigation, and diagnostics see the concrete model.App::make(),makeWith(), andresolve()return the requested class.App::make(CurrencyHelper::class)->format()now resolves, including when chained directly.- Facade static calls keep concrete return types. Calls through facades resolve via
getFacadeAccessor()and@mixintargets before__callStatic(). Contributed by @calebdw. - Dotted container keys are not truncated.
app('demo.bakery')no longer resolves to a class namedDemo. $this,self::, andstatic::in macro closures resolve to the macro target. Diagnostics, hover, and go-to-definition now agree with completion, and Carbon'sself::this()idiom works.- Macros registered through facades bind
$thisto the facade target.Request::macro()andContext::macro()closures see the class behind the facade. Contributed by @calebdw. - Request accessors return what each call returns.
header(),query(),cookie(),post(),input(), andfile()return the whole bag without a key, the item with one, and dropnullwhen a non-null default is given.file('photo')uses validation rules to tell single uploads from lists, and named arguments (file(key: 'photos')) bind to the right parameter. - Translation helpers return what the key names.
__(),trans(), andLang::get()returnstringfor a single line, an array for a group, andnullwith no key, so{{ __('messages.welcome') }}is no longer reported. url()with a path returnsstring. Contributed by @shuvroroy (#337).view('name')returns the concreteIlluminate\View\View. Components declaringrender(): Viewno longer report a mismatch.- View names with
/resolve.view('redirects/create')and@include('partials/modal')work like the dotted spelling. - Custom view directories are recognized. Views under paths registered in
config/view.phpresolve, complete, and navigate. - Routes under dynamic groups are not reported as unknown. Groups named with a variable (
Route::name($panelId),Route::name('filament.' . $panelId . '.'),Route::group(['as' => $dynamic], …), as Filament does) no longer flag the routes they register, while other route names are still checked. Route::resource()names with a slash are correct.Route::resource('photos/comments', …)registerscomments.show, notphotos.comments.show. Contributed by @shuvroroy (#308).- Laravel Folio page routes are recognized. Named Folio pages complete, hover, navigate, and are no longer reported as unknown routes.
- Service provider changes apply immediately. Container bindings, view and translation paths, routes, config files, and component namespaces registered by a provider update when it is edited or added.
- Non-Laravel projects are left alone. A project's own
config(),route(),view(),__(), ortrans()no longer gets Laravel hover, navigation, or rename. - Virtual property hover and navigation prefer accessors. Go-to-definition on accessor properties lands on the accessor, and legacy mutators appear in hover. Contributed by @calebdw.
Blade templates¶
- Raw echoes work.
{!! $html !!}is now analysed as PHP, and each echo form only closes at its own terminator. - An unterminated echo no longer breaks the rest of the template. A
{{or{!!without a closer only affects its own line. - Inline
@php(…)no longer hides the rest of the template. It ends at its closing parenthesis and updates the template's variables. - Blade comments are just text. Quotes,
*/,@endphp, and commented-out echoes inside{{-- … --}}no longer break the code after them, and an unterminated comment no longer swallows the file. - Blade comments with quotes no longer corrupt the file. Contributed by @krist7599555 (#303).
- All of Laravel's Blade directives are understood.
@can,@lang,@choice,@unset,@js,@vite,@dd,@pushIf,@pushOnce,@hasSection,@json,@dump, and others are now analysed.@class,@style,@checked,@selected,@disabled,@readonly,@required,@stack,@unless,@isset,@empty, and@switch/@casewith class constants no longer cause cascading errors, and<?xml ?>declarations are no longer read as PHP. @use,@inject, and imports in templates work.usestatements in@phpor<?phpblocks and@use(...)import classes for the whole template,@injectdefines its variable, and unused imports are reported.- Raw
<?php ?>tags are passed through. Strings like'@context'inside them are no longer read as directives. - Bound component attributes are analysed as PHP.
:src="../$image"and:$messagesupport hover, navigation, and completion, and their variables count as used. @extendsFirstand@componentFirstare understood. Every candidate layout or component is used.@varannotations apply inside echoes. A standalone/** @var Collection<string, Loaf> $byName */now types{{ $byName->get(...) }}with its generic arguments.- Go-to-definition on
{{agrees with hover. Both now point at the implicite()call. - Completion edits land in the right place. Completions that insert text (view names, string keys,
usestatements) no longer edit a spot several lines below the cursor. analyzereports Blade diagnostics on the right line. They were six lines too high.- Parameter-name inlay hints use the right viewport. Hints in templates no longer go missing or appear for off-screen arguments.
- Renaming a class no longer writes into templates that only receive it. Rename and references ignore PHPantom's generated template header.
- Formatting a
.blade.phpfile does nothing. It is no longer sent through a PHP formatter.
Navigation, references, and rename¶
- Find References matches receivers by type. Receivers reached through properties or calls are now typed, so
$context->getAll()is no longer counted as a reference just because of its spelling. Deprecated methods reached through calls (request()->get(...)) are now reported. - Find References and Rename no longer match unrelated same-named methods. Calls on untyped receivers are no longer matched, and references on an interface method include its implementations. Contributed by @sidux in https://github.com/PHPantom-dev/phpantom_lsp/pull/186.
- References match PHP's case rules. Calls to
HELPER()ornew WIDGET()are found and renamed withhelperandWidget, including through imports. Constants stay case-sensitive. - Constructor references include
new self(),new static(), andnew parent(). - Global functions used from namespaced code are counted. A
helper()call insidenamespace App;now counts as a reference to the globalhelper(). - Same-named symbols are no longer mixed up. Renaming
App\A\VERSIONno longer renamesApp\B\VERSION, renaming a global constant no longer touches a class constant of the same name, and Find References on a constant respectsincludeDeclaration: false. - Constants declared with
define()are navigable. Rename, references, hover, and highlights include the name indefine('FOO', 1),defined('FOO'), andconstant('FOO'). use functionanduse constimports are part of their symbol. They navigate, hover, appear in references, and keep their namespace and aliases when renamed. Globalconst FOO = 1;declarations can start a rename. Contributed by @petrovo-as.- Rename works from a fully-qualified call.
\Support\shout()can now start a rename. - Renaming a promoted constructor property updates
$this->propuses. - Renaming a namespace keeps group
usestatements valid. - Rename no longer edits stale positions. If a file changed since its last parse, rename offers nothing rather than editing the wrong code.
- Method chains no longer use another file's imports. Find References and reference counts no longer mix up same-named classes imported in different files.
- Docblock navigation is more reliable.
{@see}nested in other text or tags, multi-line@methodand@propertytags, and types mixing*with non-ASCII names now navigate correctly. {@see method()}finds the class's own method.- Go-to-definition on an override jumps to what it overrides. This works for methods, properties, constants, and classes with a parent. Contributed by @calebdw.
- Code lens navigation works in every editor. Lenses adapt to what the editor supports instead of guessing by name. Contributed by @calebdw.
- Go-to-implementation is more reliable. Results no longer depend on which files you viewed earlier, interfaces from dependencies (such as Symfony's
HttpKernelInterface) are answered from their packages, abstract classes with a method body and classes inheriting a method are included. Built-in interfaces likeCountablestill search only your project. - Go-to-implementation works when an interface and class share a short name. Contributed by @calebdw.
- Searches during indexing show what they are waiting for. Find References, Rename, and Go to Implementation show "Waiting for workspace index" in their progress.
- Hover no longer depends on indexing timing. Requests on a file that has not been parsed yet parse it immediately.
- Hover is quiet on every declaration. Global functions, top-level
const, and promoted constructor parameters no longer repeat their own signature.
Completion, hover, and code actions¶
- Comments and line breaks no longer break string completion. Completion inside strings (Eloquent columns and relations, request keys, route, config, view, and translation keys,
model-property, and route and Artisan parameters) now works when comments or line breaks sit between the call and the string, and knows when the cursor is outside a string. Escaped quotes in names are read correctly. - String completion no longer scans the whole file. The search for the enclosing call is bounded.
- Completion works after a multi-line closure argument.
->map(function () { … })->now offers members. Contributed by @calebdw. - Member names no longer suggest classes. Typing after
function,const, orcaseno longer offers class names. Contributed by @calebdw. extendsis not offered for enums.- Vendor functions and constants rank as vendor code in completion.
- Generated PHPDoc uses the file's imports. Completions and code actions write
Collection<TKey, TValue>instead of the fully-qualified name. - Override completion writes valid return types.
@return $thisbecomes: static, template types are not used as native hints, and overrides of trait methods restate the docblock types the signature cannot express. - Generated return types understand any expression. Calls, ternaries,
match, property access, and multi-line arrays are resolved instead of becomingmixed. - "Extract function" leaves by-reference writes alone. Selections that write to a by-reference variable are no longer extracted.
- "Promote to constructor property" keeps attributes and docblock. Attributes move to the parameter, and the property's docblock is removed with it.
- "Make constructor final" puts
finalon the constructor. - Semantic highlighting is more accurate. Class constants use the constant color, attributes use the decorator color, and deprecated enum cases are marked. Contributed by @calebdw.
@propertytag names are colored as properties.- Hover lists a one-sided
ifunion in source order. - Short chains after
new X(...)are not broken across lines. From mago 1.44.0.
External tools and configuration¶
- PHPStan is detected more accurately. It runs for Laravel projects with Larastan (or a fork), for any project with a
phpstan.neon,phpstan.neon.dist, orphpstan.dist.neon, and for projects that requirephpstan/phpstandirectly. Avendor/bin/phpstanfrom a transitive dependency is ignored, and plain PHPStan is not run on a Laravel application without Larastan, whether fromvendor/binor$PATH. - PHPStan sees the file's real location. Location-aware rules (such as Larastan's
env()check) no longer fire while you edit. - Project-wide scans no longer overwrite newer results. PHPStan, PHPCS, and Mago scans no longer restore diagnostics to closed files or replace newer per-file results.
- phpcbf is used when the project has a PHPCS config. A
phpcs.xml(or variant) enables it even when PHP_CodeSniffer is a transitive dependency. - Mago formatting wins when configured. A
[formatter]table inmago.tomlkeeps formatting with Mago even when aphpcs.xmlexists. - Mago checks run only when configured.
mago lintruns with a[linter]table andmago analyzewith an[analyzer]table, only whencarthage-software/magois a direct dependency. On Laravel projects,mago analyzeruns only with a Laravel extension configured.[mago]settings in.phpantom.tomloverride this. .phpantom.tomlcompletion knows the Magolintandanalyzekeys.- The macOS global config path is documented correctly. It is
~/.config/phpantom_lsp/.phpantom.toml. - Drupal test base classes resolve.
web/core/tests/is now indexed. Contributed by @syntlyx. analyzeandfixresolve paths from the working directory. A path that matches nothing is now an error.- Linux binaries run on any distribution. They are statically linked, so they work on older glibc and musl systems, and use less memory.
Editor integration and stability¶
- Workspace diagnostics settings apply without a restart. Turning
workspaceon starts a scan, and turning it off stops the scan and clears its results. - Workspace scans finish even when files stall. Workers that time out are replaced, so the rest of the project is still checked.
- Background requests to the editor time out. Diagnostic refresh requests give up after ten seconds.
- Diagnostics stay current. Closing a file mid-computation no longer brings its problems back, results that finish out of order no longer overwrite newer ones, and reopened files no longer show diagnostics from before they were closed.
- Inlay hints update after edits. Contributed by @calebdw.
- Parameter-name inlay hints are correct for partly visible calls.
- Editing during indexing shows current results. Open files keep their edited state while the workspace indexes.
- Workspaces opened through symlinks work.
vendor/is recognized under either path spelling, Blade templates match their view roots, and a newvendor/fromcomposer installis picked up without a restart. Contributed by @shuvroroy. analyzegives the same results every run. Results no longer depend on worker timing or core count, and classes or functions declared in more than one file always resolve to the same declaration, even after the winning file changes.- Functions behind
__DIR__-relativerequire_oncechains are indexed. Calls like\Safe\base64_decode()are found. (#318) - Phar archives without a line break after the stub are read.
- Crashes and hangs are fixed. Very long fluent chains, long
??chains and nested ternaries, deeply nestedarray_map/array_filterclosures, Pest expectation chains through union types,"\x8b"byte escapes, and non-ASCII characters in edited files no longer crash, hang, or stop analysis. - Variable resolution with
globalno longer hangs. - Deeply nested class hierarchies resolve completely. Only real dependency cycles fall back to partial results, and they do so consistently.
- Lower memory use and faster analysis. Assertion narrowing no longer leaks memory, stub indexes are shared instead of copied (roughly halving
analyzetime on large Laravel projects), and the deprecation check parses each file once.
0.9.0 - 2026-07-20¶
Added¶
Diagnostics¶
- Return type mismatches (
type_mismatch_return).returnstatements are checked against the declared return type, including values returned fromvoidfunctions and barereturn;in non-void functions. Generators are skipped. Contributed by @calebdw. - Property type mismatches (
type_mismatch_property). Plain=assignments to typed properties ($this->prop = …,self::$prop = …) are checked against the declared type. Untyped andmixedproperties are not flagged. Contributed by @calebdw. - PSR-4 mismatches and rename-based moves. A file whose namespace or class name does not match its PSR-4 path warns, with quick fixes. Renaming a class from its declaration lets you edit the full name to move it between namespaces, and renaming a namespace moves PSR-4 directories and updates references across the project. Contributed by @calebdw.
- Case-sensitive autoloading. A class reference whose casing differs from the declaration is flagged with a quick fix, catching code that works on macOS or Windows but fails on Linux.
- Ignore rules in
.phpantom.toml.[[diagnostics.ignore]]silences matching diagnostics project-wide by file path (glob), message (regex), and/or diagnostic code, similar to PHPStan'signoreErrors.
Type inference¶
- Conditional return types keep intersections. A
@return ($x is class-string<T> ? T&SomeInterface : SomeInterface)resolves to the class intersected with the interface, somock(Foo::class)and$this->mock(Foo::class)resolve toFoo&MockInterfacewithout spurious mismatches. array_mapinfers its output from the callback. The result reflects what the callback returns, from its return type hint or its body, soarray_map(fn(Item $item): string => $item->id, $items)islist<string>. Fixes #147. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/195.@templateon@methodtags. Virtual methods can declare their own template parameters (@method TVal get<TVal of mixed>(TVal $default)), inferred at call sites like real methods.#[ArrayShape]attribute. Functions annotated with#[ArrayShape([...])], such asparse_url,stat, andpathinfo, give array key completion, hover types, and correct resolution.
Laravel¶
- Macros are real methods. Methods registered with
SomeClass::macro()in your providers or installed packages complete, show their parameters and return type in hover and signature help, chain, and jump to their registration. Facade macros attach to the underlying class, and Find References and rename link registrations and calls. - Macro hover shows origin and inferred return types. Hover labels macro methods as "macro" and, when the closure has no return type, shows the type inferred from its body marked "(inferred)". Regular methods with inferred return types get the same marker. Contributed by @calebdw.
- Custom Eloquent builders. Models using
#[UseEloquentBuilder]forward the builder's methods as static methods, andquery(),newQuery(), andnewModelQuery()return the custom builder. Contributed by @MingJen in https://github.com/PHPantom-dev/phpantom_lsp/pull/118. - Relation and column name completion. Strings passed to
with(),load(),whereHas(), and similar methods complete relationship names (with dot notation for nested relations), andwhere(),orderBy(),select(),pluck(), and similar complete column names. - The authenticated user resolves to your model.
$request->user(),auth()->user(), andAuth::user()resolve to the model configured inconfig/auth.php, including per-guard models likeauth('admin')->user(). When the model could vary at runtime, the result is a union of the candidates. - Container string aliases and global facades.
resolve('blade.compiler')andapp('cache')resolve to the class Laravel binds, and global aliases such as\Appand\DBresolve to their facades. Both tables are read from the Laravel version you have installed, and your own classes still win over an alias of the same name. model-property<T>is recognised. Larastan's pseudo-type no longer triggers "unknown class" and is treated as a string.- Route controller actions. Method-name strings inside
Route::controller(X::class)->group(…)resolve to the controller's methods, with completion, go-to-definition, Find References, rename, hover, and diagnostics. Contributed by @calebdw.
Completion and hover¶
- Completion ranked by where symbols come from. Project code ranks first, then PHP core, then your direct Composer dependencies, then transitive ones. Contributed by @calebdw.
- Imported and same-namespace symbols rank first. Symbols already imported or in the current namespace always appear above others. Contributed by @calebdw.
- Static methods complete after
->. PHP allows calling static methods through an instance, so they are now offered. Static properties remain::only. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/174. - Magic methods complete when implemented.
__invoke,__toString, and other magic methods a class declares are offered (below regular methods) and support go-to-definition. - Package badges in hover. Hover shows where a symbol comes from: 🟢 direct Composer dependency, 🟠 transitive dependency, 🟣 PHP core or extension. Project symbols show no badge. Contributed by @calebdw.
- Correct badges for external path-repository packages. Symlinked path-repository packages outside the workspace show their package badge, while modules inside the workspace still show none. Contributed by @calebdw.
@phpstan-sealedtag. Classes named in the tag count as used imports, and docblock completion offers the tag. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/190.
Editing and navigation¶
- Array-callable navigation. Method names in
[Controller::class, 'method']and[$object, 'method']support go-to-definition, Find References, and rename, which covers Laravel routes likeRoute::get('/', [IndexPageController::class, 'indexPage']). - Array-callable method completion. Typing inside the method-name string of an array callable completes the class's methods, including inherited and trait methods. (thanks @calebdw)
compact()strings are linked to variables. Rename, Find References, and go-to-definition treatcompact('user')as a use of$user. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/159.- Rename updates conditional return types. Renaming a parameter also renames it inside
@return ($param is true ? T : U). Contributed by @calebdw. @param-closure-thisin hover and navigation. Hover, go-to-definition, and go-to-type-definition on$thisinside such a closure use the overridden type, as completion already did. Contributed by @calebdw.
Code actions¶
- Convert arrow function to closure. Rewrites
fn($x) => $x * 2as a closure, capturing outer variables withuse(). Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/191. - Convert to arrow function. Rewrites a single-expression closure as an arrow function when that is safe (PHP 7.4+).
- Convert switch to match. Rewrites a
switchwhose arms all return or assign to the same variable as amatchexpression (PHP 8.0+). - Extract interface. Generates
{ClassName}Interface.phpfrom a class's public methods, keeps relevant@templatetags, and addsimplementsto the class.
Tooling and platform¶
analyzeandfixwork without composer.json. Projects that never adopted Composer (WordPress sites, legacy code) are analysed as plain PHP trees, with a note on stderr so a mistyped--project-rootis not missed.updatecommand.phpantom_lsp updatedownloads the latest release and replaces the binary.--checkreports whether an update exists and--no-confirmsuits CI. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/194.- Indexes stay fresh automatically. Files created, deleted, or edited outside the editor (e.g. by
git checkout) are picked up without a restart, and vendor packages are rescanned whencomposer.jsonorcomposer.lockchanges. - Built-in formatter respects
mago.toml. The fallback formatter applies the[formatter]settings from amago.tomlat the workspace root. Contributed by @enwi in https://github.com/PHPantom-dev/phpantom_lsp/pull/233. - Path-repository packages are part of the project. Local Composer packages installed through path repositories (such as
internachi/modularmodules) have their PSR-4 mappings included. Packages living outsidevendor/are analysed as your own code, the rest as dependencies. Contributed by @calebdw.
Changed¶
- Laravel analysis runs only in Laravel projects. Projects that do not depend on Laravel or an Illuminate component skip all Laravel-specific work and index faster.
- More responsive editing. Parsing and diagnostics run in the background, so completion and hover no longer wait for a full-file parse while you type. Contributed by @MingJen in https://github.com/PHPantom-dev/phpantom_lsp/pull/118.
- Faster repeat completions. Narrowing a completion by typing more characters returns instantly. Contributed by @MingJen in https://github.com/PHPantom-dev/phpantom_lsp/pull/118.
- No first-use delay on Eloquent completions. Common builder types are prepared at startup. Contributed by @MingJen in https://github.com/PHPantom-dev/phpantom_lsp/pull/118.
- Faster code actions. The lightbulb menu appears sooner because all refactorings share one parse of the file.
- Lower memory use while indexing. Files are read through the operating system's page cache instead of being copied into memory.
Fixed¶
Type inference¶
- Array keys written in only one branch are kept. When
if/elsebranches write different keys, the merged shape keeps all of them and marks one-sided keys optional (array{a: int, b?: string}). - Conditional
@returntypes declared on interfaces are evaluated. Calls like Spatie LaravelData'sData::collect([...])resolve to the narrowed branch instead of the broad union, removing false "incompatible with declared type" reports. new ReflectionClass($class)instances. With aclass-string<T>argument,newInstance()andnewInstanceArgs()resolve toT. Docblock types also refine nativeobject|stringhints now.- Return types inferred from a method body stay put. Variables assigned from an un-annotated method (such as a query builder) keep their type across the whole method, removing intermittent "type could not be resolved" warnings.
forloop variables resolve in the condition and update clauses, not only in the body.- Closure parameters keep their declared union type when passed to a method on a union of differently typed collections.
- Callable return templates bind from unannotated closures.
$items->reduce(fn(Decimal $carry, $op) => $carry->add(…), new Decimal('0'))resolves toDecimal. - Dynamic array keys.
$prices[$key]resolves to the union of the shape's value types, and maps written through dynamic keys in loops read back correctly, including nested key paths. \response()->json(...)with a leading backslash resolves like the unqualified call.- Conditional returns with generic
static<...>branches keep their type arguments, soforeach ($items->chunk(500) as $batch)gives$batcha type. - Conditional returns that select
mixedgive the valuemixedso it can be narrowed later (e.g. Laravel'ssession($key)), and out-of-order named arguments now pick the right branch. - Fluent chains through a trait's
return $thiscontinue on the class using the trait, fixing chained test-assertion helpers. @phpstan-require-extendsin traits.$thisinside the trait sees the base class's members even when the trait is viewed on its own.- Parenthesized return types such as
(Foo&object{pivot: Bar})|nullresolve instead of being dropped, fixing$model->relation()->first(). - Indexing a call result inline.
$node->findChildrenOfType(Attr::class)[0]->getParent()andStatus::cases()[0]->valueresolve. array_mapandarray_filtertype their callback parameter from the array's element type, including when the array comes from a call.- Class-string unions through
foreach. Iterating[A::class, B::class]gives each element its class, soapp()->make($r)resolves. - SPL iterators in
foreach. Iterators with a third inner-iterator generic argument and directly constructed ones likenew DirectoryIterator($dir)give the loop variable the right type. - Inline
@varbeforeforeachrefines a broad iterable. The annotation now applies even if the variable wasmixed, a barearray, or a method chain. $thisinside an anonymous class resolves to the anonymous class, not the class containing it.- A namespaced class named like a built-in (e.g.
App\Input\Iterator) resolves to the project's class before the global one, as PHP does. - Conditional types nested inside generics (as on
Collection::groupBy/keyBy) are evaluated at the call site, and branches are chosen from the argument's resolved type. - Assigning an object to a property tracks its type, so
stdClassconfiguration graphs built field by field resolve. Later not-null assertions clear a previously assignednull. - Quoted namespaced class names like
'App\\Models\\User'resolve to the class. - Static calls see return types from parents, interfaces, and framework corrections, as instance calls already did.
- Positional array shapes.
$pair[0]onarray{Foo, Bar}resolves toFoo, and multi-line shapes work too. Class::classis aclass-string<Class>instead of a plainstring.- Tuple elements with a class-string fallback (
$row[2] ?? Fallback::class) stay aclass-string. - Mocks from test helpers keep the mocked class.
$this->mock(Foo::class),partialMock(), andspy()resolve toFoointersected with the Mockery contract. - Mockery
shouldHaveReceived()/shouldHaveBeenCalled()chains such as->with(...)->once()resolve. - Classes implementing
Iteratordirectly type theirforeachvalues, fixingSimpleXMLElement::children(). - The
@operator no longer blocks type resolution ($xml = @simplexml_load_string($content)). - Assignments inside conditions are tracked, including
if (!$item = find())andwhile (is_object($token = $iter->next())). iterator_to_array()returns an array with the iterator's key and value types. Contributed by @calebdw.- Reassigning a variable from its own element (
$value = $value[0]) updates its type. Contributed by @calebdw. - A class named after a pseudo-type, such as PHP 8.4's
BcMath\Number, resolves to the real class. Fixes #170. - Generator closures bind templates.
LazyCollection::make(function() { yield (string) $x; })resolves toLazyCollection<int, string>. Contributed by @calebdw. foreachkeys through a genericIteratorAggregateuse the declared key type. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/216.Generic<T>[],array{…}[], and(…)[]types parse as arrays. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/215.+=on arrays infersarrayinstead ofint|float. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/214.$str[0] = 'z'keeps a string a string. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/209.mixedarray values. Reading a key fromarray<string, mixed>givesmixedinstead of nothing, removing false type mismatches and member warnings. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/210.- Classes defined inside conditional blocks (like Doctrine's per-version
ServiceEntityRepository) keep their parent and generics. Contributed by @MrSrsen in https://github.com/PHPantom-dev/phpantom_lsp/pull/154. - PDO fetch methods follow the fetch mode.
fetch(PDO::FETCH_OBJ)is an object andfetch(PDO::FETCH_ASSOC)an array. Conditional return types keyed on class constants are evaluated in general. - Chained and untyped access. Null-safe chains like
$a->b?->c()resolve, array access on unknown types givesmixed,foreachresolves through distant iterable interfaces, and nested shape narrowing targets the right key. self::inside class attributes resolves against the decorated class.@methodtags override inherited methods, so repositoryfindOneBy()returns the concrete entity.??=keeps the resolved type.- Generics with fewer arguments than parameters.
@extends Collection<User>bindsUserto the value parameter. - Nullable generic returns through inheritance. A repository's
find()returnsEntity|nullinstead ofobject|null. Contributed by @MrSrsen in https://github.com/PHPantom-dev/phpantom_lsp/pull/152. - Conditional
is nullreturn types resolve consistently, and an explicitnullargument picks the null branch. @mixin Foo|Barexposes members from every class in the union.@mixinof an Eloquent model exposes the model's relationships, scopes, casts, and accessors.@mixin Tof a template parameter resolves through its bound, using the most specific bound in the chain.- Method-level templates bound to array types resolve inside the method's own body.
- Generic inference through call arguments.
first(self::getEmailConfigs())binds the template, and closure parameters no longer borrow an outer variable's type. - Templated helpers with a
class-stringdefault resolve when called with no arguments, soapp()resolves likeapp(Foo::class). - Callbacks passed to generic helpers.
Cache::remember($key, $ttl, fn() => new Order())resolves toOrder(and likewiserememberForever,sear,flexible,withoutOverlapping). __benevolent<T>resolves to its inner type.ArrayAccessindexing resolves through the generic annotation oroffsetGet(). A class's own template parameter used in its@implements/@extendsalso resolves correctly.- Self-referencing reassignment. In
$items = implode(', ', array_map($fn, $items)), the$itemson the right uses its previous type. - PHPDoc tags indented with extra spaces after the
*are read like normal tags. - Leading-backslash types like
\Redisresolve to the global class even when a same-named class is imported.
Type narrowing¶
- Assertions on destructured variables.
assertInstanceOf()narrows variables destructured from an untyped array. assertInstanceOfwith a class held in a variable narrows like the inlineWanted::class, including in loop-based data provider patterns.- Narrowing applies to array elements.
assertInstanceOf()andis_a(..., true)narrow$arr['key']and$arr[0]. array<T>|falsekeeps its element type after afalsecheck.- A guard that reassigns one path (
if (!$type instanceof Country) { $type = Country::ADMIN; }) leaves the variable typed afterwards. - Member-existence guards.
property_exists(),method_exists(), andisset($obj->name)prove the member exists inside the guarded branch. assertTrue()/assertFalse()narrow like the equivalentif.assertIs*()/assertIsNot*()narrow like the matchingis_*()checks.class_exists()keepsclass-string<Foo>, sonew $var()still resolves toFoo.- Each
if/elseifbranch narrows a property path independently. instanceofnarrows inside arrow-function bodies across&&.- Type guards trust the runtime check when the static type was incomplete, removing "cannot access property on scalar" warnings.
is_a($value, Class::class, true)andclass_exists()narrow a string toclass-string.is_numeric()on a string narrows tonumeric-string.- A bare truthy check strips
null. - Compound conditions and non-variable subjects. Narrowing carries across
&&and||, applies to property paths, array elements, and inline assignments in conditions, and@phpstan-assertworks on properties and indexed arguments. assertInstanceOf()with an unknown variable class keeps the subject's existing type minusnull.$thisnarrowed byassert()works in top-level test closures (e.g. Pest) and for subclasses in regular methods.- Short-circuit conditions narrow later operands, so
if (!$x instanceof Foo || !$x->method())resolves$x->method(). - Assertion methods narrow however they are called: via
$this->,self::,static::,parent::, or a subclass. The@phpstan-assert =Fooform is parsed too. - Reassignments in an
ifbranch no longer leak into laterelseiforelsebranches. Contributed by @calebdw. - The alternate
if:/endif;syntax narrows like the brace syntax. - Ternary conditions narrow properties and method calls, as in
$this->node instanceof Artifact ? $this->node->getCompilationUnit() : null.
Argument type checks¶
array-keyandint|stringare interchangeable.class-string<A|B>satisfiesclass-string<T>.- A project class sharing a global interface's short name (e.g.
App\Input\Iterator) no longer breaks checks against the global\Iteratoror\Traversable. - Implicitly nullable parameters accept
null, both with a narrowing@paramover a nullable native type and with a= nulldefault. - Class names as string literals satisfy
class-string<Bound>when the class fits, as in$this->expectException('RuntimeException'). - Class constants passed to generic parameters bind the constant's value type, fixing
assertSame(Command::INVALID, $exitCode). - Class names passed to
class-string<T>bind the named class, and bareclass-stringvalues are accepted. - Unions of class names passed to
class-string<T>bind each class and check each against the bound. ::classarguments bound to a bare template no longer report a mismatch, fixingMockery::type(SomeClass::class).- Generic calls no longer borrow types from other call sites with the same text.
- Overloaded built-in functions like
strtr()are only flagged when no signature matches. Contributed by @calebdw. @phpstan-type/@psalm-typealiases are expanded before checking, and imported aliases are not mistaken for classes. Contributed by @calebdw.int<min,max>ranges and refined ints (positive-int,non-negative-int, and so on) are compatible with each other where they should be. Contributed by @calebdw.- Intersections with extra members satisfy narrower intersections, as with
Mockery::mock(Foo::class)passed toFoo&MockInterface. - Resource handles that became objects (
finfo_open,imap_open,pg_connect, and others) return the object type for your PHP version. Fixes #164. - Integer literals satisfy integer ranges, e.g.
usleep(10_000)againstint<0, max>. Contributed by @calebdw. - Literal types.
orderBy('id', 'desc')matches'asc'|'desc', and a provably wrong literal is flagged. Fixes #180. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/191. declare(strict_types=1)is honoured. Coercions PHP disallows under strict types (such as int to string) are flagged. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/193.- Named arguments match parameters by name, fixing conditional returns, missing-argument errors, and by-reference inference with out-of-order named arguments.
- Argument-count false positives. Extra arguments to a class without a constructor,
\mt_rand()with a leading backslash, and immediately invoked returned callables (makeHandler($a, $b)($request)) are checked correctly, including their inlay hints. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/191. - Integer literals and refined ints.
1satisfiespositive-int,0does not, andnon-zero-intandcallable-stringtypes are recognised.
Diagnostics¶
- No PSR-4 warnings for inline test fixtures. Test files that mix top-level calls like Pest's
it(...)with inline classes are skipped. Contributed by @calebdw. - No duplicate native diagnostics in pull-mode editors. Contributed by @calebdw.
compact()with an array argument counts its variables as used, with rename and navigation support.- Variables used only as dynamic member names (
$obj->{$name}()) count as used. - Array literals that only look like callables (
[Foo::class, 'label']used as data) are no longer reported as missing methods. isset()andempty()on unknown properties are no longer flagged.- Results of methods returning
objector?objectallow member access. @see Class#methodreferences resolve the class instead of reporting the whole string as unknown.- Calls handled by
__call/__callStaticare no longer flagged, and their return type keeps the chain going. - By-reference closure captures (
use (&$var)) count as used. stream_bucket_make_writeable()results no longer warn on PHP versions before 8.4.- Diagnostics update after a function signature changes. Other open files calling the function are refreshed on save, and a
didSavehandler helps editors like Neovim. Fixes #123. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/196. - Inherited members are not flagged right after opening a project.
@varannotations no longer leak between functions.- Unused-import dimming lands on the right line when imports share a prefix.
get_defined_vars()counts as using every variable in scope. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/158.
Laravel¶
- Date helpers respect
Date::use().now(),today(), andDatefacade calls resolve to the class your provider configures (e.g.CarbonImmutable), and changes apply during the session. - Values typed as a Laravel contract use their concrete class, so macros and other
__callmethods are not reported missing. - Relations resolve regardless of casing, as Laravel does (
$order->orderproductsfororderProducts()). - Paginated results carry their model.
foreach (User::paginate() as $user)gives$userthe model type. Storage::fake()andpersistentFake()resolve toFilesystemAdapter, so test assertions complete.Conditionable::when()callbacks get the argument's type instead ofnull. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/205.
Editing and navigation¶
- Extract Variable is no longer offered on declarations. Contributed by @calebdw.
- Extract Method handles more selections. Variables read before being assigned are passed in as well as returned, and early returns that use selection-local variables stay inside the new method.
- "Go to Declaration or Usages" lists usages when invoked on a declaration. Fixes #125.
- Edited functions and constants update immediately in completion, hover, and go-to-definition.
- Reloaded files no longer leave ghost classes in completion, implementations, or type hierarchy.
@see self::member()navigates. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/212.- Multi-line grouped imports no longer cause false unknown-class errors, and go-to-definition works on grouped names. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/213.
- Type Hierarchy works in more editors, notably Zed. Contributed by @sidux in https://github.com/PHPantom-dev/phpantom_lsp/pull/179.
- More accurate go-to-definition and rename. Qualified names in
@seeland correctly, and renaming a property selects the whole$name. @phpstan-require-extendsand@phpstan-require-implementsnavigation. Names in these tags support go-to-definition and hover and count as used imports. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/172.- Renaming variables in nested closures and arrow functions updates every occurrence. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/145.
- Variables in dynamic property access (
$message->{$attribute}) count as used and are included in references and rename. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/174. - Member rename stays on its own declaration, leaving unrelated classes, sibling implementations, and unresolvable receivers alone. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/160.
- Find References on a constructor lists
newcalls, attribute usages, andparent::__construct()-style calls, including for subclasses that inherit it. Contributed by @RemcoSmitsDev in https://github.com/PHPantom-dev/phpantom_lsp/pull/155. - Correct columns on lines with multibyte characters for signature help, navigation, named-argument completion, import removal, and the
@phpstan-ignorequick fix. - Document outline ranges cover the whole declaration, as editors expect.
- Type Hierarchy finds the class name when it is on a different line from
class. - Edits on Windows (CRLF) files land correctly for rename, import removal, and the PHPStan return-type quick fix.
- Code lens clicks work in all editors, including Zed, Neovim, and Emacs.
- Promote to constructor property no longer deletes sibling properties declared on the same line.
Completion, hover, and highlighting¶
- Symfony polyfills count as PHP core for completion ranking and hover badges. Contributed by @calebdw.
- Misspelled members are not coloured as valid code. Semantic highlighting checks that a member exists, and existing members get deprecated and static styling. Fixes #187.
- Highlighting no longer goes stale while typing.
namespaceanduselines keep the editor's own colouring in PHP files.throw newandcatchcompletion offer only Throwable classes and rank, shorten, and style names like other class completion.- HTML lists in docblocks render on hover. Contributed by @calebdw.
- No duplicate parentheses when you type
(yourself after a method name instead of accepting the completion.
External tools¶
- External diagnostics are no longer hidden by a native diagnostic on the same line, and diagnostics on a line are ordered most severe first.
- External formatters no longer break the connection. php-cs-fixer and PHP_CodeSniffer could swallow editor input and drop the server. Timeouts now name the tool and can be raised with
[formatting] timeout. Fixes #149. - PHPStan, PHPCS, and Mago run on open and save only, without a debounce delay. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/196.
@phpstan-ignorewith a reason clears the diagnostic immediately. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/196.- Large external tool reports no longer time out.
Indexing¶
- Framework helpers loaded outside Composer autoload are indexed, such as CakePHP's
__(),h(), andenv(). Contributed by @dereuromark in https://github.com/PHPantom-dev/phpantom_lsp/pull/175. - Vendor symbols removed by
composer updatedisappear from completion and navigation.
Performance and stability¶
- Deeply nested code no longer crashes the analyser or editor (e.g. WordPress' bundled getID3 tables).
- Large procedural files no longer stall. The worst observed file went from over two minutes to under a second.
- Self-referencing property assignments no longer crash (
$this->items = array_unique(array_merge($this->items, $more))). - Results are the same on every run. Two timing issues could make types fail to resolve depending on which files were analysed together.
- The editor stays responsive during fast typing. Request bursts are processed concurrently, diagnostics compute in the background, and superseded requests are dropped instead of piling up.
- Large files no longer peg the CPU while typing. Semantic highlighting, the outline, and folding are now effectively instant on large files.
- The first use of a global helper no longer stalls. Helpers like Laravel's
app()are parsed during indexing. - Editing a widely extended base class stays responsive.
- Completion latency stays flat during long typing bursts.
- The server no longer freezes after a burst of cancelled requests.
- No hang on cyclic class inheritance written mid-refactor.
- Returning to a backgrounded editor stays responsive.
- A rare internal parser error no longer breaks a file for the rest of the session.
- Malformed
@methodtags no longer crash requests. - Analysis deadlock fixed between lazy vendor parsing and file-change handling.
- Memory no longer grows as files are opened and closed over a long session.
0.8.0 - 2026-05-14¶
Added¶
Blade templates¶
- Blade template support. Completion, hover, go-to-definition, diagnostics, semantic tokens, and inlay hints work inside
.blade.phpfiles. Contributed by @MingJen in https://github.com/PHPantom-dev/phpantom_lsp/pull/100. - Blade highlighting. Directives, echo delimiters, PHP keywords, casts, comments, and PHPDoc tags in Blade files are coloured.
- View navigation from directives. Go-to-definition on view names in
@include,@extends,@component,@each, and the other include directives opens the template.
Diagnostics¶
- Argument type mismatches. Calls whose argument types are incompatible with the parameter types are flagged.
- Invalid class kinds. Using a class-like where it is guaranteed to fail at runtime is flagged:
newon an abstract class, interface, trait, or enum,extendson a final class,implementswith a non-interface,catchwith a non-Throwable, and similar. - Unused variables. Variables that are assigned but never read are dimmed. Names like
$_or starting with$_are exempt. - Mago diagnostics. Mago lint and analyze results appear in the editor with quick fixes. Configure under
[mago]in.phpantom.toml. - PHPCS diagnostics. PHP_CodeSniffer violations appear in the editor. Configure under
[phpcs]in.phpantom.toml. - Magic property diagnostics. With
report-magic-propertiesunder[diagnostics], classes with__getand declared virtual properties (such as@propertytags or Eloquent columns) report unknown properties instead of allowing everything. - Inline suppression.
// @phpantom-ignore codeon the same line or the line above suppresses a diagnostic. Separate several codes with commas, or leave the code off to suppress everything on that line.
Type inference¶
- Broader type narrowing.
instanceof, type-guard functions, strictin_array(),assert(),@phpstan-assert-if-true/-if-false, and&&/||conditions narrow types in branches, guard clauses,whilebodies, ternaries, andmatch(true)arms. - Return types inferred from method bodies. Methods without a declared return type get one from their
returnstatements. - Closure parameter inference. Untyped closure parameters are inferred from the callable signature they are passed to, including through
static-returning chains and generics. - Generics.
@mixin Tresolves through the template bound,new $var()withclass-string<T>givesT, and SPL collection classes carry template parameters. - Untyped properties are inferred from the constructor. Contributed by @lucasacoutinho in https://github.com/PHPantom-dev/phpantom_lsp/pull/81.
- Binary operator types. Hover and resolution show results for arithmetic operators (
int + floatisfloat,int / intisint|float), and compound assignments update the variable. - Nested array shapes from key assignments.
$b['a']['b'] = 'x'producesarray{a: array{b: string}}, so incrementally built arrays get key completion. - Loop type propagation. Variables assigned late in a loop body are visible from the start of later iterations.
globalvariables resolve to their top-level type.array_reduce,array_sum, andarray_productreturn the expected types.
Laravel¶
- View, route, and translation key navigation. Go to Definition works for
view('...'),route('...'),__('...'),trans(...), andLang::get(...). Contributed by @MingJen in https://github.com/PHPantom-dev/phpantom_lsp/pull/101. - Config and env key navigation. Go to Definition and Find All References work for
config('app.name')andenv('APP_KEY'). Contributed by @MingJen in https://github.com/PHPantom-dev/phpantom_lsp/pull/93.
Editing and navigation¶
- Namespace renaming. Renaming a namespace segment updates declarations, imports, and references across the workspace and moves the PSR-4 directory.
- Linked editing ranges. All occurrences of a variable in its scope can be edited together.
- Find References and rename for PHPDoc virtual members.
@property,@property-read,@property-write, and@methoddeclarations are included alongside their usages, including on nullable and union types. Contributed by @AbyssWaIker in https://github.com/PHPantom-dev/phpantom_lsp/pull/115. - Closure inlay hints. Closures passed to callable parameters show their inferred parameter and return types.
Code actions¶
- Replace FQCN with import. Adds a
usestatement and shortens every occurrence of the name in the file. A second action does this for every fully-qualified name at once, skipping conflicts. - Import all missing classes. Imports every unresolved class in the file at once, leaving ambiguous names for you to choose.
- Context-aware import candidates. Import suggestions only offer interfaces after
implements, traits afteruse, and so on. - Convert to instance variable. Promotes a local variable to a class property and rewrites its uses to
$this->prop(orself::$propin static methods).
Tooling and platform¶
- Laravel Pint formatting. Projects with
laravel/pintinrequire-devformat with Pint automatically. Setpint = "path"orpint = ""under[formatting]to override or disable. - Machine-readable CLI output.
analyzeandfixaccept--format table|github|json, and table output adds GitHub annotations whenGITHUB_ACTIONSis set.
Changed¶
Behaviour¶
- First-class callables use the shared return type logic.
$fn = $obj->method(...)is more accurate for chained calls and generics. - Diagnostics arrive sooner. Editors with pull diagnostics get results on first open without a delay, and external tool updates no longer re-run native diagnostics.
- Mixins and virtual accessors are always fully resolved, so they no longer go missing after edits.
- Consistent diagnostic codes. All codes use
snake_casenoun phrases such asunknown_variable,type_mismatch_argument,argument_count_mismatch,deprecated_usage, andmissing_implementation. Editor filters on the old codes need updating. - Updated embedded phpstorm-stubs.
Performance and memory¶
- Faster and fresher Find References. Searches skip more unnecessary work, still follow aliased imports, and pick up newly added files. Contributed by @MingJen in https://github.com/PHPantom-dev/phpantom_lsp/pull/116.
- Incremental text sync. The editor sends only changed ranges instead of the whole file on every keystroke.
- More responsive requests. Hover, go-to-definition, signature help, code actions, rename, and other requests run on background threads, so slow ones no longer block others.
- Faster analysis on large projects.
- Less duplicate parsing. Threads needing the same vendor file wait for one parse instead of each parsing it.
- Faster recovery after edits. Classes affected by an edit are re-resolved eagerly in dependency order.
- Lower memory use. Vendor and stub files keep less data after parsing, go-to-implementation uses a dedicated index, and variable type tracking uses less memory.
- Faster variable completion and go-to-definition. Both use precomputed data instead of re-parsing. Variable completion also keeps
foreachvariables after the loop, includes@varnames, and dropsunset()variables.
Fixed¶
Completion¶
throw newandcatchcompletion include vendor classes whose Throwable ancestry was not yet known.- No phantom function suggestions from
use functionlines being mistaken for declarations. - No duplicate
use functionwhen the import already exists. - Function import conflicts. If a different function with the same short name is imported, completion inserts the fully-qualified name.
- Standalone
/** @var Type $var */docblocks give the variable member completion and go-to-definition. - Completion in loops and branches. Shape keys added in
ifblocks, variables assigned later in loops, and variables on the right of a reassignment resolve. class-string<T>parameters resolve to the bound class for member access.
Type inference¶
- Mixin members update after edits without restarting the server.
@removedconstants (e.g.MCRYPT_ENCRYPT) are hidden when your PHP version is newer.@vardocblocks with extra tags like@psalm-suppresskeep the right type.foreach@varannotations for both key and value are honoured.foreachover a barearraygivesmixedinstead of nothing.breakinelsecontributes to the type after the loop.- The pre-loop value of a loop target no longer survives after looping over a non-empty literal array.
foreachover::classliteral arrays supports$className::CONSTand$className::method().- Hover on the left side of a reassignment shows the new type.
- Magic
__getand__callreturn their declared types, and__getwithkey-of<T>infers the property's type. SoapClientaccepts any method call.- Literal
true/falsestay precise in template inference. @psalm-methodoverrides@method.- Prefixed tag priority.
@phpstan-parambeats@psalm-param, which beats@param, as in PHPStan and Psalm. self/statichandling.staticsurvives through first-class callables,@var self|nullproperties show the owning class, and trait methods returningselfresolve to the declaring class.- Interface return types are inherited by overriding methods without a return type, with templates substituted.
- Conditional return types with scalar arguments (
$param is string) resolve. - SPL iterators. Decorators like
CachingIteratorandLimitIteratorkeep the wrapped iterator's generics, andnew ArrayIterator($typedArray)infers its types. range()returnslist<string>orlist<int|float>.(object)casts give an object shape matching the operand.$obj[$key] = $valonArrayAccesskeeps the object's type.$variable::method()on a union of class-strings resolves through every class.- Array shape keys with special characters are quoted and escaped in type display.
- Chained calls with complex arguments.
redirect($string . $var)->with(...)resolves toRedirectResponse. - Mixins. Static calls resolve through
@mixin,@methodand@propertytags on mixin classes carry over, and$thisreturns resolve to the consuming class. @methodtags. Colon return syntax, parenthesised returns, and a lonestaticparse correctly, and templates in@methodreturns are substituted through@extendsand@implements.- Immediately invoked first-class callables (
Foo::method(...)()) resolve to the method's return type. @return numericresolves correctly.- Array access on bare
arrayandmixedgivesmixed. - Promoted properties honour inline
/** @var */inside the constructor. - Backed enums.
->valueresolves to the backing type, and@implementsgenerics on enums work. - Inherited class constants resolve through several levels via
self::or a child class. - Type display.
T[]shows asarray<T>,mixed[]asarray, aliases are normalised, andparentreturns show the real class. - Chain assignments like
$a = $b = new Foo()type every variable. - Destructuring with
[...],list(), keys, nesting, and inforeachresolves. - Short class names in
@var,@param, andneware fully qualified before use. $thisno longer resolves inside static methods.- Hover reflects docblock edits in other files immediately.
foreachelement types resolve through nested generic access, static properties, type aliases, and by-reference bindings.- Variables stay visible after a closure argument in a chained call.
@paramannotations no longer leak across sibling methods or closures.- Inherited parameter types carry over to child methods.
- Union-typed method calls keep resolving on their second occurrence.
- Fluent
static/selfchains work in namespaced classes. - Type narrowing.
is_*()guards narrow multi-member unions,instanceofnarrowsmixedandobject,=== nulland== nullnarrow,assert()narrowing persists,isset()/empty()stripnull, properties and shape keys narrow, OR'dinstanceofgives a union, the loop condition's inverse applies after the loop, and branch merges keep nullability.
Generics¶
@template-implementson stub interfaces passes substituted return types to child methods.- Generic
@varannotations substitute class templates into method return types. - Several arguments bound to one template produce a union.
- Nested templates are inferred when a template has a generic bound.
@template K as key-of<TData>resolves to the matching array shape value type.@psalm-if-this-isinfers method templates from the receiver's type.self::classandstatic::classpassed toclass-string<T>resolve to the enclosing class.- Constructor and chained generics. Inherited constructors infer generics through
@extendschains, class templates survive chained calls, templates fall back to their bound, unions of generic types resolve per branch,key-of<T>andvalue-of<T>evaluate, and array literal keys and values are inferred separately. (new Box(new Product()))->get()keeps the constructor's inferred generics.- Closure inlay hints substitute templates from sibling arguments.
Name resolution¶
- Files with several namespaces. Class names, variables, function return types, and static calls resolve against the namespace block they appear in.
- Short names in type hints prefer the owning type's namespace.
- Unqualified class names in namespaced code fall back to the global class when no namespaced one exists.
- Imported classes are not shadowed by global stubs, fixing Laravel facade static calls.
- Same-named classes in other namespaces no longer hide inherited members or count as the same class.
- Transitive interface inheritance is recognised in subtype checks.
- Conditional return types check interface implementations and resolve names through the defining file's imports.
Diagnostics¶
- Fewer unused-variable false positives for
compact(), by-reference out-parameters likepreg_match()'s$matches, andglobalvariables. - Fewer type-mismatch false positives for bare
arrayarguments, properties narrowed withinstanceof, type alias parameters, and shadowed imports. - Functions inside
if (!function_exists(...))no longer produce unresolved-member errors. parent::__construct()with@extendsgenerics no longer reports false type errors.- Vendor functions and constants are indexed at startup, removing false unknown-function errors.
\Closuresatisfiescallable.- Fewer undefined-variable false positives for by-reference parameters, nested array assignments, and names starting with
$this. catchtypes match across namespaces.- Nested
match(true)no longer produces wrong diagnostics. - Lowercase built-in class names count as objects.
- No false "class not found" for global classes loaded through Composer
filesautoloading. - Generic class methods have templates substituted before argument checks.
- No false errors on startup for files opened while indexing.
- Duplicate or stale pull diagnostics no longer appear.
- Non-deterministic results on generics-heavy projects are gone.
Editing and navigation¶
- Renaming a class keeps
self,static, andparent. - Renaming a variable follows closure
usecaptures and arrow functions. - Eloquent
$datesproperties andwhere{Property}()methods support go-to-definition. - Type hierarchy registration respects the editor's capabilities.
- Auto-import formatting. A blank line is added before the first import, and removing unused imports works in braced namespaces.
- Implement methods no longer writes generic docblock syntax as a native return type.
- Laravel scopes. Public methods with
#[Scope]are no longer treated as scopes.
Indexing¶
- Composer
filesautoload packages have their classes discovered. - Class name collisions prefer the file matching PSR-4.
Performance and stability¶
- No deadlock when navigating to an unparsed vendor class.
- No freezes under heavy editor activity. Server-to-client requests can no longer deadlock, and the process exits cleanly if its main loop stops.
- No hangs on deeply nested loops or on
$arr['key'] = f($arr['key'])patterns. - No stack overflows on large files.
- Hover scales linearly on files with many method calls.
analyzeandfixrun at the same speed however they are invoked.
0.7.0 - 2026-04-08¶
Added¶
Type inference¶
@psalm-return,@psalm-param, and@psalm-var. Psalm-prefixed tags are recognised alongside their PHPStan equivalents everywhere types are read.- Type-guard narrowing.
is_array(),is_string(),is_int(),is_float(),is_bool(),is_object(),is_numeric(), andis_callable()narrow unions in branches and after guard clauses, keeping generic element types. - Array value tracking. Arrays built with variable keys in loops keep their element types through
foreach, bracket access, and??, andforeachover generic arrays keeps shape and scalar element types. - Inherited docblock types. A child method without its own
@returnor@paramdocblock inherits the parent's richer types and descriptions. - Templates inferred from closures in both directions. Templates in callable signatures are inferred from a closure's return type and its parameter types.
- Element types from property generics.
$this->cache[$key]->resolves the element type of generic array and collection properties, including through chains. @phpstan-assert-if-true $this. Methods that assert on$thisnarrow the receiver in the matching branch. Contributed by @syntlyx in https://github.com/PHPantom-dev/phpantom_lsp/pull/52.- Standalone
@varfor untyped closure parameters. A@varblock above the usage types the parameter. - Method-level templates inside the method body.
@template T of Builderwith@param T $querygives$querythe bound's members inside the method. - By-reference parameter types for methods and constructors. Passing a variable to a typed
&$paramgives it that type afterwards, now for method, static, and constructor calls too.
Completion and hover¶
- Keyword completion. PHP keywords are suggested by context, such as
returnonly inside functions andbreakonly inside loops. Contributed by @ryangjchandler in https://github.com/PHPantom-dev/phpantom_lsp/pull/43. - Attribute completion. Inside
#[…]only attribute classes valid for the target are offered. new self,new static, andnew parent. Constructor snippets and signature help work for these. Contributed by @RemcoSmitsDev in https://github.com/PHPantom-dev/phpantom_lsp/pull/51.- Hover on parameters at their definition. Shows the resolved type, using the
@paramtype when it is richer. Contributed by @RemcoSmitsDev in https://github.com/PHPantom-dev/phpantom_lsp/pull/68. - Namespace completion from the file path. Typing
namespacein a new file suggests the namespace from its location and PSR-4 mappings, with the most specific one preselected.
Code actions¶
- Refactoring actions. Extract function, method, variable, and constant, inline variable, promote constructor parameter, generate constructor, getters/setters, and property hooks (PHP 8.4+). The lightbulb menu appears instantly because edits are only computed when you pick an action.
- PHPStan quick fixes. Automatic fixes for many PHPStan errors, including mismatched
@return/@param/@vartags, unsafenew static(),#[Override],#[\ReturnTypeWillChange], void return mismatches, unreachable statements, always-trueassert()calls, visibility of overrides, and ternaries that can become??or?->. Each fix clears its diagnostic immediately.
Diagnostics¶
- Undefined variables. Reading a variable with no prior definition in the same scope is flagged, catching use-before-assign bugs. Assignments in branches, by-reference parameters (built-in and your own), superglobals,
isset()/empty(),compact(),extract(), variable variables, and@varannotations are all accounted for. Top-level code is skipped.
Laravel¶
- Eloquent model improvements. Timestamps are typed as
Carbon(respecting$timestamps = falseand custom columns),$datesand$appendsproduce typed properties,where{Column}()methods are available on the model and builder,whereHasclosures get the related model's builder (with dot notation), andwhen()/unless()chains keep their type.
Tooling and platform¶
fixcommand.phpantom_lsp fixapplies automated fixes across a project. Choose rules with--ruleor run all preferred fixers, and use--dry-runto preview. The first rule,unused_import, removes unusedusestatements (contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/54).- Drupal support. Drupal projects are detected and their extra PHP file types (
.module,.install,.theme,.profile,.inc,.engine) are indexed. Contributed by @syntlyx in https://github.com/PHPantom-dev/phpantom_lsp/pull/52. --stdioflag. Accepted and ignored, for clients that pass it by default. Contributed by @markkimsal in https://github.com/PHPantom-dev/phpantom_lsp/pull/67.--tcpflag.phpantom_lsp --tcp 9257listens on a TCP port (or a full address like127.0.0.1:9257) instead of stdin/stdout, serving one connection.- Zed extension setup instructions. Contributed by @daronspence in https://github.com/PHPantom-dev/phpantom_lsp/pull/47.
- SETUP.md improvements. Contributed by @mattsches in https://github.com/PHPantom-dev/phpantom_lsp/pull/61.
Changed¶
- Fewer false-positive diagnostics. Completion, hover, and diagnostics now agree on every variable's type.
@phpstan-ignoreis never the preferred quick fix, so keyboard shortcuts no longer apply it by accident.- Generate PHPDoc infers
@returnfrom the body, e.g.@return list<string>instead of@return array<mixed>. - Faster startup. Stubs load much faster.
- More accurate generics for unions, intersections, array shapes, and deeply nested arguments.
nullis case-insensitive (NULL,Null) everywhere, as in PHP.- Go-to-definition on a declaration returns its own location, so editors can fall back to Find References. Contributed by @lucasacoutinho in https://github.com/PHPantom-dev/phpantom_lsp/pull/76.
Fixed¶
Type inference¶
- Case-insensitive
self,static, andparent, includingparent::method(...)in chained callables. - Intersection types display as intersections in hover, extracted parameters, and generated docblocks instead of unions.
- Return types carry class information so hover, narrowing, and completion need no second pass.
- Generic parameters are kept on catch variables, by-reference and closure parameters, and constructor calls.
- Type guards keep the remaining class when narrowing unions like
Foobar|string|int. $this->propas an argument keeps its generic, nullable, or union type.@phpstan-assertand@psalm-assertwith generics parse the full type.parent::method()as an argument resolves its return type.- Conditional return types show the resolved class in hover, e.g. Symfony's
SerializerInterface::deserialize(). - Null narrowing from
!== null,!is_null(), and truthy checks, in chains, ternaries, andreturnstatements. - Assignments in
if/whileconditions type the variable in the body. - Loop-body assignments are visible throughout the loop.
@varannotations no longer leak across classes and methods.- An inline
@varcast does not affect the right side of the same assignment. foreachover unions containing arrays (User|array<User>) yields the element type.@paramoverrides a native type hint when it is more specific. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/55.- Reassignments in
try/catch/finallyare tracked. instanceofwith an unloadable class treats the variable as unknown instead of keeping the old type.objectandstdClassallow any property, andis_object()narrowsmixedtoobject.- Docblock refinement no longer treats a class like
PointOfInterestas anintrefinement. - Static calls on
class-string<Foo>resolve, includingstatic. self,static, and$thisin return types from other files resolve without needing an import.in_arrayguard clauses no longer wipe out the variable's type.- Chains through
__callkeep their type when__callreturns$this,static, orself. - Generic types in hover for closure parameters, chained
staticreturns, and assignments. - Callable parameters keep the receiver's generics, so
fn(Builder $q)in aBuilder<Product>chain sees the model's scopes. - Nullable
staticreturns resolve to the calling subclass across files. foreachover a variadic parameter gives the element type.- Anonymous class variables resolve through inherited members.
parent::method()assignments get the parent's return type.- Closure parameters inside
switchcases andifconditions are inferred. - No stack overflow when a
foreachvalue shadows the iterated receiver (foreach ($category->getBranch() as $category)). - PHPStan
*wildcards and variance annotations in generic arguments parse correctly. - Interleaved array and property access like
$results[$i]->activities[$id]->extrasresolves. \assert()with a leading backslash narrows.- Array shapes built in branches inside loops are kept through
foreach. - Self-referential reassignments in nested loops no longer cause false "type could not be resolved" errors.
Generics¶
- Nested generics in template binding (
Wrapper<Collection<T>, V>) work. Collection<User>binds to the value parameter.@return TValue|nullkeeps|nullafter substitution.@mixin Tpulls in the concrete type's methods.@propertyand@methodkeep nullable types.- Function-level templates with
array,iterable, andlistwrappers substitute at call sites. - Closure parameters for
array_anyandarray_allare inferred from the array. $this->itemsas a templated argument resolves for binding.- Generic arguments flow through transitive
@extendschains. - Templates as the base of a generic (
T<int>withT=Collection<string>) produceCollection<int>.
Laravel¶
- Eloquent builder and collection types with generics or nullability resolve for scopes, custom collections, and relationships.
- Scope methods returning a bare
Builderkeep the model in the chain. - Scope methods on relationship results appear in completion.
DB::select()returnsarray<int, stdClass>andDB::selectOne()returns?stdClass.- Redis connection methods resolve through the phpredis stubs.
Diagnostics¶
- Static property access (
self::$prop) is not reported as an undefined variable. Contributed by @lucasacoutinho in https://github.com/PHPantom-dev/phpantom_lsp/pull/75. - Files without a namespace get correct "class not found" diagnostics and import actions.
- Broken chains report only the first missing link.
- Vendor files open in the editor get diagnostics.
- PHPStan diagnostics are not hidden by unrelated native ones on the same line.
- Aliased namespace imports used in attributes (
#[Assert\Uuid]) are not reported as unused. - Deprecated classes in
implementsare shown with strikethrough. - Callable types inside unions are parenthesised correctly in hover and completion, e.g.
(Closure(int): string)|Foo.
Editing and navigation¶
- Completion no longer triggers on
<?php. - Update docblock compares types structurally and no longer proposes needless changes.
- No crash generating docblocks on lines with multibyte characters.
@throwson methods resolves imported short names.- Find References for global classes no longer includes same-named namespaced classes.
@seetags in loose docblocks support go-to-definition.- Attributes on properties, constants, parameters, and enum cases support hover and go-to-definition.
- Functions imported with
use functionresolve. - Generate getter uses
isFoo()for?boolproperties.
0.6.0 - 2026-03-26¶
Added¶
Diagnostics¶
- PHPStan diagnostics. PHPStan errors appear inline as you edit, using
vendor/bin/phpstanor$PATH, without blocking native diagnostics. Configure with[phpstan]in.phpantom.toml(command,memory-limit,timeout). Code actions add or remove inline@phpstan-ignorecomments. - Syntax errors appear instantly as you type.
- Missing implementations. Concrete classes that do not implement all required interface or abstract methods are flagged, with the "Implement missing methods" quick fix alongside.
- Argument count. Calls with too few arguments are flagged. Too many arguments is off by default (PHP ignores extras) and can be enabled with
extra-arguments = trueunder[diagnostics].
Completion and hover¶
- Semantic tokens. Type-aware highlighting gives classes, interfaces, enums, traits, methods, properties, parameters, variables, functions, constants, and template parameters distinct colours, with modifiers for declarations, static, readonly, deprecated, and abstract.
- Inlay hints. Parameter names and by-reference markers appear at call sites, except where the argument already makes the parameter obvious.
- PHPDoc generation. Typing
/**above a declaration generates a docblock, adding tags only where they add information beyond the native types, including@extends/@implementsand@throwswith auto-import. - Completion documentation. The completion popup shows the full signature, description, deprecation notice, and parameter details.
- Method commit character. Typing
(on a highlighted method completion accepts it and starts the argument list. - PHPDoc
@varcompletion. Inline@varabove an assignment sorts first and pre-fills the inferred type, and@templateparameters enrich@param,@return, and@varsuggestions.
Editing and navigation¶
- Document symbols. The outline and breadcrumbs show classes, members, and functions with nesting, icons, visibility, and deprecation.
- Workspace symbols. "Go to Symbol in Workspace" searches all indexed files, including vendor classes.
- Type hierarchy. Browse a class's supertypes and subtypes across files.
- Code lens. Methods that override or implement a parent method show a clickable link to the original.
- File rename on class rename. Renaming a class in a PSR-4 file also renames the file, when the file holds a single class and the editor supports it.
- Folding ranges for class and function bodies, closures, arrays, argument lists, control flow, doc comments, and comment groups.
- Selection ranges. Smart expand selection follows the code structure.
- Document links.
require/includepaths are Ctrl+Clickable, including__DIR__anddirname()forms. @seeand@link.@seereferences support go-to-definition, hover shows@linkand@seeURLs, and deprecation messages include@seetargets.- Progress indicators for Go to Implementation and Find References.
Code actions¶
- Update docblock. Brings an out-of-date docblock in line with the signature: adds, removes, and reorders
@paramtags, fixes contradicted types, and drops redundant@return void, keeping refinements and other tags. - Change visibility of a method, property, constant, or promoted parameter.
@throwsfixes. Add missing or remove unnecessary@throwstags from PHPStan diagnostics, with imports and cleanup handled. The diagnostic clears immediately.
Type inference¶
??refinement. If the left side can never be null, the result is just its type. Otherwisenullis removed from the left side and combined with the right.@mixin Foo<T>generics are substituted into the mixin's members, including through inheritance.
Tooling and platform¶
- Formatting. Built-in PER-CS 2.0 formatting works out of the box. Projects with php-cs-fixer or PHP_CodeSniffer in
require-devuse those instead (both can run in sequence). Configure under[formatting]in.phpantom.toml. analyzecommand.phpantom_lsp analyzereports PHPantom's diagnostics for a whole Composer project in a PHPStan-like table, optionally limited to a path. Supports--severityand--no-colour.- Classes in
.phararchives (such asphpstan.phar) are indexed, with no PHP runtime needed. Only uncompressed phars are supported. - PSR-0 autoloading is supported.
- Global config. A
.phpantom.tomlin your config directory (typically~/.config/phpantom_lsp/.phpantom.toml) provides defaults that project configs override. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/39. - Config schema. A bundled JSON schema enables completion and validation of
.phpantom.tomlin supporting editors. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/38.
Changed¶
Completion and hover¶
- More accurate hover. Hover uses the same type resolution as completion, so all narrowing applies and only the type visible in the current branch is shown.
- Cleaner completion labels. Methods show parameter names and their return type (e.g.
setName($name): User), properties and constants show their type, and the class detail line moved to the documentation panel. - Member completion is grouped by kind: constants, then properties, then methods.
- Better class name ranking. Exact matches come first, then prefix matches, then substring matches, with imported and same-namespace classes first within each group.
- Smarter
usecompletion. Same-namespace and already-imported classes are left out. - Deprecation uses the modern
tagsfield. Rendering is unchanged. - Import Class orders candidates by the namespaces you already import.
Behaviour¶
- Pull diagnostics. Editors that support LSP 3.17 pull diagnostics only request them for visible files. Other editors keep the push model.
- Version-aware stub types. Built-in signatures match your project's PHP version, removing false positives from outdated types.
- Leading backslashes no longer break cross-file resolution.
- Embedded stubs track upstream master, picking up fixes and new PHP versions sooner, as PHPStan does.
Fixed¶
Performance¶
- Faster
analyze. Single files are up to 5.8× faster and full projects of ~2 500 files up to 10× faster. - Faster unknown-member diagnostics on large files, up to 7×.
Editing and navigation¶
- Correct positions in files containing emoji or other supplementary Unicode characters.
- Parameter rename and references cover the body and the
@paramtag, from either side. Document highlight is fixed too. - Class rename updates imports, keeping aliases and adding one if the new name collides.
- Trait alias go-to-definition jumps to the trait method.
Diagnostics¶
$this,self::,static::, andparent::inside traits no longer report missing members.- Same-named variables in different methods are resolved independently.
- Namespaced constants like
\PHPStan\PHP_VERSION_IDare not reported as unknown classes. - Diagnostics on the same line are no longer merged. When PHPantom and PHPStan report the same issue, the more precise one is kept.
- More accurate checks. Enums are checked for missing interface methods, scalar access through method chains is detected, and by-reference
@paramtags no longer report unknown classes. - Removed PHP functions and classes (e.g.
mysql_tablename,each) are hidden when your PHP version is newer.
Completion and hover¶
- Hover on union members shows every branch that declares the member, deduplicated when they share a declaring class.
- Hover on inherited members shows the declaring class.
- No double parentheses when completing a call that already has
()after the cursor. - Namespace alias completion (
OA\Rewithuse OpenApi\Attributes as OA) suggests classes. - Catch completion includes Throwable interfaces and abstract exceptions.
- Traits are excluded from type-hint and PHPDoc type completion.
Type inference¶
- Constants. Variables assigned from untyped constants get the type of the constant's value.
- Reassigned parameters use their new type afterwards.
- Variables reassigned inside
foreachare visible after the loop. - Variable-to-variable assignments (
$found = $pen) carry the type. - Self-referencing assignments. In
$request = new Foo(arg: $request->uuid), the inner$requestuses its original type. - Variables inside anonymous classes resolve.
- Closure and arrow function scope follows PHP's rules for variable completion.
- Function return types from other files resolve imported short names, as do parameter and
@throwstypes. - Docblock types only override native types when they are a compatible refinement.
- PHPStan pseudo-types like
non-positive-int,lowercase-string, andcallable-objectare recognised. ?ClassNameandCollection<Item>resolve everywhere.- Generics through transitive interfaces are substituted at every level.
- Templates inside array and object shapes are substituted through
@extends. - Narrowing distinguishes same-named classes from different namespaces.
- Guard clauses no longer affect later
instanceofchecks on the same variable. instanceof self,static, andparentnarrow in all contexts.- Narrowing inside
returnstatements works for&&chains and ternaries. - Inline array access on method returns like
$c->items()[0]->getLabel()resolves. - Array shape access.
$data['name']and chained$result['items'][0]give the right types. - Members of ternary and
??expressions like($a ?: $b)->propertyresolve. - Null-safe method calls resolve their return type, including across files.
(clone $var)->has the same type as$var.self::Active->valueand similar chains resolve.- Inherited methods through deep stub chains are found.
- Interface constants through several parent interfaces are found.
- No crash on
$numbers['price'] = $numbers['price']->add(...).
Laravel¶
morphedByManyrelationships produce virtual and_countproperties.- Native property types are considered when merging virtual properties, so they are not overridden by less specific ones.
0.5.0 - 2026-03-12¶
Added¶
Diagnostics and code actions¶
- Diagnostics. Unknown classes, members, and functions are flagged. An opt-in unresolved member access diagnostic is available via
.phpantom.toml. - Deprecation support.
@deprecatedtags and#[Deprecated]attributes show in hover, completion (strikethrough), and diagnostics. A quick fix rewrites deprecated calls when areplacementtemplate is available. - Implement missing methods. Generates stubs for missing interface or abstract methods.
Editing and navigation¶
- Find References. Find every usage of a class, method, property, constant, function, or variable. Variables are scoped to their function or closure, and members to the class hierarchy.
- Rename. Rename variables, classes, methods, properties, functions, and constants across the workspace.
- Document highlighting. Highlights all occurrences of the symbol under the cursor, distinguishing reads and writes for variables.
- Reverse go-to-implementation. Jump from a concrete method to the interface or abstract declaration, and back.
- Go to Type Definition. Jump from a variable, property, or call to the class of its type. Union types give several locations.
- Docblock navigation. Go-to-definition and hover work on class names inside callable types and array/object shapes.
- Go-to-definition from parameters and properties jumps to the type hint's class.
Type inference¶
@implementsgenerics.@implements Interface<ConcreteType>substitutes types into the interface's members, andforeachover generic iterables resolves keys and values.- Interface template inheritance. Implementing classes inherit templates, conditional return types, and assertions from their interfaces.
- Function-level
@templatein generic return types resolves from call arguments. @phpstan-assertwithclass-string<T>narrows to the passed class.- Property narrowing.
if ($this->prop instanceof Foo)narrows the property in branches and after guard clauses. &&narrowing. The right side of&&sees the left side's narrowing.- Compound negated guards.
if (!$x instanceof A && !$x instanceof B) { return; }narrows$xtoA|B. - Closure scope isolation. Outer variables are only offered inside a closure if captured with
use(). - Pipe operator (PHP 8.5).
$input |> trim(...) |> createDate(...)resolves through the chain. - Array type inference. Shape keys, element access, spreads, and push-style assignments resolve.
new $classStringVarand$classStringVar::method()resolve.- Invoked closures like
(fn(): Foo => ...)()resolve to their return type. - PHP version-aware stubs. The target PHP version is read from
composer.jsonand built-in signatures are filtered to match. @param-closure-this.$thisinside a closure uses the declared type.- By-reference parameter types. A variable passed to a typed
&$varparameter takes that type. iterator_to_array()resolves the element type from the iterator's generics.- Enum case properties.
$case->nameand$case->valueresolve. - Inline
@varon promoted constructor properties overrides the native type.
Tooling and platform¶
- Project configuration.
.phpantom.tomlsets the PHP version, diagnostic toggles, and indexing strategy. Runphpantom --initto create one. - Works without an optimised classmap. PHPantom scans autoload directories itself when
composer dump-autoload -ohas not been run, and supports non-Composer projects by scanning all PHP files. - Monorepo support. Subdirectories that are separate Composer projects are each handled fully.
- Non-Composer functions and constants support completion, go-to-definition, and resolution across files.
- Indexing progress is shown in the editor, per subproject in monorepos.
--versionand--helpflags. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/7.
Changed¶
- Resolution engine rewritten on the AST for more accurate types and navigation.
- Hover redesigned. Short names with a
namespaceline, real default values,@linkURLs, constructor signatures onnew, template details, enum cases, trait members, origin indicators, and deprecation explanations. - Richer signature help. Compact parameters with native types, per-parameter
@paramdescriptions, defaults, and attribute support. - Faster resolution and lower memory usage.
- Parallel workspace indexing across all CPU cores, respecting
.gitignore. - Diagnostics in two phases. Cheap diagnostics (unused imports, deprecation) appear immediately, and expensive ones follow.
- Classmaps and scanning combined. Stale Composer classmaps are supplemented by scanning automatically.
- Automatic stub fetching. The build downloads phpstorm-stubs when missing, so Composer is no longer needed to build PHPantom. Contributed by @calebdw in https://github.com/PHPantom-dev/phpantom_lsp/pull/16.
- Feature comparison table corrected. Phactor capabilities updated in the README. Contributed by @dantleech in https://github.com/PHPantom-dev/phpantom_lsp/pull/10.
Fixed¶
- Cross-file inheritance from global-scope classes imported via
use. - Inherited
@methodand@propertytags across files. - Diagnostics refresh across open files when a class signature changes.
- Variable types resolve through ternary, elvis, null-coalesce, and match assignments.
instanceofnarrowing no longer widens specific types.- Elseif chain narrowing and sequential assert narrowing.
@phpstan-typealiases in foreach,list(), and key types.- False-positive unknown-class warnings on PHPStan type syntax.
- Go-to-implementation no longer produces false positives across namespaces.
__invoke()return type resolution. Works with chaining, foreach, and parenthesized invocations.- Enum
from()andtryFrom()chaining. static/self/$thisin method return types used as iterable expressions.- Mixed
->then::accessor chains. - Inline
(new Foo)->method()chaining. ?->null-safe chain resolution.- Array function resolution for
array_pop,array_filter,array_values,end,array_map. - Inline
@varannotations no longer leak across scopes. - Literal string conditional return types.
- Class constant and enum case assignment resolution.
- Go-to-definition on trait
asalias andinsteadofdeclarations. - Inline array-element function calls resolve correctly in diagnostics.
end($obj->items)->method()no longer produces a false diagnostic. - Double-negated
instanceofnarrowing. - Self-referential array key assignments no longer crash.
0.4.0 - 2026-03-01¶
Added¶
- Signature help. Parameter hints in function/method calls with active parameter highlighting.
- Hover. Type, signature, and docblock in a Markdown popup for all symbol kinds.
- Closure and callable inference. Untyped closure parameters inferred from the callable signature. First-class callable syntax resolves return types.
- Laravel Eloquent. Relationships, scopes, Builder forwarding, factories, custom collections, casts, accessors, mutators,
$attributes, and$visible. - Type narrowing.
in_array()with strict mode, early return guards,instanceofin ternaries and with interfaces. - Anonymous class support.
$this->resolves inside anonymous classes with full inheritance support. - Context-aware completions.
extends,implements,useinside class body, union member sorting, namespace segments, string literal suppression. - Additional resolution. Multi-line chains, nested array keys, generator yield types, conditional return types with template substitution, switch/unset variable tracking.
- Transitive interface go-to-implementation.
Fixed¶
- Visibility filtering, scope isolation, static call chains,
staticreturn type, trait resolution, mixin fluent chains, go-to-definition accuracy, import handling, UTF-8 boundaries, and parenthesized RHS expressions.
0.3.0 - 2026-02-21¶
Added¶
- Go-to-implementation. Interface/abstract class to all concrete implementations.
- Method-level
@template. InfersTfrom the call-site argument. @phpstan-type/@psalm-typealiases and@phpstan-import-type.- Array function type preservation.
array_filter,array_map,array_pop,current, etc. - Early return narrowing. Guard clauses narrow types for subsequent code.
- Callable variable invocation.
$fn()->resolves return types. - Additional resolution. Spread operators, trait
insteadof/as, chained assignments, destructuring, foreach on function returns, type hint completion, try-catch suggestions.
Fixed¶
- PHPDoc type parsing and internal stability fixes.
0.2.0 - 2026-02-18¶
Added¶
- Generics. Class-level
@templatewith@extendssubstitution. Method-levelclass-string<T>. Generic trait substitution. - Array shapes and object shapes. Key completion from literals, incremental assignments, destructuring, element access.
- Foreach type resolution. Generic iterables, array shapes,
Collection<User>,Generator<int, Item>,IteratorAggregate. - Expression type inference. Ternary, null-coalescing, and match expressions.
- Additional completions. Named arguments, variable name suggestions, standalone functions,
define()constants, PHPDoc tags, deprecated members, promoted property types, property chaining,require_oncediscovery, go-to type definition.
Fixed¶
@mixincontext for return types, global class imports, namespace resolution, and aliased class go-to-definition.
0.1.0 - 2026-02-16¶
Initial release.
Added¶
- Completion. Methods, properties, and constants via
->,?->, and::with visibility filtering. - Type resolution. Inheritance merging,
self/static/parent, union types, nullsafe chains. - PHPDoc support.
@return,@property,@method,@mixin, conditional return types, inline@var. - Type narrowing.
instanceof,is_a(),@phpstan-assert. - Enum support. Case completion and
UnitEnum/BackedEnuminterface members. - Go-to-definition. Classes, methods, properties, constants, functions,
newexpressions, variables. - Class name completion with auto-import.
- PSR-4 lazy loading and Composer classmap support.
- Embedded phpstorm-stubs.
- Zed editor extension.