feat: introduce method to get parameter by index

This commit is contained in:
Romain Canon 2022-02-15 21:38:36 +01:00
parent d6e778aff7
commit 380961247e
3 changed files with 57 additions and 0 deletions

View File

@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace CuyZ\Valinor\Definition\Exception;
use CuyZ\Valinor\Definition\Parameters;
use LogicException;
/** @internal */
final class InvalidParameterIndex extends LogicException
{
public function __construct(int $index, Parameters $parameters)
{
$max = $parameters->count() - 1;
parent::__construct(
"Index $index is out of range, it should be between 0 and $max.",
1644936619
);
}
}

View File

@ -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);

View File

@ -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(