Skip to content

Commit

Permalink
Return empty array if no valid command detected
Browse files Browse the repository at this point in the history
In some edge cases, the formatContent() method may return a document stream row containing an invalid command. Make sure we just ignore these commands instead of triggering warnings for missing $matches array elements.
  • Loading branch information
GreyWyvern committed Sep 26, 2023
1 parent 7fb1398 commit 5455990
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Smalot/PdfParser/PDFObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -974,6 +974,11 @@ public function getCommandsText(string $text_part, int &$offset = 0): array

preg_match('/^(([\/\[\(<])?.*)(?<!\w)([a-z01\'\"*]+)$/i', $text_part, $matches);

// If no valid command is detected, return an empty array
if (!isset($matches[1]) || !isset($matches[2]) || !isset($matches[3])) {
return [];
}

$type = $matches[2];
$operator = $matches[3];
$command = trim($matches[1]);
Expand Down
19 changes: 19 additions & 0 deletions tests/PHPUnit/Integration/PDFObjectTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -463,4 +463,23 @@ public function testFontIDWithHyphen(): void
$this->assertEquals('Tf', $fontCommandHyphen[0]['o']);
$this->assertEquals('FID-01 15.00', $fontCommandHyphen[0]['c']);
}

/**
* Tests that an invalid command does not cause an error, but just
* returns an empty array
*/
public function testInvalidCommand(): void
{
$pdfObject = $this->getPdfObjectInstance(new Document());

$validCommand = $pdfObject->getCommandsText('75 rg');

$this->assertEquals('', $validCommand[0]['t']);
$this->assertEquals('rg', $validCommand[0]['o']);
$this->assertEquals('75', $validCommand[0]['c']);

$invalidCommand = $pdfObject->getCommandsText('75');

$this->assertEquals([], $invalidCommand);
}
}

0 comments on commit 5455990

Please sign in to comment.