ExtensionManager.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. <?php
  2. declare(strict_types=1);
  3. namespace SixShop\System;
  4. use Composer\InstalledVersions;
  5. use RuntimeException;
  6. use SixShop\Core\Contracts\ExtensionInterface;
  7. use SixShop\Core\Service\CoreService;
  8. use SixShop\Payment\Contracts\PaymentExtensionInterface;
  9. use SixShop\System\Config\ExtensionConfig;
  10. use SixShop\System\Enum\ExtensionStatusEnum;
  11. use SixShop\System\Model\ExtensionConfigModel;
  12. use SixShop\System\Model\ExtensionModel;
  13. use think\Collection;
  14. use think\db\Query;
  15. use think\exception\ValidateException;
  16. use think\facade\Cache;
  17. use think\facade\Db;
  18. use think\facade\Event;
  19. use think\facade\Log;
  20. use think\facade\Validate;
  21. use think\Service;
  22. use function SixShop\Core\extension_name_list;
  23. class ExtensionManager extends Service
  24. {
  25. /**
  26. * @var array 扩展列表
  27. */
  28. private array $extensionList = [];
  29. /**
  30. * @var array 分类列表
  31. */
  32. private array $categoryMap = [];
  33. /**
  34. * 安装扩展
  35. */
  36. public function install(string $extensionID): void
  37. {
  38. $extensionModel = ExtensionModel::where(['id' => $extensionID])->findOrFail();
  39. if ($extensionModel->status === ExtensionStatusEnum::INSTALLED) {
  40. throw new RuntimeException("{$extensionID}扩展已安装");
  41. }
  42. $this->app->make(Migrate::class, [$this->app, $extensionID])->install();
  43. $extension = $this->getExtension($extensionID);
  44. $extension->install();
  45. $config = $this->getExtensionConfig($extensionID);
  46. if (empty($config)) {
  47. $updateData = [];
  48. $formConfig = $extension->getConfig();
  49. foreach ($formConfig as $item) {
  50. if (isset($item['value'])) {
  51. $updateData[$item['field']] = $item['value'];
  52. }
  53. }
  54. if (!empty($updateData)) {
  55. $this->saveConfig($extensionID, $updateData);
  56. }
  57. }
  58. $extensionModel->status = ExtensionStatusEnum::INSTALLED;
  59. $extensionModel->save();
  60. }
  61. public function getExtension(string $extensionID): ExtensionInterface|PaymentExtensionInterface
  62. {
  63. return $this->app->get('extension.' . $extensionID);
  64. }
  65. public function getExtensionConfig(string $extensionID, string $key = '', bool $onlyValue = true): mixed
  66. {
  67. $extensionConfig = ExtensionConfigModel::where('extension_id', $extensionID)->when($key, function (Query $query) use ($key) {
  68. $query->where('key', $key);
  69. })->column(['value', 'type',], 'key', true);
  70. if (count($extensionConfig) === 0) {
  71. return $key ? null : [];
  72. }
  73. if ($onlyValue) {
  74. $extensionConfig = array_map(fn($item) => $item['value'], $extensionConfig);
  75. }
  76. return $key != '' ? $extensionConfig[$key] : $extensionConfig;
  77. }
  78. public function saveConfig(string $extensionID, array $data): bool
  79. {
  80. $config = $this->getLocalConfig($extensionID)->toArray();
  81. $updateData = [];
  82. foreach ($config as $item) {
  83. if (isset($item['field'])) {
  84. if (isset($data[$item['field']])) {
  85. $updateData[] = [
  86. 'extension_id' => $extensionID,
  87. 'key' => $item['field'],
  88. 'value' => $data[$item['field']],
  89. 'type' => $item['type'],
  90. 'title' => $item['title']
  91. ];
  92. }
  93. } else {
  94. if (isset($item['children'])) {
  95. foreach ($item['children'] as $childItem) {
  96. if (isset($childItem['field'], $data[$childItem['field']])) {
  97. $updateData[] = [
  98. 'extension_id' => $extensionID,
  99. 'key' => $childItem['field'],
  100. 'value' => $data[$childItem['field']],
  101. 'type' => $childItem['type'],
  102. 'title' => $childItem['title']
  103. ];
  104. }
  105. if (isset($childItem['children'])) {
  106. foreach ($childItem['children'] as $grandChildItem) {
  107. if (isset($grandChildItem['field'], $data[$grandChildItem['field']])) {
  108. $updateData[] = [
  109. 'extension_id' => $extensionID,
  110. 'key' => $grandChildItem['field'],
  111. 'value' => $data[$grandChildItem['field']],
  112. 'type' => $grandChildItem['type'],
  113. 'title' => $grandChildItem['title'],
  114. ];
  115. }
  116. }
  117. }
  118. }
  119. }
  120. }
  121. }
  122. if (!empty($updateData)) {
  123. Db::transaction(function () use ($updateData) {
  124. foreach ($updateData as $item) {
  125. $configModel = ExtensionConfigModel::where([
  126. 'extension_id' => $item['extension_id'],
  127. 'key' => $item['key']
  128. ])->findOrEmpty();
  129. $configModel->save($item);
  130. Event::trigger('after_write_extension_config:' . $item['extension_id'] . ':' . $item['key'], $item);
  131. }
  132. Event::trigger('after_write_extension_config:' . $item['extension_id'], array_column($updateData, null, 'key'));
  133. });
  134. }
  135. return true;
  136. }
  137. /**
  138. * 卸载扩展
  139. */
  140. public function uninstall(string $extensionID): void
  141. {
  142. $extensionModel = ExtensionModel::where(['id' => $extensionID])->findOrFail();
  143. if ($extensionModel->status === ExtensionStatusEnum::UNINSTALLED) {
  144. throw new RuntimeException("{$extensionID}扩展未安装");
  145. }
  146. $this->app->make(Migrate::class, [$this->app, $extensionID])->uninstall();
  147. $this->getExtension($extensionID)->uninstall();
  148. $extensionModel->status = ExtensionStatusEnum::UNINSTALLED;
  149. $extensionModel->save();
  150. }
  151. /**
  152. * 启用扩展
  153. */
  154. public function enable(string $extensionID): void
  155. {
  156. $extensionModel = ExtensionModel::where(['id' => $extensionID])->findOrFail();
  157. match ($extensionModel->status) {
  158. ExtensionStatusEnum::UNINSTALLED => throw new RuntimeException("{$extensionID}扩展未安装"),
  159. ExtensionStatusEnum::ENABLED => throw new RuntimeException("{$extensionID}扩展已启用"),
  160. default => null,
  161. };
  162. $extensionModel->status = ExtensionStatusEnum::ENABLED;
  163. $extensionModel->save();
  164. }
  165. /**
  166. * 禁用扩展
  167. */
  168. public function disable(string $extensionID): void
  169. {
  170. $extensionModel = ExtensionModel::where(['id' => $extensionID])->findOrEmpty();
  171. if ($extensionModel->isEmpty()) {
  172. Cache::delete(sprintf(ExtensionModel::EXTENSION_INFO_CACHE_KEY, $extensionID));
  173. throw new RuntimeException("{$extensionID}扩展不存在");
  174. }
  175. if ($extensionModel->status != ExtensionStatusEnum::ENABLED) {
  176. throw new RuntimeException("{$extensionID}扩展未启用");
  177. }
  178. $extensionModel->status = ExtensionStatusEnum::DISABLED;
  179. $extensionModel->save();
  180. }
  181. /**
  182. * 获取扩展信息
  183. */
  184. public function getInfo(string $name): ExtensionModel
  185. {
  186. return $this->extensionList[$name] ?? ($this->extensionList[$name] = $this->app->cache->remember(
  187. sprintf(ExtensionModel::EXTENSION_INFO_CACHE_KEY, $name),
  188. function () use ($name) {
  189. return $this->initExtensionInfo($name);
  190. }));
  191. }
  192. private function initExtensionInfo(string $name): ExtensionModel
  193. {
  194. $categoryMap = $this->getCategoryMap();
  195. $extensionInfo = $this->getExtension($name)->getInfo();
  196. try {
  197. Validate::rule([
  198. 'id' => 'require|max:50',
  199. 'name' => 'require|max:100',
  200. 'is_core' => 'in:0,1',
  201. 'category' => 'in:' . implode(',', array_keys($categoryMap)),
  202. 'description' => 'max:65535',
  203. 'version' => 'max:20',
  204. 'core_version' => 'max:20',
  205. 'author' => 'max:100',
  206. 'email' => 'email|max:100',
  207. 'website' => 'url|max:255',
  208. 'image' => 'url|max:255',
  209. 'license' => 'max:50',
  210. ])->failException()->check($extensionInfo);
  211. } catch (ValidateException $exception) {
  212. Log::warning('module(' . $name . ') info error:' . $exception->getError());
  213. }
  214. if (!isset($extensionInfo['id']) || $extensionInfo['id'] !== $name) {
  215. throw new RuntimeException("{$name}扩展id({$extensionInfo['id']})与目录名不一致");
  216. }
  217. if (!isset($extensionInfo['version'])) {
  218. $extensionInfo['version'] = '1.0.0';
  219. }
  220. if (!isset($extensionInfo['core_version'])) {
  221. $extensionInfo['core_version'] = '^1.0';
  222. }
  223. if (!isset($extensionInfo['author'])) {
  224. $extensionInfo['author'] = '未知';
  225. }
  226. $extension = ExtensionModel::where(['id' => $name])->append(['status_text'])->findOrEmpty();
  227. if ($extension->isEmpty()) {
  228. $extensionInfo['status'] = 1; // 下载的扩展默认未安装
  229. if (isset($extensionInfo['is_core']) && $extensionInfo['is_core'] == 1) {
  230. $extensionInfo['status'] = 3; // 核心扩展默认启用
  231. }
  232. $extension->save($extensionInfo);
  233. }
  234. $extension['category_text'] = $categoryMap[$extension['category']] ?? '未知';
  235. return $this->extensionList[$name] = $extension;
  236. }
  237. /**
  238. * @return array
  239. */
  240. public function getCategoryMap(): array
  241. {
  242. if (empty($this->categoryMap)) {
  243. $this->categoryMap = array_to_map($this->getExtensionConfig('system', 'category'), 'code', 'text');
  244. }
  245. return $this->categoryMap;
  246. }
  247. public function getExtensionList(): array
  248. {
  249. foreach (extension_name_list() as $name) {
  250. $this->extensionList[$name] = $this->app->cache->remember(sprintf(ExtensionModel::EXTENSION_INFO_CACHE_KEY, $name), function () use ($name) {
  251. return $this->initExtensionInfo($name);
  252. });
  253. }
  254. return $this->extensionList;
  255. }
  256. public function getExtensionConfigForm(string $extensionID): Collection
  257. {
  258. $config = $this->getLocalConfig($extensionID)->toArray();
  259. $extensionConfig = ExtensionConfigModel::where('extension_id', $extensionID)->column(['value', 'type',], 'key', true);
  260. foreach ($config as $key => &$item) {
  261. if (isset($item['field'])) {
  262. if (isset($extensionConfig[$item['field']])) {
  263. $config[$key]['value'] = $extensionConfig[$item['field']]['value'];
  264. }
  265. } else {
  266. if (isset($item['children'])) {
  267. foreach ($item['children'] as $childKey => $childItem) {
  268. if (isset($childItem['field'], $extensionConfig[$childItem['field']])) {
  269. $config[$key]['children'][$childKey]['value'] = $extensionConfig[$childItem['field']]['value'];
  270. }
  271. if (isset($childItem['children'])) {
  272. foreach ($childItem['children'] as $grandChildKey => $grandChildItem) {
  273. if (isset($grandChildItem['field'], $extensionConfig[$grandChildItem['field']])) {
  274. $config[$key]['children'][$childKey]['children'][$grandChildKey]['value'] = $extensionConfig[$grandChildItem['field']]['value'];
  275. }
  276. }
  277. }
  278. }
  279. }
  280. }
  281. }
  282. return new Collection($config);
  283. }
  284. public function migrations(string $id)
  285. {
  286. return app(Migrate::class, [$this->app, $id])->getMigrationList();
  287. }
  288. public function refresh(string $id): void
  289. {
  290. // 获取当前版本更新版本信息
  291. $currentVersion = '0.0.0';
  292. if (isset(CoreService::$extensionComposerMap[$id])) {
  293. $packageName = CoreService::$extensionComposerMap[$id]['name'];
  294. $currentVersion = InstalledVersions::getPrettyVersion($packageName);
  295. }
  296. ExtensionModel::where([
  297. ['id', '=', $id],
  298. ['version', '<>', $currentVersion],
  299. ])->update(['version' => $currentVersion]);
  300. }
  301. private function getLocalConfig(string $extensionID): Collection
  302. {
  303. $config = array_merge(ExtensionConfig::BASE, $this->getExtension($extensionID)->getConfig());
  304. $configCollection = new Collection($config);
  305. Event::trigger('after_read_extension_config', [$configCollection, $extensionID]);
  306. Event::trigger('after_read_extension_config_' . $extensionID, $configCollection);
  307. return $configCollection;
  308. }
  309. }