Skip to content

Commit bb9d361

Browse files
authored
Merge pull request #476 from PHPCSStandards/feature/abstractarraydeclaration-bugfix
AbstractArrayDeclarationSniff: extra defensive coding for live coding/parse errors
2 parents 9fe6c2f + 2db1534 commit bb9d361

File tree

3 files changed

+44
-1
lines changed

3 files changed

+44
-1
lines changed

PHPCSUtils/AbstractSniffs/AbstractArrayDeclarationSniff.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,9 +184,14 @@ final public function process(File $phpcsFile, $stackPtr)
184184
return;
185185
}
186186

187+
$openClose = Arrays::getOpenClose($phpcsFile, $stackPtr, true);
188+
if ($openClose === false) {
189+
// Parse error or live coding.
190+
return;
191+
}
192+
187193
$this->stackPtr = $stackPtr;
188194
$this->tokens = $phpcsFile->getTokens();
189-
$openClose = Arrays::getOpenClose($phpcsFile, $stackPtr, true);
190195
$this->arrayOpener = $openClose['opener'];
191196
$this->arrayCloser = $openClose['closer'];
192197
$this->itemCount = \count($this->arrayItems);

Tests/AbstractSniffs/AbstractArrayDeclaration/AbstractArrayDeclarationSniffTest.inc

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,7 @@ $array = [1, 'a' => 2, ];
3030

3131
/* testShortList */
3232
[$a, $b] = $array;
33+
34+
/* testLiveCoding */
35+
// This must be the last test in the file!!
36+
$array = array(

Tests/AbstractSniffs/AbstractArrayDeclaration/AbstractArrayDeclarationSniffTest.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -611,4 +611,38 @@ public function testShortCircuitOnProcessComma()
611611

612612
$mockObj->process(self::$phpcsFile, $target);
613613
}
614+
615+
/**
616+
* Test that the abstract sniff correctly bows out when presented with an unfinished array.
617+
*
618+
* @return void
619+
*/
620+
public function testBowOutOnUnfinishedArray()
621+
{
622+
$target = $this->getTargetToken('/* testLiveCoding */', Collections::arrayOpenTokensBC());
623+
624+
$mockObj = $this->getMockBuilder('\PHPCSUtils\AbstractSniffs\AbstractArrayDeclarationSniff')
625+
->setMethods($this->methodsToMock)
626+
->getMockForAbstractClass();
627+
628+
$mockObj->expects($this->never())
629+
->method('processOpenClose');
630+
631+
$mockObj->expects($this->never())
632+
->method('processKey');
633+
634+
$mockObj->expects($this->never())
635+
->method('processNoKey');
636+
637+
$mockObj->expects($this->never())
638+
->method('processArrow');
639+
640+
$mockObj->expects($this->never())
641+
->method('processValue');
642+
643+
$mockObj->expects($this->never())
644+
->method('processComma');
645+
646+
$mockObj->process(self::$phpcsFile, $target);
647+
}
614648
}

0 commit comments

Comments
 (0)