Skip to content

Commit

Permalink
Experimental include and embed support for variable usage detection
Browse files Browse the repository at this point in the history
  • Loading branch information
OwlyCode authored and OwlyCode committed Dec 15, 2021
1 parent 74d9b92 commit a4c7b57
Show file tree
Hide file tree
Showing 31 changed files with 508 additions and 27 deletions.
41 changes: 39 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ Tips: You can use multiple _exclude_ parameters.

By default TwigCS will output all lines that have violations regardless of whether they match the severity level
specified or not. If you only want to see violations that are greater than or equal to the severity level you've specified
you can use the `--display` option. For example.
you can use the `--display` option. For example.

```bash
twigcs /path/to/views --severity error --display blocking
Expand Down Expand Up @@ -86,7 +86,7 @@ You can create a class implementing `RulesetInterface` and supply it as a `--rul
twigcs /path/to/views --ruleset \MyApp\TwigCsRuleset
```

*Note:* `twigcs` needs to be used via composer and the ruleset class must be reachable via composer's autoloader for this feature to work.
_Note:_ `twigcs` needs to be used via composer and the ruleset class must be reachable via composer's autoloader for this feature to work.
Also note that depending on your shell, you might need to escape backslashes in the fully qualified class name:

```bash
Expand Down Expand Up @@ -148,6 +148,43 @@ If you explicitly supply a path to the CLI, it will be added to the list of lint
twigcs ~/dirC # This will lint ~/dirA, ~/dirB and ~/dirC using the configuration file of the current directory.
```

## Template resolution

Using file based configuration, you can provide a way for twigcs to resolve template. This enables better unused variable/macro detection. Here's the
simplest example when you have only one directory of templates.

```php
<?php

use FriendsOfTwig\Twigcs\TemplateResolver\FileResolver;

return \FriendsOfTwig\Twigcs\Config\Config::create()
// ...
->setTemplateResolver(new FileResolver(__DIR__))
->setRuleSet(FriendsOfTwig\Twigcs\Ruleset\Official::class)
;
```

Here is a more complex example that uses a chain resolver and a namespaced resolver to handle vendor templates:

```
<?php
use FriendsOfTwig\Twigcs\TemplateResolver;
return \FriendsOfTwig\Twigcs\Config\Config::create()
->setFinder($finder)
->setTemplateResolver(new TemplateResolver\ChainResolver([
new TemplateResolver\FileResolver(__DIR__ . '/templates'),
new TemplateResolver\NamespacedResolver([
'acme' => new TemplateResolver\FileResolver(__DIR__ . '/vendor/Acme/AcmeLib/templates')
]),
]))
;
```

This handles twig namespaces of the form `@acme/<templatepath>`.

## Upgrading

If you're upgrading from 3.x to 4.x or later, please read the [upgrade guide](doc/upgrade.md).
Expand Down
36 changes: 29 additions & 7 deletions src/Config/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,28 @@
namespace FriendsOfTwig\Twigcs\Config;

use FriendsOfTwig\Twigcs\Ruleset\Official;
use FriendsOfTwig\Twigcs\TemplateResolver\NullResolver;
use FriendsOfTwig\Twigcs\TemplateResolver\TemplateResolverInterface;

/**
* Special thanks to https://github.com/c33s/twigcs/ which this feature was inspired from.
*/
class Config implements ConfigInterface
{
private $name;
private $finders;
private $severity = 'warning';
private $reporter = 'console';
private $ruleset = Official::class;
private $specificRulesets = [];
private string $name;
private array $finders;
private ?TemplateResolverInterface $loader;
private string $severity = 'warning';
private string $reporter = 'console';
private string $ruleset = Official::class;
private array $specificRulesets = [];
private $display = ConfigInterface::DISPLAY_ALL;

public function __construct($name = 'default')
public function __construct(string $name = 'default')
{
$this->name = $name;
$this->finders = [];
$this->loader = new NullResolver();
}

/**
Expand Down Expand Up @@ -136,6 +140,24 @@ public function setRuleset(string $ruleSet): self
return $this;
}

/**
* {@inheritdoc}
*/
public function getTemplateResolver(): TemplateResolverInterface
{
return $this->loader;
}

/**
* {@inheritdoc}
*/
public function setTemplateResolver(TemplateResolverInterface $loader): self
{
$this->loader = $loader;

return $this;
}

public function getSpecificRulesets(): array
{
return $this->specificRulesets;
Expand Down
9 changes: 9 additions & 0 deletions src/Config/ConfigInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace FriendsOfTwig\Twigcs\Config;

use FriendsOfTwig\Twigcs\TemplateResolver\TemplateResolverInterface;

/**
* Special thanks to https://github.com/c33s/twigcs/ which this feature was inspired from.
*
Expand Down Expand Up @@ -62,4 +64,11 @@ public function getSpecificRuleSets(): array;
* @return self
*/
public function setSpecificRuleSets(array $ruleSet);

public function getTemplateResolver(): TemplateResolverInterface;

/**
* @return self
*/
public function setTemplateResolver(TemplateResolverInterface $loader);
}
9 changes: 8 additions & 1 deletion src/Config/ConfigResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use FriendsOfTwig\Twigcs\Container;
use FriendsOfTwig\Twigcs\Finder\TemplateFinder;
use FriendsOfTwig\Twigcs\Ruleset\RulesetInterface;
use FriendsOfTwig\Twigcs\Ruleset\TemplateResolverAwareInterface;
use FriendsOfTwig\Twigcs\Validator\Violation;
use Symfony\Component\Filesystem\Filesystem;
use function fnmatch;
Expand Down Expand Up @@ -117,7 +118,13 @@ public function getRuleset(string $file)
throw new \InvalidArgumentException('Ruleset class must implement '.RulesetInterface::class);
}

return new $rulesetClassName($this->options['twig-version']);
$instance = new $rulesetClassName($this->options['twig-version']);

if ($instance instanceof TemplateResolverAwareInterface) {
$instance->setTemplateResolver($this->config->getTemplateResolver());
}

return $instance;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
use FriendsOfTwig\Twigcs\Reporter\CsvReporter;
use FriendsOfTwig\Twigcs\Reporter\EmacsReporter;
use FriendsOfTwig\Twigcs\Reporter\GithubActionReporter;
use FriendsOfTwig\Twigcs\Reporter\JsonReporter;
use FriendsOfTwig\Twigcs\Reporter\JUnitReporter;
use FriendsOfTwig\Twigcs\Validator\Validator;
use FriendsOfTwig\Twigcs\Reporter\JsonReporter;

class Container extends \ArrayObject
{
Expand Down
13 changes: 11 additions & 2 deletions src/Rule/UnusedMacro.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,31 @@
namespace FriendsOfTwig\Twigcs\Rule;

use FriendsOfTwig\Twigcs\Scope\ScopeBuilder;
use FriendsOfTwig\Twigcs\TemplateResolver\NullResolver;
use FriendsOfTwig\Twigcs\TemplateResolver\TemplateResolverInterface;
use FriendsOfTwig\Twigcs\TwigPort\TokenStream;

class UnusedMacro extends AbstractRule implements RuleInterface
{
public function __construct(int $severity, TemplateResolverInterface $loader = null)
{
$this->loader = $loader ?: new NullResolver();

parent::__construct($severity);
}

/**
* {@inheritdoc}
*/
public function check(TokenStream $tokens)
{
$builder = ScopeBuilder::createMacroScopeBuilder();
$builder = ScopeBuilder::createMacroScopeBuilder($this->loader);

$root = $builder->build($tokens);

$violations = [];

foreach ($root->flatten()->getUnusedDeclarations() as $declaration) {
foreach ($root->flatten()->getRootUnusedDeclarations() as $declaration) {
$token = $declaration->getToken();

$violations[] = $this->createViolation(
Expand Down
13 changes: 11 additions & 2 deletions src/Rule/UnusedVariable.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,31 @@
namespace FriendsOfTwig\Twigcs\Rule;

use FriendsOfTwig\Twigcs\Scope\ScopeBuilder;
use FriendsOfTwig\Twigcs\TemplateResolver\NullResolver;
use FriendsOfTwig\Twigcs\TemplateResolver\TemplateResolverInterface;
use FriendsOfTwig\Twigcs\TwigPort\TokenStream;

class UnusedVariable extends AbstractRule implements RuleInterface
{
public function __construct(int $severity, TemplateResolverInterface $loader = null)
{
$this->loader = $loader ?: new NullResolver();

parent::__construct($severity);
}

/**
* {@inheritdoc}
*/
public function check(TokenStream $tokens)
{
$builder = ScopeBuilder::createVariableScopeBuilder();
$builder = ScopeBuilder::createVariableScopeBuilder($this->loader);

$root = $builder->build($tokens);

$violations = [];

foreach ($root->flatten()->getUnusedDeclarations() as $declaration) {
foreach ($root->flatten()->getRootUnusedDeclarations() as $declaration) {
$token = $declaration->getToken();

$violations[] = $this->createViolation(
Expand Down
16 changes: 13 additions & 3 deletions src/Ruleset/Official.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,25 @@
use FriendsOfTwig\Twigcs\RegEngine\RulesetBuilder;
use FriendsOfTwig\Twigcs\RegEngine\RulesetConfigurator;
use FriendsOfTwig\Twigcs\Rule;
use FriendsOfTwig\Twigcs\TemplateResolver\NullResolver;
use FriendsOfTwig\Twigcs\TemplateResolver\TemplateResolverInterface;
use FriendsOfTwig\Twigcs\Validator\Violation;

/**
* The official twigcs ruleset, based on http://twig.sensiolabs.org/doc/coding_standards.html.
*
* @author Tristan Maindron <tmaindron@gmail.com>
*/
class Official implements RulesetInterface
class Official implements RulesetInterface, TemplateResolverAwareInterface
{
private $twigMajorVersion;

private TemplateResolverInterface $resolver;

public function __construct(int $twigMajorVersion)
{
$this->twigMajorVersion = $twigMajorVersion;
$this->resolver = new NullResolver();
}

/**
Expand All @@ -34,8 +39,13 @@ public function getRules()
new Rule\LowerCaseVariable(Violation::SEVERITY_ERROR),
new Rule\RegEngineRule(Violation::SEVERITY_ERROR, $builder->build()),
new Rule\TrailingSpace(Violation::SEVERITY_ERROR),
new Rule\UnusedMacro(Violation::SEVERITY_WARNING),
new Rule\UnusedVariable(Violation::SEVERITY_WARNING),
new Rule\UnusedMacro(Violation::SEVERITY_WARNING, $this->resolver),
new Rule\UnusedVariable(Violation::SEVERITY_WARNING, $this->resolver),
];
}

public function setTemplateResolver(TemplateResolverInterface $resolver)
{
$this->resolver = $resolver;
}
}
3 changes: 3 additions & 0 deletions src/Ruleset/RulesetInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@

use FriendsOfTwig\Twigcs\Rule\RuleInterface;

/**
* @author Tristan Maindron <tmaindron@gmail.com>
*/
interface RulesetInterface
{
public function __construct(int $twigMajorVersion);
Expand Down
13 changes: 13 additions & 0 deletions src/Ruleset/TemplateResolverAwareInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace FriendsOfTwig\Twigcs\Ruleset;

use FriendsOfTwig\Twigcs\TemplateResolver\TemplateResolverInterface;

/**
* @author Tristan Maindron <tmaindron@gmail.com>
*/
interface TemplateResolverAwareInterface
{
public function setTemplateResolver(TemplateResolverInterface $resolver);
}
13 changes: 12 additions & 1 deletion src/Scope/Declaration.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,16 @@ class Declaration
*/
private $token;

public function __construct(string $name, Token $token)
/**
* @var Scope
*/
private $origin;

public function __construct(string $name, Token $token, Scope $origin)
{
$this->name = $name;
$this->token = $token;
$this->origin = $origin;
}

public function getName(): string
Expand All @@ -32,6 +38,11 @@ public function getToken(): Token
return $this->token;
}

public function getOrigin(): Scope
{
return $this->origin;
}

public function __toString()
{
return sprintf('declaration of %s', $this->name);
Expand Down
17 changes: 17 additions & 0 deletions src/Scope/FlattenedScope.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,23 @@ public function getQueue(): array
return $this->queue;
}

public function getRootUnusedDeclarations(): array
{
$unused = $this->getUnusedDeclarations();

$unused = array_filter($unused, function (Declaration $declaration) {
$scope = $declaration->getOrigin();

while ('file' !== $scope->getType() && $scope->getParent()) {
$scope = $scope->getParent();
}

return 'root' === $scope->getName();
});

return $unused;
}

public function getUnusedDeclarations(): array
{
$unused = [];
Expand Down
Loading

0 comments on commit a4c7b57

Please sign in to comment.