创建一个 PHP 5 到 PHP 7 代码转换器

在大多数情况下,PHP 5. x 代码可以不加修改地在 PHP 7上运行。然而,有一些变化被归类为向后不兼容。这意味着,如果你的 PHP 5代码是以某种方式编写的,或者使用已经被删除的函数,你的代码就会中断,你就会得到一个严重的错误。

做好准备

PHP 5到PHP 7代码转换器有两个作用:

  • 扫描你的代码文件,并将PHP 5中已被删除的功能转换为PHP 7中的相应功能。
  • 在语言用法发生变化但无法重写的情况下,添加带//警告的注释。

{% hint style=”info” %} 请注意,在运行转换器后,你的代码不能保证在 PHP 7 中工作。你仍然需要检查添加的 // WARNING 标签。至少,这个配方将给你一个良好的开端,将你的 PHP 5 代码转换为在 PHP 7 中工作。 {% endhint %}

这个配方的核心是 PHP 7 的新函数 preg_replace_callback_array() 。这个神奇的函数允许你做的是将一个正则表达式数组作为键,其值代表一个独立的回调。然后,你可以将字符串通过一系列的转换。不仅如此,回调数组本身也可以是一个数组。

如何做…

1.在一个新的 Application\Parse\Convert 类中,我们首先使用 scan() 方法,它接受一个文件名作为参数。它检查文件是否存在。如果存在,它调用PHP file() 函数,将文件加载到一个数组中,每个数组元素代表一行。

  1. public function scan($filename)
  2. {
  3. if (!file_exists($filename)) {
  4. throw new Exception(
  5. self::EXCEPTION_FILE_NOT_EXISTS);
  6. }
  7. $contents = file($filename);
  8. echo 'Processing: ' . $filename . PHP_EOL;
  9. $result = preg_replace_callback_array( [

2.接下来,我们开始传递一系列的键/值对。键是一个正则表达式,它将针对字符串进行处理。任何匹配的结果都会被传递给回调,回调的值是键/值对的值部分。我们检查PHP 7中已被删除的打开和关闭标签:

  1. // 替换不再支持的开始标签
  2. '!^\<\%(\n| )!' =>
  3. function ($match) {
  4. return '<?php' . $match[1];
  5. },
  6. // 替换不再支持的开始标签
  7. '!^\<\%=(\n| )!' =>
  8. function ($match) {
  9. return '<?php echo ' . $match[1];
  10. },
  11. // 替换不再支持的结束标签
  12. '!\%\>!' =>
  13. function ($match) {
  14. return '?>';
  15. },

3.接下来是一系列的警告,当检测到某些操作,并且在PHP 5和PHP 7中处理这些操作的方式之间存在潜在的代码断裂。在所有这些情况下,代码不会被重新编写。取而代之的是一个带有 WARNING 字样的内联注释:

  1. // 改变 $xxx 解释的处理方式
  2. '!(.*?)\$\$!' =>
  3. function ($match) {
  4. return '// WARNING: variable interpolation
  5. . ' now occurs left-to-right' . PHP_EOL
  6. . '// see: http://php.net/manual/en/'
  7. . '// migration70.incompatible.php'
  8. . $match[0];
  9. },
  10. // list()运算符处理方式的更改
  11. '!(.*?)list(\s*?)?\(!' =>
  12. function ($match) {
  13. return '// WARNING: changes have been made '
  14. . 'in list() operator handling.'
  15. . 'See: http://php.net/manual/en/'
  16. . 'migration70.incompatible.php'
  17. . $match[0];
  18. },
  19. // 实例 \u{
  20. '!(.*?)\\\u\{!' =>
  21. function ($match) {
  22. return '// WARNING: \\u{xxx} is now considered '
  23. . 'unicode escape syntax' . PHP_EOL
  24. . '// see: http://php.net/manual/en/'
  25. . 'migration70.new-features.php'
  26. . '#migration70.new-features.unicode-'
  27. . 'codepoint-escape-syntax' . PHP_EOL
  28. . $match[0];
  29. },
  30. // 依赖于 set_error_handler()
  31. '!(.*?)set_error_handler(\s*?)?.*\(!' =>
  32. function ($match) {
  33. return '// WARNING: might not '
  34. . 'catch all errors'
  35. . '// see: http://php.net/manual/en/'
  36. . '// language.errors.php7.php'
  37. . $match[0];
  38. },
  39. // session_set_save_handler(xxx)
  40. '!(.*?)session_set_save_handler(\s*?)?\((.*?)\)!' =>
  41. function ($match) {
  42. if (isset($match[3])) {
  43. return '// WARNING: a bug introduced in'
  44. . 'PHP 5.4 which '
  45. . 'affects the handler assigned by '
  46. . 'session_set_save_handler() and '
  47. . 'where ignore_user_abort() is TRUE
  48. . 'has been fixed in PHP 7.'
  49. . 'This could potentially break '
  50. . 'your code under '
  51. . 'certain circumstances.' . PHP_EOL
  52. . 'See: http://php.net/manual/en/'
  53. . 'migration70.incompatible.php'
  54. . $match[0];
  55. } else {
  56. return $match[0];
  57. }
  58. },

4.任何试图使用 <<>> 与负运算符,或超过64的尝试,都会被包装在 try { xxx } catch() { xxx } 块中,寻找一个 ArithmeticError 并被抛出。

  1. // 在 try/catch 中包装 bit shift 操作
  2. '!^(.*?)(\d+\s*(\<\<|\>\>)\s*-?\d+)(.*?)$!' =>
  3. function ($match) {
  4. return '// WARNING: negative and '
  5. . 'out-of-range bitwise '
  6. . 'shift operations will now
  7. . 'throw an ArithmeticError' . PHP_EOL
  8. . 'See: http://php.net/manual/en/'
  9. . 'migration70.incompatible.php'
  10. . 'try {' . PHP_EOL
  11. . "\t" . $match[0] . PHP_EOL
  12. . '} catch (\\ArithmeticError $e) {'
  13. . "\t" . 'error_log("File:"
  14. . $e->getFile()
  15. . " Message:" . $e->getMessage());'
  16. . '}' . PHP_EOL;
  17. },

{% hint style=”info” %} PHP 7 改变了错误的处理方式。在某些情况下,错误被移到了类似于异常的分类中,并且可以被捕获 ErrorException 类都实现了 Throwable 接口。如果你想捕获 ErrorException,请捕获 Throwable。 {% endhint %}

5.接下来,转换器重写了在PHP 7中被删除的 call_user_method*() 的所有用法。这些都被等同的call_user_func*() 所取代。

  1. // 将“call_user_method()”替换为
  2. // “call_user_func()”
  3. '!call_user_method\((.*?),(.*?)(,.*?)\)(\b|;)!' =>
  4. function ($match) {
  5. $params = $match[3] ?? '';
  6. return '// WARNING: call_user_method() has '
  7. . 'been removed from PHP 7' . PHP_EOL
  8. . 'call_user_func(['. trim($match[2]) . ','
  9. . trim($match[1]) . ']' . $params . ');';
  10. },
  11. // 将“call_user_method_array()”
  12. // 替换为 “call_user_func_array()”
  13. '!call_user_method_array\((.*?),(.*?),(.*?)\)(\b|;)!' =>
  14. function ($match) {
  15. return '// WARNING: call_user_method_array()'
  16. . 'has been removed from PHP 7'
  17. . PHP_EOL
  18. . 'call_user_func_array(['
  19. . trim($match[2]) . ','
  20. . trim($match[1]) . '], '
  21. . $match[3] . ');';
  22. },

6.最后,任何尝试使用 /e 修饰符的 preg_replace() 都会使用 preg_replace_callback() 重写:

  1. '!^(.*?)preg_replace.*?/e(.*?)$!' =>
  2. function ($match) {
  3. $last = strrchr($match[2], ',');
  4. $arg2 = substr($match[2], 2, -1 * (strlen($last)));
  5. $arg1 = substr($match[0],
  6. strlen($match[1]) + 12,
  7. -1 * (strlen($arg2) + strlen($last)));
  8. $arg1 = trim($arg1, '(');
  9. $arg1 = str_replace('/e', '/', $arg1);
  10. $arg3 = '// WARNING: preg_replace() "/e" modifier
  11. . 'has been removed from PHP 7'
  12. . PHP_EOL
  13. . $match[1]
  14. . 'preg_replace_callback('
  15. . $arg1
  16. . 'function ($m) { return '
  17. . str_replace('$1','$m', $match[1])
  18. . trim($arg2, '"\'') . '; }, '
  19. . trim($last, ',');
  20. return str_replace('$1', '$m', $arg3);
  21. },
  22. // 数组结
  23. ],
  24. // 这就是转变的目标
  25. $contents
  26. );
  27. // 以字符串形式返回结果
  28. return implode('', $result);
  29. }

如何运行…

若要使用转换器,请从命令行运行以下代码。您需要提供 PHP 5代码的文件名作为参数进行扫描。

这段代码,chap_01_php5_to_php7_code_converter.php,从命令行运行,调用转换器:

  1. <?php
  2. // 从命令行获取要扫描的文件名
  3. $filename = $argv[1] ?? '';
  4. if (!$filename) {
  5. echo 'No filename provided' . PHP_EOL;
  6. echo 'Usage: ' . PHP_EOL;
  7. echo __FILE__ . ' <filename>' . PHP_EOL;
  8. exit;
  9. }
  10. // 设置类自动加载
  11. require __DIR__ . '/../Application/Autoload/Loader.php';
  12. // 在路径中添加工作目录
  13. Application\Autoload\Loader::init(__DIR__ . '/..');
  14. // 获取深度扫描类
  15. $convert = new Application\Parse\Convert();
  16. echo $convert->scan($filename);
  17. echo PHP_EOL;

参考

有关向后不兼容的更改的更多信息,请参考 http://php.net/manual/en/migration70.incompatible.php