Skip to content

Commit

Permalink
Merge pull request #346 from tighten/drift/request-validation-must-ex…
Browse files Browse the repository at this point in the history
…tend-controller

Require request validation formatter to extend controller
  • Loading branch information
driftingly authored Nov 17, 2023
2 parents a51d151 + 568b467 commit 8637bc3
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/Commands/FormatCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ private function formatFile(InputInterface $input, OutputInterface $output, $fil
if (! empty($only = $input->getOption('only'))) {
$formatters = array_filter($this->getAllFormatters($file), function ($formatter) use ($only) {
foreach ($only as $filter) {
if (false !== strpos($formatter, $filter)) {
if (strpos($formatter, $filter) !== false) {
return true;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Commands/LintCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ private function lintFile(InputInterface $input, OutputInterface $output, $file)
if (! empty($only = $input->getOption('only'))) {
$linters = array_filter($this->getAllLinters($file), function ($linter) use ($only) {
foreach ($only as $filter) {
if (false !== strpos($linter, $filter)) {
if (strpos($linter, $filter) !== false) {
return true;
}
}
Expand Down
20 changes: 20 additions & 0 deletions src/Formatters/RequestValidation.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,28 @@ private function visitor(): NodeVisitorAbstract
{
return new class extends NodeVisitorAbstract
{
private bool $extendsController = false;

public function beforeTraverse(array $nodes)
{
$this->extendsController = false;

return null;
}

public function enterNode(Node $node): Node|int|null
{
if ($node instanceof Node\Stmt\Class_
&& ! empty($node->extends)
&& $node->extends->toString() === 'Controller'
) {
$this->extendsController = true;
}

if (! $this->extendsController) {
return null;
}

if (! $node instanceof Node\Expr\MethodCall) {
return null;
}
Expand Down
22 changes: 22 additions & 0 deletions tests/Formatting/Formatters/RequestValidationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,4 +114,26 @@ public function store()

$this->assertSame($file, $formatted);
}

/** @test */
public function it_ignores_classes_that_do_not_extend_controller()
{
$file = <<<'file'
<?php
namespace App;
class ControllerA extends NotController
{
public function store()
{
$this->validate(['name' => 'required'], ['name.required' => 'Name is required']);
}
}
file;

$formatted = (new TFormat)->format(new RequestValidation($file));

$this->assertSame($file, $formatted);
}
}

0 comments on commit 8637bc3

Please sign in to comment.