Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -665,6 +665,73 @@ final class Alert

<br>

### ForbiddenReadonlyRule

Forbid the use of `readonly` on Twig Component classes and properties, except for constructor-promoted properties (injected services).

Using `readonly` on component classes or properties prevents the TwigComponent system from setting prop values after instantiation.
Services injected via the constructor can be `readonly` since they are assigned at instantiation time.

Learn more at https://symfony.com/bundles/ux-twig-component/current/index.html#readonly-components-and-immutability

```yaml
rules:
- Kocal\PHPStanSymfonyUX\Rules\TwigComponent\ForbiddenReadonlyRule
```

```php
// src/Twig/Components/Alert.php
namespace App\Twig\Components;

use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent]
final readonly class Alert
{
public string $message;
}
```

```php
// src/Twig/Components/Alert.php
namespace App\Twig\Components;

use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent]
final class Alert
{
public readonly string $message;
}
```

:x:

<br>

```php
// src/Twig/Components/Alert.php
namespace App\Twig\Components;

use Psr\Log\LoggerInterface;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent]
final class Alert
{
public string $message;

public function __construct(
private readonly LoggerInterface $logger,
) {
}
}
```

:+1:

<br>

### MethodsVisibilityRule

Enforces that all methods in Twig Components are either public or private, but not protected.
Expand Down
2 changes: 2 additions & 0 deletions phpstan.dist.neon
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,6 @@ parameters:
- method.unused
- missingType.iterableValue
- missingType.property
- property.uninitializedReadonly
- property.unused
- property.onlyWritten
90 changes: 90 additions & 0 deletions src/Rules/TwigComponent/ForbiddenReadonlyRule.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php

declare(strict_types=1);

namespace Kocal\PHPStanSymfonyUX\Rules\TwigComponent;

use Kocal\PHPStanSymfonyUX\NodeAnalyzer\AttributeFinder;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

/**
* @implements Rule<Class_>
*/
final class ForbiddenReadonlyRule implements Rule
{
public function getNodeType(): string
{
return Class_::class;
}

public function processNode(Node $node, Scope $scope): array
{
if (! AttributeFinder::findAnyAttribute($node, [AsTwigComponent::class, AsLiveComponent::class])) {
return [];
}

$errors = [];

// Check if class is readonly
if ($node->isReadonly()) {
$errors[] = RuleErrorBuilder::message('Twig component class must not be readonly.')
->identifier('symfonyUX.twigComponent.forbiddenReadonlyClass')
->line($node->getLine())
->tip('Remove the "readonly" keyword from the class declaration. Twig components need mutable properties to receive props.')
->build();
}

// Get constructor parameter names to exclude them from validation
$constructorParamNames = $this->getConstructorParameterNames($node);

// Check for readonly properties (excluding constructor-promoted parameters)
foreach ($node->getProperties() as $property) {
if (! $property->isReadonly()) {
continue;
}

foreach ($property->props as $prop) {
$propertyName = $prop->name->toString();

// Skip if this property is a constructor parameter (injected service)
if (\in_array($propertyName, $constructorParamNames, true)) {
continue;
}

$errors[] = RuleErrorBuilder::message(sprintf('Property "$%s" must not be readonly.', $propertyName))
->identifier('symfonyUX.twigComponent.forbiddenReadonlyProperty')
->line($property->getLine())
->tip('Remove the "readonly" keyword from the property declaration. Only constructor-promoted properties (injected services) can be readonly.')
->build();
}
}

return $errors;
}

/**
* @return list<string>
*/
private function getConstructorParameterNames(Class_ $node): array
{
$constructor = $node->getMethod('__construct');
if ($constructor === null) {
return [];
}

$paramNames = [];
foreach ($constructor->params as $param) {
if ($param->var instanceof Node\Expr\Variable && \is_string($param->var->name)) {
$paramNames[] = $param->var->name;
}
}

return $paramNames;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Kocal\PHPStanSymfonyUX\Tests\Rules\TwigComponent\ForbiddenReadonlyRule\Fixture;

use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;

#[AsLiveComponent]
final class LiveComponentWithReadonlyProperty
{
public readonly string $message;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Kocal\PHPStanSymfonyUX\Tests\Rules\TwigComponent\ForbiddenReadonlyRule\Fixture;

final readonly class NotAComponent
{
public function __construct(
public string $message,
) {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace Kocal\PHPStanSymfonyUX\Tests\Rules\TwigComponent\ForbiddenReadonlyRule\Fixture;

use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;

#[AsLiveComponent]
final readonly class ReadonlyLiveComponent
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

declare(strict_types=1);

namespace Kocal\PHPStanSymfonyUX\Tests\Rules\TwigComponent\ForbiddenReadonlyRule\Fixture;

use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent]
final readonly class ReadonlyTwigComponent
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Kocal\PHPStanSymfonyUX\Tests\Rules\TwigComponent\ForbiddenReadonlyRule\Fixture;

use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent]
final class TwigComponentWithReadonlyProperty
{
public readonly string $message;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

declare(strict_types=1);

namespace Kocal\PHPStanSymfonyUX\Tests\Rules\TwigComponent\ForbiddenReadonlyRule\Fixture;

use Psr\Log\LoggerInterface;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;

#[AsLiveComponent]
final class ValidLiveComponent
{
public string $message;

public function __construct(
private readonly LoggerInterface $logger,
) {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

declare(strict_types=1);

namespace Kocal\PHPStanSymfonyUX\Tests\Rules\TwigComponent\ForbiddenReadonlyRule\Fixture;

use Psr\Log\LoggerInterface;
use Symfony\UX\TwigComponent\Attribute\AsTwigComponent;

#[AsTwigComponent]
final class ValidTwigComponent
{
public string $message;

public function __construct(
private readonly LoggerInterface $logger,
) {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

declare(strict_types=1);

namespace Kocal\PHPStanSymfonyUX\Tests\Rules\TwigComponent\ForbiddenReadonlyRule;

use Kocal\PHPStanSymfonyUX\Rules\TwigComponent\ForbiddenReadonlyRule;
use PHPStan\Rules\Rule;
use PHPStan\Testing\RuleTestCase;

/**
* @extends RuleTestCase<ForbiddenReadonlyRule>
*/
final class ForbiddenReadonlyRuleTest extends RuleTestCase
{
public function testReadonlyClassViolations(): void
{
$this->analyse(
[__DIR__ . '/Fixture/ReadonlyTwigComponent.php'],
[
[
'Twig component class must not be readonly.',
9,
'Remove the "readonly" keyword from the class declaration. Twig components need mutable properties to receive props.',
],
]
);

$this->analyse(
[__DIR__ . '/Fixture/ReadonlyLiveComponent.php'],
[
[
'Twig component class must not be readonly.',
9,
'Remove the "readonly" keyword from the class declaration. Twig components need mutable properties to receive props.',
],
]
);
}

public function testReadonlyPropertyViolations(): void
{
$this->analyse(
[__DIR__ . '/Fixture/TwigComponentWithReadonlyProperty.php'],
[
[
'Property "$message" must not be readonly.',
12,
'Remove the "readonly" keyword from the property declaration. Only constructor-promoted properties (injected services) can be readonly.',
],
]
);

$this->analyse(
[__DIR__ . '/Fixture/LiveComponentWithReadonlyProperty.php'],
[
[
'Property "$message" must not be readonly.',
12,
'Remove the "readonly" keyword from the property declaration. Only constructor-promoted properties (injected services) can be readonly.',
],
]
);
}

public function testNoViolations(): void
{
$this->analyse([__DIR__ . '/Fixture/NotAComponent.php'], []);
$this->analyse([__DIR__ . '/Fixture/ValidTwigComponent.php'], []);
$this->analyse([__DIR__ . '/Fixture/ValidLiveComponent.php'], []);
}

public static function getAdditionalConfigFiles(): array
{
return [__DIR__ . '/config/configured_rule.neon'];
}

protected function getRule(): Rule
{
return self::getContainer()->getByType(ForbiddenReadonlyRule::class);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
includes:
- ../../../../test-extension.neon

rules:
- Kocal\PHPStanSymfonyUX\Rules\TwigComponent\ForbiddenReadonlyRule