VincentLanglet / Twig-CS-Fixer

A tool to automatically fix Twig Coding Standards issues
MIT License
202 stars 18 forks source link

Indentation in hash parameters #243

Open lukepass opened 6 days ago

lukepass commented 6 days ago

Expected behavior

I wish that hash arguments were indented when on multiple lines. For example:

From:

{{ form_start(form, {
                    attr: {
                    class: 'quiz',
                    'data-controller': 'ajax-form quiz',
                    'data-ajax-form-targets-value': ['#ajax-content-1', '#ajax-content-2', '#lesson-footer']|serialize('json') ,
    'data-ajax-form-spinner-html-value': include('shared/_spinner.html.twig'),
    'data-ajax-form-scroll-to-value': '#ajax-content-1',
}
}) }}

To:

{{ form_start(form, {
    attr: {
        class: 'quiz',
        'data-controller': 'ajax-form quiz',
        'data-ajax-form-targets-value': ['#ajax-content-1', '#ajax-content-2', '#lesson-footer']|serialize('json') ,
        'data-ajax-form-spinner-html-value': include('shared/_spinner.html.twig'),
        'data-ajax-form-scroll-to-value': '#ajax-content-1',
    }
}) }}

Actual behavior

Hash indentation is not changed.

VincentLanglet commented 6 days ago

Hi, do you want to try working on a rule ?

lukepass commented 6 days ago

Yes, of course! I would like to! How can I do that?

VincentLanglet commented 6 days ago

You can play with https://github.com/VincentLanglet/Twig-CS-Fixer/blob/main/tests/Token/Tokenizer/TokenizerTest.php to understand how the code is Tokenized.

For example {{ {'foo': 42} }} is tokenized with tokens of the type

Notice that in case of the token } you'll have $token->getRelatedToken() returning the one which is opening {. (This is currently used only for ternary $a ? $b : $c here https://github.com/VincentLanglet/Twig-CS-Fixer/blob/1f1bcc5b7a608c64603e8d3a879508316bfc9919/src/Rules/Operator/OperatorSpacingRule.php#L35-L37).

You rule will need to be configurable to know what should be used for indent (tab or space ? And how many space ?) an example can be found here https://github.com/VincentLanglet/Twig-CS-Fixer/blob/main/src/Rules/Whitespace/IndentRule.php#L14

Here you have an example of rule which works on ), } and ] https://github.com/VincentLanglet/Twig-CS-Fixer/blob/1f1bcc5b7a608c64603e8d3a879508316bfc9919/src/Rules/Punctuation/TrailingCommaMultiLineRule.php#L31 ; I assume you'll have to

But the issue you'll encounter will be

My fear is the fact that putting one step in the indentation rule will end with having to indenting everything ({, (, operator, ...) which seems kinda complicated (PHP-Cs-Fixer rule is not even perfect ATM).

ruudk commented 5 days ago

@lukepass Just wanted to say that I'm also very much interested in having this properly formatted. So thanks in advance for your work on this 🙌 💪