Skip to content

Commit 954863e

Browse files
Enhance error handling in encoding functions and update TOC test with static HTML content
1 parent 6ca8c9f commit 954863e

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

src/PhpWord/Shared/Microsoft/PasswordEncoder.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818

1919
namespace PhpOffice\PhpWord\Shared\Microsoft;
2020

21+
use PhpOffice\PhpWord\Exception\Exception;
22+
2123
/**
2224
* Password encoder for microsoft office applications.
2325
*/
@@ -119,8 +121,11 @@ public static function hashPassword($password, $algorithmName = self::ALGORITHM_
119121
// Get the single-byte values by iterating through the Unicode characters of the truncated password.
120122
// For each character, if the low byte is not equal to 0, take it. Otherwise, take the high byte.
121123
$passUtf8 = mb_convert_encoding($password, 'UCS-2LE', 'UTF-8');
122-
$byteChars = [];
124+
if (!is_string($passUtf8)) {
125+
throw new Exception('Failed to convert password to UCS-2LE');
126+
}
123127

128+
$byteChars = [];
124129
for ($i = 0; $i < mb_strlen($password); ++$i) {
125130
$byteChars[$i] = ord(substr($passUtf8, $i * 2, 1));
126131

src/PhpWord/Shared/Text.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818

1919
namespace PhpOffice\PhpWord\Shared;
2020

21+
use PhpOffice\PhpWord\Exception\Exception;
22+
2123
/**
2224
* Text.
2325
*/
@@ -148,6 +150,9 @@ public static function toUTF8($value = '')
148150
if (null !== $value && !self::isUTF8($value)) {
149151
// PHP8.2 : utf8_encode is deprecated, but mb_convert_encoding always usable
150152
$value = (function_exists('mb_convert_encoding')) ? mb_convert_encoding($value, 'UTF-8', 'ISO-8859-1') : utf8_encode($value);
153+
if ($value === false) {
154+
throw new Exception('Unable to convert text to UTF-8');
155+
}
151156
}
152157

153158
return $value;

tests/bootstrap.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,9 @@ function phpunit10ErrorHandler(int $errno, string $errstr, string $filename, int
5454

5555
function utf8decode(string $value, string $toEncoding = 'ISO-8859-1'): string
5656
{
57-
return function_exists('mb_convert_encoding') ? mb_convert_encoding($value, $toEncoding, 'UTF-8') : utf8_decode($value);
57+
$result = function_exists('mb_convert_encoding') ? mb_convert_encoding($value, $toEncoding, 'UTF-8') : utf8_decode($value);
58+
59+
return $result === false ? '' : $result;
5860
}
5961

6062
if (!method_exists(PHPUnit\Framework\TestCase::class, 'setOutputCallback')) {

0 commit comments

Comments
 (0)