|
2 | 2 |
|
3 | 3 | namespace WP_CLI;
|
4 | 4 |
|
| 5 | +use Exception; |
| 6 | + |
5 | 7 | class SearchReplacer {
|
6 | 8 |
|
7 | 9 | private $from, $to;
|
@@ -102,7 +104,17 @@ private function _run( $data, $serialised, $recursion_level = 0, $visited_data =
|
102 | 104 | $search_regex .= $this->from;
|
103 | 105 | $search_regex .= $this->regex_delimiter;
|
104 | 106 | $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; |
106 | 118 | } else {
|
107 | 119 | $data = str_replace( $this->from, $this->to, $data );
|
108 | 120 | }
|
@@ -135,5 +147,21 @@ public function get_log_data() {
|
135 | 147 | public function clear_log_data() {
|
136 | 148 | $this->log_data = array();
|
137 | 149 | }
|
| 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 | + } |
138 | 166 | }
|
139 | 167 |
|
0 commit comments