dump.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. <?php
  2. define('APP_PATH', __DIR__);
  3. include "vendor/autoload.php";
  4. // 调试输出
  5. function vd($msg)
  6. {
  7. print_r($msg);
  8. echo PHP_EOL;
  9. }
  10. function vde($msg)
  11. {
  12. vd($msg);
  13. exit;
  14. }
  15. // 解析参数
  16. function explainArgv($argv)
  17. {
  18. $args = [];
  19. foreach ($argv as $value) {
  20. list($k, $v) = explode('=', $value);
  21. $k = ltrim(ltrim(trim($k), '--'), '-');
  22. $v = trim($v);
  23. $args[$k] = $v;
  24. }
  25. return $args;
  26. }
  27. function usage()
  28. {
  29. echo '使用示例:' . PHP_EOL;
  30. echo 'php ./dump.php -app=test' . PHP_EOL;
  31. // echo 'php ./dump.php -app=test -split=true' . PHP_EOL;
  32. }
  33. class Dump
  34. {
  35. // 文件夹路径符
  36. private static $DS = '/';
  37. /**
  38. * @var string
  39. */
  40. private $appName;
  41. /**
  42. * 是否需要分子目录
  43. *
  44. * @var boolean
  45. */
  46. private $split = false;
  47. /**
  48. * 源文件目录
  49. */
  50. private $sourceDir;
  51. /**
  52. * 脚本目录
  53. */
  54. private $scriptDir;
  55. /**
  56. * 导出文件目录
  57. */
  58. private $outputDir;
  59. /**
  60. * 生成json目录
  61. */
  62. private $jsonDir;
  63. /**
  64. * 生成model目录
  65. */
  66. private $modelDir;
  67. /**
  68. * 默认配置地址
  69. */
  70. private $defaultConfigFile;
  71. /**
  72. * 导出文件数
  73. */
  74. private $success = 0;
  75. /**
  76. * Dump constructor.
  77. *
  78. * @param array $args
  79. */
  80. public function __construct($args)
  81. {
  82. if (!isset($args['app'])) {
  83. vd('参数错误');
  84. usage();
  85. exit;
  86. }
  87. // 初始化导出参数
  88. $this->appName = $args['app'];
  89. if (isset($args['split'])) {
  90. $this->split = $args['split'];
  91. }
  92. $this->sourceDir = __DIR__ . self::$DS . 'projects' . self::$DS . $this->appName . self::$DS . 'source';
  93. $this->scriptDir = __DIR__ . self::$DS . 'projects' . self::$DS . $this->appName . self::$DS . 'script';
  94. $this->outputDir = __DIR__ . self::$DS . 'projects' . self::$DS . $this->appName . self::$DS . 'output';
  95. $this->jsonDir = __DIR__ . self::$DS . 'projects' . self::$DS . $this->appName . self::$DS . 'json';
  96. $this->modelDir = __DIR__ . self::$DS . 'projects' . self::$DS . $this->appName . self::$DS . 'model';
  97. // 检查目录文件是否缺失
  98. if (!is_dir($this->sourceDir)) {
  99. vde('源文件目录缺失:' . $this->sourceDir);
  100. }
  101. if (!is_dir($this->scriptDir)) {
  102. vde('脚本目录缺失:' . $this->scriptDir);
  103. }
  104. if (!is_dir($this->outputDir)) {
  105. vde('输出配置目录缺失:' . $this->outputDir);
  106. }
  107. if (!is_dir($this->jsonDir)) {
  108. vde('输出json目录缺失:' . $this->jsonDir);
  109. }
  110. if (!is_dir($this->modelDir)) {
  111. vde('输出model目录缺失:' . $this->modelDir);
  112. }
  113. // 初始化默认配置文件
  114. $this->defaultConfigFile = __DIR__ . self::$DS . 'default-script.php';
  115. }
  116. /**
  117. * 执行主函数
  118. */
  119. public function run()
  120. {
  121. // 遍历源目录, 找出所有可执行的文件
  122. $files = [];
  123. $sourceDir = dir($this->sourceDir);
  124. while ($file = $sourceDir->read()) {
  125. if ($file == '.' || $file == '..') {
  126. continue;
  127. }
  128. $pathInfo = pathinfo($file);
  129. // 现在仅支持xlsx文件
  130. if ($pathInfo['extension'] != 'xlsx') {
  131. continue;
  132. }
  133. $files[] = $pathInfo;
  134. }
  135. $sourceDir->close();
  136. if (empty($files)) {
  137. vde('源目录为空, 未找到.xlsx文件, 源目录:' . $this->sourceDir);
  138. }
  139. // 执行导出
  140. foreach ($files as $fileInfo) {
  141. $this->dump($fileInfo);
  142. }
  143. vd(sprintf("导出完成,共[%d]个文件, 成功[%d]个文件.", count($files), $this->success));
  144. }
  145. /**
  146. * 导出表
  147. *
  148. * @param array $fileInfo
  149. * @return bool
  150. */
  151. private function dump($fileInfo)
  152. {
  153. // 源文件
  154. $file = $this->sourceDir . self::$DS . $fileInfo['basename'];
  155. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
  156. $reader->setReadDataOnly(true);
  157. $spreadsheet = $reader->load($file);
  158. // 读取所有sheet
  159. $sheetList = $spreadsheet->getSheetNames();
  160. foreach ($sheetList as $index => $sheetName) {
  161. $sourceData = $spreadsheet->getSheet($index)->toArray();
  162. $this->dumpSheet($fileInfo['basename'], $sheetName, $sourceData);
  163. }
  164. }
  165. /**
  166. * 导出sheet中的数据
  167. * @param string $fileName 文件名
  168. * @param string $sheetName sheet名
  169. * @param array $sourceData
  170. * @return boolean
  171. */
  172. private function dumpSheet($fileName, $sheetName, $sourceData)
  173. {
  174. // 找到文件对应的执行脚本
  175. // 如果找不到, 则使用默认的配置
  176. $script = $this->scriptDir . self::$DS . $sheetName . '.php';
  177. if (!file_exists($script)) {
  178. vd(sprintf('[%s][%s]对应的脚本文件不存在, 脚本文件:%s', $fileName, $sheetName, $script));
  179. // return false;
  180. $script = $this->defaultConfigFile;
  181. vd(sprintf('[%s][%s]使用默认配置, 脚本文件:%s', $fileName, $sheetName, $script));
  182. }
  183. // 引入脚本
  184. include $script;
  185. // 处理excel文件内容
  186. if (count($sourceData) < $dataLine) {
  187. vd(sprintf('[%s][%s]文件没有数据', $fileName, $sheetName));
  188. return false;
  189. }
  190. // 如果未设置字段名列, 那么自动生成, 到处所有列
  191. if (empty($columns)) {
  192. foreach ($sourceData[$columnLine - 1] as $key => $columnName) {
  193. $columnName = trim($columnName);
  194. if (strlen($columnName) == 0) {
  195. continue;
  196. }
  197. $columnType = trim($sourceData[$typeLine - 1][$key]);
  198. $columns[$columnName] = $columnType;
  199. }
  200. }
  201. // 处理导出列对应的索引
  202. $indexes = [];
  203. // vd($sourceData[$columnLine - 1]);
  204. foreach ($sourceData[$columnLine - 1] as $index => $columnName) {
  205. $columnName = trim($columnName);
  206. if (isset($columns[$columnName])) {
  207. $indexes[$columnName] = $index;
  208. }
  209. }
  210. // 主键列
  211. if (!$keyColumn) {
  212. $keyColumn = current($sourceData[$columnLine - 1]);
  213. }
  214. // 普通处理逻辑
  215. $data = [];
  216. foreach ($sourceData as $k => $v) {
  217. // 非数据列不处理
  218. if ($k < $dataLine - 1) {
  219. continue;
  220. }
  221. $row = [];
  222. foreach ($columns as $columnName => $columnType) {
  223. $columnValue = trim($v[$indexes[$columnName]]);
  224. switch ($columnType) {
  225. case 'float':
  226. $columnValue = floatval($columnValue);
  227. break;
  228. case 'number':
  229. $columnValue = intval($columnValue);
  230. break;
  231. case 'json':
  232. $columnValue = json_decode($columnValue, true);
  233. break;
  234. default:
  235. $columnValue = strval($columnValue);
  236. break;
  237. }
  238. $row[$columnName] = $columnValue;
  239. }
  240. // 跳过空行
  241. if (!$row[$keyColumn]) {
  242. continue;
  243. }
  244. $data[$row[$keyColumn]] = $row;
  245. }
  246. // 额外处理逻辑
  247. $handle = $sheetName . '_handle';
  248. if (function_exists($handle)) {
  249. $data = $handle($data);
  250. }
  251. // 写入PHP文件
  252. $this->writePHP($sheetName, $data);
  253. // 生成json文件
  254. $this->writeJSON($sheetName, $data);
  255. // 生成model文件
  256. $this->writeModel($sheetName, $clientColumns);
  257. $this->success++;
  258. }
  259. /**
  260. * @param string $file 源文件地址
  261. * @return array
  262. */
  263. private function getDataFromSource($file)
  264. {
  265. $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
  266. // $reader->setReadDataOnly(['Sheet 1']);
  267. $reader->setReadDataOnly(true);
  268. $spreadsheet = $reader->load($file);
  269. // $data = $spreadsheet->getActiveSheet()->toArray();
  270. $data = $spreadsheet->getSheet(5)->toArray();
  271. vde($data);
  272. return $data;
  273. }
  274. /**
  275. * 写入php文件
  276. *
  277. * @param string $filename 写入文件路径
  278. * @param array $data 写入文件内容
  279. * @return void
  280. */
  281. private function writePHP($filename, $data)
  282. {
  283. $file = $this->outputDir . self::$DS . $filename . '.config.php';
  284. // 写入配置文件
  285. $configs = var_export($data, true);
  286. // 整理输出格式
  287. $config = <<<TXT
  288. <?php
  289. return {$configs};
  290. TXT;
  291. // 写入导出文件
  292. file_put_contents($file, $config);
  293. }
  294. /**
  295. * 生成json文件
  296. *
  297. * @param string $filename 写入文件名称
  298. * @param array $data 待写入的文件内容
  299. */
  300. private function writeJSON($filename, $data)
  301. {
  302. $file = $this->jsonDir . self::$DS . $filename . '.json';
  303. // 写入导出文件
  304. file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE));
  305. }
  306. /**
  307. * 写入php model 文件
  308. *
  309. * @param string $filename 写入文件路径
  310. * @param array $clientColumns 输出给客户端的字段列表
  311. * @return void
  312. */
  313. private function writeModel($filename, $clientColumns)
  314. {
  315. $columnString = "[]";
  316. if (count($clientColumns) > 0) {
  317. $columnString = '["' . join('", "', $clientColumns) . '"]';
  318. }
  319. $className = str_replace(" ", "", ucwords(str_replace("_", " ", $filename)));
  320. $file = $this->modelDir . self::$DS . $className . '.php';
  321. // 整理输出格式
  322. $config = <<<TXT
  323. <?php
  324. class {$className}
  325. {
  326. /**
  327. * Returns table name mapped in the model.
  328. *
  329. * @return string
  330. */
  331. public static function getSource()
  332. {
  333. return '{$filename}';
  334. }
  335. /**
  336. * 获取导出给客户端所需要的字段
  337. *
  338. * @return array
  339. */
  340. public static function getToClientColumns()
  341. {
  342. return {$columnString};
  343. }
  344. /**
  345. * 生成客户端需要的字段, 生成列表
  346. *
  347. * @return array
  348. */
  349. public static function getListForClient()
  350. {
  351. \$data = [];
  352. if (empty(self::getToClientColumns())) {
  353. \$data = array_values(self::getList());
  354. } else {
  355. foreach (self::getList() as \$key => \$value) {
  356. foreach (\$value as \$k => \$v) {
  357. if (!in_array(\$k, self::getToClientColumns())) {
  358. unset(\$value[\$k]);
  359. }
  360. }
  361. \$data[] = \$value;
  362. }
  363. }
  364. return \$data;
  365. }
  366. /**
  367. * 获取单条配置内容
  368. *
  369. * @return array
  370. */
  371. public static function get(\$configId)
  372. {
  373. return IConfig::get()->loadAppConfig(self::getSource(), \$configId);
  374. }
  375. /**
  376. * 获取所有配置
  377. *
  378. * @return array
  379. */
  380. public static function getList()
  381. {
  382. return IConfig::get()->loadAppConfig(self::getSource());
  383. }
  384. }
  385. TXT;
  386. // 写入导出文件
  387. file_put_contents($file, $config);
  388. }
  389. }
  390. /*
  391. * 使用说明
  392. * php ./dump.php -app=shot -split=false
  393. */
  394. // 读取 & 解析命令行参数
  395. array_shift($argv);
  396. $args = explainArgv($argv);
  397. // 执行导出
  398. $dump = new Dump($args);
  399. $dump->run();