44
55class Migrator
66{
7+ /**
8+ * @var string[]
9+ */
10+ private $ from ;
11+
12+ /**
13+ * @var string[]
14+ */
15+ private $ to ;
16+
17+ public function __construct ()
18+ {
19+ $ this ->from = array_keys ($ this ->getMapping ());
20+ $ this ->to = array_values ($ this ->getMapping ());
21+ }
22+
723 /**
824 * Return the ordered mapping from old PHPExcel class names to new PhpSpreadsheet one.
925 *
@@ -258,9 +274,6 @@ private function recursiveReplace($path)
258274 '/*.phtml ' ,
259275 ];
260276
261- $ from = array_keys ($ this ->getMapping ());
262- $ to = array_values ($ this ->getMapping ());
263-
264277 foreach ($ patterns as $ pattern ) {
265278 foreach (glob ($ path . $ pattern ) as $ file ) {
266279 if (strpos ($ path , '/vendor/ ' ) !== false ) {
@@ -269,12 +282,7 @@ private function recursiveReplace($path)
269282 continue ;
270283 }
271284 $ original = file_get_contents ($ file );
272- $ converted = str_replace ($ from , $ to , $ original );
273-
274- // The string "PHPExcel" gets special treatment because of how common it might be.
275- // This regex requires a word boundary around the string, and it can't be
276- // preceded by $ or -> (goal is to filter out cases where a variable is named $PHPExcel or similar)
277- $ converted = preg_replace ('/(?<!\$|->)\bPHPExcel\b/ ' , \PhpOffice \PhpSpreadsheet \Spreadsheet::class, $ original );
285+ $ converted = $ this ->replace ($ original );
278286
279287 if ($ original !== $ converted ) {
280288 echo $ file . " converted \n" ;
@@ -303,4 +311,23 @@ public function migrate()
303311 $ this ->recursiveReplace ($ path );
304312 }
305313 }
314+
315+ /**
316+ * Migrate the given code from PHPExcel to PhpSpreadsheet.
317+ *
318+ * @param string $original
319+ *
320+ * @return string
321+ */
322+ public function replace ($ original )
323+ {
324+ $ converted = str_replace ($ this ->from , $ this ->to , $ original );
325+
326+ // The string "PHPExcel" gets special treatment because of how common it might be.
327+ // This regex requires a word boundary around the string, and it can't be
328+ // preceded by $ or -> (goal is to filter out cases where a variable is named $PHPExcel or similar)
329+ $ converted = preg_replace ('~(?<!\$|->)(\b| \\\\)PHPExcel\b~ ' , '\\' . \PhpOffice \PhpSpreadsheet \Spreadsheet::class, $ converted );
330+
331+ return $ converted ;
332+ }
306333}
0 commit comments