From cc4c77f6c789354f1cee30d7369a6f65856f741e Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Fri, 21 Aug 2020 10:35:13 +0200 Subject: [PATCH] Fix error when Font aren't available This can happen (like in many places of `Page.php`) when the retrieved element is missing (and the instance if `ElementMissing`. In that case, we just return an empty array (the default value). --- src/Smalot/PdfParser/Page.php | 4 ++++ tests/Integration/PageTest.php | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/Smalot/PdfParser/Page.php b/src/Smalot/PdfParser/Page.php index f0b2e2d5..b9d6f684 100644 --- a/src/Smalot/PdfParser/Page.php +++ b/src/Smalot/PdfParser/Page.php @@ -64,6 +64,10 @@ public function getFonts() $resources = $this->get('Resources'); if (method_exists($resources, 'has') && $resources->has('Font')) { + if ($resources->get('Font') instanceof ElementMissing) { + return []; + } + if ($resources->get('Font') instanceof Header) { $fonts = $resources->get('Font')->getElements(); } else { diff --git a/tests/Integration/PageTest.php b/tests/Integration/PageTest.php index 1247a700..c923eb51 100644 --- a/tests/Integration/PageTest.php +++ b/tests/Integration/PageTest.php @@ -32,7 +32,10 @@ namespace Tests\Smalot\PdfParser\Integration; +use Smalot\PdfParser\Document; +use Smalot\PdfParser\Element\ElementMissing; use Smalot\PdfParser\Font; +use Smalot\PdfParser\Page; use Tests\Smalot\PdfParser\TestCase; class PageTest extends TestCase @@ -71,6 +74,35 @@ public function testGetFonts() $this->assertEquals(0, \count($fonts)); } + public function testGetFontsElementMissing() + { + $headerResources = $this->getMockBuilder('Smalot\PdfParser\Header') + ->disableOriginalConstructor() + ->getMock(); + + $headerResources->expects($this->once()) + ->method('has') + ->willReturn(true); + + $headerResources->expects($this->once()) + ->method('get') + ->willReturn(new ElementMissing()); + + $header = $this->getMockBuilder('Smalot\PdfParser\Header') + ->disableOriginalConstructor() + ->getMock(); + + $header->expects($this->once()) + ->method('get') + ->willReturn($headerResources); + + $page = new Page(new Document(), $header); + $fonts = $page->getFonts(); + + $this->assertEmpty($fonts); + $this->assertEquals([], $fonts); + } + public function testGetFont() { // Document with text.