Skip to content

Commit

Permalink
feat: add empty usage inspector
Browse files Browse the repository at this point in the history
- closes #25
  • Loading branch information
imdhemy committed Jul 20, 2024
1 parent 580c943 commit 757e15f
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/Inspector/CodeStyle/EmptyFunctionUsageInspector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

declare(strict_types=1);

namespace Symblaze\MareScan\Inspector\CodeStyle;

use PhpParser\Node\Expr\Empty_;
use PhpParser\Node\Stmt;
use PhpParser\NodeFinder;
use SplFileInfo;
use Symblaze\MareScan\Inspector\CodeIssue;
use Symblaze\MareScan\Inspector\CodeLocation;
use Symblaze\MareScan\Inspector\InspectorInterface;

final class EmptyFunctionUsageInspector implements InspectorInterface
{
private const string MESSAGE = 'Usage of `empty()` function is discouraged.';
private const string SHORT_MESSAGE = 'The `empty()` function may lead to unexpected results. Use type-safe strict comparison instead.';

public function shortName(): string
{
return 'empty_function_usage';
}

public function displayName(): string
{
return 'Empty function usage';
}

public function description(): string
{
return 'Detects the usage of `empty()` function.';
}

public function inspect(SplFileInfo $file, Stmt ...$statement): array
{
$result = [];
$nodeFinder = new NodeFinder();

$emptyFunctionNodes = $nodeFinder->findInstanceOf($statement, Empty_::class);
foreach ($emptyFunctionNodes as $emptyFunctionNode) {
$result[] = new CodeIssue(
message: self::MESSAGE,
severity: CodeIssue::SEVERITY_WARNING,
codeLocation: CodeLocation::fromNode($file, $emptyFunctionNode),
type: 'empty_function_usage',
shortMessage: self::SHORT_MESSAGE,
);
}

return $result;
}
}
33 changes: 33 additions & 0 deletions tests/Inspector/CodeStyle/EmptyFunctionUsageInspectorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace Symblaze\MareScan\Tests\Inspector\CodeStyle;

use PHPUnit\Framework\Attributes\Test;
use Symblaze\MareScan\Inspector\CodeStyle\EmptyFunctionUsageInspector;
use Symblaze\MareScan\Tests\TestCase;

final class EmptyFunctionUsageInspectorTest extends TestCase
{
#[Test]
public function definition(): void
{
$sut = new EmptyFunctionUsageInspector();

$this->assertSame('empty_function_usage', $sut->shortName());
$this->assertSame('Empty function usage', $sut->displayName());
$this->assertSame('Detects the usage of `empty()` function.', $sut->description());
}

#[Test]
public function inspect_empty_usage(): void
{
$fixture = $this->fixtureInfo('code_style/empty_used_with_scalars.php');
$sut = new EmptyFunctionUsageInspector();

$result = $sut->inspect($fixture, ...$this->parse($fixture));

$this->assertCount(6, $result);
}
}

0 comments on commit 757e15f

Please sign in to comment.