diff --git a/src/Smalot/PdfParser/Encoding.php b/src/Smalot/PdfParser/Encoding.php index d1779d85..369d3af6 100644 --- a/src/Smalot/PdfParser/Encoding.php +++ b/src/Smalot/PdfParser/Encoding.php @@ -126,13 +126,23 @@ public function translateChar($dec) } /** - * @return string + * Returns the name of the encoding class, if available. * - * @throws \Exception + * @return string Returns encoding class name if available or empty string (only prior PHP 7.4). + * + * @throws \Exception On PHP 7.4+ an exception is thrown if encoding class doesn't exist. */ public function __toString() { - return $this->getEncodingClass(); + try { + return $this->getEncodingClass(); + } catch (Exception $e) { + // prior to PHP 7.4 toString has to return an empty string. + if (version_compare(\PHP_VERSION, '7.4.0', '<')) { + return ''; + } + throw $e; + } } /** diff --git a/tests/Integration/EncodingTest.php b/tests/Integration/EncodingTest.php index de1f98ac..f6ef6464 100644 --- a/tests/Integration/EncodingTest.php +++ b/tests/Integration/EncodingTest.php @@ -54,8 +54,13 @@ public function testGetEncodingClass() /** * This tests checks behavior if given Encoding class doesn't exist. + * + * Protected method getEncodingClass is called in init and __toString. + * It throws an exception if class is not available. + * Calling init is enough to trigger the exception, but __toString call afterwards + * makes sure that we don't missing it. */ - public function testGetEncodingClassMissingClassException() + public function testInitGetEncodingClassMissingClassException() { $this->expectException(Exception::class); $this->expectExceptionMessage('Missing encoding data for: "invalid"'); @@ -67,4 +72,32 @@ public function testGetEncodingClassMissingClassException() $encoding->__toString(); } + + /** + * This tests focuses on behavior of Encoding::__toString when running PHP 7.4+ and prior. + * + * Prior PHP 7.4 we expect an empty string to be returned (based on PHP specification). + * PHP 7.4+ we expect an exception to be thrown when class is invalid. + */ + public function testToStringGetEncodingClassMissingClassException() + { + // prior to PHP 7.4 toString has to return an empty string. + if (version_compare(\PHP_VERSION, '7.4.0', '<')) { + $header = new Header(['BaseEncoding' => new Element('invalid')]); + + $encoding = new Encoding(new Document(), $header); + + $this->assertEquals('', $encoding->__toString()); + } else { + // PHP 7.4+ + $this->expectException(Exception::class); + $this->expectExceptionMessage('Missing encoding data for: "invalid"'); + + $header = new Header(['BaseEncoding' => new Element('invalid')]); + + $encoding = new Encoding(new Document(), $header); + + $encoding->__toString(); + } + } }