Skip to content

Allow rules to be configured for specific paths only #381

@ruudk

Description

@ruudk

I'd like to enable a few rules only for specific directories.

I solved it by creating a rule that wraps another rule like this:

<?php

declare(strict_types=1);

namespace Dev\TicketSwap\Shared\Infrastructure\Twig;

use Override;
use Twig\Environment;
use Twig\Node\Node;
use TwigCsFixer\Report\Report;
use TwigCsFixer\Rules\Node\NodeRuleInterface;
use Webmozart\Assert\Assert;

final readonly class PathSpecificRule implements NodeRuleInterface
{
    /**
     * @param list<string> $paths
     */
    public function __construct(
        private array $paths,
        private NodeRuleInterface $rule,
    ) {}

    #[Override]
    public function setReport(Report $report, array $ignoredViolations = []) : void
    {
        $this->rule->setReport($report, $ignoredViolations);
    }

    #[Override]
    public function enterNode(Node $node, Environment $env) : Node
    {
        Assert::notNull($node->getSourceContext(), 'Node has no source context');

        if ( ! array_any($this->paths, fn(string $path) => fnmatch($path, $node->getSourceContext()->getName()))) {
            return $node;
        }

        return $this->rule->enterNode($node, $env);
    }

    #[Override]
    public function leaveNode(Node $node, Environment $env) : ?Node
    {
        Assert::notNull($node->getSourceContext(), 'Node has no source context');

        if ( ! array_any($this->paths, fn(string $path) => fnmatch($path, $node->getSourceContext()->getName()))) {
            return $node;
        }

        return $this->rule->leaveNode($node, $env);
    }

    #[Override]
    public function getPriority() : int
    {
        return $this->rule->getPriority();
    }
}
$ruleset->addRule(
     new PathSpecificRule(
         ['templates/mail/**'],
         new ForbiddenFunctionRule(['path']),
     ),
 );

But would be great to have this natively supported.

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is needed

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions