Skip to content

Commit b45eeb4

Browse files
Merge pull request #75 from wp-cli/65-check-for-pcre-error-on-return
Handle PCRE errors gracefully
2 parents 9da6770 + 5002a64 commit b45eeb4

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

src/WP_CLI/SearchReplacer.php

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace WP_CLI;
44

5+
use Exception;
6+
57
class SearchReplacer {
68

79
private $from, $to;
@@ -102,7 +104,17 @@ private function _run( $data, $serialised, $recursion_level = 0, $visited_data =
102104
$search_regex .= $this->from;
103105
$search_regex .= $this->regex_delimiter;
104106
$search_regex .= $this->regex_flags;
105-
$data = preg_replace( $search_regex, $this->to, $data );
107+
108+
$result = preg_replace( $search_regex, $this->to, $data );
109+
if ( null === $result || PREG_NO_ERROR !== preg_last_error() ) {
110+
\WP_CLI::warning(
111+
sprintf(
112+
'The provided regular expression threw a PCRE error - %s',
113+
$this->preg_error_message( $result )
114+
)
115+
);
116+
}
117+
$data = $result;
106118
} else {
107119
$data = str_replace( $this->from, $this->to, $data );
108120
}
@@ -135,5 +147,21 @@ public function get_log_data() {
135147
public function clear_log_data() {
136148
$this->log_data = array();
137149
}
150+
151+
/**
152+
* Get the PCRE error constant name from an error value.
153+
*
154+
* @param integer $error Error code.
155+
* @return string Error constant name.
156+
*/
157+
private function preg_error_message( $error ) {
158+
$constants = get_defined_constants( true );
159+
if ( ! array_key_exists( 'pcre', $constants ) ) {
160+
return '<unknown error>';
161+
}
162+
163+
$names = array_flip( $constants['pcre'] );
164+
return isset( $names[ $error ] ) ? $names[ $error ] : '<unknown error>';
165+
}
138166
}
139167

0 commit comments

Comments
 (0)