Manager.php 12 KB

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