Skip to content

Scope to use attribute rule #320

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 22, 2025
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
3 changes: 3 additions & 0 deletions config/sets/laravel120.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
declare(strict_types=1);

use Rector\Config\RectorConfig;
use RectorLaravel\Rector\ClassMethod\ScopeNamedClassMethodToScopeAttributedClassMethodRector;
use RectorLaravel\Rector\MethodCall\ContainerBindConcreteWithClosureOnlyRector;

// see https://laravel.com/docs/12.x/upgrade
Expand All @@ -11,4 +12,6 @@

// https://github.com/laravel/framework/pull/54628
$rectorConfig->rule(ContainerBindConcreteWithClosureOnlyRector::class);
// https://github.com/laravel/framework/pull/54450
$rectorConfig->rule(ScopeNamedClassMethodToScopeAttributedClassMethodRector::class);
};
26 changes: 21 additions & 5 deletions docs/rector_rules_overview.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# 77 Rules Overview
# 78 Rules Overview

## AbortIfRector

Expand Down Expand Up @@ -1325,6 +1325,26 @@ Use PHP callable syntax instead of string syntax for controller route declaratio

<br>

## ScopeNamedClassMethodToScopeAttributedClassMethodRector

Changes model scope methods to use the scope attribute

- class: [`RectorLaravel\Rector\ClassMethod\ScopeNamedClassMethodToScopeAttributedClassMethodRector`](../src/Rector/ClassMethod/ScopeNamedClassMethodToScopeAttributedClassMethodRector.php)

```diff
class User extends Model
{
- public function scopeActive($query)
+ #[\Illuminate\Database\Eloquent\Attributes\Scope]
+ public function active($query)
{
return $query->where('active', 1);
}
}
```

<br>

## ServerVariableToRequestFacadeRector

Change server variable to Request facade's server method
Expand Down Expand Up @@ -1459,12 +1479,8 @@ Use the base collection methods instead of their aliases.
$collection = new Collection([0, 1, null, -1]);
-$collection->average();
-$collection->some(fn (?int $number): bool => is_null($number));
-$collection->unlessEmpty(fn(Collection $collection) => $collection->push('Foo'));
-$collection->unlessNotEmpty(fn(Collection $collection) => $collection->push('Foo'));
+$collection->avg();
+$collection->contains(fn (?int $number): bool => is_null($number));
+$collection->whenNotEmpty(fn(Collection $collection) => $collection->push('Foo'));
+$collection->whenEmpty(fn(Collection $collection) => $collection->push('Foo'));
```

<br>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php

declare(strict_types=1);

namespace RectorLaravel\Rector\ClassMethod;

use PhpParser\Node;
use PhpParser\Node\Attribute;
use PhpParser\Node\AttributeGroup;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Stmt\Class_;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Type\ObjectType;
use Rector\Php80\NodeAnalyzer\PhpAttributeAnalyzer;
use RectorLaravel\AbstractRector;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;

/**
* @see \RectorLaravel\Tests\Rector\ClassMethod\ScopeNamedClassMethodToScopeAttributedClassMethodRector\ScopeNamedClassMethodToScopeAttributedClassMethodRectorTest
*/
final class ScopeNamedClassMethodToScopeAttributedClassMethodRector extends AbstractRector
{
private const string SCOPE_ATTRIBUTE = 'Illuminate\Database\Eloquent\Attributes\Scope';

public function __construct(
private readonly PhpAttributeAnalyzer $phpAttributeAnalyzer,
private readonly ReflectionProvider $reflectionProvider,
) {}

public function getRuleDefinition(): RuleDefinition
{
return new RuleDefinition(
'Changes model scope methods to use the scope attribute',
[new CodeSample(
<<<'CODE_SAMPLE'
class User extends Model
{
public function scopeActive($query)
{
return $query->where('active', 1);
}
}
CODE_SAMPLE,
<<<'CODE_SAMPLE'
class User extends Model
{
#[\Illuminate\Database\Eloquent\Attributes\Scope]
public function active($query)
{
return $query->where('active', 1);
}
}
CODE_SAMPLE
)]
);
}

/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Class_::class];
}

/**
* @param Class_ $node
*/
public function refactor(Node $node): ?Node
{
if (! $this->isObjectType($node, new ObjectType('Illuminate\Database\Eloquent\Model'))) {
return null;
}

if (! is_string($className = $this->getName($node))) {
return null;
}

$classReflection = $this->reflectionProvider->getClass($className);

$changes = false;
foreach ($node->getMethods() as $classMethod) {
$name = $this->getName($classMethod);
// make sure it starts with scope and the next character is upper case
if (! str_starts_with($name, 'scope') || ! ctype_upper(substr($name, 5, 1))) {
continue;
}

$newName = lcfirst(str_replace('scope', '', $name));

if ($classReflection->hasMethod($newName)) {
continue;
}

if ($this->phpAttributeAnalyzer->hasPhpAttribute($classMethod, self::SCOPE_ATTRIBUTE)) {
continue;
}

$classMethod->name = new Identifier($newName);
$classMethod->attrGroups[] = new AttributeGroup([new Attribute(new FullyQualified(self::SCOPE_ATTRIBUTE))]);
$changes = true;
}

if ($changes === false) {
return null;
}

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

namespace RectorLaravel\Tests\Rector\ScopeNamedClassMethodToScopeAttributedClassMethodRector\Fixture;

use Illuminate\Database\Eloquent\Model;

class SomeClass extends Model
{
public function scopeSomeMethod()
{

}
}

?>
-----
<?php

namespace RectorLaravel\Tests\Rector\ScopeNamedClassMethodToScopeAttributedClassMethodRector\Fixture;

use Illuminate\Database\Eloquent\Model;

class SomeClass extends Model
{
#[\Illuminate\Database\Eloquent\Attributes\Scope]
public function someMethod()
{

}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace RectorLaravel\Tests\Rector\ScopeNamedClassMethodToScopeAttributedClassMethodRector\Fixture;

use Illuminate\Database\Eloquent\Model;

class NonDuplicateAttributeNodes extends Model
{
#[\Illuminate\Database\Eloquent\Attributes\Scope]
public function scopeSomeMethod()
{

}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace RectorLaravel\Tests\Rector\ScopeNamedClassMethodToScopeAttributedClassMethodRector\Fixture;

use Illuminate\Database\Eloquent\Model;

class NonMatchingMethods extends Model
{
public function scopefoo()
{

}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace RectorLaravel\Tests\Rector\ScopeNamedClassMethodToScopeAttributedClassMethodRector\Fixture;

use Illuminate\Database\Eloquent\Model;

class NonDuplicateMethod extends Model
{
public function scopeSomeMethod()
{

}

public function someMethod()
{

}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace RectorLaravel\Tests\Rector\ScopeNamedClassMethodToScopeAttributedClassMethodRector\Fixture;

class NonModelClass
{
public function scopeSomeMethod()
{

}
}

?>
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

declare(strict_types=1);

namespace RectorLaravel\Tests\Rector\ClassMethod\ScopeNamedClassMethodToScopeAttributedClassMethodRector;

use Iterator;
use PHPUnit\Framework\Attributes\DataProvider;
use Rector\Testing\PHPUnit\AbstractRectorTestCase;

final class ScopeNamedClassMethodToScopeAttributedClassMethodRectorTest extends AbstractRectorTestCase
{
public static function provideData(): Iterator
{
return self::yieldFilesFromDirectory(__DIR__ . '/Fixture');
}

/**
* @test
*/
#[DataProvider('provideData')]
public function test(string $filePath): void
{
$this->doTestFile($filePath);
}

public function provideConfigFilePath(): string
{
return __DIR__ . '/config/configured_rule.php';
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use RectorLaravel\Rector\ClassMethod\ScopeNamedClassMethodToScopeAttributedClassMethodRector;

return static function (RectorConfig $rectorConfig): void {
$rectorConfig->rule(ScopeNamedClassMethodToScopeAttributedClassMethodRector::class);
};