From 28a7a95f4c03408947bf5116b93572544fe68b9c Mon Sep 17 00:00:00 2001 From: Jaapio Date: Tue, 4 Jan 2022 08:34:33 +0100 Subject: [PATCH] Throw exception on invalid array start When the current type index is null, no type was resolved yet. So an array start is invalid. An `[]` array operator should always be prefixed with a type notation. --- src/TypeResolver.php | 7 ++++++- tests/unit/TypeResolverTest.php | 13 +++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/TypeResolver.php b/src/TypeResolver.php index 415b374..188dc07 100644 --- a/src/TypeResolver.php +++ b/src/TypeResolver.php @@ -38,6 +38,7 @@ use function class_exists; use function class_implements; use function count; +use function current; use function end; use function in_array; use function key; @@ -273,6 +274,10 @@ private function parseTypes(ArrayIterator $tokens, Context $context, int $parser } elseif ($token === self::OPERATOR_ARRAY) { end($types); $last = key($types); + if ($last === null) { + throw new InvalidArgumentException('Unexpected array operator'); + } + $lastItem = $types[$last]; if ($lastItem instanceof Expression) { $lastItem = $lastItem->getValueType(); @@ -317,7 +322,7 @@ private function parseTypes(ArrayIterator $tokens, Context $context, int $parser ); } } elseif (count($types) === 1) { - return $types[0]; + return current($types); } if ($compoundToken === '|') { diff --git a/tests/unit/TypeResolverTest.php b/tests/unit/TypeResolverTest.php index 7a8f062..deff9ce 100644 --- a/tests/unit/TypeResolverTest.php +++ b/tests/unit/TypeResolverTest.php @@ -714,6 +714,19 @@ public function testExceptionIsThrownIfTypeIsEmpty(): void $fixture->resolve(' ', new Context('')); } + /** + * @uses \phpDocumentor\Reflection\Types\Context + * + * @covers ::__construct + * @covers ::resolve + */ + public function testInvalidArrayOperator(): void + { + $this->expectException('InvalidArgumentException'); + $fixture = new TypeResolver(); + $fixture->resolve('[]', new Context('')); + } + /** * Returns a list of keywords and expected classes that are created from them. *