Plugin.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. declare(strict_types=1);
  3. namespace SixShop\Core;
  4. use Composer\Composer;
  5. use Composer\EventDispatcher\EventSubscriberInterface;
  6. use Composer\InstalledVersions;
  7. use Composer\IO\IOInterface;
  8. use Composer\Plugin\PluginInterface;
  9. use Composer\Script\Event;
  10. use Composer\Script\ScriptEvents;
  11. use RuntimeException;
  12. class Plugin implements PluginInterface, EventSubscriberInterface
  13. {
  14. public const string EXTENSION_TYPE = 'sixshop-extension';
  15. public static array $installedSixShopExtensions = [];
  16. public static function getSubscribedEvents(): array
  17. {
  18. return [
  19. ScriptEvents::POST_AUTOLOAD_DUMP => 'onPostAutoloadDump',
  20. ];
  21. }
  22. /**
  23. * @return array{root: array{reference: string}, versions: array<string, array>}
  24. */
  25. public static function getInstalledSixShopExtensions(): array
  26. {
  27. if (self::$installedSixShopExtensions) {
  28. return self::$installedSixShopExtensions;
  29. }
  30. $composerDir = dirname(InstalledVersions::getInstallPath('composer/composer'),2);
  31. $filePath = $composerDir . '/installedSixShop.php';
  32. if (file_exists($filePath)) {
  33. return self::$installedSixShopExtensions = require $filePath;
  34. }
  35. throw new RuntimeException('Please run "composer dump-autoload" to generate installedSixShop.php');
  36. }
  37. public function activate(Composer $composer, IOInterface $io): void
  38. {
  39. $installer = new ExtensionInstaller($io, $composer, self::EXTENSION_TYPE);
  40. $composer->getInstallationManager()->addInstaller($installer);
  41. }
  42. public function deactivate(Composer $composer, IOInterface $io): void
  43. {
  44. }
  45. public function uninstall(Composer $composer, IOInterface $io): void
  46. {
  47. }
  48. public function onPostAutoloadDump(Event $event): void
  49. {
  50. $installedSixShopExtensions = [
  51. 'root' => [],
  52. 'versions' => []
  53. ];
  54. $referenceMap = [];
  55. foreach (InstalledVersions::getAllRawData() as $installed) {
  56. foreach ($installed['versions'] as $name => $package) {
  57. if (isset($package['type']) && $package['type'] === self::EXTENSION_TYPE) {
  58. $installedSixShopExtensions['versions'][$name] = $package;
  59. $referenceMap[$name] = $package['reference'];
  60. }
  61. }
  62. }
  63. $installedSixShopExtensions['root']['reference'] = hash('md5', json_encode($referenceMap));
  64. $filePath = $event->getComposer()->getConfig()->get('vendor-dir') . '/composer/installedSixShop.php';
  65. file_put_contents($filePath, '<?php return ' . var_export($installedSixShopExtensions, true) . ';');
  66. }
  67. }