dump.php 12 KB

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