Skip to content

Commit

Permalink
Font.php: hot fix for calculateTextWidth in case Widths key is not set (
Browse files Browse the repository at this point in the history
#645)

* Font.php: Small workaround if Widths-key is not set in $details array

* FontTest.php: add test to check behavior if Widths key is not set in $details array

* Font.php: refined wording in comment
  • Loading branch information
k00ni authored Oct 2, 2023
1 parent 778e307 commit 52c4f6c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Smalot/PdfParser/Font.php
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,9 @@ public function calculateTextWidth(string $text, array &$missing = null): ?float
{
$index_map = array_flip($this->table);
$details = $this->getDetails();
$widths = $details['Widths'];

// Usually, Widths key is set in $details array, but if it isn't use an empty array instead.
$widths = $details['Widths'] ?? [];

// Widths array is zero indexed but table is not. We must map them based on FirstChar and LastChar
$width_map = array_flip(range($details['FirstChar'], $details['LastChar']));
Expand Down
23 changes: 23 additions & 0 deletions tests/PHPUnit/Integration/FontTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,29 @@ public function testCalculateTextWidth(): void
$this->assertEquals([], $missing);
}

/**
* Check behavior if getDetails() does return an array without a Widths-key.
*
* @see https://github.com/smalot/pdfparser/issues/619
*/
public function testCalculateTextWidthNoWidthsKey(): void
{
$document = $this->createMock(Document::class);

$header = $this->createMock(Header::class);
$header->method('getDetails')->willReturn([
'FirstChar' => '',
'LastChar' => '',
// 'Widths' key is not set, so without the fix in Font.php a warning would be thrown.
]);

$font = new Font($document, $header);
$font->setTable([]);
$width = $font->calculateTextWidth('foo');

$this->assertNull($width);
}

/**
* Check behavior if iconv function gets input which contains illegal characters.
*
Expand Down

0 comments on commit 52c4f6c

Please sign in to comment.