NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
Packagist, #1012 most downloaded on Packagist
Mago is a toolchain for PHP that aims to provide a set of tools to help developers write better code.
Latest stable
1.60.2
Last release 6 days ago
16 Nov 2026
Ships fairly regularly
a new release about every 2 weeks
Nearly every release is documented
notes for 60 of the last 60 stable releases
Nothing withdrawn
no release was ever pulled
2 years old
199 releases · first in 2025
Drag across the ruler to compare, or tap a release to open it.
This release delivers major improvements to the incremental analysis engine for watch mode, new type narrowing capabilities, return type providers for
This release delivers major improvements to the incremental analysis engine for watch mode, new type narrowing capabilities, return type providers for filter_var() / filter_input(), and a large number of bug fixes across the analyzer, linter, formatter, and type system.
is_a() and is_subclass_of() type narrowing: The analyzer now narrows types after calls to is_a() and is_subclass_of(), including support for class-string parameters (#1102)filter_var() and filter_input(): These functions now return precise types based on the filter and flags arguments (e.g., FILTER_VALIDATE_INT returns int|false, FILTER_VALIDATE_EMAIL with FILTER_NULL_ON_FAILURE returns string|null) (#1117)array{valid: true, result: string}|array{valid: false, errorCode: string}), the analyzer now correctly filters out incompatible variants based on the narrowed key type, instead of blindly overwriting all variants. This also works for object property narrowing on union types (#1093)no-isset array access ignore option: The no-isset rule now supports an allow-array-access option, allowing you to flag isset($var) while still permitting isset($array['key']) for array offset checks (#1097, #1120) by @dotdashfunction() { ... }() as error, requiring parentheses around the closure for immediate invocation (#1118)The watch mode (mago analyze --watch) received a complete overhaul of its incremental analysis pipeline:
extend_ref and remove_entries operations allow fine-grained metadata updates without rebuilding the entire codebasenon-existent-class-like errors in watch moderequire-extends/require-implements resolution: Members from @require-extends and @require-implements types are now correctly resolved (#1064, #1070)\true, \false, and \null are now correctly recognized (#1099, #1100) by @kzmshxget_substituted_method function is now correctly applied to the child method when checking method signature compatibility, fixing false positives with generic abstract method inheritanceIteratorIterator) are now preserved during method resolution, fixing incorrect return types (#1106)for ($i = 0; $i < 10; $i++)) are now properly extracted from the AST for type narrowing (#1089)redundant-type-comparison when using count checks or string narrowing in || conditions (#1112)HasAtLeastCount assertions no longer incorrectly set an exact known_count on lists with unknown count, preventing false unreachable-code reports (#1104)@var docblock type: The analyzer now prefers @var docblock types over inferred types for class constants, fixing cases where properly typed array values stayed as mixed (#1090, #1094)never as bottom type: never is now correctly treated as a subtype of all types in extends_or_implements checks (#1107, #1109) by @kzmshx@psalm-type / @phpstan-type alias names are now pre-registered before parsing, so aliases can reference each other regardless of declaration order (#1116)impossible-condition false positives when comparing strtolower()/strtoupper() results with literals containing non-alphabetic characters (spaces, digits, etc.) (#1086)no-redundant-use whole-word matching: Docblock reference checking now uses whole-word matching instead of substring matching, so use Config; is correctly flagged as unused even when ConfigUsage appears in a docblock (#1078)inline-variable-return with by-reference assignment: The fixer no longer inlines assignments of by-reference expressions, which would produce invalid PHP (#1114)prefer-early-continue with non-block body: Fixed the fixer for cases where the loop body is a single statement without braces (#1085) by @chrisopperwall-qz$foo(...)) are no longer incorrectly treated as breaking expressions, fixing misformatted output (#1091)explode() return type: Corrected to properly return list<string> instead of non-empty-list<string> when the separator could be empty (#1095)array_slice() return type: Now correctly preserves string keys in the return type (#1096)ldap_sasl_bind() stubs: Updated all arguments except the first to be nullable (#1098)bin2hex() stubs: Improved type definition (#1101) by @veeweeIncrementalAnalysisService encapsulating the full incremental analysis pipeline for watch mode and LSPCodebaseDiff::between() for metadata comparison and mark_safe_symbols() for incremental analysisA huge thank you to everyone who contributed code to this release:
Thank you to everyone who reported issues and requested features that shaped this release:
Full Changelog: https://github.com/carthage-software/mago/compare/1.7.0...1.8.0
Your coding agent can read these notes before it upgrades. Set up the MCP server →
This release introduces new type system features, improved type inference for built-in functions, a new linter rule, and numerous bug fixes for the an
This release introduces new type system features, improved type inference for built-in functions, a new linter rule, and numerous bug fixes for the analyzer, formatter, and type system. A significant internal effort also went into reducing dependencies and binary size.
uppercase-string and non-empty-uppercase-string types: Full support for these PHPDoc types in type syntax, codex, and analyzer. This resolves cascading errors when these types were previously unrecognized (#1057)Return type providers for min() and max(): These functions now return precise types based on their arguments (#1074)
array_filter() callback parameter type inference: The analyzer now respects the mode argument (ARRAY_FILTER_USE_KEY, ARRAY_FILTER_USE_BOTH) when inferring closure parameter types, fixing incorrect mixed inference for callback parameters (#1031)
Switch statement fallthrough analysis: The analyzer now correctly recognizes that non-terminating code paths in a case block fall through to the next case. A case with a conditional return followed by a case that always returns is no longer flagged as missing-return-statement (#1081)
no-redundant-isset rule: New rule that detects redundant arguments in isset() calls. For example, in isset($a, $a['key'], $a['key']['nested']), the first two checks are redundant because isset on a nested access implicitly checks all parent accesses (#769)--ignore-baseline flag: New flag for lint and analyze commands that temporarily ignores the baseline file, useful for reviewing and fixing baselined issues (#1076)reqwest, openssl, num_cpus, strum_macros, derivative, strsim, bitflags, async-walkdir), replacing them with standard library equivalents or manual implementations. reqwest/openssl were replaced with ureq/rustls for a significantly smaller and faster-compiling binary[$this, 'method']) and string callbacks ('ClassName::method') are now correctly tracked as used (#1069, #1044)@psalm-require-extends support in traits: Methods, properties, and class constants inherited from required parent classes via @psalm-require-extends or @phpstan-require-extends are now properly resolved in traits, eliminating false non-existent-property, non-existent-class-constant, and unknown-ref errors (#1064, #1068, #1070)invalid-return-type errors (#1061)PHP_INT_SIZE, PHP_INT_MAX, and PHP_FLOAT_DIG now use platform-aware range/union types instead of host-specific literal values. PHP_INT_SIZE > 4 is no longer flagged as a redundant comparison (#1084)align-assignment-like is enabled, the alignment context from consecutive variable assignments no longer leaks into nested array key-value pairs (#1082)prefer-first-class-callable with reference captures: Skip suggesting first-class callable syntax when the callee variable is captured by reference in a closure's use clause, as the two forms have different semantics (#1067, #1063) by @kzmshxarray_walk generics: Fixed generic templates for array_walk to properly infer callback parameter types (#1066, #1045) by @ddanielouarray_splice type precision: Improved type definitions for array_splice to preserve list<T> types and correctly handle non-array replacement arguments (#1072, #1080)usort, uasort, uksort, etc.) to preserve non-empty array types (#1083)reqwest + openssl with ureq + rustls in self-update modulenum_cpus with std::thread::available_parallelism()bitflags with manual bit flag implementationsderivative, strum_macros, strsim, and async-walkdir dependenciesA huge thank you to everyone who contributed code to this release:
Thank you to everyone who reported issues and requested features that shaped this release:
Full Changelog: https://github.com/carthage-software/mago/compare/1.6.0...1.7.0
Removed deprecated rules: The deprecated constant-type, no-boolean-literal-comparison, parameter-type, property-type, and return-type linter rules hav…
This release brings new analyzer checks for class design enforcement, new linter rules for file organization, path-scoped ignore/exclusion support, formatter fixes, and numerous bug fixes across the board.
class-must-be-final check: New opt-in enforce-class-finality setting that reports classes not declared final, abstract, or annotated with @api/@psalm-api when they have no children (#1054)
[analyzer]
enforce-class-finality = true
missing-api-or-internal check: New opt-in require-api-or-internal setting that requires abstract classes, interfaces, and traits to have @api or @internal annotations, forcing projects to declare extensibility intent (#1055)
[analyzer]
require-api-or-internal = true
Path-scoped ignore entries: The ignore option now supports scoping ignored codes to specific paths (#1037, #1043)
[analyzer]
ignore = [
"mixed-argument",
{ code = "missing-return-type", in = "tests/" },
{ code = "unused-parameter", in = ["tests/", "src/Generated/"] },
]
Literal types for enum properties: Enum name and value properties now return literal types instead of generic string/int, enabling more precise type inference (#1035, #952) by @veewee
Severity level in code-count format: The code-count reporting format now includes the severity level for each issue code (#987)
file-name rule: New rule that enforces file names match the class/interface/enum/trait they contain (#1049)
single-class-per-file rule: New rule that enforces each file contains at most one class-like declaration
Per-rule path exclusions: Linter rules now support path-based exclusions, allowing you to disable specific rules for specific directories (#1037)
[linter.rules]
no-isset = { exclude = ["src/Legacy/"] }
no-isset and readable-literal enabled by default: These rules are now enabled out of the box
Removed deprecated rules: The deprecated constant-type, no-boolean-literal-comparison, parameter-type, property-type, and return-type linter rules have been removed — their functionality has been moved to the analyzer
inline-empty-function-braces and inline-empty-method-braces now default to true, matching the PER Coding Style specification (#1053)--only rules: The --only flag now accepts multiple comma-separated rules (#1046)foldhash replaces ahash: Switched to foldhash for faster hashing across the codebaseArc<T> replaces Box<T> in codex: Improves cloning performance for shared metadataswitch statements no longer incorrectly narrow variable types, preventing false redundant null-check warnings (#1038)@var docblocks: Imported type aliases are now correctly expanded in @var docblock annotations (#1029, #1030)extends/implements (#1040)FORCE_COLOR support: The FORCE_COLOR environment variable is now respected in reporting output (#1042)readable-literal false positive on floats: Fixed the rule triggering on float literals like 123.45 where neither side of the decimal benefits from separators, producing a no-op suggestionarray_walk generics: Added generic templates to array_walk for proper type inference (#1045)curl_multi_exec signature: Corrected the signature of curl_multi_exec (#1033)setcookie duplicate: Removed duplicate definition for setcookie that only accepted the old syntax (#1032)atty dependencytime from 0.3.46 to 0.3.47 (#1039) by @dependabotA huge thank you to everyone who contributed code to this release:
Thank you to everyone who reported issues and requested features that shaped this release:
Full Changelog: https://github.com/carthage-software/mago/compare/1.5.0...1.6.0
This release brings PSR-11 container support, custom help text for disallowed functions, and several important bug fixes for type narrowing and linter
This release brings PSR-11 container support, custom help text for disallowed functions, and several important bug fixes for type narrowing and linter false positives.
PSR-11 container support: New psr-container plugin that infers types from class-string arguments when calling ContainerInterface::get(). This eliminates mixed-method-access and mixed-argument errors when using PSR-11 service containers (#1015) by @Noojuno
[analyzer]
plugins = ["psr-container"]
Custom help text for disallowed functions: The disallowed-functions rule now supports custom help messages per function or extension. Entries can be simple strings or objects with name and optional help fields (#1024)
[linter.rules]
disallowed-functions = {
functions = [
"eval",
{ name = "error_log", help = "Use MyLogger instead." },
],
extensions = [
"curl",
{ name = "ffi", help = "FFI is disabled for security reasons." },
],
}
Nullsafe operator type narrowing: Fixed incorrect type narrowing in the false branch of if statements using nullsafe operators (?->). Previously, the variable was incorrectly narrowed to null in the else branch. Now if ($user?->isAuthorized()) correctly preserves the original type in the else branch, matching the semantics of $user !== null && $user->isAuthorized() (#1025)
Redundant instanceof detection: Fixed false positive for undefined variables when a variable is assigned in exhaustive if/elseif branches over a union type. The analyzer now correctly detects redundant instanceof checks and tracks variable assignments across all branches (#1026)
prefer-first-class-callable: Skip suggesting first-class callable syntax for runtime-dependent call targets where conversion would change evaluation semantics. This includes method chains (adminUrlGenerator()->generateUrl()), nullsafe calls ($obj?->method()), and dynamic method names ($obj->$method()) (#1027, #1020) by @kzmshxbytes from 1.11.0 to 1.11.1 (#1023) by @dependabotA huge thank you to everyone who contributed code to this release:
Thank you to everyone who reported issues that were fixed in this release:
Full Changelog: https://github.com/carthage-software/mago/compare/1.4.1...1.5.0
Patch release with two bug fixes.
Patch release with two bug fixes.
(void) cast expressions (#1021)JSON_THROW_ON_ERROR detection: Detect JSON_THROW_ON_ERROR flag when combined with other flags using bitwise OR (e.g., JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT) (#1022, #886) by @kzmshxFull Changelog: https://github.com/carthage-software/mago/compare/1.4.0...1.4.1
This release brings significant improvements including method call assertions, a new parser configuration section, fault-tolerant parsing, new linter
This release brings significant improvements including method call assertions, a new parser configuration section, fault-tolerant parsing, new linter fixers, and numerous bug fixes addressing false positives in the analyzer. A massive thank you to everyone who contributed!
@assert-if-true and @assert-if-false docblock assertions on method calls, enabling type narrowing based on method return values (#763)no-redundant-string-concat: Automatically fix redundant string concatenations (#1018) by @dotdashno-trailing-space: Automatically remove trailing whitespace (#1017) by @dotdashbraced-string-interpolation: Automatically add braces around interpolated variables (#1013) by @dotdashmax-statements-before-early-continue option to control when the early-continue rule recommends refactoring (#979, #975) by @dotdash[parser] configuration section: Configure parser-level settings including the ability to disable short opening tag recognition via enable-short-tags = false (#841)FORCE_COLOR environment variable: Force colored output even when piping to files or other commands, taking precedence over NO_COLOR (#1012)ascii_lowercase_atom for common casesprivate(set) in child classes (#985)!empty() check (#973)$_SERVER array shape typo: Fix arvc typo to argc in $_SERVER array shape (#990, #972) by @kzmshxsort-class-methods is enabled, comments now move with their associated methods instead of stacking on the first method (#994)space-around-assignment-in-declare to false in Pint preset to match actual Pint behavior (#1011, #974) by @kzmshxinline-variable-return when closure has reference capture (#997, #981) by @kzmshxend, prev, next, reset with @param-out annotations to preserve array type after by-reference calls (#980, #984)array_unshift signature: Preserve list type in @param-out annotation (#970)pathinfo() where the second argument is optional (#969).gitattributes to exclude more files from export (#1008) by @shyimconsts to typos dictionaryA huge thank you to everyone who contributed code to this release:
Thank you to everyone who reported issues that were fixed in this release:
Full Changelog: https://github.com/carthage-software/mago/compare/1.3.0...1.4.0
This release comes with significant performance improvements, bug fixes addressing false positives, and new formatter options. A massive thank you to
This release comes with significant performance improvements, bug fixes addressing false positives, and new formatter options. A massive thank you to everyone who reported issues and contributed!
always-next-line brace style: New always-next-line value for brace style options (method-brace-style, function-brace-style, closure-brace-style, classlike-brace-style, control-brace-style) that always places the opening brace on the next line, even for multiline signatures (#897)This release includes substantial performance optimizations:
AtomSet instead of Vec for clause key lookupsHashMap for boundsAtomMap and ControlActionSet bitfield for faster block context cloningHashMap instead of IndexMap for constants and enum_cases where ordering is not requiredIndexMap for overridden_method_ids to ensure deterministic ordering (#907)static return types correctly in method chains across inheritance (#880, #949, #964)mixed (#946, #947)isset() type narrowing (#900)&& operator (#912)never to stringNO_COLOR environment variable and --colors never flag globally across all output (#922)&$param) in @param tags (#955)null and bool values in sprintf, printf, sscanf, and fscanf functions (#953)$_FILES superglobal as potentially empty (#954)Vec to IndexMap with GenericTemplate struct for cleaner codeu32 bitflagsA huge thank you to everyone who contributed code to this release:
Thank you to everyone who reported issues that were fixed in this release:
Full Changelog: https://github.com/carthage-software/mago/compare/1.2.2...1.3.0
The 1.2.1 release binaries failed to build due to a breaking change in cargo-pgo v0.2.10 (released January 24, 2026) which changed how arguments are p…
Patch release to fix binary builds broken by upstream dependency.
The 1.2.1 release binaries failed to build due to a breaking change in cargo-pgo v0.2.10 (released January 24, 2026) which changed how arguments are passed to the optimize command. This release contains no code changes-only a CI workflow fix.
Full Changelog: https://github.com/carthage-software/mago/compare/1.2.1...1.2.2
Turns out releasing at 4 AM after a break isn't the best idea. Sorry about that!
Turns out releasing at 4 AM after a break isn't the best idea. Sorry about that!
Y::create(...) now correctly returns Y instead of the parent class X)Full Changelog: https://github.com/carthage-software/mago/compare/1.2.0...1.2.1
First of all, I want to apologize for the delayed release — I've been on a break the past couple of weeks. Thank you all for your patience! 🙏
First of all, I want to apologize for the delayed release — I've been on a break the past couple of weeks. Thank you all for your patience! 🙏
This release brings significant improvements to the analyzer, including unused code detection, better type inference, and numerous bug fixes addressing false positives reported by the community.
no-isset rule: New rule to prevent usage of the isset construct (#924) by @djschillingno-redundant-use rule (#921)lowercase-type-hint and lowercase-keyword: New fixers for these linter rules (#911) by @dotdashmago.dist.toml and mago.dist.json files (#903) by @Bleksakinline-abstract-property-hooks setting for PER-CS 4.10 compliant property hook formatting (#919)$foo->bar(...)) and partial function application ($foo->bar(?, ?)) to prevent false positive unused method errorsparent:: calls: Treat parent:: calls as instance calls for magic methods (#916)#[Override] for @method: Don't suggest #[Override] attribute for @method pseudo-methods (#914)never RHS: Suppress false positive for possibly-undefined array index in null coalesce with never RHS (#923)DatePeriod type parameters: Specify IteratorAggregate type parameters for DatePeriod (#932)strpos offset type: strpos supports negative offsets, replace int<0, max> with int (#890) by @Bleksakno-insecure-comparison: Ignore CLI flags like --password in the rule (#917)NO_COLOR environment variable: Respect NO_COLOR env variable (#922)FormatterPreset config deserialization (#879) by @magic-akariA huge thank you to everyone who contributed to this release:
Thank you to everyone who reported issues that were fixed in this release:
More improvements and features coming soon! Stay tuned.
Full Changelog: https://github.com/carthage-software/mago/compare/1.1.0...1.2.0
Note: This release includes a breaking change in the formatter's default behavior for heredoc indentation.
This release includes a significant number of new features, bug fixes, and improvements across the formatter, analyzer, linter, and codex.
Note: This release includes a breaking change in the formatter's default behavior for heredoc indentation.
indent-heredoc to false in your configuration.psr-12, per-cs, drupal, etc.) (#839)following-clause-on-newline option to place else, catch, and finally on a new line (#860)uppercase-literal-keyword option for uppercase TRUE, FALSE, NULL literals (Drupal style) (#857)empty-line-before-class-like-close setting for empty line before closing brace (#855)newline-after-class-like-opening-brace setting (#853)@mixin docblock annotationsexplicit-nullable-param lint (#847)$x['foo'] ?? null)invalid-extend reporting when a readonly class extends a non-readonly class (#873)static and $this type handling and expansion in template contextsarray_filter type narrowing to support first-class callables and string literalsclone for PHP 8.3+self::TypeAlias in @extends)init flownon-empty-mixed type syntaxFull Changelog: https://github.com/carthage-software/mago/compare/1.0.3...1.1.0
This release includes several bug fixes across the formatter, linter, analyzer, and prelude, along with new features.
This release includes several bug fixes across the formatter, linter, analyzer, and prelude, along with new features.
As always, we'd love to hear from you! Please keep filing bug reports and feature requests - your feedback is what drives Mago forward.
Our team will be taking a well-deserved break over the holidays. Merry Christmas to those who celebrate, and happy holidays to everyone! We'll be back in full swing in the new year, but rest assured we'll still be keeping an eye out for any critical issues.
null|array no longer causes formatting oscillation)wrap! macro to prevent node stack corruptionprefer-arrow-function and prefer-static-closure rulesprefer-anonymous-migration rule to correctly flag named migration classesno-redundant-use ruleClosure::bind scope changes for protected member access analysisgetimagesizefromstring second parameter as optionalno-assign-in-argument rule to detect assignments in call arguments (#821)Closure::bind scope changes, allowing accurate analysis of protected/private member access within rebound closuresif let to fix unnecessary_unwrap warning (#781)Full Changelog: https://github.com/carthage-software/mago/compare/1.0.2...1.0.3
Fixed idempotent formatting issues with comments inside binary operations
inline-empty-classlike-braces default to true per PER-CS specification@extends validationarray_map now correctly returns non-empty-array when given a non-empty-array (#815)current() return typenull-pipe is not a valid value for null-type-hint setting (#814)source-code.tar.gz and source-code.zip archives containing full source codeFull Changelog: https://github.com/carthage-software/mago/compare/1.0.1...1.0.2
This release includes various bug fixes across the analyzer, formatter, codex, and prelude.
This release includes various bug fixes across the analyzer, formatter, codex, and prelude.
@var docblock handling when used on top of an assignmentvoid as falsycurrent function return typeDirectoryIterator::isDot methodFull Changelog: https://github.com/carthage-software/mago/compare/1.0.0...1.0.1
| Security | Potential security vulnerabilities |
After over 1,000 commits, 13 release candidates, 34 betas, and 12 alphas, we are thrilled to announce Mago 1.0.0 - the first stable release of the Mago PHP toolchain.
Mago is a comprehensive PHP toolchain written in Rust that combines a linter, formatter, and static analyzer into a single, blazingly fast binary. Whether you're working on a small project or a massive codebase with millions of lines, Mago delivers consistent, reliable feedback in seconds.
If you last used Mago at version 0.26.1, the tool has evolved dramatically:
@throws validationThe linter includes 135 rules organized into 9 categories:
| Category | Focus |
|---|---|
| Best Practices | Idiomatic PHP patterns and conventions |
| Clarity | Code readability and expressiveness |
| Consistency | Uniform coding style across your codebase |
| Correctness | Logic errors and potential bugs |
| Deprecation | Outdated patterns and deprecated features |
| Maintainability | Long-term code health |
| Redundancy | Unnecessary or duplicate code |
| Safety | Type safety and null handling |
| Security | Potential security vulnerabilities |
Many rules include automatic fixes that can be applied with mago lint --fix.
The formatter produces clean, consistent code following PER Coding Style with over 50 customization options:
Run mago format --check in CI to ensure consistent formatting across your team.
The analyzer performs deep static analysis with:
check-throws) to ensure exceptions are caught or documentedThe analyzer supports plugins for library-specific type inference:
| Plugin | Description |
|---|---|
stdlib |
PHP built-in functions (enabled by default) |
psl |
azjezz/psl type providers |
flow-php |
flow-php/etl type providers |
Enable plugins in your mago.toml:
[analyzer]
plugins = ["psl", "flow-php"]
More plugins coming soon for Symfony, Laravel, Doctrine, and PHPUnit.
Guard enforces architectural rules and dependency boundaries across your codebase:
[guard.perimeter]
# Defines the architectural layers from core to infrastructure.
layering = [
"CarthageSoftware\\Domain",
"CarthageSoftware\\Application",
"CarthageSoftware\\UI",
"CarthageSoftware\\Infrastructure"
]
# Creates reusable aliases for groups of namespaces.
[guard.perimeter.layers]
core = ["@native", "Psl\\**"]
psr = ["Psr\\**"]
framework = ["Symfony\\**", "Doctrine\\**"]
# Defines dependency rules for specific namespaces.
[[guard.perimeter.rules]]
namespace = "CarthageSoftware\\Domain"
permit = ["@layer:core"]
[[guard.perimeter.rules]]
namespace = "CarthageSoftware\\Application"
permit = ["@layer:core", "@layer:psr"]
[[guard.perimeter.rules]]
namespace = "CarthageSoftware\\Infrastructure"
permit = ["@layer:core", "@layer:psr", "@layer:framework"]
[[guard.perimeter.rules]]
namespace = "CarthageSoftware\\Tests"
permit = ["@all"]
Run mago guard to check for architectural violations. This helps maintain clean architecture by:
Mago 1.0.0 is production ready and actively used by companies analyzing millions of lines of PHP code daily. The toolchain has been battle-tested across diverse codebases, from legacy monoliths to modern frameworks.
Introducing static analysis to an existing codebase can be overwhelming. Mago supports baselines that let you:
mago analyze --generate-baselinemago analyze --baseline baseline.tomlWe are committed to fixing reported issues quickly. Most bug reports are addressed within 1-2 days. While false positives may occasionally occur, we treat them as high-priority bugs.
This release includes the following changes since the last release candidate:
properties-of<T> now correctly expands to array<non-empty-string, mixed> for generic object constraintspossibly-null-array-index warnings for keyed arrays with null key coercionarray and iterable types now handled correctlyexplicit-octal ruleMago is significantly faster than traditional PHP-based tools. On the wordpress-develop codebase:
| Analyzer | Time |
|---|---|
| Mago | 3.88s |
| Psalm | 45.53s |
| PHPStan | 120.35s |
Mago analyzes the entire WordPress codebase in under 4 seconds—12x faster than Psalm and 31x faster than PHPStan.
For full benchmarks including the linter and formatter, see mago.carthage.software/benchmarks.
curl --proto '=https' --tlsv1.2 -sSfO https://carthage.software/mago.sh && bash mago.sh
brew install carthage-software/tap/mago
composer require --dev carthage-software/mago
cargo install mago
For more installation options, see the Installation Guide.
Initialize Mago in your project:
mago init
Run the linter:
mago lint
Run the analyzer:
mago analyze
Format your code:
mago format
For comprehensive documentation, visit mago.carthage.software.
The 1.0.0 release is just the beginning. Our roadmap includes:
Mago would not exist without the pioneering work of:
Mago is developed and maintained by Carthage Software. For companies interested in supporting Mago or needing expert PHP tooling consulting, get in touch.
Thank you to our sponsors who make this work possible:
Become a sponsor to support Mago's continued development.
Thank you to everyone in our Discord community who reported bugs, suggested features, and provided feedback. Your contributions have been invaluable in shaping Mago into what it is today.
Full Changelog: 0.26.1...1.0.0
This release introduces an internal plugin system for the analyzer, adds new linter rules, and continues the focus on minimizing false positives.
This release introduces an internal plugin system for the analyzer, adds new linter rules, and continues the focus on minimizing false positives.
UnitEnum::cases() return type provider: Properly infers the return type of cases() on unit enumsinstanceof-stringable rule: Suggests using $x instanceof Stringable instead of the verbose is_object($x) && method_exists($x, '__toString') patternparent:: now works in traits with @require-extends annotation (#732)__toString method can be cast to string without errors?->)$this handling corrected in type expansionFull Changelog: https://github.com/carthage-software/mago/compare/1.0.0-rc.12...1.0.0-rc.13
This release continues our focus on reducing false positives, improving generic type handling, and enhancing PHP 8.4+ property hooks support.
This release continues our focus on reducing false positives, improving generic type handling, and enhancing PHP 8.4+ property hooks support.
fmt --staged command for formatting only staged files, along with a pre-commit hooks guide for seamless CI integration.=== '', === 0, === 1.5, === true, === false) after type narrowing in OR conditions.unimplemented-abstract-property-hook when a concrete class inherits the hook implementation from a parent class.is_callable() Narrowing: Added support for is_callable() type narrowing on array callables with class-string elements (e.g., array{class-string<Foo>, 'method'}).isset() on Open Array Shapes: Fixed false positives when using isset() checks on open array shapes with mixed values.stdClass: Allowed dynamic property access on stdClass without triggering errors.@method Tag Parsing: Fixed parsing of @method tags with leading whitespace./** @lang SQL */) were incorrectly moved after the opening identifier, resulting in invalid code.empty_line_after_opening_tag default behavior consistent across configurations.Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-rc.11...1.0.0-rc.12
This release focuses on reducing false positives, improving type system accuracy, performance optimizations, and introducing new linter rules.
This release focuses on reducing false positives, improving type system accuracy, performance optimizations, and introducing new linter rules.
New property-name rule (#703)
Added a new linter rule to enforce consistent property naming conventions across your codebase.
New use-specific-assertions rule
Introduced a new rule that encourages using specific assertion methods (e.g., assertTrue, assertNull) instead of generic assertEquals/assertSame with literal values for better clarity and intent.
function_exists(), method_exists(), property_exists(), and defined(). This eliminates false positives when conditionally using symbols after checking their existence.Fixed false positives for class-string comparisons and static variable initialization Resolved issues where the analyzer incorrectly flagged valid code involving class-string type comparisons and static variable initialization patterns.
Fixed false positive for count() comparison on non-empty-list
The analyzer no longer incorrectly reports issues when comparing the count of a non-empty-list with integer values.
Fixed list type preservation when narrowing with is_array()
Using is_array() on a union type containing a list no longer incorrectly loses the list type information.
Fixed interface method resolution for __callStatic
The analyzer now only reports interface implementation issues when resolving actual methods, not when resolving magic __callStatic calls.
Fixed invalid array access assignment value checking Improved detection of invalid values being assigned through array access expressions.
@method tag with static return type
The docblock parser now correctly handles @method tags that specify static as their return type.strict-assertions rule less strict
The strict-assertions rule has been adjusted to reduce noise while still catching problematic assertion patterns.Optimized type combiner Significant performance improvements to the type combination logic, reducing analysis time for codebases with complex type operations.
Lowered analysis thresholds Adjusted internal thresholds for formula complexity and algebra operations to improve analysis speed on large codebases without sacrificing accuracy.
Early return optimization for pragma collection Added early return when no pragmas are present, avoiding unnecessary processing.
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-rc.10...1.0.0-rc.11
This release focuses on reducing false positives across multiple analysis scenarios, improving type system accuracy, and enhancing PHP compatibility.
This release focuses on reducing false positives across multiple analysis scenarios, improving type system accuracy, and enhancing PHP compatibility.
Foo can be Bar at runtime (#707)$value === [] on non-null or mixed types (#701)unimplemented-abstract-property-hook incorrectly reported on interfacesIterator key/value types from key() and current() method return typesfloat and array-key in string concatenation with improved __toString trait detection$_COOKIE superglobalself type resolution to use intersection with @require-implements/@require-extends constraintscall_user_func and sprintf stubs with Stringable supportFull Changelog: https://github.com/carthage-software/mago/compare/1.0.0-rc.9...1.0.0-rc.10
Fixed stack overflow when analyzing projects with complex generic types - Analysis of certain codebases (including tempest-framework) would crash with
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-rc.8...1.0.0-rc.9
This release brings significant analyzer enhancements including full property hooks support, unused template parameter detection, and improved type as
This release brings significant analyzer enhancements including full property hooks support, unused template parameter detection, and improved type assertion analysis. The linter gains a new variable-name rule, and the prelude is updated with MongoDB, Redis, and URI extension stubs.
@assert annotations, helping catch logical errors in assertion docblocks-) operator, catching type errors earlyproperties-of<T> Support: The properties-of<T> type is now fully implemented with proper visibility filtering (public-properties-of<T>, protected-properties-of<T>, private-properties-of<T>)variable-name Rule: Enforces consistent variable naming conventions (snake_case or camelCase) with configurable options for parameter checking and promoted property exclusion (#695)!is_string() on an int) are now reported as warnings instead of impossible errorsfclose() stubliteral-named-argument rule now skips the first argument by default, as it's typically self-explanatory. A new check-first-argument option preserves the original behavior (#694)Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-rc.7...1.0.0-rc.8
Added support for int-mask<1, 2, 3> and int-mask-of types
Type System
int-mask<1, 2, 3> and int-mask-of<Foo::*> typesliteral-float typeAnalyzer
Playground
Formatter
Analyzer
Codex
Linter
literal-named-argument rule to ignore variadic functionsPrelude
ReflectionNamedType::getName method (#673)CLI
init command to match the latest configuration schemaWASM
Performance
CLI
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-rc.6...1.0.0-rc.7
Use constant REQUEST_TIME for $_SERVER to ensure deterministic error messages for baseline matching
REQUEST_TIME for $_SERVER to ensure deterministic error messages for baseline matching (#669)$_SESSION superglobal as possibly undefined (#670)ArrayAccess implementations (#671)possibly_undefined when checking redundant nullsafe operator (#672)missing-magic-method (#667)int|float instead of mixed (#664)|> to be parenthesized (#662)(file, code, message) tuple with occurrence counts, making baselines stable even when line numbers shift. The previous strict format (exact line matching) remains available via configuration. (#492)Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-rc.5...1.0.0-rc.6
Semicolon as a switch case separator is now deprecated for PHP >= 8.5
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-rc.4...1.0.0-rc.5
Partial Function Application (RFC)
Partial Function Application (RFC)
Mago now fully supports PHP 8.6's Partial Function Application RFC, enabling first-class callable creation using placeholder syntax. You can use positional (?), named (name: ?), and variadic (...) placeholders to create closures from existing functions and methods, with full type inference and validation to ensure type safety across your partial applications.
PHP Version Support
Looking Ahead to PHP 8.6
This release demonstrates Mago's unique capability to stay ahead of the PHP ecosystem. While PHP 8.6 won't be released for another year and the Partial Function Application RFC hasn't even been merged into PHP yet, Mago already provides full support for this feature. By controlling our entire stack, from parser to analyzer, we can implement and validate upcoming PHP features much faster than traditional tools, giving developers early access to write future-proof code with confidence.
Linter
no-redundant-yield-from rule to identify unnecessary yield from expressions that can be simplifiedAnalyzer
@method annotations in child classes for return type refinementself, static, and $this keywords#[Override] attribute issues before PHP 8.3numeric and array-key typesarray_merge() result computation when using empty arrays as argumentsCodex
Database
Linter
no-redundant-math rule for float division operationssensitive-parameter rule for PHP versions below 8.2$thisFormatter
instanceof binary operationsDocblock
Collector
Installation
Syntax
Expression, Statement, and Node enums as #[non_exhaustive] for future compatibilityFull Changelog: https://github.com/carthage-software/mago/compare/1.0.0-rc.3...1.0.0-rc.4
`--retain-code` option: Filter reported issues by specific codes (e.g., --retain-code semantics --retain-code invalid-argument). Unlike --only in lint
--retain-code option: Filter reported issues by specific codes (e.g., --retain-code semantics --retain-code invalid-argument). Unlike --only in lint, this runs all checks but filters the
outputisset() checks on nested array access@var docblocks on promoted constructor propertiesself types: Support self parameter types in closures defined in trait methodsarray_merge() type inferencestrpos === false → !str_contains). Only provide fixes for strict equality (=== and !==) to prevent unsafe replacements. Report warnings for loose equality (==, !=, <>) due to strpos returning 0 at position 0 (closes #494)Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-rc.2...1.0.0-rc.3
Type alias imports: Fixed false positive "class not found" errors when importing type aliases from classes that haven't been populated yet #624
Bug Fixes
new ArrayIterator([]) or similar empty containers to typed iterable parameters #626Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-rc.1...1.0.0-rc.2
⚠️ BREAKING CHANGE: Configuration files are no longer merged from multiple locations.
1.0.0-rc.1 🎉We're excited to announce Mago 1.0.0-rc.1, a major milestone toward the 1.0.0 release! This release candidate includes significant performance improvements, comprehensive type system enhancements, and numerous bug fixes based on community feedback.
@type, @psalm-type, and @phpstan-typeMago now has complete support for type aliases in docblocks:
/**
* @type UserId = positive-int
* @psalm-type UserData = array{id: UserId, name: string}
*/
class User {
/** @param UserData $data */
public function __construct(private array $data) {}
}
/**
* @import-type UserData from User
*/
class UserService {
/** @param !User::UserData $data */ // Reference without importing
public function process(array $data): void {}
}
Features:
@type, @psalm-type, and @phpstan-type tags@import-type (with as keyword support for renaming)!ClassName::AliasName syntaxself and static referencesAdded support for T[K] (index access) type syntax for more precise array typing.
Added support for literal-int type to distinguish between literal integer values (e.g., 42) and general integer types.
@inheritDoc SupportFull support for @inheritDoc tag in docblocks, including inline {@inheritDoc} syntax.
Mago now validates class inheritance, interface implementation, and trait composition following PHP's type system rules and the Liskov Substitution Principle.
Validates:
New Issue Codes (20+):
IncompatibleConstantAccess, IncompatibleConstantOverride, IncompatibleConstantTypeIncompatibleParameterCount, IncompatibleParameterName, IncompatibleParameterTypeIncompatiblePropertyAccess, IncompatiblePropertyDefault, IncompatiblePropertyOverride, IncompatiblePropertyTypeIncompatibleReturnType, IncompatibleVisibilityMissingOverrideAttributeValidates trait constant override rules - prevents classes from overriding trait constants with different values.
The analyzer can now automatically fix various redundancy issues with mago analyze --fix --fmt.
json_encode()Special handler recognizes the JSON_THROW_ON_ERROR flag and returns string instead of string|false.
array_merge and Psl\Dict\mergeSpecial type inference for array_merge and PSL's Psl\Dict\merge with proper key/value tracking.
array_filter with Callback AssertionBetter type narrowing when using array_filter with callback assertions like is_int(...).
compact() HandlerPreserves type information when using compact() - knows the exact keys and their types.
$x = $x;)$thisThe following rules are now enabled by default:
no-redundant-use - Detects unused importsno-variable-variable - Warns about variable variablesno-redundant-readonly - Detects redundant readonly modifierssensitive-parameter - Validates sensitive parameter handlingAdded support for SARIF (Static Analysis Results Interchange Format) for integration with GitHub Code Scanning, security dashboards, and CI/CD pipelines.
mago analyze --reporting-format sarif > results.sarif
Major improvements to baseline management:
fail_on_out_of_sync_baseline parametermago-reporting crate for reusabilityAnnotation messages now included in GitHub, GitLab, and Checkstyle formats with column information and detailed context.
Generate JSON schema for configuration validation with IDE autocomplete:
mago config --schema > mago-schema.json
Configuration files can now be written in YAML or JSON in addition to TOML.
Search Order: workspace directory → XDG_CONFIG_HOME → home directory
Format Priority: TOML > YAML > JSON
Generate shell completions for Bash, Zsh, Fish, and PowerShell:
mago generate-completions bash > /etc/bash_completion.d/mago
Installation script now supports version selection:
curl -sSL https://mago.sh/install | bash -s -- --version=1.0.0-rc.1
New --watch flag for continuous analysis during development:
mago analyze --watch
Watches your filesystem and automatically re-analyzes only the files that changed and their dependencies. Powered by intelligent incremental analysis internally - dramatically faster than re-analyzing the entire codebase!
Re-use pre-allocated types for better memory usage and performance.
⚠️ BREAKING CHANGE: Configuration files are no longer merged from multiple locations.
What Changed:
Migration: Consolidate your configuration into a single file if you previously relied on merging.
Several linter rules are now enabled by default. You may see new warnings/errors for:
The new strict inheritance validation may report issues in class hierarchies that were previously undetected.
never typeisset()"$array[class]")static in constant expressions (matches PHP behavior)neverMajor architectural refactoring introducing the orchestrator crate - separates CLI from core analysis engine.
Updated to Rust 1.91 for latest language features and performance improvements.
Improved SPL (Standard PHP Library) stubs with better type definitions.
mago config --schema > mago-schema.jsonThank you to all contributors who reported issues, provided feedback, and helped make this release possible! 💝
Special thanks to our community contributors who submitted pull requests:
This release closes 67 GitHub issues:
#623, #622, #621, #620, #619, #618, #617, #616, #615, #614, #612, #610, #609, #608, #607, #606, #604, #603, #602, #601, #600, #599, #598, #597, #596, #595, #593, #592, #591, #590, #589, #588, #587, #586, #584, #583, #582, #580, #576, #575, #566, #542, #533, #526, #525, #519, #496, #486, #452, #447, #425, #424, #423, #420, #404, #398, #385, #378, #373, #353, #350, #340, #302, #265, #233, #202, #201, #74
curl -sSL https://mago.sh/install | bash
curl -sSL https://mago.sh/install | bash -s -- --version=1.0.0-rc.1
mago self-update
This release candidate represents a significant milestone toward version 1.0.0. The architectural refactoring, comprehensive type system improvements, and performance enhancements set a solid foundation for future development. 🚀
LSP support has been intentionally delayed to version 2.0.0 to ensure Mago 1.0.0 delivers a solid, stable foundation without rushing critical features. Read more about this decision: Why Mago 1.0.0 Won't Ship With an LSP
Upcoming in Future Releases:
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.34...1.0.0-rc.1
This is a focused patch release that addresses a key correctness issue in the analyzer's handling of generic types, particularly when working with ::c
1.0.0-beta.34This is a focused patch release that addresses a key correctness issue in the analyzer's handling of generic types, particularly when working with ::class strings.
The analyzer's type comparator has been improved to be smarter about generic types.
Previously, comparing a "raw" generic class (e.g., BoxImpl) against a version with explicit type parameters (e.g., BoxImpl<mixed>) would fail. This commonly caused false positive errors when passing a literal class string like BoxImpl::class to a function expecting class-string<BoxImpl<mixed>>.
The analyzer now correctly understands that when type parameters are missing from a generic class, they should be treated as their default template constraints (which is usually mixed). This makes the comparison logic more robust and aligns it with developer expectations.
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.33...1.0.0-beta.34
The following linter rules are now deprecated in favor of the more powerful analyzer-based checks. They will be removed in a future release.
1.0.0-beta.33This release introduces a powerful and highly-requested set of new analysis features for detecting missing type hints. We've also made the analyzer significantly smarter at handling superglobals and boolean comparisons, landed a raft of critical bug fixes that improve type-narrowing, and shipped a major performance optimization for large projects.
The analyzer can now detect and report missing type hints for constants, properties, parameters, and return types, helping you improve the strictness and reliability of your codebase. This new analyzer-based feature is more powerful and accurate than the old linter rules it replaces.
missing-constant-type, missing-property-type, missing-parameter-type, and missing-return-type issues.mago.toml:
check-missing-type-hints: The main switch to enable/disable this feature.check-closure-missing-type-hints: Toggles checks specifically for closures.check-arrow-function-missing-type-hints: Toggles checks specifically for arrow functions.$_ (a common convention for unused variables).__construct) and destructors (__destruct) for return type checks.A significant performance bottleneck in the type reconciliation logic for sealed classes has been eliminated. The impact of this optimization is most dramatic on very large projects that make extensive use of sealed type hierarchies with many instanceof checks.
When analyzing a large codebase like the Symfony framework, this release is over 6x faster than the previous version.
Symfony Benchmarks:
Benchmark 1: mago-32 analyze --reporting-format count
Time (mean ± σ): 8.894 s ± 0.326 s [User: 11.398 s, System: 4.137 s]
Range (min … max): 8.509 s … 9.508 s 10 runs
Warning: Ignoring non-zero exit code.
Benchmark 2: mago-33 analyze --reporting-format count
Time (mean ± σ): 1.455 s ± 0.071 s [User: 7.138 s, System: 1.680 s]
Range (min … max): 1.351 s … 1.536 s 10 runs
Warning: Ignoring non-zero exit code.
Summary
mago-33 analyze --reporting-format count ran
6.11 ± 0.37 times faster than mago-32 analyze --reporting-format count
For smaller projects or codebases that do not heavily rely on this specific pattern (like PSL or WordPress), the performance will remain similar to the already fast previous versions. This targeted optimization ensures that Mago scales efficiently, even for the most complex architectural patterns, without introducing regressions elsewhere.
Psl Benchmarks:
Benchmark 1: mago-32 --config config/mago.toml analyze
Time (mean ± σ): 233.6 ms ± 13.4 ms [User: 612.0 ms, System: 400.4 ms]
Range (min … max): 224.4 ms … 271.2 ms 10 runs
Warning: Statistical outliers were detected. Consider re-running this benchmark on a quiet system without any interferences from other programs. It might help to use the '--warmup' or '--prepare' options.
Benchmark 2: mago-33 --config config/mago.toml analyze
Time (mean ± σ): 224.4 ms ± 8.4 ms [User: 631.4 ms, System: 402.6 ms]
Range (min … max): 214.0 ms … 237.2 ms 10 runs
Summary
mago-33 --config config/mago.toml analyze ran
1.04 ± 0.07 times faster than mago-32 --config config/mago.toml analyze
WordPress Benchmarks:
Benchmark 1: mago-32 analyze --reporting-format count
Time (mean ± σ): 3.853 s ± 0.147 s [User: 15.298 s, System: 0.752 s]
Range (min … max): 3.467 s … 3.946 s 10 runs
Warning: Ignoring non-zero exit code.
Warning: Statistical outliers were detected. Consider re-running this benchmark on a quiet system without any interferences from other programs. It might help to use the '--warmup' or '--prepare' options.
Benchmark 2: mago-33 analyze --reporting-format count
Time (mean ± σ): 3.832 s ± 0.200 s [User: 16.264 s, System: 0.758 s]
Range (min … max): 3.488 s … 3.991 s 10 runs
Warning: Ignoring non-zero exit code.
Summary
mago-33 analyze --reporting-format count ran
1.01 ± 0.07 times faster than mago-32 analyze --reporting-format count
The analyzer is now much smarter about superglobals ($_GET, $_SERVER, etc.). They are now pre-registered in all scopes by default, which resolves a major pain point where type narrowing on superglobal array keys (e.g., in if (isset($_GET['user']))) would fail. You can control this with the new register-super-globals setting.
The no-boolean-literal-comparison check has been moved from the linter to the analyzer. Because the analyzer is type-aware, it can now avoid false positives by understanding the context. For example, it will correctly allow a check like $foo === false if the type of $foo is a union that includes false (e.g., false|string).
static return types, detecting callables in ::class strings, and handling chained null checks. (#511, #549, #577)isset() was not correctly narrowing a nullable array key to non-null within a conditional block. (#573)The following linter rules are now deprecated in favor of the more powerful analyzer-based checks. They will be removed in a future release.
constant-typeparameter-typeproperty-typereturn-typeno-boolean-literal-comparisonFull Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.32...1.0.0-beta.33
This is a massive stability and correctness release for the analyzer. We've significantly improved its ability to understand complex conditional logic
1.0.0-beta.32This is a massive stability and correctness release for the analyzer. We've significantly improved its ability to understand complex conditional logic and type hierarchies, leading to smarter type narrowing and the elimination of many false positives. As we get closer to the first release candidate, these foundational fixes are crucial for providing a reliable analysis experience.
A huge thank you to @baukevdw for their contribution to this release!
The analyzer's ability to narrow types within if and match statements has been made much more powerful and correct.
Sealed Types (@psalm-inheritors) (#537): The analyzer now understands the @psalm-inheritors tag. When you check and negate an instanceof on a sealed interface or class, it will correctly infer the remaining possible types from the inheritor list. This is a huge improvement for codebases using algebraic data types.
Null Coalesce Assertions (??) (#531): The analyzer now correctly understands that a check like ($var ?? null) !== null guarantees that $var is both set and not null, eliminating false "possibly undefined" errors inside the if block.
Assignments in && Conditions (#538): Fixed a bug where a variable assigned on the right-hand side of an && in a condition was incorrectly reported as undefined.
Multiple isset() Assertions (#564): The analyzer now correctly processes all assertions in conditions with multiple isset() calls, like isset($a, $b) or isset($a) && isset($b).
Several fundamental bugs in the type system and reconciler have been fixed to improve soundness.
!isset is null, not never (#570): A !isset() check now correctly reconciles the variable's type to null (or possibly_undefined), not never. This fixes a major bug that caused the analyzer to incorrectly mark valid code paths as unreachable.
Differentiated Null Array Access (#568): The analyzer now distinguishes between accessing an array on a variable that is definitely null (a NullArrayAccess error) versus one that is possibly null (a PossiblyNullArrayAccess warning). This provides more precise and appropriately severe feedback.
array vs Traversable (#563): A soundness issue was fixed where array was incorrectly treated as a subtype of Traversable. The type comparator now correctly distinguishes between them, fixing incorrect type narrowing for instanceof checks.
strict-list-index-checks Option (#565): A new configuration option, strict-list-index-checks (default: false), has been added. When enabled, it enforces that array list indices must be non-negative-int, providing stricter validation for users who want it.Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.31...1.0.0-beta.32
This is a hotfix release that addresses a critical panic in the mago ast command, ensuring stability when processing files with multi-byte characters.
1.0.0-beta.31This is a hotfix release that addresses a critical panic in the mago ast command, ensuring stability when processing files with multi-byte characters.
A critical bug has been fixed that could cause the mago ast --tokens command to panic and crash when processing files containing multi-byte UTF-8 characters (e.g., emojis or CJK characters).
The crash occurred because the table-formatting logic was incorrectly truncating token values by byte length, which is unsafe for UTF-8 strings and can lead to a panic if a slice ends in the middle of a character.
The logic has been rewritten to be fully UTF-8 aware. It now correctly measures the visual width of characters and truncates strings on proper character boundaries. This not only resolves the panic but also ensures the token table aligns correctly for all character sets.
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.30...1.0.0-beta.31
This release introduces `mago guard`, a powerful new tool for enforcing architectural rules in your PHP projects. We've also added a new list-files ut
1.0.0-beta.30This release introduces mago guard, a powerful new tool for enforcing architectural rules in your PHP projects. We've also added a new list-files utility command and landed several key correctness fixes for the analyzer and formatter as we get closer to our first release candidate.
A huge thank you to our community contributors for this release: @dotdash and @bendavies!
mago guardWe are thrilled to introduce mago guard, a high-performance tool for defining and enforcing architectural boundaries directly within your project. It combines the power of dependency validation (like deptrac) and structural rule-checking (like arkitect) into a single, cohesive command.
The goal of guard is to provide instant feedback on architectural violations, helping you maintain a clean and scalable codebase. Its concepts are designed to be intuitive, using a "Fortress" metaphor:
BoundaryBreach.final, all Repositories implement an interface). A violation is a StructuralFlaw.All rules are defined declaratively in your mago.toml file.
Read the full documentation for mago guard here.
list-files Command (#552): A new mago list-files command has been added. This utility prints a list of all files that would be processed by the lint, format, analyze, or guard commands, based on your configuration. It's an excellent tool for debugging your [source] paths and exclusion rules. (Thanks, @dotdash!)email in array{email?: string}) would not produce a nullable type. Accessing such a key now correctly results in a T|null type. (#557)isset() check on a possibly undefined array key was not correctly narrowing the type to null. (Thanks, @bendavies!)list, which correctly converts the type to a keyed array. (#559)catch blocks with multiple exception types that exceeded the print width were not being correctly broken onto multiple lines. (#556)prefer-arrow-function rule will no longer suggest converting a closure to an arrow function if the closure imports variables by reference, which is unsafe. (#554)Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.28...1.0.0-beta.30
Nothing published for this version
This release is packed with significant correctness fixes for the analyzer, focusing on advanced type system features like enums, generics, and traits
1.0.0-beta.28This release is packed with significant correctness fixes for the analyzer, focusing on advanced type system features like enums, generics, and traits. The formatter also receives critical bug fixes for operator precedence and brace placement.
A massive thank you to our community for driving this release forward with their contributions: @bendavies, @yankewei, @dragosprotung, and @muro3r!
The analyzer's accuracy has been substantially improved with fixes for several fundamental type system and control flow bugs.
Enum Method Analysis (#546): The analyzer now synthetically generates full metadata for built-in enum methods (from, tryFrom, cases). This provides precise parameter and return types, enabling correct analysis of first-class callables like Category::from(...).
Template & Type System Correctness:
extends or implements on an interface or class are now correctly resolved and applied.enum_exists Narrowing (#541): Fixed a bug where intersecting a specific class with a generic type would incorrectly discard the more specific class information, improving type narrowing after checks like enum_exists().count() Assertions (#540): Assertions from count() calls (e.g., if (count($arr) > 0)) are now correctly applied, allowing the analyzer to understand that an array is non-empty.Flow PHP Types Support (#527): Added special handling for the flow-php/types library, including support for its type_structure() function. (Thanks, @bendavies!)
Imagick Support (#543): The analyzer now has stubs for Imagick class constants, improving type safety when working with the Imagick extension. (Thanks, @dragosprotung!)
Operator Precedence with clone (#536): Fixed a critical bug where the formatter would incorrectly remove parentheses from a ternary expression inside a clone() call, which would change the code's behavior. The logic is now more robust for other unary constructs as well.
Brace Placement (#545): Corrected an issue where the opening brace for functions or methods with long signatures but short parameter lists was being placed on the same line, violating the NextLine brace style.
yoda-conditions Rule Disabled by Default (#505): In response to community feedback, the yoda-conditions rule is now disabled by default. It was found to be too noisy for many projects, and its primary goal of preventing accidental assignments is already covered by the no-assign-in-condition rule. Teams that prefer this style can still enable it in their mago.toml.
New Rule: no-variable-variable: A new rule has been added to disallow the use of variable-variables (e.g., $$foo), which can make code difficult to understand and analyze.
no-redundant-use Improvements: This rule has been improved to understand Tempest view classes, reducing false positives in projects using this framework. (#532)
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.27...1.0.0-beta.28
This release is packed with community contributions, featuring powerful new linter rules, major analyzer correctness fixes, and expanded support for t
1.0.0-beta.27This release is packed with community contributions, featuring powerful new linter rules, major analyzer correctness fixes, and expanded support for the PHP ecosystem.
We're thrilled to welcome several new contributors to the project! A huge thank you to @yigitcukuren, @rachidify, @thorsten, @dotdash, and @bendavies for their fantastic work on this release!
The linter has received a huge upgrade, thanks to our community.
New Rule: no-redundant-use (#439): The highly-requested rule for detecting and removing unused use statements is here! It correctly handles symbols used in docblocks and comes with a powerful auto-fix. (Thanks, @rachidify!)
New Suggestions & Fixes for final & readonly (#530, #522, #529):
private instead of protected for members in final classes.readonly modifiers (no-redundant-readonly rule).no-redundant-final rule.
(Thanks, @dotdash!)__DIR__, __FILE__, and __LINE__, leading to more precise path analysis.use Trait { method as private newName; }) were not being respected.@method Parameter Casing (#507): The analyzer now correctly handles case-sensitivity for named arguments in magic methods defined with @method tags.Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.26...1.0.0-beta.27
This release is a major step forward in the analyzer's correctness and reliability. It's packed with bug fixes that address a wide range of issues, es
1.0.0-beta.26This release is a major step forward in the analyzer's correctness and reliability. It's packed with bug fixes that address a wide range of issues, especially for advanced object-oriented features like traits, generics, and intersection types.
This release significantly improves the accuracy of the type analyzer by resolving several fundamental bugs:
Callable Type Detection (#508): The analyzer's ability to determine if a type is callable has been completely overhauled. It now correctly handles inheritance for __invoke, methods in array callables [$obj, 'method'], intersection types, and generics.
Trait Support Overhaul (#514, #9110b3f): The tool's understanding of traits is now much more robust. It correctly resolves method aliases (use Trait { method as newName; }), respects visibility overrides, and correctly resolves self in a trait method's return type to the consuming class.
static Return Type Resolution (#414): Fixed a critical bug where a static return type would be incorrectly resolved to the calling class scope instead of the class the method was called on, eliminating a class of false positive InvalidReturnStatement errors.
Template Inference Fallback (#513): Un-inferred generic template parameters now correctly fall back to their upper bound (usually mixed) instead of never. This fixes a major source of false positives for functions like current() when used with mixed input.
Boolean Comparison Assertions (#510): The analyzer now correctly creates type assertions from identity comparisons with true and false (e.g., if (true === ($a !== null && $b !== null))). This makes type narrowing in if and match statements significantly more powerful.
install.sh script has been made more robust and can now correctly parse the latest release version even if the API response includes HTTP headers. (#516)We're incredibly honored to be featured in the latest JetBrains blog post, Moving PHP Open Source Forward.
Following this, we're thrilled to officially welcome @JetBrainsOfficial as a major sponsor! Their generous support is a huge vote of confidence in the project's vision and will be instrumental in helping us reach a stable 1.0 release.
We also want to give a warm welcome to our other new sponsors, @JacerOmri and @yigitcukuren!
And, as always, our heartfelt gratitude goes to our long-time supporters who continue to make this project sustainable:
Finally, thank you to @mathe42 for their code contribution in this release! (#497)
Your sponsorship helps dedicate more time to bug fixes, new features, and community support. If you or your company find this tool valuable, please consider sponsoring the project on GitHub. Thank you! 🙏
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.25...1.0.0-beta.26
This release is packed with significant formatter improvements, fixing a large number of regressions and introducing a new, smarter heuristic for buil
1.0.0-beta.25This release is packed with significant formatter improvements, fixing a large number of regressions and introducing a new, smarter heuristic for builder patterns. The analyzer also continues to get more accurate, with major correctness fixes for traits and magic methods.
This release addresses many long-standing formatting issues and regressions, resulting in much more stable and beautiful output for complex, real-world code.
preserve-breaking-member-access-chain (#503).The analyzer's accuracy for complex object-oriented patterns has been significantly improved.
@method Support: The analyzer now correctly handles pseudo methods (@method) defined on traits, making them inheritable by the classes that use them. It also no longer reports false errors when a @method tag is used to provide a more specific type for a real method. (#491, #500)array_shift() when used with mixed inputs has been resolved, eliminating a class of false positives. (#498)Psl\Type\shape and added support for Psl\Type\optional function. (#501)redundant-var-docblock: A new analyzer check has been added to flag @var docblocks that are redundant with a native property type. (#502)sensitive-parameter: A new security rule, security/sensitive-parameter, has been added. It detects parameters with sensitive names (e.g., $password, $token) and reports an error if they are missing the #[SensitiveParameter] attribute. This rule includes an auto-fix.mago.toml.Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.24...1.0.0-beta.25
This is a hotfix release that addresses a critical panic in the parser, ensuring greater stability when processing files with mixed PHP and HTML.
1.0.0-beta.24This is a hotfix release that addresses a critical panic in the parser, ensuring greater stability when processing files with mixed PHP and HTML.
A bug has been fixed that would cause the parser to panic when a short echo tag (<?=) immediately followed a closing tag (?>).
Failing Code (Before):
<?php echo 'First'; ?><?= 'Second'; ?>
This was caused by a legacy check that remained after the recent refactoring of how echo tags are handled. The parser now correctly processes this sequence, making it more robust.
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.23...1.0.0-beta.24
WordPress Security: New rules to prevent common vulnerabilities like unescaped output (no-unescaped-output), schema changes outside of activation hook…
1.0.0-beta.23This release introduces a powerful new set of linter rules with a major focus on WordPress security and best practices. It also includes a fundamental correctness fix for how short echo tags (<?=) are handled across the entire toolchain, resolving a number of bugs and regressions.
A batch of new linter rules has been added to help you write safer and more maintainable code, especially for WordPress projects:
no-unescaped-output), schema changes outside of activation hooks (no-db-schema-change), and using roles instead of capabilities for checks (no-roles-as-capabilities).no-direct-db-query) and encourage using the WordPress HTTP and Filesystem APIs over native PHP functions (use-wp-functions).yoda-conditions rule to prevent accidental assignment bugs and a require-preg-quote-delimiter rule for safer regular expressions.<?= Echo Tag HandlingThe short echo tag (<?=) is now parsed and analyzed correctly as a statement, not just an opening tag. This architectural fix resolves a cascade of issues across the toolchain:
<?= $a, $b ?>).unused-statement errors for expressions inside <?= ... ?>.no-unescaped-output now correctly inspect expressions inside echo tags.Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.22...1.0.0-beta.23
New `--colors` Flag: The old --no-color flag has been deprecated in favor of a more flexible --colors=[auto|always|never] option. This aligns with mod…
1.0.0-beta.22Mago 1.0.0-beta.22 is a quality-of-life release focused on improving the analysis of common PHP patterns, especially in template files, and making the command-line interface more intuitive and powerful.
This release resolves two key issues that significantly improve the experience of analyzing files that mix PHP and HTML.
<?=) Usage: Variables and expressions used inside short echo tags (<?= $var ?>) are now correctly recognized as "used," eliminating a common source of unused-statement false positives. (#479)@var Before Closing Tag: @var docblocks placed immediately before a PHP closing tag (?>) are now correctly processed. This makes it much easier to properly type-hint variables that are available to the template scope. (#445)--colors Flag: The old --no-color flag has been deprecated in favor of a more flexible --colors=[auto|always|never] option. This aligns with modern CLI tool conventions and allows you to force colorized output in CI environments with --colors=always. (#481)--generate-baseline and --verify-baseline now automatically use the baseline path from your mago.toml file. You no longer need to specify --baseline <path> on the command line every time. (#480)no-noop Rule Fix & Auto-Fix: The no-noop rule has been corrected to avoid false positives on intentional empty statements (e.g., if(...);). Additionally, it now has a safe auto-fix to remove truly redundant semicolons when you run mago lint --fix.Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.21...1.0.0-beta.22
This is a highly focused patch release that addresses a critical correctness bug in the type analyzer, ensuring that analysis results are consistent a
1.0.0-beta.21This is a highly focused patch release that addresses a critical correctness bug in the type analyzer, ensuring that analysis results are consistent and deterministic across all environments.
A bug has been fixed in the core type comparator that could cause Mago to report different errors for the same code when run on different machines (e.g., locally vs. CI).
The issue was caused by the order of types in a union (e.g., TypeA|null vs. null|TypeA) affecting the outcome of the type comparison. This has been resolved, and the type analysis is now fully order-independent. This change is crucial for providing reliable and reproducible builds.
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.20...1.0.0-beta.21
This is a focused release that addresses several critical bugs in the linter, significantly improving its correctness and restoring a key auto-fix fea
1.0.0-beta.20This is a focused release that addresses several critical bugs in the linter, significantly improving its correctness and restoring a key auto-fix feature as we continue to stabilize for the first release candidate.
A bug has been fixed where some linter rules (like no-request-all) would run on nested code blocks, causing the same issue to be reported multiple times within a single function or method. The linter now correctly targets the top-level scope, ensuring that issues are reported only once.
strict-types Rule Restored and ImprovedA significant logic error in the strict-types rule has been fixed. The rule was previously failing to report missing declare(strict_types=1); statements in most cases.
More importantly, the auto-fix for this rule has been restored. After being removed during the linter rewrite, you can now once again automatically add the strict types declaration to your files by running:
mago lint --fix --unsafe
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.19...1.0.0-beta.20
This release introduces a major step forward in the type system's expressiveness and the analyzer's developer experience. The highlights are full supp
1.0.0-beta.19This release introduces a major step forward in the type system's expressiveness and the analyzer's developer experience. The highlights are full support for object{...} shapes for documenting plain objects, and beautiful type diffs in error messages to make debugging complex type mismatches easier than ever.
A huge thank you to @Bleksak for their significant contributions to this release!
object{...} Shape SupportMago's PHPDoc parser and analyzer now have full, robust support for the object{...} shape syntax, allowing you to precisely document the structure of generic objects with required and optional properties. This was a highly requested feature and the initial implementation was contributed by @Bleksak in #468
This includes support for:
... to specify if an object can have additional properties beyond those listed.? to mark properties that may not exist.PossiblyNonExistentProperty for optional properties and stricter NonExistentProperty checks for sealed objects.Example:
/**
* @param object{name: string, id?: string, ...} $user
*/
function process(object $user): void
{
echo $user->name; // no issues!
echo $user->id; // @mago-expect analysis:possibly-non-existent-property
echo $user->email; // @mago-expect analysis:ambiguous-object-property-access,mixed-argument
}
To dramatically improve the experience of debugging complex type errors, the analyzer now includes a colored, pretty-printed diff in the error report when a mismatch occurs between two complex types (like large array or object shapes). This makes it immediately obvious where the two types diverge, saving you time and effort. (#471)
<img width="1494" height="704" alt="Screenshot 2025-09-23 at 01 27 37" src="https://github.com/user-attachments/assets/52f74a15-c3f1-407e-9f2c-9e21f2950220" />
array{...} shapes is now stricter and more correct, preventing unsafe assignments where an optional key in the destination could conflict with the source's generic value type.throw on the right-hand side of a null coalesce operator (??) would incorrectly mark subsequent code as unreachable. (#448)use-compound-assignment rule is now more accurate and will only apply to simple assignment operators. (Thanks @Bleksak!) (#472)no-shorthand-ternary rule has been relaxed to allow nested shorthand ternaries, a common pattern.Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.18...1.0.0-beta.19
This release introduces a major step forward in the analyzer's accuracy and its understanding of advanced PHPDoc, headlined by full support for proper
1.0.0-beta.18This release introduces a major step forward in the analyzer's accuracy and its understanding of advanced PHPDoc, headlined by full support for property assertions. We've also landed a series of critical correctness fixes for match expressions and array shape analysis, eliminating a significant number of false positives.
The analyzer now has full support for property-level assertions like @psalm-assert, @phpstan-assert, @assert, and their variants. This allows the analyzer to correctly understand and apply type narrowing from assertion helper methods that operate on object properties.
/**
* @var null|array{'uuid': string}
*/
private null|array $data;
/**
* @assert !null $this->data
*/
private function assertDataIsNotNull(): void
{
// ...
}
public function getUuid(): string
{
// Mago now understands that after this call, $this->data is not null.
$this->assertDataIsNotNull();
return $this->data['uuid']; // No error!
}
This change is a huge improvement for analyzing object-oriented code that relies on assertion helpers to maintain type safety.
match (true) Exhaustiveness (#459): A major bug has been fixed where the analyzer would incorrectly report match-not-exhaustive errors for valid match (true) expressions. The analyzer now correctly understands this common pattern for type narrowing and control flow.
Array Shape Reconciliation (#459): The core type system is now much smarter at combining and subtracting specific, "sealed" array shapes (e.g., list{true, false}). This makes type inference in conditional logic far more accurate, especially for match expressions on array subjects, e.g match ([$is_foo, $is_bar]).
Array Shape Key Parsing (#466): Fixed a critical bug where unquoted string keyword keys in PHPDoc array shapes (e.g., {self: string}) could be incorrectly resolved as class names, which was a significant source of false positives.
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.17...1.0.0-beta.18
This release introduces two major new analyzer features—full support for argument unpacking and `@var` support for constants—along with a host of othe
1.0.0-beta.17This release introduces two major new analyzer features—full support for argument unpacking and @var support for constants—along with a host of other correctness fixes and quality-of-life improvements for the CLI and configuration.
...)Mago's analyzer now has comprehensive support for argument unpacking (...), closing a significant gap in its capabilities. The analyzer correctly validates the number of arguments and performs full type-checking on each element within an unpacked array, for both positional and named arguments. This significantly improves correctness for modern PHP code.
@var Support for ConstantsThe analyzer now fully supports @var docblocks on both const and define() declarations. This allows you to provide explicit types for constants with complex values (like function calls).
To encourage good practice, the analyzer also introduces a new non-documented-constant warning. If a constant is defined with a complex value but lacks a @var tag, the analyzer will issue a warning and suggest the inferred type, helping you make your code more robust and analyzable.
Analyzer:
{dateTime: string}) could be incorrectly resolved as class names, leading to false positives. (#413)Configuration & CLI:
baseline path in your mago.toml for both the [analyzer] and [linter] sections, removing the need to pass the --baseline flag on every run. (#460)Internal:
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.16...1.0.0-beta.17
This release introduces a major upgrade to the baseline feature, making it a powerful tool for CI/CD workflows. We've also added significant quality-o
1.0.0-beta.16This release introduces a major upgrade to the baseline feature, making it a powerful tool for CI/CD workflows. We've also added significant quality-of-life improvements to issue suppression pragmas and fixed a key regression in the analyzer's closure type inference.
The baseline feature has been enhanced with new verification capabilities, designed to keep your baseline file perfectly in sync with your codebase.
--verify-baseline Flag: You can now use this flag in your CI pipeline to fail the build if the baseline is out of date. It checks for both new issues not in the baseline and fixed issues that are still listed, ensuring your baseline is always an accurate representation of your project's acknowledged issues.--fail-on-out-of-sync-baseline Flag: A stricter option that will fail the build if the baseline contains fixed issues, even if no new issues are reported.linter (for lint) and analyzer or analyser (for analysis).@mago-expect are now correctly detected when they are on their own line inside a multi-line PHPDoc block, making suppression behavior more intuitive.return was being inferred incorrectly. The analyzer now correctly infers void or never, eliminating a major source of false positive errors. (#455)unused-parameter rule has been relaxed and will no longer report parameters that are marked as unused ( prefixed with $_ ), reducing noise.Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.15...1.0.0-beta.16
This is a huge release focused on deepening the analyzer's capabilities with best-in-class support for magic methods and properties. We've also landed
1.0.0-beta.15This is a huge release focused on deepening the analyzer's capabilities with best-in-class support for magic methods and properties. We've also landed a massive number of fixes and improvements for the formatter, resolving many regressions and significantly improving output quality for complex, real-world code.
A big thank you to our community for their amazing contributions to this release: @Bleksak, @dantleech, and @paulschreiber!
Mago's understanding of "magic" members defined via @method and @property docblocks has been completely overhauled. The new system is much stricter and provides far more accurate diagnostics for a wide range of common errors and patterns.
@method/@property Parsing: The analyzer now fully supports typed, untyped, read-only (@property-read), and write-only (@property-write) tags.__call/__callStatic Validation: Mago now verifies that a class with magic docblocks has the required __call() or __callStatic() method to handle them, catching bugs that would lead to fatal runtime errors.@method static on an instance (e.g., $obj->magicStatic()).@method or @property tag, encouraging better, more analyzable code.This release fixes numerous formatting regressions, restoring and improving upon the stability of earlier versions.
$this->assertSame(...)).yield Formatting: The logic for yield key => value expressions has been improved to produce more compact and intelligent layouts, consistent with other assignments.--minimum-report-level, has been added to all commands. This allows you to filter out diagnostics below a certain severity (e.g., --minimum-report-level=warning will hide note and help issues).@mago-expect and @mago-ignore now support a comma-separated list of issue codes (e.g., @mago-expect analysis:code-a,code-b).count() and array_key_exists(), especially when they are aliased or used inside namespaces.invalid-open-tag linter rule when encountering multi-byte UTF-8 characters like emojis. (#436)Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.14...1.0.0-beta.15
This release introduces a new linter rule to promote best practices and improves the formatter's handling of yield expressions.
1.0.0-beta.14This release introduces a new linter rule to promote best practices and improves the formatter's handling of yield expressions.
no-ini-setA new rule, best-practices/no-ini-set, has been added to discourage the use of ini_set() and its alias ini_alter().
Changing PHP settings at runtime can make application behavior unpredictable and mask server misconfigurations. This rule encourages managing configuration explicitly through php.ini or framework-level settings for more stable and consistent applications.
Contributed by @Bleksak in #422.
The formatter now correctly handles line breaks in yield key => value expressions. Previously, long values like closures could create unreadably long lines. Now, the formatter will break the line after the => and indent the value if necessary.
Before:
yield ['some_key'] => /**
* comment
*/
static function () { /* ... */ };
After:
yield ['some_key'] =>
/**
* comment
*/
static function () { /* ... */ };
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.13...1.0.0-beta.14
This is a massive release packed with a major documentation expansion, a major CLI user experience overhaul with integrated pager support, and a raft
1.0.0-beta.13This is a massive release packed with a major documentation expansion, a major CLI user experience overhaul with integrated pager support, and a raft of powerful new analysis checks and correctness fixes.
This release wouldn't have been possible without our amazing community. A huge thank you to @Bleksak, @BackEndTea, and @z4nder for their significant contributions!
The documentation site has received a major overhaul to improve its structure and cover many previously undocumented features. Key changes include:
The command-line experience has been significantly improved to be more powerful and ergonomic.
--pager or use-pager = true in your mago.toml. It intelligently activates only for interactive terminals and supports the standard PAGER environment variable.--no-color flag is now a global option that disables color for all output.--diff Alias: The --dry-run flag has been aliased to the more intuitive --diff.mago-pager Crate: We've replaced the unmaintained external pager dependency with our own robust mago-pager crate, which correctly handles exit codes and is fully cross-platform.The analyzer has received a host of new features and correctness fixes, making it more powerful and reliable.
return statement, which can lead to bugs when a return value is expected.array_column is used on an array of objects. (#408)mixed types with booleans and floats has been corrected.clone $this is now correctly recognized when used inside a trait. (#416)\count() function is now correctly resolved when used with a leading backslash. (#418)itoa and ryu crates, fixing potential panics and improving performance.Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.12...1.0.0-beta.13
This release is packed with major improvements to the static analyzer, focusing on enhanced type inference for arrays, closures, and ArrayAccess objec
1.0.0-beta.12This release is packed with major improvements to the static analyzer, focusing on enhanced type inference for
arrays, closures, and ArrayAccess objects. We've also added support for recursive closures and array
unpacking on all iterables.
...) now works on all iterable types, not just arrays. You can now unpack any object that implements Traversable, and Mago will correctly infer the key and value types. (#361)Psl\Regex Analysis: A special type provider has been added for Psl\Regex\capture_groups. Mago can now infer a precise shape for the returned type based on the capture group names you provide, giving you much better type safety when working with regular expressions. (#364)undefined-variable error. The analyzer now correctly handles the pattern where a closure takes a reference to itself (e.g., $fn = function () use (&$fn) { ... };). (#368)$a = fn() => 'foo'; $b = $a();) now correctly uses the specific inferred return type ('foo') instead of falling back to a generic mixed. (#355)null: Assigning to an index on a null or non-existent variable (e.g., $a = null; $a[] = 1;) now correctly promotes the variable to an array type, matching PHP's runtime behavior. (#360)ArrayAccess Append: Appending to an ArrayAccess object with a non-negative-int key type now correctly infers the new key as non-negative-int instead of a general int. (#362)self & static: Corrected an issue where self and static were not being properly resolved to the enum's type within its own methods, eliminating false-positive errors. (#357)array_search Stub: The built-in stub for array_search has been corrected to reflect that the $needle is a value from the array, not a key. (#358)Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.11...1.0.0-beta.12
PHP 8.5 `#[Deprecated]` on Traits: Mago now recognizes the #[Deprecated] attribute on traits, a new feature in PHP 8.5. (#386 by @DanielEScherzer)
1.0.0-beta.11This release introduces support for new PHP features, adds stubs for the php-decimal extension, and fixes several bugs in type inference and assertion logic.
mago.toml file using common lowercase aliases. For example, instead of just "Error", you can now use "error", "err", or "deny". This makes configuration more intuitive and consistent with other tools. (#381 by @azjezz)#[Deprecated] on Traits: Mago now recognizes the #[Deprecated] attribute on traits, a new feature in PHP 8.5. (#386 by @DanielEScherzer)php-decimal Extension Support: Stubs for the php-decimal extension have been added to the prelude, improving analysis accuracy for projects that use this extension. (#397 by @Bleksak)array_key_exists(), key_exists(), and Psl\Iter\contains_key() now correctly inform the type system that a key exists after being checked. (#392 by @Bleksak)isset($a['foo'])) would incorrectly imply that a different key also exists. (#393, #394 by @Bleksak)unset() on Lists: Fixed a type inference bug where using unset() on an element of a list<T> would incorrectly preserve the list type. The type is now correctly widened to array<int, T>, reflecting that the keys may no longer be sequential. (#396 by @azjezz)count($array) === 1) now correctly narrow the array's type to be non-empty. (#388 by @azjezz)end() Stub: The return type annotation for the built-in end() function has been made more precise, correctly distinguishing between the return types for empty and non-empty arrays. (#387 by @Bleksak)sizeof() Alias: The function stub for sizeof() now exactly mirrors count(), as it's a direct alias, ensuring consistent type analysis. (#389 by @Bleksak)mago-prelude for built-in PHP stubs. This reduces boilerplate in test files and ensures that tests run against the same definitions used in production analysis. (by @azjezz)Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.10...1.0.0-beta.11
Welp, no release is perfect\! This is a quick patch release to address a bug in the type inference for the iterator_to_array function that was introdu
1.0.0-beta.10Welp, no release is perfect! This is a quick patch release to address a bug in the type inference for the iterator_to_array function that was introduced in the previous version.
iterator_to_array has been fixed. It was previously reading the wrong argument for the $preserve_keys parameter and did not correctly handle its default value (true). This could lead to incorrect return types when converting iterators to arrays. The handler is now more precise, leading to more accurate type inference.Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.9...1.0.0-beta.10
This release focuses on deep type inference for ::class comparisons. It also includes a new linter rule to help modernize your code, along with severa
1.0.0-beta.9This release focuses on deep type inference for ::class comparisons. It also includes a new linter rule to help modernize your code, along with several important bug fixes and community contributions.
::class AnalysisThe analyzer is now significantly smarter about the ::class magic constant, enabling more powerful and precise type narrowing.
::class as instanceof: A condition like if ($var::class === A::class) is now treated as an instanceof check, correctly narrowing the type of $var to A within the block. This works across all control structures, including if, switch, and match, and correctly handles final vs. non-final classes. (Closes #367)class-string Logic: This is powered by a completely overhauled understanding of class-string types. The analyzer can now reconcile literal class strings from unions and resolves $foo::class on final objects to a precise literal type.class-string('Foo'), while generic class strings remain class-string<Foo>, making error messages much easier to understand.prefer-arrow-functionA new linter rule, prefer-arrow-function, has been added to the Best Practices category. It identifies traditional closures that can be simplified to the more concise arrow function syntax and provides a potentially unsafe autofix.
Iterator<Value>). A new, more precise return type handler for the SPL function iterator_to_array has also been added. (Closes #359)const A = B::C) was not being fully resolved, leading to more accurate type inference. (Closes #363)foreach by-reference loop (... as &$var) were sometimes reported as undefined. A new warning (reference-reused-from-confusing-scope) has also been added to detect a common source of bugs with lingering references after a loop. (Closes #369)@param tags is now more robust, correctly normalizing the variable name and handling trailing punctuation, by-reference (&), and variadic (...) syntax. Thanks to @z4nder! (Closes #376)mago.toml by default. Thanks to @Bleksak! (Closes #349)Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.8...1.0.0-beta.9
This is a minor maintenance release that includes several important bug fixes for the linter, formatter, and the core lexer, improving overall stabili
This is a minor maintenance release that includes several important bug fixes for the linter, formatter, and the core lexer, improving overall stability and correctness.
no-redundant-nullsafe autofix. Previously, when fixing code like $a?->b ?? $c, the linter would incorrectly change the ?? operator instead of the ?-> operator, resulting in broken code. The autofix now correctly produces $a->b ?? $c. (closes #370)Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.7...1.0.0-beta.8
This release includes a critical bug fix for the parser and an optimization for memory usage.
1.0.0-beta.7This release includes a critical bug fix for the parser and an optimization for memory usage.
&). Expressions like &$foo->bar() were being incorrectly parsed as (&$foo)->bar(), which could lead to incorrect formatting. The parser now correctly understands this as &($foo->bar()).Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.6...1.0.0-beta.7
This release focuses on improving the stability of the linter and introducing a new rule for modern MVC frameworks.
1.0.0-beta.6This release focuses on improving the stability of the linter and introducing a new rule for modern MVC frameworks.
final-controller: A new rule has been added to the BestPractices category. This rule enforces that controller classes (e.g., UserController) are declared as final. In modern frameworks, controllers should not be extended; this rule helps enforce the best practice of favoring composition over inheritance. This rule is automatically enabled when using the Laravel, Symfony, CakePHP, Yii, Spiral, or Tempest integrations.We've made significant internal improvements to how the linter handles rule requirements. While these changes won't be visible to most users, they lay the groundwork for us to add more powerful and context-aware rules in the future. The only user-facing change from this work is the new final-controller rule.
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.5...1.0.0-beta.6
*Note for library consumers: This release introduces breaking changes to the mago_syntax AST, most notably the removal of BinaryOperator::Elvis in fav…
1.0.0-beta.5 - The Correctness UpdateThis is a landmark release focused entirely on the correctness and reliability of our expression parser and formatter. After extensive testing, we discovered that the root cause of many formatting bugs was not the formatter itself, but subtle inaccuracies in the parser's operator precedence rules. An incorrect Abstract Syntax Tree (AST) will always lead to incorrect formatting.
This version fundamentally addresses these issues, ensuring that Mago handles even the most complex PHP expressions with perfect accuracy. For end-users, this is a stability and bug-fix release.
Note for library consumers: This release introduces breaking changes to the mago_syntax AST, most notably the removal of BinaryOperator::Elvis in favor of a unified Conditional node. For end-users of the formatter tool, these changes manifest as critical bug fixes that make formatting safer and more reliable.
This release overhauls the entire expression parsing and formatting pipeline to be 100% compatible with nikic/php-parser, the de-facto standard for PHP AST generation.
Parser Overhaul for PHP Compatibility: The operator precedence and associativity tables have been completely re-architected. This fixes dozens of bugs related to how logical operators (and, ||), assignment (=, &=), unary operators (@, &, ++), and ternaries interact. The parser now produces a semantically correct AST for all expressions.
Unified Ternary/Elvis AST: The ?: (Elvis) operator is no longer a unique binary operator in the AST. Both ?: and the full ternary (? :) are now correctly represented by a single Conditional node. This simplifies the AST, aligns our tooling with the broader PHP ecosystem, and makes analysis logic more robust.
Smarter Parenthesis Formatting: With a guaranteed-correct AST, the formatter's parenthesis logic has been rewritten from the ground up. It now operates on two principles:
All other truly redundant parentheses are confidently removed for the cleanest possible output.
Massive New Test Suite: To validate these foundational changes, we have integrated a new test suite of 100s of programmatically-generated expressions. We now verify our parser's output directly against nikic/php-parser's output, guaranteeing a 1:1 match in AST structure and ensuring these bugs will not return.
Improved Inlining Logic: A subtle but important bug in how the formatter handles chains of inlined binary expressions has been fixed, resulting in cleaner and more consistent output.
This is the most significant step we have ever taken to guarantee the reliability of the formatter. You can now format your code with confidence, knowing that its behavior will not be altered.
A special thanks goes to @bendavies, who reported a critical bug on our Discord server. His report on an incorrect parenthesis issue with ($value = &$data[$field->getName()]) ?? null; was the spark that initiated this deep investigation, ultimately leading to the discovery and resolution of dozens of underlying parser bugs.
We're incredibly grateful for community contributions like this that make Mago better. Join the conversation and help us find the next bug on Discord: https://discord.gg/mwyyjr27eu
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.4...1.0.0-beta.5
Welcome to the 1.0.0-beta.4 release of Mago! This update is packed with significant formatter enhancements that make your code look even better, plus
1.0.0-beta.4Welcome to the 1.0.0-beta.4 release of Mago! This update is packed with significant formatter enhancements that make your code look even better, plus a nice quality-of-life improvement for the linter and some documentation polish. ✨
This release includes a major tune-up for the code formatter, focusing on stability and smarter formatting for complex expressions. Your code should now be more readable and consistently formatted across the board.
Key improvements include:
->of(), ->to()), resulting in more compact and readable fluent interfaces. (Closes #334)match Expressions: Formatting for match expressions, especially those with multiple arms, has been improved.no-nested-ternary: A new rule has been added to detect and warn against nested ternary expressions ($a ? $b : ($c ? $d : $e)). This encourages writing more readable code and helps prevent bugs related to PHP's confusing operator associativity rules.assertion-style: You can now configure the assertion-style rule in your mago.toml file using the more intuitive values "self" or "$this".Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.3...1.0.0-beta.4
This is another quick bug-fix release that addresses a few important issues reported by the community since the last beta.
1.0.0-beta.3 Release NotesThis is another quick bug-fix release that addresses a few important issues reported by the community since the last beta.
Smarter Formatter Line Breaking: The formatter's heuristics have been improved to better handle line breaking for complex, nested expressions (such as a new expression inside a function call) and code containing comments. This results in more consistent and predictable output, especially in intricate method chains and argument lists. (closes #332)
mago init Configuration Fix: The mago init command was generating a mago.toml file with outdated snake_case keys (e.g., php_version). This has been corrected to use the proper kebab-case format (e.g., php-version), ensuring that newly initialized projects work out-of-the-box without requiring manual changes.
Full Changelog: https://github.com/carthage-software/mago/compare/1.0.0-beta.2...1.0.0-beta.3
One column per month.