Skip to content

Commit 28a7a95

Browse files
committed
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.
1 parent 2c26b0e commit 28a7a95

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/TypeResolver.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
use function class_exists;
3939
use function class_implements;
4040
use function count;
41+
use function current;
4142
use function end;
4243
use function in_array;
4344
use function key;
@@ -273,6 +274,10 @@ private function parseTypes(ArrayIterator $tokens, Context $context, int $parser
273274
} elseif ($token === self::OPERATOR_ARRAY) {
274275
end($types);
275276
$last = key($types);
277+
if ($last === null) {
278+
throw new InvalidArgumentException('Unexpected array operator');
279+
}
280+
276281
$lastItem = $types[$last];
277282
if ($lastItem instanceof Expression) {
278283
$lastItem = $lastItem->getValueType();
@@ -317,7 +322,7 @@ private function parseTypes(ArrayIterator $tokens, Context $context, int $parser
317322
);
318323
}
319324
} elseif (count($types) === 1) {
320-
return $types[0];
325+
return current($types);
321326
}
322327

323328
if ($compoundToken === '|') {

tests/unit/TypeResolverTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -714,6 +714,19 @@ public function testExceptionIsThrownIfTypeIsEmpty(): void
714714
$fixture->resolve(' ', new Context(''));
715715
}
716716

717+
/**
718+
* @uses \phpDocumentor\Reflection\Types\Context
719+
*
720+
* @covers ::__construct
721+
* @covers ::resolve
722+
*/
723+
public function testInvalidArrayOperator(): void
724+
{
725+
$this->expectException('InvalidArgumentException');
726+
$fixture = new TypeResolver();
727+
$fixture->resolve('[]', new Context(''));
728+
}
729+
717730
/**
718731
* Returns a list of keywords and expected classes that are created from them.
719732
*

0 commit comments

Comments
 (0)