Skip to content

Use Only mb_convert_encoding in StringHelper sanitizeUTF8 #2994

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 13, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/PhpSpreadsheet/Shared/StringHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ public static function controlCharacterPHP2OOXML($textValue)
public static function sanitizeUTF8(string $textValue): string
{
$textValue = str_replace(["\xef\xbf\xbe", "\xef\xbf\xbf"], "\xef\xbf\xbd", $textValue);
if (class_exists(UConverter::class)) {
if (class_exists(UConverter::class, false)) {
$returnValue = UConverter::transcode($textValue, 'UTF-8', 'UTF-8');
if ($returnValue !== false) {
return $returnValue;
Expand All @@ -349,8 +349,11 @@ public static function sanitizeUTF8(string $textValue): string
}
}

$subst = mb_substitute_character(); // default is question mark
mb_substitute_character(65533); // Unicode substitution character
// Phpstan does not think this can return false.
$returnValue = mb_convert_encoding($textValue, 'UTF-8', 'UTF-8');
mb_substitute_character($subst);

return $returnValue;
// @codeCoverageIgnoreEnd
Expand Down
35 changes: 35 additions & 0 deletions tests/PhpSpreadsheetTests/Shared/StringHelperInvalidCharTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace PhpOffice\PhpSpreadsheetTests\Shared;

use Exception as Except;
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -41,4 +42,38 @@ public function testInvalidChar(): void
);
}
}

public function fakespl(string $name): void
{
if (strlen($name) > 0) {
throw new Except("$name not found");
}
}

public function testClassNotFound(): void
{
// see issue 2982.
// This test will work all the time, but it is valuable
// only if php-intl not available
// and a user-supplied autoloader can issue exception.
/** @var callable */
$fakespl = [$this, 'fakespl'];
spl_autoload_register($fakespl);

try {
self::assertFalse(class_exists('abc123xyz'));
self::fail('Expected exception here');
} catch (Except $e) {
// Nothing to do here
}

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');

$spreadsheet->disconnectWorksheets();

spl_autoload_unregister($fakespl);
self::assertFalse(class_exists('abc123wxyz'));
}
}