Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions config-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,10 @@
"type": "object",
"description": "Controls the formatting strategy. PHPantom ships a built-in formatter (PER-CS 2.0 style). Projects with php-cs-fixer or PHP_CodeSniffer in composer.json require-dev automatically use those tools instead. Explicit configuration here always takes priority.",
"properties": {
"enabled": {
"type": "boolean",
"description": "Whether formatting is enabled at all. Unset or true: format with the resolved strategy. false: answer no formatting requests, the built-in formatter included."
},
"pint": {
"type": "string",
"description": "Command or path to run Laravel Pint. Unset: auto-detect from composer.json require-dev. Empty string: disable Pint. Any other value: use as the command."
Expand Down
2 changes: 2 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Stubs that override.** List stub files and directories under `[stubs] paths` in `.phpantom.toml`, and what they declare wins over every other declaration of the same name, PHP's own built-in stubs included. Use it for hand-written stubs of a PHP extension or to correct a signature you disagree with. Stub files are never analysed or edited, and an editor extension can pass a bundled stubs directory the same way. See [configuration.md](configuration.md#stubs).
- **The other folders of a multi-root workspace resolve.** Classes, functions, and constants declared in another folder of the editor's workspace now complete, resolve, and jump to their declaration from this one. That folder is treated as a library, like `vendor/`, so its own diagnostics and renames stay with the folder itself. Adding or removing a folder takes effect without a restart.
- **Stub packages installed with Composer.** A stub package such as `php-stubs/wordpress-stubs` or `php-stubs/woocommerce-stubs` works like a `[stubs]` path with nothing to configure, so WordPress and WooCommerce functions and classes resolve in a theme or plugin that requires them. An installed `jetbrains/phpstorm-stubs` takes over PHP's own functions and classes, and go-to-definition on a built-in opens it there. Installing, updating, or removing a package takes effect without a restart.
- **Turn formatting off.** `enabled = false` under `[formatting]` in `.phpantom.toml` stops PHPantom from formatting, built-in formatter included. Contributed by @enwi.

### Changed

Expand All @@ -215,6 +216,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Diagnostic identifiers follow one naming scheme.** Ahead of 1.0, these were renamed: `invalid_member_access` is now `inaccessible_member`, `invalid_laravel_trans` is `invalid_laravel_translation`, `invalid_command_parameter` is `invalid_laravel_command_parameter`, `missing_view_variable`, `unused_view_variable` and `type_mismatch_view_variable` are `missing_blade_variable`, `unused_blade_variable` and `type_mismatch_blade_variable`, and `blade_signature_widens_layout` is `incompatible_blade_signature`. The old names keep working in `[[diagnostics.ignore]]`, `@phpantom-ignore` and `analyze --code`, and the config and command line warn when they meet one. The [Diagnostics Reference](diagnostics.md) lists every identifier.
- **Configuration names follow one spelling.** Ahead of 1.0, every section and key in `.phpantom.toml` is kebab-case: `[semantic_tokens]` is now `[semantic-tokens]`, `[inlay_hints]` is `[inlay-hints]`, and `report-magic-properties` under `[diagnostics]` is `magic-properties`, to match the other diagnostic toggles. The old names keep working, with a warning that names the new one.
- **A member used on a class that cannot be found is reported as `unknown_class`.** "Cannot check method save(), because type App\Models\User could not be resolved" used to carry `unknown_member`. It now carries `unknown_class`, so ignoring missing classes covers it too, and `unknown_member` is left for members a class really lacks.
- **Disabling every external formatter keeps the built-in one.** Setting `pint`, `php-cs-fixer`, and `phpcbf` all to `""` under `[formatting]` now formats with the built-in formatter instead of turning formatting off. Use `enabled = false` to turn it off. Contributed by @enwi.
- **Updated embedded phpstorm-stubs.** Adds the `ps`, `proctitle`, and `yaz` extensions, updates Judy and Relay, and corrects many parameter and return types to match the PHP documentation, including `oci_fetch_object()`, `pg_loopen()`, and nullable RdKafka message payloads.

#### Performance and memory
Expand Down
5 changes: 4 additions & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,7 @@ Your editor can switch these off too, see [Editor-supplied inlay hint toggles](#

| Key | Type | Default | Description |
| -------------- | ------- | ------- | ----------- |
| `enabled` | boolean | unset | Whether formatting is enabled at all. Unset or `true`: format with the strategy below. `false`: turn formatting off, built-in formatter included. |
| `pint` | string | unset | Command or path for Laravel Pint. Unset: auto-detect from `require-dev`. `""`: disable. |
| `pint-blade` | boolean | unset | Whether `.blade.php` files are formatted by Pint's `Pint/laravel_blade` rule. Unset: follow the workspace `pint.json`. `true`: send them to Pint with `--blade`. `false`: never. |
| `blade-formatter` | string | unset | Command or path for [blade-formatter](https://github.com/shufo/blade-formatter), used for `.blade.php` files. Unset: use it when the project does (see below). `""`: never. Any other value: always, even over Pint. |
Expand Down Expand Up @@ -428,7 +429,9 @@ PHPantom ships a built-in PHP formatter (mago-formatter) that works out of the b

1. **Explicit config wins.** A tool path set under `[formatting]` in `.phpantom.toml` (`pint`, `php-cs-fixer`, or `phpcbf`) is always used. Setting a tool to `""` disables it.
2. **Composer `require-dev` wins over the built-in formatter.** If `composer.json` lists `laravel/pint`, `friendsofphp/php-cs-fixer`, or `squizlabs/php_codesniffer` in `require-dev`, PHPantom resolves the binary through Composer's bin-dir and runs it as a subprocess. A `phpcs.xml`, `.phpcs.xml`, `phpcs.xml.dist`, or `.phpcs.xml.dist` file at the workspace root certifies phpcbf the same way, so a project that only pulls `squizlabs/php_codesniffer` in transitively (e.g. through `slevomat/coding-standard`) is still detected. These tools discover their own project config (`pint.json`, `.php-cs-fixer.php`, `.phpcs.xml`, etc.) as they normally would.
3. **Otherwise, the built-in formatter is used.**
3. **Otherwise, the built-in formatter is used.** This includes projects that set every external tool to `""`.

To turn formatting off entirely, set `enabled = false` under `[formatting]`.

**Formatting a selection** (`textDocument/rangeFormatting`) works with every one of these. None of them can format part of a file, so PHPantom formats the whole file and applies only the changes on the selected lines. A change that runs past the edge of the selection is applied whole, so the file never ends up half-formatted mid-statement, and lines the formatter moved (sorted imports, for example) are moved as a unit rather than dropped or duplicated.

Expand Down
29 changes: 29 additions & 0 deletions src/config/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -771,9 +771,38 @@ fn formatting_empty_string_disables_tool() {
assert_eq!(config.formatting.php_cs_fixer.as_deref(), Some(""));
assert_eq!(config.formatting.phpcbf.as_deref(), Some(""));
assert_eq!(config.formatting.pint.as_deref(), Some(""));
assert!(!config.formatting.is_disabled());
}

#[test]
fn formatting_enabled_false_disables_formatting() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(CONFIG_FILE_NAME);
std::fs::write(&path, "[formatting]\nenabled = false\n").unwrap();
let config = load_config(dir.path()).unwrap();
assert_eq!(config.formatting.enabled, Some(false));
assert!(config.formatting.is_disabled());
}

#[test]
fn formatting_enabled_true_is_not_disabled() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(CONFIG_FILE_NAME);
std::fs::write(&path, "[formatting]\nenabled = true\n").unwrap();
let config = load_config(dir.path()).unwrap();
assert!(!config.formatting.is_disabled());
}

#[test]
fn formatting_enabled_unset_is_not_disabled() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(CONFIG_FILE_NAME);
std::fs::write(&path, "[formatting]\ntimeout = 5000\n").unwrap();
let config = load_config(dir.path()).unwrap();
assert_eq!(config.formatting.enabled, None);
assert!(!config.formatting.is_disabled());
}

#[test]
fn formatting_defaults() {
let config = Config::default();
Expand Down
15 changes: 9 additions & 6 deletions src/config/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,16 @@ use serde::Deserialize;
/// Explicit configuration in `.phpantom.toml` always takes priority:
/// set a tool path to use it, or set it to `""` to disable it.
/// When no external tool is configured or detected, the built-in
/// formatter is used.
/// formatter is used. `enabled = false` turns formatting off entirely.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct FormattingConfig {
/// Whether formatting is enabled at all.
///
/// - `None` (default) or `true` — format with the resolved strategy.
/// - `false` — answer no formatting requests, built-in formatter
/// included.
pub enabled: Option<bool>,
/// Command (path or name) to run php-cs-fixer.
///
/// - `None` (default) — check `require-dev` in `composer.json`;
Expand Down Expand Up @@ -90,12 +96,9 @@ impl FormattingConfig {
self.timeout.unwrap_or(10_000)
}

/// Whether formatting is entirely disabled (every tool explicitly
/// set to an empty string).
/// Whether formatting is turned off with `enabled = false`.
pub fn is_disabled(&self) -> bool {
crate::formatting::Tool::ALL
.into_iter()
.all(|tool| tool.configured(self) == Some(""))
self.enabled == Some(false)
}
}

Expand Down
18 changes: 17 additions & 1 deletion src/format_cli/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ fn formatting_disabled_in_config_reports_no_run_at_all() {
write_file(
dir.path(),
".phpantom.toml",
"[formatting]\npint = \"\"\nphp-cs-fixer = \"\"\nphpcbf = \"\"\n",
"[formatting]\nenabled = false\n",
);

assert!(
Expand All @@ -198,6 +198,22 @@ fn formatting_disabled_in_config_reports_no_run_at_all() {
assert_eq!(run(options(dir.path(), true)), 0);
}

#[test]
fn every_external_tool_disabled_still_formats_with_the_builtin_formatter() {
let dir = workspace(&[("src/Foo.php", "<?php\nnamespace App;\nclass Foo {}\n")]);
write_file(
dir.path(),
".phpantom.toml",
"[formatting]\npint = \"\"\nphp-cs-fixer = \"\"\nphpcbf = \"\"\n",
);

assert_eq!(
unformatted(dir.path(), true),
vec!["src/Foo.php".to_string()]
);
assert_eq!(run(options(dir.path(), true)), 2);
}

// ── Machine-readable output ─────────────────────────────────────────

fn sample() -> (Vec<Reformatted>, Vec<Failure>) {
Expand Down
4 changes: 1 addition & 3 deletions src/formatting/blade/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1242,9 +1242,7 @@ fn blade_strategy_is_builtin_without_pint() {
#[test]
fn blade_strategy_is_disabled_when_formatting_is() {
let config = FormattingConfig {
pint: Some(String::new()),
php_cs_fixer: Some(String::new()),
phpcbf: Some(String::new()),
enabled: Some(false),
..FormattingConfig::default()
};
let strategy = resolve_blade_strategy(None, &config, None, None, PhpVersion::default());
Expand Down
4 changes: 2 additions & 2 deletions src/formatting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,13 +185,13 @@ pub enum FormattingStrategy {
/// the workspace root.
///
/// Resolution rules:
/// - If `config.is_disabled()` (every tool set to `""`) → `Disabled`.
/// - If `config.is_disabled()` (`enabled = false`) → `Disabled`.
/// - If any tool has an explicit non-empty path in config →
/// `External` with those tools.
/// - Otherwise every tool the project's metadata selects (see
/// [`Tool::detected`]) and whose binary the Composer bin-dir holds →
/// `External`.
/// - Otherwise → `BuiltIn`.
/// - Otherwise (including when every tool is set to `""`) → `BuiltIn`.
///
/// `phpcs_standard` is the `[phpcs]` standard, handed on to phpcbf.
pub fn resolve_strategy(
Expand Down
28 changes: 27 additions & 1 deletion src/formatting/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,8 +270,19 @@ fn malformed_mago_toml_returns_error_not_panic() {
}

#[test]
fn strategy_both_disabled() {
fn strategy_disabled() {
let config = FormattingConfig {
enabled: Some(false),
..FormattingConfig::default()
};
let strategy = resolve_strategy(None, &config, None, None, None);
assert!(matches!(strategy, FormattingStrategy::Disabled));
}

#[test]
fn strategy_all_tools_disabled_falls_back_to_builtin() {
let config = FormattingConfig {
enabled: Some(true),
pint: Some(String::new()),
php_cs_fixer: Some(String::new()),
phpcbf: Some(String::new()),
Expand All @@ -281,12 +292,24 @@ fn strategy_both_disabled() {
timeout: None,
};
let strategy = resolve_strategy(None, &config, None, None, None);
assert!(matches!(strategy, FormattingStrategy::BuiltIn(None)));
}

#[test]
fn strategy_disabled_wins_over_explicit_command() {
let config = FormattingConfig {
enabled: Some(false),
php_cs_fixer: Some("/usr/bin/php-cs-fixer".to_string()),
..FormattingConfig::default()
};
let strategy = resolve_strategy(None, &config, None, None, None);
assert!(matches!(strategy, FormattingStrategy::Disabled));
}

#[test]
fn strategy_explicit_commands() {
let config = FormattingConfig {
enabled: Some(true),
pint: None,
php_cs_fixer: Some("/usr/bin/php-cs-fixer".to_string()),
phpcbf: Some("/usr/bin/phpcbf".to_string()),
Expand All @@ -311,6 +334,7 @@ fn strategy_explicit_commands() {
#[test]
fn strategy_one_explicit_one_disabled() {
let config = FormattingConfig {
enabled: Some(true),
pint: None,
php_cs_fixer: Some("/usr/bin/php-cs-fixer".to_string()),
phpcbf: Some(String::new()),
Expand Down Expand Up @@ -639,6 +663,7 @@ fn strategy_explicit_overrides_require_dev() {

// User explicitly set a different path.
let config = FormattingConfig {
enabled: Some(true),
pint: None,
php_cs_fixer: Some("/opt/php-cs-fixer".to_string()),
phpcbf: Some(String::new()),
Expand Down Expand Up @@ -904,6 +929,7 @@ fn execute_builtin_reformats_messy_class() {
fn execute_disabled_returns_none() {
let content = "<?php\necho 'hello';\n";
let config = FormattingConfig {
enabled: Some(true),
pint: None,
php_cs_fixer: Some(String::new()),
phpcbf: Some(String::new()),
Expand Down
Loading