diff --git a/src/Rules/String/SingleQuoteRule.php b/src/Rules/String/SingleQuoteRule.php new file mode 100644 index 00000000..16362d38 --- /dev/null +++ b/src/Rules/String/SingleQuoteRule.php @@ -0,0 +1,43 @@ +isTokenMatching($token, Token::STRING_TYPE)) { + return; + } + + $content = $token->getValue(); + if ( + '"' !== $content[0] +// && (true === $this->configuration['strings_containing_single_quote_chars'] || !str_contains($content, "'")) + // regex: odd number of backslashes, not followed by double quote or dollar + ) { + return; + } + + $fixer = $this->addFixableError('String should be defined with single quotes.', $token); + if (null === $fixer) { + return; + } + + $content = substr($content, 1, -1); + $content = str_replace( + ['\\"', '\\#{', '#\\{', '\\\'', '\''], + ['"', '#{', '#{', '\'', '\\\''], + $content); + $fixer->replaceToken($tokenPosition, '\''.$content.'\''); + } +} diff --git a/tests/Rules/String/SimpleQuote/SingleQuoteRuleTest.fixed.twig b/tests/Rules/String/SimpleQuote/SingleQuoteRuleTest.fixed.twig new file mode 100644 index 00000000..3bd55dcd --- /dev/null +++ b/tests/Rules/String/SimpleQuote/SingleQuoteRuleTest.fixed.twig @@ -0,0 +1,11 @@ +'foo' +"foo" + +{% set foo = 'foo' %} +{% set foo2 = 'foo' %} +{% set foo3 = '\'foo\'' %} +{% set foo4 = '\'foo\'' %} + +{% set foo5 = "#{p.first}" %} +{% set foo6 = '#{p.first}' %} +{% set foo7 = '#{p.first}' %} diff --git a/tests/Rules/String/SimpleQuote/SingleQuoteRuleTest.php b/tests/Rules/String/SimpleQuote/SingleQuoteRuleTest.php new file mode 100644 index 00000000..7322aaba --- /dev/null +++ b/tests/Rules/String/SimpleQuote/SingleQuoteRuleTest.php @@ -0,0 +1,20 @@ +checkRule(new SingleQuoteRule(), [ + 'SingleQuote.Error:5:15' => 'String should be defined with single quotes.', + 'SingleQuote.Error:6:15' => 'String should be defined with single quotes.', + 'SingleQuote.Error:7:15' => 'String should be defined with single quotes.', + 'SingleQuote.Error:10:15' => 'String should be defined with single quotes.', + 'SingleQuote.Error:11:15' => 'String should be defined with single quotes.', + ]); + } +} diff --git a/tests/Rules/String/SimpleQuote/SingleQuoteRuleTest.twig b/tests/Rules/String/SimpleQuote/SingleQuoteRuleTest.twig new file mode 100644 index 00000000..abd2206f --- /dev/null +++ b/tests/Rules/String/SimpleQuote/SingleQuoteRuleTest.twig @@ -0,0 +1,11 @@ +'foo' +"foo" + +{% set foo = 'foo' %} +{% set foo2 = "foo" %} +{% set foo3 = "'foo'" %} +{% set foo4 = "\'foo\'" %} + +{% set foo5 = "#{p.first}" %} +{% set foo6 = "\#{p.first}" %} +{% set foo7 = "#\{p.first}" %}