CopyrightController.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. namespace app\commands;
  8. use yii\console\Controller;
  9. use yii\console\ExitCode;
  10. /**
  11. * copyright command
  12. * @package app\commands
  13. * @author Syan mzsongyan@gmail.com
  14. * @date 2022-05-30
  15. */
  16. class CopyrightController extends Controller
  17. {
  18. /**
  19. * 批量更新或添加文件版权信息
  20. * @return int
  21. * @author Syan mzsongyan@gmail.com
  22. * @date 2022-05-30
  23. */
  24. public function actionUpdate()
  25. {
  26. $allFile = $this->allFiles(\Yii::$app->basepath, '*.php', [\Yii::$app->basepath . '/vendor']);
  27. foreach ($allFile as $file) {
  28. $this->addCopyright($file);
  29. }
  30. return ExitCode::OK;
  31. }
  32. /**
  33. *
  34. * @param mixed $file
  35. * @return bool
  36. * @author Syan mzsongyan@gmail.com
  37. * @date 2022-05-30
  38. */
  39. private function addCopyright($file)
  40. {
  41. $content = file_get_contents($file);
  42. if ($content === false) {
  43. return false;
  44. }
  45. $copyright = <<<COPYRIGHT
  46. /**
  47. * 重庆赤晓店信息科技有限公司
  48. * https://www.chixiaodian.com
  49. * Copyright (c) 2023 赤店商城 All rights reserved.
  50. */
  51. COPYRIGHT;
  52. $content = preg_replace_callback('/\<\?php(\s+)?(\/\*\*.*?\*\/)?/mis', function ($matches) use ($copyright) {
  53. $result = '<?php' . PHP_EOL . $copyright;
  54. if (!isset($matches[2])) {
  55. $result .= PHP_EOL;
  56. }
  57. return $result;
  58. }, $content);
  59. file_put_contents($file, $content, LOCK_EX);
  60. return true;
  61. }
  62. /**
  63. * 根据给出的路径获取所有相关文件
  64. * @param string $dir
  65. * @param string $pattern
  66. * @param array $exclude 排除路径
  67. * @return array
  68. * @author Syan mzsongyan@gmail.com
  69. * @date 2022-05-30
  70. */
  71. private function allFiles(string $dir, string $pattern = '*', array $exclude = [])
  72. {
  73. $result = [];
  74. $items = glob($dir . '/' . $pattern, GLOB_BRACE);
  75. foreach ($items as $item) {
  76. if (is_file($item)) {
  77. $result[] = $item;
  78. }
  79. }
  80. $items = glob($dir . '/*', GLOB_ONLYDIR);
  81. foreach ($items as $item) {
  82. if (is_dir($item)) {
  83. if (in_array($item, $exclude)) {
  84. continue;
  85. }
  86. $result = array_merge($result, $this->allFiles($item, $pattern));
  87. }
  88. }
  89. return $result;
  90. }
  91. }