php-ruleset-formatter

Adding Custom Rules to PHPFormatExtension

This guide explains how to add your own custom formatting rules to the PHPFormatExtension project, and how to contribute them back to the project if you wish.

1. Adding Custom Rules (For Personal Use)

Step 1: Understand the Rule System

Step 2: Create Your Rule Logic

Step 3: Register the Rule

Step 4: Enable the Rule

Step 5: Test Your Rule


2. Contributing Your Rule to the Project

If you want to share your new rule with others:

Step 1: Follow Project Guidelines

Step 2: Add Documentation

Step 3: Submit a Pull Request


3. Example: Enforce a Blank Line After Each Function Declaration

Suppose you want to add a custom rule that ensures there is exactly one blank line after every function’s closing brace. Here’s how you could do it:

Step 1: Add the Rule Logic

export function blankLineAfterFunction(lines: string[]): string[] {
  const output: string[] = [];
  for (let i = 0; i < lines.length; i++) {
    output.push(lines[i]);
    // Detect end of function (simple heuristic: line with only '}' and previous line starts with 'function')
    if (
      lines[i].trim() === '}' &&
      i > 0 &&
      /^\s*function\b/.test(lines[i - 1])
    ) {
      // If next line exists and is not blank, insert a blank line
      if (lines[i + 1] && lines[i + 1].trim() !== '') {
        output.push('');
      }
    }
  }
  return output;
}

Step 2: Register the Rule

import { blankLineAfterFunction } from './rules';
// ...existing code...
if (rules.blankLineAfterFunction) {
  lines = blankLineAfterFunction(lines);
}

Step 3: Add a Rule Option

blankLineAfterFunction?: boolean;

Step 4: Enable the Rule (Optional)

if (hasRuleRef(xml, 'Custom.Functions.BlankLineAfterFunction')) {
  parsed.blankLineAfterFunction = true;
}

Step 5: Test the Rule

Step 6: Enabling the Rule in Your Ruleset XML

To enable your new rule via the ruleset XML file, add a <rule ref="..."/> entry that matches the reference you used in your XML parsing logic. For the example above, add this to your ruleset XML:

<rule ref="Custom.Functions.BlankLineAfterFunction"/>

This will activate the rule if your src/rules-xml.ts file includes logic like:

if (hasRuleRef(xml, 'Custom.Functions.BlankLineAfterFunction')) {
  parsed.blankLineAfterFunction = true;
}

Make sure to reload or re-run the formatter after updating your ruleset XML.


This example demonstrates how to add a brand new custom rule, register it, and (optionally) enable it via your ruleset XML file.