Skip to content

Commit

Permalink
Merge pull request #1176 from sparklink-pro/master
Browse files Browse the repository at this point in the history
Ensure that a #[GQL\Arg] on method has a matching parameter
  • Loading branch information
Vincz authored Apr 2, 2024
2 parents f990e0b + c45817f commit e16d86d
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/Config/Parser/MetadataParser/MetadataParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use ReflectionClassConstant;
use ReflectionException;
use ReflectionMethod;
use ReflectionParameter;
use ReflectionProperty;
use Reflector;
use RuntimeException;
Expand Down Expand Up @@ -591,7 +592,13 @@ private static function getTypeFieldConfigurationFromReflector(ReflectionClass $
/** @var Metadata\Arg[] $argAnnotations */
$argAnnotations = self::getMetadataMatching($metadatas, Metadata\Arg::class);

$validArgNames = array_map(fn (ReflectionParameter $parameter) => $parameter->getName(), $reflector instanceof ReflectionMethod ? $reflector->getParameters() : []);

foreach ($argAnnotations as $arg) {
if ($reflector instanceof ReflectionMethod && !in_array($arg->name, $validArgNames, true)) {
throw new InvalidArgumentException(sprintf('The argument "%s" defined with #[GQL\Arg] attribute/annotation on method "%s" does not match any parameter name in the method.', $arg->name, $reflector->getName()));
}

$args[$arg->name] = ['type' => $arg->type];

if (isset($arg->description)) {
Expand Down
12 changes: 12 additions & 0 deletions tests/Config/Parser/MetadataParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,18 @@ public function testInvalidParamGuessing(): void
}
}

public function testInvalidArgumentMatching(): void
{
try {
$file = __DIR__.'/fixtures/annotations/Invalid/InvalidArgumentNaming.php';
$this->parser('parse', new SplFileInfo($file), $this->containerBuilder, $this->parserConfig);
$this->fail('Missing matching argument should have raise an exception');
} catch (Exception $e) {
$this->assertInstanceOf(InvalidArgumentException::class, $e);
$this->assertMatchesRegularExpression('/The argument "missingParameter" defined/', $e->getPrevious()->getMessage());
}
}

public function testInvalidReturnGuessing(): void
{
try {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Overblog\GraphQLBundle\Tests\Config\Parser\fixtures\annotations\Invalid;

use Overblog\GraphQLBundle\Annotation as GQL;

/**
* @GQL\Type
*/
#[GQL\Type]
final class InvalidArgumentNaming
{
/**
* @GQL\Field(name="guessFailed")
*
* @GQL\Arg(name="missingParameter", type="String")
*/
#[GQL\Field(name: 'guessFailed')]
#[GQL\Arg(name: 'missingParameter', type: 'String')]
public function guessFail(int $test): int
{
return 12;
}
}

0 comments on commit e16d86d

Please sign in to comment.