Manager.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. <?php
  2. namespace Dcat\Admin\Extend;
  3. use Dcat\Admin\Admin;
  4. use Dcat\Admin\Exception\AdminException;
  5. use Dcat\Admin\Exception\RuntimeException;
  6. use Dcat\Admin\Models\Extension;
  7. use Dcat\Admin\Models\Extension as ExtensionModel;
  8. use Dcat\Admin\Support\Composer;
  9. use Dcat\Admin\Support\Helper;
  10. use Dcat\Admin\Support\Zip;
  11. use Illuminate\Contracts\Container\Container;
  12. use Illuminate\Filesystem\Filesystem;
  13. use Illuminate\Support\Collection;
  14. use Illuminate\Support\Str;
  15. use RecursiveDirectoryIterator;
  16. use RecursiveIteratorIterator;
  17. class Manager
  18. {
  19. use Note;
  20. /**
  21. * @var Container
  22. */
  23. protected $app;
  24. /**
  25. * @var ServiceProvider[]|Collection
  26. */
  27. protected $extensions;
  28. /**
  29. * @var array
  30. */
  31. protected $extensionPaths = [];
  32. /**
  33. * @var ExtensionModel[]|Collection
  34. */
  35. protected $settings;
  36. /**
  37. * @var Filesystem
  38. */
  39. protected $files;
  40. public function __construct(Container $app)
  41. {
  42. $this->app = $app;
  43. $this->extensions = new Collection();
  44. $this->files = app('files');
  45. }
  46. /**
  47. * 注册扩展.
  48. *
  49. * @return void
  50. */
  51. public function register()
  52. {
  53. $this->load();
  54. $this->extensions->each->register();
  55. }
  56. /**
  57. * 初始化扩展.
  58. */
  59. public function boot()
  60. {
  61. $this->extensions->each->boot();
  62. }
  63. /**
  64. * 判断扩展是否启用.
  65. *
  66. * @param string|null $name
  67. *
  68. * @return bool
  69. */
  70. public function enabled(?string $name)
  71. {
  72. return (bool) optional($this->settings()->get($name))->is_enabled;
  73. }
  74. /**
  75. * 启用或禁用扩展.
  76. *
  77. * @param string|null $name
  78. * @param bool $enable
  79. *
  80. * @return void
  81. */
  82. public function enable(?string $name, bool $enable = true)
  83. {
  84. $name = $this->getName($name);
  85. $extension = Extension::where('name', $name)->first();
  86. if (! $extension) {
  87. throw new RuntimeException(sprintf('Please install the extension(%s) first!', $name));
  88. }
  89. $extension->is_enabled = $enable;
  90. $extension->save();
  91. }
  92. /**
  93. * 加载扩展,注册自动加载规则.
  94. *
  95. * @return $this
  96. */
  97. public function load()
  98. {
  99. foreach ($this->getExtensionDirectories() as $directory) {
  100. try {
  101. $this->loadExtension($directory);
  102. } catch (\Throwable $e) {
  103. $this->reportException($e);
  104. }
  105. }
  106. return $this;
  107. }
  108. /**
  109. * 获取扩展路径.
  110. *
  111. * @param string|ServiceProvider $name
  112. * @param string|null $path
  113. *
  114. * @return string|void
  115. *
  116. * @throws \ReflectionException
  117. */
  118. public function path($name, $path = null)
  119. {
  120. if (! $extension = $this->get($name)) {
  121. return;
  122. }
  123. return $extension->path($path);
  124. }
  125. /**
  126. * 获取扩展对象.
  127. *
  128. * @param string|ServiceProvider $name
  129. *
  130. * @return ServiceProvider|null
  131. */
  132. public function get($name)
  133. {
  134. if ($name instanceof ServiceProvider) {
  135. return $name;
  136. }
  137. return $this->extensions->get($this->formatName($name));
  138. }
  139. /**
  140. * 判断插件是否存在.
  141. *
  142. * @param string $name
  143. *
  144. * @return bool
  145. */
  146. public function has($name)
  147. {
  148. return $this->extensions->has($this->formatName($name));
  149. }
  150. /**
  151. * @param string $name
  152. *
  153. * @return mixed
  154. */
  155. protected function formatName($name)
  156. {
  157. if (! is_string($name)) {
  158. return $name;
  159. }
  160. return str_replace('/', '.', $name);
  161. }
  162. /**
  163. * 获取所有扩展.
  164. *
  165. * @return ServiceProvider[]|Collection
  166. */
  167. public function all()
  168. {
  169. return $this->extensions;
  170. }
  171. /**
  172. * 获取已启用的扩展.
  173. *
  174. * @return ServiceProvider[]|Collection
  175. */
  176. public function available()
  177. {
  178. return $this->all()->filter->enabled();
  179. }
  180. /**
  181. * 加载扩展.
  182. *
  183. * @param string $directory
  184. * @param bool $addPsr4
  185. *
  186. * @return ServiceProvider|null
  187. */
  188. public function loadExtension(string $directory, bool $addPsr4 = true)
  189. {
  190. if (array_key_exists($directory, $this->extensionPaths)) {
  191. return $this->extensionPaths[$directory];
  192. }
  193. $this->extensionPaths[$directory] = $serviceProvider = $this->resolveExtension($directory, $addPsr4);
  194. if ($serviceProvider) {
  195. $this->addExtension($serviceProvider);
  196. }
  197. return $serviceProvider;
  198. }
  199. /**
  200. * 获取扩展类实例.
  201. *
  202. * @param string $directory
  203. * @param bool $addPsr4
  204. *
  205. * @return ServiceProvider
  206. */
  207. public function resolveExtension(string $directory, bool $addPsr4 = true)
  208. {
  209. $composerProperty = Composer::parse($directory.'/composer.json');
  210. $serviceProvider = $composerProperty->get('extra.dcat-admin');
  211. $psr4 = $composerProperty->get('autoload.psr-4');
  212. if (! $serviceProvider || ! $psr4) {
  213. return;
  214. }
  215. if ($addPsr4) {
  216. $this->registerPsr4($directory, $psr4);
  217. }
  218. $serviceProvider = new $serviceProvider($this->app);
  219. return $serviceProvider->withComposerProperty($composerProperty);
  220. }
  221. /**
  222. * 获取扩展目录.
  223. *
  224. * @param string $dirPath
  225. *
  226. * @return array
  227. */
  228. public function getExtensionDirectories($dirPath = null)
  229. {
  230. $extensions = [];
  231. $dirPath = $dirPath ?: admin_extension_path();
  232. if (! is_dir($dirPath)) {
  233. return $extensions;
  234. }
  235. $it = new RecursiveIteratorIterator(
  236. new RecursiveDirectoryIterator($dirPath, RecursiveDirectoryIterator::FOLLOW_SYMLINKS)
  237. );
  238. $it->setMaxDepth(2);
  239. $it->rewind();
  240. while ($it->valid()) {
  241. if ($it->getDepth() > 1 && $it->getFilename() === 'composer.json') {
  242. $extensions[] = dirname($it->getPathname());
  243. }
  244. $it->next();
  245. }
  246. return $extensions;
  247. }
  248. /**
  249. * 添加扩展.
  250. *
  251. * @param \Dcat\Admin\Extend\ServiceProvider $serviceProvider
  252. */
  253. public function addExtension(ServiceProvider $serviceProvider)
  254. {
  255. if (! $serviceProvider->getName()) {
  256. $json = dirname(dirname(Helper::guessClassFileName($serviceProvider))).'/composer.json';
  257. if (! is_file($json)) {
  258. throw new RuntimeException(sprintf('Error extension "%s"', get_class($serviceProvider)));
  259. }
  260. $serviceProvider->withComposerProperty(Composer::parse($json));
  261. }
  262. $this->extensions->put($serviceProvider->getName(), $serviceProvider);
  263. $this->app->instance($abstract = get_class($serviceProvider), $serviceProvider);
  264. $this->app->alias($abstract, $serviceProvider->getName());
  265. }
  266. /**
  267. * 获取扩展名称.
  268. *
  269. * @param $extension
  270. *
  271. * @return string
  272. */
  273. public function getName($extension)
  274. {
  275. if ($extension instanceof ServiceProvider) {
  276. return $extension->getName();
  277. }
  278. return $this->formatName($extension);
  279. }
  280. /**
  281. * 解压缩扩展包.
  282. *
  283. * @param string $filePath
  284. * @param bool $force
  285. *
  286. * @return string
  287. */
  288. public function extract($filePath, bool $force = false)
  289. {
  290. $filePath = is_file($filePath) ? $filePath : $this->getFilePath($filePath);
  291. $name = $this->extractZip($filePath, $force);
  292. @unlink($filePath);
  293. return $name;
  294. }
  295. /**
  296. * @param string $filePath
  297. * @param bool $force
  298. *
  299. * @return bool
  300. */
  301. public function extractZip($filePath, bool $force = false)
  302. {
  303. // 创建临时目录.
  304. $tempPath = $this->makeTempDirectory();
  305. try {
  306. $filePath = is_file($filePath) ? $filePath : $this->getFilePath($filePath);
  307. if (! Zip::extract($filePath, $tempPath)) {
  308. throw new AdminException(sprintf('Unable to extract core file \'%s\'.', $filePath));
  309. }
  310. $extensions = $this->getExtensionDirectories($tempPath);
  311. // 无上层目录
  312. $directory = $tempPath;
  313. if (count($extensions) === 1) {
  314. // 双层目录
  315. $directory = current($extensions);
  316. } elseif (count($results = $this->scandir($tempPath)) === 1) {
  317. // 单层目录
  318. $directory = current($results);
  319. }
  320. // 验证扩展包内容是否正确.
  321. if (! $this->checkFiles($directory)) {
  322. throw new RuntimeException(sprintf('Error extension file "%s".', $filePath));
  323. }
  324. $composerProperty = Composer::parse($directory.'/composer.json');
  325. $extensionDir = admin_extension_path($composerProperty->name);
  326. if (! $force && is_dir($extensionDir)) {
  327. throw new RuntimeException(sprintf('The extension [%s] already exist!', $composerProperty->name));
  328. }
  329. if (! is_dir($extensionDir)) {
  330. $this->files->makeDirectory($extensionDir, 0755, true);
  331. }
  332. $this->files->copyDirectory($directory, $extensionDir);
  333. return $composerProperty->name;
  334. } finally {
  335. $this->files->deleteDirectory($tempPath);
  336. }
  337. }
  338. /**
  339. * 校验扩展包内容是否正确.
  340. *
  341. * @param $directory
  342. *
  343. * @return bool
  344. */
  345. protected function checkFiles($directory)
  346. {
  347. if (
  348. ! is_dir($directory.'/src')
  349. || ! is_file($directory.'/composer.json')
  350. || ! is_file($directory.'/version.php')
  351. ) {
  352. return false;
  353. }
  354. $composerProperty = Composer::parse($directory.'/composer.json');
  355. if (! $composerProperty->name || ! $composerProperty->get('extra.dcat-admin')) {
  356. return false;
  357. }
  358. return true;
  359. }
  360. /**
  361. * 生成临时文件.
  362. *
  363. * @param string $fileCode A unique file code
  364. * @return string Full path on the disk
  365. */
  366. protected function getFilePath($fileCode)
  367. {
  368. $name = md5($fileCode).'.arc';
  369. return $this->makeTempDirectory('extensions').'/'.$name;
  370. }
  371. /**
  372. * 获取配置.
  373. *
  374. * @return ExtensionModel[]|Collection
  375. */
  376. public function settings()
  377. {
  378. if ($this->settings === null) {
  379. try {
  380. $this->settings = ExtensionModel::all()->keyBy('name');
  381. } catch (\Throwable $e) {
  382. $this->reportException($e);
  383. $this->settings = new Collection();
  384. }
  385. }
  386. return $this->settings;
  387. }
  388. /**
  389. * @return UpdateManager
  390. */
  391. public function updateManager()
  392. {
  393. return app('admin.extend.update');
  394. }
  395. /**
  396. * @return VersionManager
  397. */
  398. public function versionManager()
  399. {
  400. return app('admin.extend.version');
  401. }
  402. /**
  403. * 创建临时目录.
  404. *
  405. * @param string $dir
  406. *
  407. * @return string
  408. */
  409. protected function makeTempDirectory($dir = null)
  410. {
  411. $tempDir = storage_path('tmp/'.($dir ?: time().Str::random()));
  412. if (! is_dir($tempDir)) {
  413. if (! $this->files->makeDirectory($tempDir, 0777, true)) {
  414. throw new RuntimeException(sprintf('Cannot write to directory "%s"', storage_path()));
  415. }
  416. }
  417. return $tempDir;
  418. }
  419. /**
  420. * 注册 PSR4 验证规则.
  421. *
  422. * @param string $directory
  423. * @param array $psr4
  424. */
  425. protected function registerPsr4($directory, array $psr4)
  426. {
  427. $classLoader = Admin::classLoader();
  428. foreach ($psr4 as $namespace => $path) {
  429. $path = $directory.'/'.trim($path, '/').'/';
  430. $classLoader->addPsr4($namespace, $path);
  431. }
  432. }
  433. /**
  434. * 上报异常.
  435. *
  436. * @param \Throwable $e
  437. */
  438. protected function reportException(\Throwable $e)
  439. {
  440. Admin::reportException($e);
  441. }
  442. /**
  443. * @param string $dir
  444. *
  445. * @return array
  446. */
  447. protected function scandir($dir)
  448. {
  449. $results = [];
  450. foreach (scandir($dir) as $value) {
  451. if (
  452. $value !== '.'
  453. && $value !== '..'
  454. && is_dir($value = $dir.'/'.$value)
  455. ) {
  456. $results[] = $value;
  457. }
  458. }
  459. return $results;
  460. }
  461. }