alfredbez / mago-symfony
Symfony support for the Mago static analyzer.
Requires
- php: ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0
- ext-dom: *
- ext-libxml: *
- ext-tokenizer: *
- ext-xmlreader: *
- carthage-software/mago: ^1.60.2
Requires (Dev)
- symfony/config: ^6.4 || ^7.0
- symfony/console: ^6.4 || ^7.0
- symfony/dependency-injection: ^6.4 || ^7.0
- symfony/event-dispatcher: ^6.4 || ^7.0
- symfony/form: ^6.4 || ^7.0
- symfony/framework-bundle: ^6.4 || ^7.0
- symfony/http-foundation: ^6.4 || ^7.0
- symfony/messenger: ^6.4 || ^7.0
- symfony/routing: ^6.4 || ^7.0
- symfony/security-bundle: ^6.4 || ^7.0
- symfony/security-core: ^6.4 || ^7.0
- symfony/serializer: ^6.4 || ^7.0
- symfony/validator: ^6.4 || ^7.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Symfony support for Mago. It teaches Mago the types behind Symfony's container, config builders, console commands, lifecycle hooks, and HTTP, Form, Serializer, Messenger, and Security APIs.
- Reports private service access and console argument or option typos that Symfony only rejects at runtime.
- Turns
ContainerInterface::get()and parameter lookups into concrete types. - Types
TreeBuilderandNodeBuilderchains, so node methods andend()return values resolve. - Recognizes Symfony lifecycle initializers, public
#[Required]properties, and method-level entry points. - Narrows
Request,HeaderBag,Form,Serializer, and Security calls that returnmixedor a broad type on Symfony 6.4 and 7.x.
A console typo Mago reports before the command runs:
$this->addArgument('username', InputArgument::REQUIRED); // ... $input->getArgument('user_name'); // alfredbez/symfony/unknown-console-argument
Setup
Requires PHP 8.1 or newer (with dom, libxml, tokenizer, and xmlreader), Mago ^1.60.2, and Symfony ^6.4 || ^7.0.
composer require --dev alfredbez/mago-symfony
Register the bundled worker in mago.toml:
[source] includes = ["vendor/symfony", "vendor/psr"] [extension-hosts.symfony] command = ["php", "-d", "xdebug.mode=off", "-d", "pcov.enabled=0", "-d", "memory_limit=512M", "vendor/bin/mago-symfony-worker"] workers = 1 # Optional. Configure container dumps, strict service checks, or a Security user class. # environment = { # MAGO_SYMFONY_CONTAINER_XML = "var/cache/dev/App_KernelDevDebugContainer.xml", # MAGO_SYMFONY_USER_CLASS = "App\\Entity\\User", # MAGO_SYMFONY_STRICT_CONTAINER_SERVICES = "1", # }
[source] includesmust contain the Symfony packages your app uses and the PSR container contracts. Mago reads those files to resolve method signatures. Listingvendor/symfonycovers every installed Symfony package. If you list individual packages instead, keep the ones your app calls.- The
-dflags keep Xdebug and PCOV out of the worker and give the worker 512M of headroom for large codebases. Small and medium applications also run within PHP's default 128M limit. - Pass worker environment variables through
[extension-hosts.symfony] environment. Leave the table unset, or omit keys you do not need, to keep defaults and auto-discovery active.
Check the worker and run the analyzer:
vendor/bin/mago extension validate vendor/bin/mago analyze
Container data
Service and parameter types come from Symfony's compiled container. Point the extension at the dump:
| Variable | What it does |
|---|---|
MAGO_SYMFONY_CONTAINER_XML |
Path to the compiled container XML, for example var/cache/dev/App_KernelDevDebugContainer.xml. When unset, the extension searches var/cache/dev/*Container.xml and var/cache/test/*Container.xml in sorted path order from the working directory. |
MAGO_SYMFONY_CONTAINER_MAP |
Path to a JSON file that maps service IDs to class or interface names. Defaults to .mago/symfony-container.json when that file exists. Targets must exist in Mago's codebase. |
MAGO_SYMFONY_USER_CLASS |
FQCN of a class or interface that implements UserInterface. Narrows Security getUser() to ConfiguredUser or null. |
MAGO_SYMFONY_STRICT_CONTAINER_SERVICES |
Set to 1 to report alfredbez/symfony/unknown-service-id for literal IDs that are missing from the compiled XML. Requires a loaded XML dump. |
Without a compiled dump or JSON map, a class-name service ID resolves to that declared class or interface rather than any container alias or decorator, and non-class string service IDs such as logger stay mixed.
Absent auto-discovery paths (.mago/symfony-container.json and var/cache/{dev,test}/*Container.xml) stay silent. When MAGO_SYMFONY_CONTAINER_XML or MAGO_SYMFONY_CONTAINER_MAP is explicitly set to a missing, unreadable, or malformed file, worker registration writes the error to stderr and fails cleanly without corrupting the worker stdout protocol. When MAGO_SYMFONY_USER_CLASS names a class that does not exist or does not implement UserInterface, the worker writes a warning to stderr and leaves getUser() unnarrowed.
Checks
| Code | Level | What it reports |
|---|---|---|
alfredbez/symfony/private-service-access |
error | A throwing get() fetches a private service or alias from a public container. Requires a compiled XML dump. |
alfredbez/symfony/unknown-service-id |
error | A literal service ID is missing from the compiled XML. Opt-in with MAGO_SYMFONY_STRICT_CONTAINER_SERVICES=1. |
alfredbez/symfony/invalid-root-node-method |
error | A TreeBuilder with a literal non-array root, such as new TreeBuilder('root', 'scalar'), calls a node method that needs an array root. |
alfredbez/symfony/unknown-console-argument |
error | getArgument('name') asks for an argument that configure() does not declare. |
alfredbez/symfony/unknown-console-option |
error | getOption('name') asks for an option that configure() does not declare. |
alfredbez/symfony/invalid-console-input-definition |
error | InputArgument or InputOption uses a mode and default combination that Symfony rejects, such as VALUE_NONE with a non-null default. |
private-service-access skips ServiceLocator, ContainerBuilder, TestContainer, PHPUnit TestCase subclasses, and calls with a non-throwing invalid-reference flag. unknown-console-* skips parent::configure(), definitions built by dynamic helper methods, direct variable lookups guarded by hasOption() or hasArgument(), and default application options derived from the analyzed Symfony Console Application class.
To silence a code in one project:
[analyzer] ignore = ["alfredbez/symfony/private-service-access"]
To silence one call:
// @mago-ignore analysis:alfredbez/symfony/private-service-access $container->get('app.private_service');
What it types
| Feature | What Mago knows |
|---|---|
ContainerInterface::get('id') and Container::get('id') |
The service class from the compiled XML or JSON map, including multi-hop aliases, class and service factories, and class-name IDs. ContainerBuilder, ServiceLocator, and ServiceProviderInterface fall back to class-name resolution. |
ParameterBagInterface::get(), ContainerInterface::getParameter(), Container::getParameter(), AbstractController::getParameter() |
The parameter's literal scalar, list, keyed array, constant, or %env(...)% type. |
Container::get() and ContainerBuilder::get() with invalid-reference flags |
Nullable returns for flags 0, 2, 3, and 4 on Container; non-null for flags 0 and 1 on ContainerBuilder. |
TreeBuilder and NodeDefinition chains |
The node type after children(), node(), prototypes, validate(), beforeNormalization(), and end(). Tracks custom NodeBuilder classes through setNodeClass() and setParent(), and accepts unparameterized concrete root-node returns (native or @return) while keeping explicit and inherited generic mismatches reported. |
HelperSet::get() and Command::getHelper() |
FormatterHelper, DebugFormatterHelper, ProcessHelper, or QuestionHelper for the four default names. |
HeaderBag::get($key, $default) |
string when the default is a non-null string. |
ParameterBag::getEnum() and InputBag::getEnum() |
The target BackedEnum when a matching non-null default is supplied. |
Request::getRequestFormat() and getPreferredFormat() |
string when the default is omitted or is a non-null string. |
Request::getPreferredLanguage() |
string for a non-empty list or keyed array containing a required 0 string entry. |
ResponseHeaderBag::getCookies() |
list<Cookie> for COOKIES_FLAT, nested Cookie arrays for COOKIES_ARRAY. |
ControllerEvent::getAttributes() and ControllerArgumentsEvent::getAttributes() |
list<T> when the class-string argument names an existing class or interface. |
FormInterface::getErrors() |
FormErrorIterator<FormError>, or an iterator of FormError and nested iterators when $deep may be true and $flatten may be false. |
SerializerInterface::deserialize() and DenormalizerInterface::denormalize() |
Foo, array<array-key, Foo>, or nested arrays for literal Foo, Foo[], and Foo[][] types, plus class-string<Foo> arguments. |
WrappedExceptionsInterface::getWrappedExceptions() |
array<array-key, T> for a concrete class or interface filter. |
Security getUser() |
ConfiguredUser or null when MAGO_SYMFONY_USER_CLASS is set. Covers AbstractController, SecurityBundle\Security, Security\Core\Security, and TokenInterface. |
Lifecycle initializers and #[Required] properties |
AbstractController::setContainer(), Command::initialize(), ConstraintValidator::initialize(), InputAwareHelper::setInput(), public non-static methods with #[Required], and non-readonly public writable properties with #[Required] (typed with a class or interface, or paired with an #[Autowire*] attribute) initialize properties when check-property-initialization = true. |
| Method-level entry points | Recognizes method attributes (#[Route], #[AsEventListener], #[AsMessageHandler], #[Callback]) and standard Symfony lifecycle overrides (Command, AbstractType, ConstraintValidator, Voter, ConfigurationInterface, ExtensionInterface, CompilerPassInterface, EventSubscriberInterface, ServiceSubscriberInterface) when find-unused-definitions = true. |
Compatibility and SemVer policy
This project follows Semantic Versioning from 1.0.0.
Public PHP API. AlfredBez\MagoSymfony\SymfonyExtension::create() is the supported entry point. Analyzer plugins, providers, hooks, and helper classes under AlfredBez\MagoSymfony\Analyzer are @internal. They can change without a major version bump.
Worker. bin/mago-symfony-worker (Composer vendor/bin/mago-symfony-worker) is the supported CLI. Stdout is the Mago extension protocol. Diagnostics and warnings go to stderr.
Diagnostic codes. alfredbez/symfony/private-service-access, alfredbez/symfony/invalid-root-node-method, alfredbez/symfony/unknown-console-argument, alfredbez/symfony/unknown-console-option, and alfredbez/symfony/invalid-console-input-definition are enabled by default. alfredbez/symfony/unknown-service-id is opt-in via MAGO_SYMFONY_STRICT_CONTAINER_SERVICES=1. Adding a new default-on diagnostic is a minor bump. Changing the meaning of an existing code, removing a code, or turning an opt-in check on by default is a major bump.
Suppression. Project-wide [analyzer] ignore = ["alfredbez/symfony/..."] and per-call // @mago-ignore analysis:alfredbez/symfony/... remain supported.
Supported floors. PHP ~8.1 through ~8.6 (with ext-dom, ext-libxml, ext-tokenizer, ext-xmlreader), Mago ^1.60.2 (verified on 1.60.2 and 1.61.0), Symfony ^6.4 || ^7.0.
Known limitations
ContainerInterface::has()cannot narrow a laterget(). Mago1.60.2through1.61.0narrows only parameter variables and$thisin invocation assertions.- Return-type providers cannot read the enclosing
Commandclass. Per-command narrowing ofgetArgument()andgetOption()stays blocked in the Mago SDK. The extension validates argument and option names instead. - Class-level
#[AsEventListener]and#[AsMessageHandler]attributes (routing to__invoke()) are not registered as entry points yet. Mago1.60.2through1.61.0matches method attributes inregisterAttributedEntryPoint(). Class-level entry points are deferred until the Mago SDK supports them. SessionInterface::get(),InputBag::get(),Route::getDefault(), andFormConfigInterface::getOption()are not narrowed on defaults. A storednullor a configured value can bypass the default at runtime.HandledStamp::getResult()staysmixedbecause compiled container XML has no message-to-handler return graph.Envelope::last(),Envelope::all(),Request::getContent(),FileLocatorInterface::locate(),EventDispatcherInterface::dispatch(),CacheInterface::get(),ValidatorInterface::validate(),RouteCollection,FormView, and Twig helpers are already typed by Mago from Symfony 6.4 and 7.x vendor signatures.HelperSet::get()andCommand::getHelper()narrowing assumes the four default helper names are not remapped to unrelated classes.ControllerEvent::getAttributes()narrowing assumes the attribute map passed tosetController()matches its class keys.WrappedExceptionsInterface::getWrappedExceptions()narrows onlyThrowablesubtypes, so non-Throwablemarker interfaces keepThrowablemethods.- On Symfony 6.4 and 7.2, an untracked
NodeBuilderstays nullable (ArrayNodeDefinition|null), and an untrackedNodeDefinitionfalls back to Symfony's declaredend()return type. ConsoleCommandArgumentsHookreads staticaddArgument(),addOption(), andsetDefinition()calls (array literals ornew InputDefinition([...]), including constant names and aliased imports) inconfigure().- When
Symfony\Bundle\FrameworkBundle\Console\Applicationis present in[source] includes,env,no-debug, andprofileare treated as default application options on everyCommandsubclass because static codebase metadata cannot determine whether a command mounts onFrameworkBundle\Console\Applicationor a standaloneConsole\Application. Excludevendor/symfony/framework-bundlefromincludesin standalone Console applications to enforce plainApplicationdefaults.
Development
composer install
php tests/check-spec.php
composer test
composer test runs Symfony runtime contract tests, validates bin/mago-symfony-worker, and checks exact diagnostics in JSON map, compiled XML, Security user, plain console, lifecycle, and explicit config-error modes.
Run pinned OSS corpus checks (symfony-demo, symfony, shopware, drupal):
php tools/corpus-run.php --check php tools/corpus-run.php --target=symfony-demo,symfony --check php tools/corpus-run.php --update-baseline
Run local benchmarks and verify conformance hashes:
php bench/run-local.php --iterations=10000 --runs=5 php spec/harvest.php
License
MIT. See LICENSE.