Skip to content

Commit 622114b

Browse files
committed
Pair error handler restoration properly
Previously, the error handlers in IconvTranscoder and MbTranscoder were not restored on error because exception was raised. And what is worse, MbTranscoder popped the error handler stack even when it did not push into it. Let’s fix the former by restoring in a finally block (not catching the raised exception), and the latter by restoring only conditionally.
1 parent e56652f commit 622114b

File tree

2 files changed

+24
-17
lines changed

2 files changed

+24
-17
lines changed

src/IconvTranscoder.php

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,13 @@ function ($no, $message) use ($string) {
3434
},
3535
E_NOTICE | E_USER_NOTICE
3636
);
37-
38-
$result = iconv($from, $to ?: $this->defaultEncoding, $string);
39-
restore_error_handler();
40-
37+
38+
try {
39+
$result = iconv($from, $to ?: $this->defaultEncoding, $string);
40+
} finally {
41+
restore_error_handler();
42+
}
43+
4144
return $result;
4245
}
4346
}

src/MbTranscoder.php

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,12 @@ public function transcode($string, $from = null, $to = null)
4141
}
4242
}
4343

44-
if (!$from || 'auto' === $from) {
44+
if ($to) {
45+
$this->assertSupported($to);
46+
}
47+
48+
$handleErrors = !$from || 'auto' === $from;
49+
if ($handleErrors) {
4550
set_error_handler(
4651
function ($no, $warning) use ($string) {
4752
throw new UndetectableEncodingException($string, $warning);
@@ -50,19 +55,18 @@ function ($no, $warning) use ($string) {
5055
);
5156
}
5257

53-
54-
if ($to) {
55-
$this->assertSupported($to);
58+
try {
59+
$result = mb_convert_encoding(
60+
$string,
61+
$to ?: $this->defaultEncoding,
62+
$from ?: 'auto'
63+
);
64+
} finally {
65+
if ($handleErrors) {
66+
restore_error_handler();
67+
}
5668
}
57-
58-
$result = mb_convert_encoding(
59-
$string,
60-
$to ?: $this->defaultEncoding,
61-
$from ?: 'auto'
62-
);
63-
64-
restore_error_handler();
65-
69+
6670
return $result;
6771
}
6872

0 commit comments

Comments
 (0)