diff --git a/src/Definition/Exception/InvalidParameterIndex.php b/src/Definition/Exception/InvalidParameterIndex.php new file mode 100644 index 0000000..e5690ac --- /dev/null +++ b/src/Definition/Exception/InvalidParameterIndex.php @@ -0,0 +1,22 @@ +count() - 1; + + parent::__construct( + "Index $index is out of range, it should be between 0 and $max.", + 1644936619 + ); + } +} diff --git a/src/Definition/Parameters.php b/src/Definition/Parameters.php index b80d25c..33e28cd 100644 --- a/src/Definition/Parameters.php +++ b/src/Definition/Parameters.php @@ -5,10 +5,13 @@ declare(strict_types=1); namespace CuyZ\Valinor\Definition; use Countable; +use CuyZ\Valinor\Definition\Exception\InvalidParameterIndex; use CuyZ\Valinor\Definition\Exception\ParameterNotFound; use IteratorAggregate; use Traversable; +use function array_values; + /** * @api * @@ -40,6 +43,18 @@ final class Parameters implements IteratorAggregate, Countable return $this->parameters[$name]; } + /** + * @param int<0, max> $index + */ + public function at(int $index): ParameterDefinition + { + if ($index >= $this->count()) { + throw new InvalidParameterIndex($index, $this); + } + + return array_values($this->parameters)[$index]; + } + public function count(): int { return count($this->parameters); diff --git a/tests/Unit/Definition/ParametersTest.php b/tests/Unit/Definition/ParametersTest.php index 4f69855..01948b0 100644 --- a/tests/Unit/Definition/ParametersTest.php +++ b/tests/Unit/Definition/ParametersTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace CuyZ\Valinor\Tests\Unit\Definition; +use CuyZ\Valinor\Definition\Exception\InvalidParameterIndex; use CuyZ\Valinor\Definition\Exception\ParameterNotFound; use CuyZ\Valinor\Definition\Parameters; use CuyZ\Valinor\Tests\Fake\Definition\FakeParameterDefinition; @@ -36,6 +37,25 @@ final class ParametersTest extends TestCase (new Parameters())->get('unknownParameter'); } + public function test_get_parameter_at_index_returns_correct_parameter(): void + { + $parameterA = FakeParameterDefinition::new('SomeParameterA'); + $parameterB = FakeParameterDefinition::new('SomeParameterB'); + $parameters = new Parameters($parameterA, $parameterB); + + self::assertSame($parameterA, $parameters->at(0)); + self::assertSame($parameterB, $parameters->at(1)); + } + + public function test_get_parameter_at_index_out_of_range_throws_exception(): void + { + $this->expectException(InvalidParameterIndex::class); + $this->expectExceptionCode(1644936619); + $this->expectExceptionMessage('Index 1 is out of range, it should be between 0 and 0.'); + + (new Parameters(FakeParameterDefinition::new()))->at(1); + } + public function test_parameters_are_countable(): void { $parameters = new Parameters(