Giter Site home page Giter Site logo

twig-cs-fixer's Introduction

Twig CS Fixer

PHP Version Latest Stable Version License Actions Status Coverage Type Coverage Infection MSI

Installation

This standard can be installed with Composer.

Add the coding standard as a dependency of your project

composer require --dev vincentlanglet/twig-cs-fixer

Then, use it!

vendor/bin/twig-cs-fixer lint /path/to/code
vendor/bin/twig-cs-fixer lint --fix /path/to/code

Twig Coding Standard Rules

From the official one.

Delimiter spacing

Ensures there is a single space after a delimiter opening ({{, {% and {#) and before a delimiter closing (}}, %} and #}).

When using a whitespace control character, do not put any spaces between it and the delimiter.

Operator spacing

Ensures there is a single space before and after the following operators: comparison operators (==, !=, <, >, >=, <=), math operators (+, -, /, *, %, //, **), logic operators (not, and, or), ~, is, in, and the ternary operator (?:).

Removes any space before and after the .. operator.

Punctuation spacing

Ensures there is a single space after : in hashes and , in arrays and hashes.

Removes any space after an opening parenthesis and before a closing parenthesis in expressions.

Removes any space before and after the following operators: |, ., [].

Removes any space before and after parenthesis in filter and function calls.

Removes any space before and after opening and closing of arrays and hashes.

Custom configuration

By default, the twig-cs-fixer standard is enabled with the twig coding standard rules and some extra rules. This tool also provides a standard with only the twig rules and another standard with extra rules from the symfony coding standards.

Everything is configurable, so take a look at the following documentation:

twig-cs-fixer's People

Contributors

94noni avatar adamzimmermann avatar alexander-schranz avatar feuerwagen avatar joolsmcfly avatar k00ni avatar llaville avatar lyrixx avatar marsender avatar ruudk avatar smnandre avatar thislg avatar tobias-93 avatar treast avatar vincentlanglet avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

twig-cs-fixer's Issues

Example in the docs

Rule(s) related to or rule(s) missing

Not a rule, just the example in the .docs/configuration.md looks to be a bit misleading.

Expected behavior

Copy and pasting the config snippet works without any issues.

Actual behavior

Get back an Error: TwigCsFixer\Ruleset\Ruleset::addRule(): Argument #1 ($rule) must be of type TwigCsFixer\Rules\RuleInterface, string given, called in /srv/.twig-cs-fixer.dist.php on line 5

Looks like amending the snippet from
$ruleset->addRule(\TwigCsFixer\Rules\Whitespace\EmptyLinesRule::class);
to
$ruleset->addRule(new \TwigCsFixer\Rules\Whitespace\EmptyLinesRule());
looks like it works as expected.

N.b. first time using this, I might have missed something obvious.

FileNameRule not works

Rule(s) related to or rule(s) missing

FileNameRule

Expected behavior

FileNameRule should report errors to me.

Actual behavior

I download Symfony with symfony new myproject --php=8.2 --webapp --docker --cloud

Then I download this bundle with symfony composer require --dev vincentlanglet/twig-cs-fixer

I put this config

// .twig-cs-fixer.php

<?php

use TwigCsFixer\Rules\File\FileNameRule;

$ruleset = new TwigCsFixer\Ruleset\Ruleset();
$ruleset->addRule(new FileNameRule(baseDirectory: 'templates', ignoredSubDirectories: ['bundles']));

$config = new TwigCsFixer\Config\Config();
$config->setRuleset($ruleset);
$config->setCacheFile(null);

return $config;

I rename templates/base.twig.html by templates/Xbase.twig.html for test this rule.

I execute vendor\bin\twig-cs-fixer lint but I have no errors.

fail to lint string slice notation

Let's say we have sth like this in the code:
{% set var = 'test'[0:1] ~ 'test'[:3] %}

After firing the lint --fix we have:
{% set var = 'test'[0: 1] ~ 'test'[: 3] %}

image

Question on some twig cs fix

Hi, first thanks for this lib, I discovered it recently and began to use it on some of my pro/perso projects :)

Rule(s) related to or rule(s) missing

I have a question regarding a fix on spaces for some twig: see after

Expected behavior

it removes extra spaces

{% extends '@Admin/base.html.twig' %}
{% block main_content %}

Actual behavior

it does not remove extra spaces

{%    extends    '@Admin/...'     %}
{%    block main_content       %}

I was expecting the same twig cs fix as for example:

{{ my_var}} => {{ my_var }}


Is it a normal behavior or should I configure something?
I am using the v0.3 with the default config (and twig/twig v2)

Thank you!

Space in single line objects

Rule(s) related to or rule(s) missing

I'm searching for a way which I can force a space around object in single lines.

Expected behavior

+{{ include('app/atoms/icon.html.twig', { icon: 'time' }, with_context = false) }
-{{ include('app/atoms/icon.html.twig', {icon: 'time'}, with_context = false) }}

Actual behavior

-{{ include('app/atoms/icon.html.twig', { icon: 'time' }, with_context = false) }
+{{ include('app/atoms/icon.html.twig', {icon: 'time'}, with_context = false) }}

Integration with Symfony/UX

Hi @VincentLanglet ! Love your tool!

We are currently considering integrating Twig-CS-Fixer into the SymfonyUX CI. There are some issues related to custom Twig components tags today (props tag/comment at least)

I know you worked on it, what are the blocking points you see today ? How can we help ? Do you see a "most praactical way" to ensure a great compatibility in the future ?

[RFC] Rule whish list

Hello,

I have a wish list ๐ŸŽ :) Feel free to close it if it's not in your scope!

Remove useless quote in hashes

Do you think it would be doable to apply this diff

- {{ include('hello.html.twig', { 'publications': alreadyPublished }) }}
+ {{ include('hello.html.twig', { publications: alreadyPublished }) }}

Use the same quote everywhere

- {{ include("hello.html.twig" }}
+ {{ include('hello.html.twig' }}

Note: It would depends on the configuration

Exclude the node_modules directory by default

Rule(s) related to or rule(s) missing

N/A

Expected behavior

I'm finally getting around to fully integrating the exclude/custom finder functionality. Thanks again for your help with that.

I created a custom .twig-cs-fixer.php per the instructions in the README and everything is working. However I realized that my change might be what we want by default.

I simply added ->exclude('node_modules'); and I'm wondering if that should be the default.

If so, I'm happy to submit a PR for that.

Actual behavior

Exclude node_modules from linting by default.

Option to exclude Symfony tokens

I didn't find a way to disable Symfony specific tokens that are included in symfony/twig-bridge.

If only twig/twig package is used and an extension is added that register a tag with the same name, but different syntax, it will cause errors. In my case, I have a trans tag with a different syntax than the one from symfony/twig-bridge.

Unknown 'form_theme' Tag Error with Custom Form Theme

Hi, I'm having a problem trying to apply a custom form theme in my Symfony project.

When I use the tag {% form_theme form with 'Form/tailwind_2_override_layout.html.twig' %} to define a custom form theme, I get the following error: File is invalid: Unknown "form_theme" tag.

The form adopts the style defined in 'Form/tailwind_2_override_layout.html.twig' but I get the error.

Expected behavior

The form_theme variable should not block twig cs fixer

Actual behavior

An error is generated indicating File is invalid: Unknown "form_theme" tag.

include syntax

Rule(s) related to or rule(s) missing

There seem to be a recent change (version 2.9.0) with the way you format includes.
But this new way, valid in twig v3, makes my code fail since i use twigjs and it does not support it
can i disable this particular rule ?

Expected behavior

{% include('template.html') with vars %}

Actual behavior

{{ include('template.html', vars) }}

Add phar?

Most tools similar to this one (e.g. phpstan, php-cs-fixer) make a phar version available for download.
It would be nice to see the same here.

`PascalCase` and `snake_case`

Rule(s) related to or rule(s) missing

  • DirectoryNameRule
  • FileNameRule

Expected behavior

Use PascalCase.

Actual behavior

I use snake_case for all my Twig files. But exceptionally in a folder, I also use another case, the PascalCase. I use the PascalCase because I use Twig Components. The files are then of the following form:

  • templates/components/Alert.html.twig
  • templates/components/Alert/Succes.html.twig
  • ...

For example, here is an error I have:

KO .\templates\components\Text\TextLink.html.twig


ERROR >> | The file name must use snake_case; expected text_link.


ERROR >> | The directory name must use snake_case; expected text.


// .twig-cs-fixer.php

<?php

$ruleset = new TwigCsFixer\Ruleset\Ruleset();
$ruleset->addStandard(new TwigCsFixer\Standard\Symfony());

$config = new TwigCsFixer\Config\Config();
$config->setRuleset($ruleset);
$config->setCacheFile(null);
$config->allowNonFixableRules();

return $config;

[DX] Aliases "check" & "fix"

i'd like to have two aliases: check & fix , so i started to see how that could be done.

This seems to work perfectly by adding thoses aliases in the entry point, and two lines in the command

// bin/twig-cs-fixer

// ...

$command = new TwigCsFixerCommand();
$command->setAliases(['fix', 'check']);

$application = new Application();
// TwigCsFixerCommand.php


    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        if ('check' === $input->getArgument('command')) {
            $input->setOption('fix', false);
        } elseif ('fix' === $input->getArgument('command')) {
            $input->setOption('fix', true);
        }

Would you be open to that ? If yes do you think there is a better way to implement it ?

Comparison to friendsoftwig/twigcs

Can you help me understand how this relates to https://github.com/friendsoftwig/twigcs with functionality and when I would want to use one vs the other?

The one big thing I've noticed so far is that this project seems to offer automated code style fixes while https://github.com/friendsoftwig/twigcs does not.

This project also seems to enforce the Symfony standard while https://github.com/friendsoftwig/twigcs enforces the "Official one from Twig".

At the moment the only available standard is the official one from twig.

I need to test them both out more this week, but wanted to file an issue to hopefully get a discussion started and document my finding too when I know more.

Any help or guidance is much appreciated!

`same as <token>` is not allowed.

Rule(s) related to or rule(s) missing

When I try same as <token> I have this error:

File is invalid: A hash value must be followed by a comma. Unexpected token "name" of value "active" ("punctuation"
          expected with value ",").

Expected behavior

active: attendance.response is same as state should works

Context:

attendance is an object
attendance.response is an enum.

state is the same enum but in a loop of all cases.

Actual behavior

active: attendance.response is same as (state) is working.

html & twig cs fixer

i dont know if i could help or something, but i saw this issue
and i was kind of sad to see there was no solution.
I'm curious to know which html formatter you actually use, that would be compatible with twig.
i'm a bit tired of new / old developers pushing untidy code, having missing/mismatch closing tags because bad indent, etc.
it's time to have a real html+twig formatter or ditch twig for good.

I have to say that vscode's default html formater destroys twig templates (for exemple "#}" => "# }" which kills rendering).

i just want something that works, any specific html cs/twig cs woud be acceptable, but here is my favorite :
indent all html tags (one per line), then indent twig correctly (one per line), and when the line is too large for a specific tag we split attributes line by lines.

<div style="{% if xx %}fdsfsdfsdf{% endif %}">
    {% if xxx %}
        <a
            href="xxxxxxxxxxxx"
            style="xxxxxxxxxxxxxxx"
        >
            <img src="" />
        </a>
    {% endif %}
</div>

everything is f**** readable now :) ๐Ÿ‘

Inability to include "&" in a translatable string without an error

Rule(s) related to or rule(s) missing

throw new Exception(sprintf('Unexpected character "%s"', $currentToken));

It seems that we need to add an additional ifelse statement to catch a translation block.

Or assuming that this is a block, perhaps this logic needs to be updated?

protected function lexBlock(): void
{
$endRegex = $this->regexes['lex_block'];
preg_match($endRegex, $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor);
/** @var array<int, array{string, int}> $match */
if (count($this->bracketsAndTernary) === 0 && isset($match[0])) {
$this->pushToken(Token::BLOCK_END_TYPE, $match[0][0]);
$this->moveCursor($match[0][0]);
$this->moveCurrentPosition();
$this->popState();
} else {
$this->lexExpression();
}

I'm happy to submit a patch if you can nudge me in the right direction.

Expected behavior

Users are able to include & in a translated string with this flagging it as an issue. I'm presuming this might be a bug for other characters as well.

Actual behavior

Template file:

{#
/**
 * @file
 * HTML for the copyright notice.
 */
#}

{% set year = "now"|date("Y") %}

<div class="structure__copyright">
  {% trans with {
    '%privacy_path%': path('entity.node.canonical', {'node': 309}),
    '%terms_path': path('entity.node.canonical', {'node': 308}),
    '%year': year
  %}
    I want to translate text about this & that.
  {% endtrans %}
</div>

Command line output:

 [ExecStack] Executing vendor/bin/twig-cs-fixer lint web/modules/custom web/themes/example
 [ExecStack] Running vendor/bin/twig-cs-fixer lint web/modules/custom web/themes/example

 KO /Users/example/www/example/web/modules/custom/example_module/templates/example-copyright-block.html.twig
 ------- ------------------------------------------------------
  FATAL   15   | %}
          16   |   I want to translate text about this & that.
          >>   | Unexpected character "&".
          17   | {% endtrans %}
 ------- ------------------------------------------------------


 [ERROR] Files linted: 118, notices: 0, warnings: 0, errors: 1


 [ExecStack]  Exit code 1  Time 1.858s
 [notice] Stopping on fail. Exiting....
 [error]  Exit Code: 1
 [error]    in task Robo\Task\Base\ExecStack


Script robo --ansi handling the robo event returned with error code 1
Script composer robo job:check-coding-standards handling the cs-check event returned with error code 1

[Feature] Ability to exclude directory

This is a shameless feature request that would solve an issue I've stumbled upon as I'm integrating this tool with more repositories. Your tool has been working wonderfully with everything it promises to do and has been a big help so far.

Some context:

Could we add the ability for twig-cs-fixer to support an --ignore flag the way phpcs does?

e.g. https://github.com/ChromaticHQ/chq-robo/blob/2.x/src/Robo/Plugin/Commands/CICommands.php#L106

I realize that I could simply separate the list of custom code paths and only point twig-cs-fixer at the templates directory in my theme. However, then there is the need to maintain two lists. I'm guessing others might find this feature useful for other purposes as well.

I assume the logic would live somewhere in here?

If so, I can take a shot at contributing something, but wanted to get your take first.

Expected behavior

The ability to ignore selected directories.

Actual behavior

Unable to do so.

--verbose option doesn't work as expected

in my case, I have some twigs file which have redundant spaces between twig filters (ex: 'Hello' | trans), but when running vendor/bin/twig-cs-fixer lint --fix --verbose it just shows like this

Screenshot from 2023-07-28 12-33-07

imo, it should show a list of fixed files so we can keep track what changed files after running the command

Unexpected token "spread operator" of value "..."

Rule(s) related to or rule(s) missing

Symfony UX component special spread operator syntax for component arguments

Other Symfony UX Components syntax is working as expected

Expected behavior

Syntax is OK

Actual behavior

Error

  FATAL   4    |                                          
          5    |    <twig:Alert {{ ...args }}></twig:Alert>                           
          >>   | File is invalid: Unexpected token "spread operator" of value "...".  
          6    | {% endblock %}  

Unknown 'trans_default_domain' tag

In Symfony 7.0, PHP 8.3, Twig 3.8.0 and twig-cs-fixer 2.0.0, I suddenly get an error for the trans_default_domain tag.

  FATAL   1    | {% extends '@EasyAdmin/page/content.html.twig' %}
          2    | {% trans_default_domain 'EasyBundle' %}
          >>   | File is invalid: Unknown "trans_default_domain" tag.
          3    | {% block page_title 'Welcome'|trans %}

or

  FATAL   1    | {% apply inky_to_html|inline_css(encore_entry_css_source('mail')) %}
          2    | {% trans_default_domain 'security' %}
          >>   | File is invalid: Unexpected "trans_default_domain" tag (expecting closing tag for the "apply" tag defined near line 2).
          3    | <container>

[RFC] rule `VariableNameRule` allowing variable prefix `_`

Rule(s) related to or rule(s) missing

v2.8 VariableNameRule

Expected behavior

{% set _user_email = user.email %} dont produce an error with snake_case config of VariableNameRule

Actual behavior

error, as _ is not handled now


Hello ๐Ÿ‘‹๐Ÿป

in our quite big codebase, we are used to an "internal twig standard" where variable passed form controller are snake_case and the one defined inside a twig template are _snake_case

so may I propose an RFC: can we imagine a configuration allowing a prefix for var naming?

This RFC can extends to:

  • FileNameRule (we name some partial views like /_info.html.twig)
  • DirectoryNameRule (we name some folder containing only partial views like _blocks/)

Custom reporters and output formats for errors

Rule(s) related to or rule(s) missing

Awesome project, would be great to have some type of --reporter checkstyle for output so we can integrate this into our pipeline. That way we can use annotations on pull requests to mark what needs to be fixed.

Expected behavior

Implementing custom reports like twigcs

twigcs /path/to/views --reporter console
twigcs /path/to/views --reporter checkstyle
twigcs /path/to/views --reporter junit
twigcs /path/to/views --reporter emacs
twigcs /path/to/views --reporter json
twigcs /path/to/views --reporter csv
twigcs /path/to/views --reporter githubAction
twigcs /path/to/views --reporter gitlab

Actual behavior

Currently do not have an option for the output format for errors.

fail to lint this : {% for a in b.in %}

when i run twigcsfixer on this particular file it fails

the run

twig-cs-fixer lint --fix test.html.twig 
Error: Cannot fix the file "test.html.twig".

the file

{% for a in b.in %}
    <tr>
    </tr>
{% endfor %}

".in" is causing twig-cs-fixer to fail. when i rename this to "ins" for exemple the code is ok.

Option to use tabs

Rule(s) related to or rule(s) missing

  • Whitespace\IndentRule
  • Whitespace\IndentStyle โ† missing

Expected behavior

Should convert spaces to tabs by indention rule.

Actual behavior

No rule to use tabs instead of spaces.

Check HTML codestyle in twig files

Hi

Thanks for your efforts to make a cs-fixer for Twig - it works very well!

Are there any plans to check also HTML codestyle? Because in most cases Twig files consist of a lot of HTML code and it would be cool if this would be checked too :-)

Add a sniff (test case) for formatting of self-closing HTML tags

Rule(s) related to or rule(s) missing

Imagine this Twig:

<hr     />
<hr />
<hr/>

Expected behavior

It would be helpful if the linter would error on 2 of the 3 examples.
And standardize on the formatting of self-closing HTML tags.

NB My phpstorm makes it <hr/>

Actual behavior

Linter does not check formatting of self-closing tags.

No output

When I run

./vendor/bin/twig-cs-fixer lint --verbose /templates/components/datatable.twig

I got the message of "using cache", and nothing else, like it hangs, I deleted the cache file just in case and now I get no output.

Is there any way to force any output to see if I'm suppressing any errors?

Add rule for single blank line at end of file

Rule(s) related to or rule(s) missing

I thought I create some rule requests which maybe could also be usable.

A new rule similar to php-cs-fixer single_blank_line_at_eof would be nice.

Expected behavior

Add if ther eis noe single blank line

-{{ twig }}
-\ No newline at end of file
+{{ twig }}

Remove to many single blank lines:

{{ twig }}
-

Actual behavior

No rule exist

partial template

Rule(s) related to or rule(s) missing

FileNameRule

Expected behavior

Sometimes we use partial templates. For example for the Symfony demo, there is the file https://github.com/symfony/demo/blob/main/templates/blog/_post.html.twig

I then tested and I got the error below:

Actual behavior

 KO .\templates\blog\_post.html.twig
 ------- ----------------------------------------------------------
  ERROR   >>   | The file name must use snake_case; expected post.

Do you think this behavior should be taken into account?

Request: Force "include with ... only"

Hi, I stumbled upon this package while searching for a way to force with ... only.

Is it possible to somehow enforce this behavior?
I'm wiling to write the sniffer myself, however I've never written one before so could use some guidance.

Expected behavior

-{% include 'template.html' with {'foo': 'bar'} %}
+{% include 'template.html' with {'foo': 'bar'} only %}

Reason

At my workplace we have a lot of templates and it becomes unclear where a used variable comes from.
By forcing ourselves to use with ... only we hope to always leave a trail.

Incompatibility with Composer 1

It seems that this library, while it does install fine on

Composer version 1.10.26 2022-04-13 16:39:56

requires Composer\InstalledVersions which is a Composer 2 thing, making it incompatible.

Might want to either

  • find an alternative to where that's used, to increase compatibility (what I'd prefer)
  • update package metadata to enforce proper compatibility checks on installation

RFC: Add some rule customisation

Hello,

First, congrats for this tool! I installed it, and ran it in a couple of seconds!

I like the updated CS, but there are two "blockers" for me:

- {{ form_label(form.markdownName, null, { label_attr: { class: 'd-md-none' }}) }}                                                                                             
+ {{ form_label(form.markdownName, null, {label_attr: {class: 'd-md-none'}}) }}

I prefer the old version, and bellow too.

- <p class="c-partner-info__address">{{ location.address | nl2br }}</p>
+ <p class="c-partner-info__address">{{ location.address|nl2br }}</p>

I read the doc, but I cannot find a way to disable/configure theses rules

Lint errors with custom twig tags

After installing https://github.com/buzzingpixel/twig-switch and using syntax like:

{% switch myVar %}
    {% case 'value1' %}
        {# ...code here to run for value1 #}
    {% case 'value2' %}
        {# ...code here to run for value2 #}
    {% default %}
        {# ...code here to run for default when no case matched #}
{% endswitch %}

The linter is now complaining it doesn't like the switch

example:
ScreenShot-2023-01-12-10 59 49

Is there any way to tell the linter that this is ok?

version 0.5.1 : The "lint" directory does not exist

i update all my tools as part of my ci.

And It used to work well (version 0.5),
But now it errors with latest version (0.5.1) :

twig-cs-fixer lint --fix /xxx/views
Error: The "lint" directory does not exist.

i reverted version, using this, and it worked again :

composer global require vincentlanglet/twig-cs-fixer:0.5

has the parameters changed in the new version ? the unit tests passed ?

[Feature] Ignore a line/rule

Can you add documentation to the README that explains how one can ignore a line(s)s of code or disable a ruleset all together during a check? I'm happy to contribute that if you can point me to some examples or even provide them here.

Expected behavior

Ability ignore certain lines/rules.

Actual behavior

I'm unable to do so, or haven't found the documentation.

Linter Fails on files with no empty trailing line

[ExecStack] Running vendor/bin/twig-cs-fixer lint docroot/modules/custom docroot/themes/example --fix
PHP Fatal error:  Uncaught TypeError: Return value of TwigCsFixer\Runner\Fixer::getTokenContent() must be of the type string, null returned in /Users/adamzimmermann/www/example-drupal-8/vendor/vincentlanglet/twig-cs-fixer/src/Runner/Fixer.php:365
Stack trace:
#0 /Users/adamzimmermann/www/example-drupal-8/vendor/vincentlanglet/twig-cs-fixer/src/Runner/Fixer.php(320): TwigCsFixer\Runner\Fixer->getTokenContent(267)
#1 /Users/adamzimmermann/www/example-drupal-8/vendor/vincentlanglet/twig-cs-fixer/src/Ruleset/Generic/BlankEOFSniff.php(46): TwigCsFixer\Runner\Fixer->addNewlineBefore(267)
#2 /Users/adamzimmermann/www/example-drupal-8/vendor/vincentlanglet/twig-cs-fixer/src/Sniff/AbstractSniff.php(65): TwigCsFixer\Ruleset\Generic\BlankEOFSniff->process(267, Array)
#3 /Users/adamzimmermann/www/example-drupal-8/vendor/vincentlanglet/twig-cs-fixer/src/Runner/Fixer.php(156): TwigCsFixer\Sniff\AbstractSniff->processFile(Array)
#4 /Users/adamzimmermann/www/example-drupal-8/vendor/vincentlanglet/twig-cs-fixer/src/Runner/Linter.ph in /Users/adamzimmermann/www/example-drupal-8/vendor/vincentlanglet/twig-cs-fixer/src/Runner/Fixer.php on line 365

Fatal error: Uncaught TypeError: Return value of TwigCsFixer\Runner\Fixer::getTokenContent() must be of the type string, null returned in /Users/adamzimmermann/www/example-drupal-8/vendor/vincentlanglet/twig-cs-fixer/src/Runner/Fixer.php:365
Stack trace:
#0 /Users/adamzimmermann/www/example-drupal-8/vendor/vincentlanglet/twig-cs-fixer/src/Runner/Fixer.php(320): TwigCsFixer\Runner\Fixer->getTokenContent(267)
#1 /Users/adamzimmermann/www/example-drupal-8/vendor/vincentlanglet/twig-cs-fixer/src/Ruleset/Generic/BlankEOFSniff.php(46): TwigCsFixer\Runner\Fixer->addNewlineBefore(267)
#2 /Users/adamzimmermann/www/example-drupal-8/vendor/vincentlanglet/twig-cs-fixer/src/Sniff/AbstractSniff.php(65): TwigCsFixer\Ruleset\Generic\BlankEOFSniff->process(267, Array)
#3 /Users/adamzimmermann/www/example-drupal-8/vendor/vincentlanglet/twig-cs-fixer/src/Runner/Fixer.php(156): TwigCsFixer\Sniff\AbstractSniff->processFile(Array)
#4 /Users/adamzimmermann/www/example-drupal-8/vendor/vincentlanglet/twig-cs-fixer/src/Runner/Linter.ph in /Users/adamzimmermann/www/example-drupal-8/vendor/vincentlanglet/twig-cs-fixer/src/Runner/Fixer.php on line 365
 [ExecStack]  Exit code 255  Time 0.815s
 [notice] Stopping on fail. Exiting....
 [error]  Exit Code: 255
 [error]    in task Robo\Task\Base\ExecStack


Script robo --ansi handling the robo event returned with error code 255
Script composer robo job:fix-coding-standards handling the cs-fix event returned with error code 255

This method claims to always return a string.

However, this line sometimes returns null in some circumstances.

This seems to occur when the file has no trailing empty line and the last array index of the tokens array is null, causing the method to return null and the fixer to break.

I'm not sure what the best solution is, but happy to contribute something if you can direct me on how it should work.

Expected behavior

The linter with the --fix flags runs without crashing.

Actual behavior

The linter with the --fix flags crashes when trying to fix some files. Seemingly ones without an empty trailing line.

Error: Infinite loop

Hi :),

I have a bellow error:
Error: Infinite loop

Why do I get this error displayed?
Thanks :)

Add a sniff (test case) for unclosed HTML tags

Rule(s) related to or rule(s) missing

Imagine this Twig:

<div class="">
</div>
</div>

<br/>
<hr/>

Expected behavior

It would be helpful when the linter notices the HTML closing errors.
In the above example the

is not closed, but the
and
are self-closing.

This might be a rule that the linter cannot fixes automatically.

Actual behavior

Linter does not check if a tag is properly closed.

Convert Tab indention to spaces

Rule(s) related to or rule(s) missing

I thought I create some rule requests which maybe could also be usable.

Why it maybe make sense to make this rule based on the outputted type e.g.:

Indention([
    'docker-compose.yml.twig' => 2,
    '*.yaml.twig' => 4,
    '*.html.twig' => 4,
])

Based on this rule all indention should be divideable by 4 or 2 or the given number, but more required in my case would be convert tabs automatically to spaces when enabled.

maybe Indention(4) is also enough as for more complicated projects different .twig-cs-fixer.php can be created which match e.g. only yaml.twig and the other html.twig files.

Expected behavior

All indention with tabs (maybe exclude tab characters elsewhere then beginning of the line?) should be converted to spaces based on the ruleset.

-	{{ test }}
+    {{ test }}

Actual behavior

Such rule does not yet exist.

user.firstName[:1] fails

Hello,

this works in twig

{{ user.firstName[:1] }}

but this tool changes it to ": 1" and it doesnt work anymore

{{ user.firstName[: 1] }}

so i am stuck now, so i replaced it to the followin (which works the same and isn't reformated => works.

{{ user.firstName|slice(0, 1) }}

Unnecessary spaces

Hallo!

W're using this libary and it works fine! Thanks!

There are already some issues about spaces. But in my opnion not all double spaces that can removed are removed. Below are just some samples. I guess the're more cases.

Sample code

{% extends                '@Admin/...' %}
{% set     test = 'test' %}
{% if    test is       not null %}{% endif %}

Expected behavior

{% extends '@Admin/...' %}
{% set test = 'test' %}
{% if test is not null %}{% endif %}

Current output after running twig-cs-fixer lint --fix

{% extends                '@Admin/...' %}
{% set     test = 'test' %}
{% if    test is       not null %}{% endif %}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.