ExtensionManager.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * An extension manager to load extensions present in CORE_EXTENSIONS_PATH and THIRDPARTY_EXTENSIONS_PATH.
  5. *
  6. * @todo see coding style for methods!!
  7. * @phpstan-import-type ExtensionMetadata from Minz_Extension
  8. */
  9. final class Minz_ExtensionManager {
  10. private static string $ext_metaname = 'metadata.json';
  11. private static string $ext_entry_point = 'extension.php';
  12. /** @var array<string,Minz_Extension> */
  13. private static array $ext_list = [];
  14. /** @var array<string,Minz_Extension> */
  15. private static array $ext_list_enabled = [];
  16. /** @var array<string,bool> */
  17. private static array $ext_auto_enabled = [];
  18. /**
  19. * List of available hooks. Please keep this list sorted.
  20. * @var array<value-of<Minz_HookType>,array{'list':list<Minz_Hook>,'signature':Minz_HookSignature}>
  21. */
  22. private static array $hook_list = [];
  23. /** Remove extensions and hooks from a previous initialisation */
  24. private static function reset(): void {
  25. $hadAny = !empty(self::$ext_list_enabled);
  26. self::$ext_list = [];
  27. self::$ext_list_enabled = [];
  28. self::$ext_auto_enabled = [];
  29. foreach (Minz_HookType::cases() as $hook_type) {
  30. $hadAny |= !empty(self::$hook_list[$hook_type->value]['list']);
  31. self::$hook_list[$hook_type->value] = [
  32. 'list' => [],
  33. 'signature' => $hook_type->signature(),
  34. ];
  35. }
  36. if ($hadAny) {
  37. gc_collect_cycles();
  38. }
  39. }
  40. /**
  41. * Initialize the extension manager by loading extensions in EXTENSIONS_PATH.
  42. *
  43. * A valid extension is a directory containing metadata.json and
  44. * extension.php files.
  45. * metadata.json is a JSON structure where the only required fields are
  46. * `name` and `entry_point`.
  47. * extension.php should contain at least a class named <name>Extension where
  48. * <name> must match with the entry point in metadata.json. This class must
  49. * inherit from Minz_Extension class.
  50. * @throws Minz_ConfigurationNamespaceException
  51. */
  52. public static function init(): void {
  53. self::reset();
  54. $list_core_extensions = array_diff(scandir(CORE_EXTENSIONS_PATH) ?: [], [ '..', '.' ]);
  55. $list_thirdparty_extensions = array_diff(scandir(THIRDPARTY_EXTENSIONS_PATH) ?: [], [ '..', '.' ], $list_core_extensions);
  56. array_walk($list_core_extensions, function (&$s) { $s = CORE_EXTENSIONS_PATH . '/' . $s; });
  57. array_walk($list_thirdparty_extensions, function (&$s) { $s = THIRDPARTY_EXTENSIONS_PATH . '/' . $s; });
  58. $list_potential_extensions = array_merge($list_core_extensions, $list_thirdparty_extensions);
  59. $system_conf = Minz_Configuration::get('system');
  60. self::$ext_auto_enabled = array_filter(
  61. $system_conf->attributeArray('extensions_enabled') ?? [],
  62. fn($value, $key): bool => is_string($key) && is_bool($value),
  63. ARRAY_FILTER_USE_BOTH);
  64. foreach ($list_potential_extensions as $ext_pathname) {
  65. if (!is_dir($ext_pathname)) {
  66. continue;
  67. }
  68. $metadata_filename = $ext_pathname . '/' . self::$ext_metaname;
  69. // Try to load metadata file.
  70. if (!file_exists($metadata_filename)) {
  71. // No metadata file? Invalid!
  72. continue;
  73. }
  74. $meta_raw_content = file_get_contents($metadata_filename) ?: '';
  75. /** @var ExtensionMetadata|null $meta_json */
  76. $meta_json = json_decode($meta_raw_content, true);
  77. if (!is_array($meta_json) || !self::isValidMetadata($meta_json)) {
  78. // metadata.json is not a json file? Invalid!
  79. // or metadata.json is invalid (no required information), invalid!
  80. Minz_Log::warning('`' . $metadata_filename . '` is not a valid metadata file');
  81. continue;
  82. }
  83. $meta_json['path'] = $ext_pathname;
  84. // Try to load extension itself
  85. $extension = self::load($meta_json);
  86. if ($extension != null) {
  87. self::register($extension);
  88. }
  89. }
  90. }
  91. /**
  92. * Indicates if the given parameter is a valid metadata array.
  93. *
  94. * Required fields are:
  95. * - `name`: the name of the extension
  96. * - `entry_point`: a class name to load the extension source code
  97. * If the extension class name is `TestExtension`, entry point will be `Test`.
  98. * `entry_point` must be composed of alphanumeric characters.
  99. *
  100. * @param ExtensionMetadata $meta is an array of values.
  101. * @return bool true if the array is valid, false else.
  102. */
  103. private static function isValidMetadata(array $meta): bool {
  104. $valid_chars = ['_'];
  105. return !(empty($meta['name']) || empty($meta['entrypoint']) || !ctype_alnum(str_replace($valid_chars, '', $meta['entrypoint'])));
  106. }
  107. /**
  108. * Load the extension source code based on info metadata.
  109. *
  110. * @param ExtensionMetadata $info an array containing information about extension.
  111. * @return Minz_Extension|null an extension inheriting from Minz_Extension.
  112. */
  113. private static function load(array $info): ?Minz_Extension {
  114. $entry_point_filename = $info['path'] . '/' . self::$ext_entry_point;
  115. $ext_class_name = $info['entrypoint'] . 'Extension';
  116. include_once $entry_point_filename;
  117. // Test if the given extension class exists.
  118. if (!class_exists($ext_class_name)) {
  119. Minz_Log::warning("`{$ext_class_name}` cannot be found in `{$entry_point_filename}`");
  120. return null;
  121. }
  122. // Try to load the class.
  123. $extension = null;
  124. try {
  125. $extension = new $ext_class_name($info);
  126. } catch (Exception $e) {
  127. // We cannot load the extension? Invalid!
  128. Minz_Log::warning("Invalid extension `{$ext_class_name}`: " . $e->getMessage());
  129. return null;
  130. }
  131. // Test if class is correct.
  132. if (!($extension instanceof Minz_Extension)) {
  133. Minz_Log::warning("`{$ext_class_name}` is not an instance of `Minz_Extension`");
  134. return null;
  135. }
  136. return $extension;
  137. }
  138. /**
  139. * Add the extension to the list of the known extensions ($ext_list).
  140. *
  141. * If the extension is present in $ext_auto_enabled and if its type is "system",
  142. * it will be enabled at the same time.
  143. *
  144. * @param Minz_Extension $ext a valid extension.
  145. */
  146. private static function register(Minz_Extension $ext): void {
  147. $name = $ext->getName();
  148. self::$ext_list[$name] = $ext;
  149. if ($ext->getType() === 'system' && !empty(self::$ext_auto_enabled[$name])) {
  150. self::enable($ext->getName(), 'system');
  151. }
  152. }
  153. /**
  154. * Enable an extension so it will be called when necessary.
  155. *
  156. * The extension init() method will be called.
  157. *
  158. * @param string $ext_name is the name of a valid extension present in $ext_list.
  159. * @param 'system'|'user'|null $onlyOfType only enable if the extension matches that type. Set to null to load all.
  160. */
  161. private static function enable(string $ext_name, ?string $onlyOfType = null): void {
  162. if (isset(self::$ext_list[$ext_name])) {
  163. $ext = self::$ext_list[$ext_name];
  164. if ($onlyOfType !== null && $ext->getType() !== $onlyOfType) {
  165. // Do not enable an extension of the wrong type
  166. return;
  167. }
  168. self::$ext_list_enabled[$ext_name] = $ext;
  169. if (method_exists($ext, 'autoload')) {
  170. spl_autoload_register([$ext, 'autoload']);
  171. }
  172. $ext->enable();
  173. try {
  174. $ext->init();
  175. } catch (Minz_Exception $e) { // @phpstan-ignore catch.neverThrown (Thrown by extensions)
  176. Minz_Log::warning('Error while enabling extension ' . $ext->getName() . ': ' . $e->getMessage());
  177. $ext->disable();
  178. unset(self::$ext_list_enabled[$ext_name]);
  179. }
  180. }
  181. }
  182. /**
  183. * Enable a list of extensions.
  184. *
  185. * @param array<string,bool> $ext_list the names of extensions we want to load.
  186. * @param 'system'|'user'|null $onlyOfType limit the extensions to load to those of those type. Set to null string to load all.
  187. */
  188. public static function enableByList(?array $ext_list, ?string $onlyOfType = null): void {
  189. if (empty($ext_list)) {
  190. return;
  191. }
  192. foreach ($ext_list as $ext_name => $ext_status) {
  193. if ($ext_status && is_string($ext_name)) {
  194. self::enable($ext_name, $onlyOfType);
  195. }
  196. }
  197. }
  198. /**
  199. * Return a list of extensions.
  200. *
  201. * @param bool $only_enabled if true returns only the enabled extensions (false by default).
  202. * @return Minz_Extension[] an array of extensions.
  203. */
  204. public static function listExtensions(bool $only_enabled = false): array {
  205. if ($only_enabled) {
  206. return self::$ext_list_enabled;
  207. } else {
  208. return self::$ext_list;
  209. }
  210. }
  211. /**
  212. * Return an extension by its name.
  213. *
  214. * @param string $ext_name the name of the extension.
  215. * @return Minz_Extension|null the corresponding extension or null if it doesn't exist.
  216. */
  217. public static function findExtension(string $ext_name): ?Minz_Extension {
  218. if (!isset(self::$ext_list[$ext_name])) {
  219. return null;
  220. }
  221. return self::$ext_list[$ext_name];
  222. }
  223. /**
  224. * Add a hook function to a given hook.
  225. *
  226. * The hook name must be a valid one. For the valid list, see Minz_HookType enum.
  227. *
  228. * @param string|Minz_HookType $hook_type the hook name (must exist).
  229. * @param callable $hook_function the function name to call (must be callable).
  230. * @param int $priority the priority of the hook, default priority is 0, the higher the value the lower the priority
  231. */
  232. public static function addHook(string|Minz_HookType $hook_type, $hook_function, int $priority = Minz_Hook::DEFAULT_PRIORITY): void {
  233. if (null === $hook_type = self::extractHookType($hook_type)) {
  234. return;
  235. }
  236. $hook_type_name = $hook_type->value;
  237. if (is_callable($hook_function)) {
  238. self::$hook_list[$hook_type_name]['list'][] = new Minz_Hook(\Closure::fromCallable($hook_function), $priority);
  239. }
  240. }
  241. /**
  242. * @param string|Minz_HookType $hook_type the hook type or its name
  243. * @return Minz_HookType|null
  244. */
  245. private static function extractHookType(string|Minz_HookType $hook_type) {
  246. if ($hook_type instanceof Minz_HookType) {
  247. return $hook_type;
  248. }
  249. return Minz_HookType::tryFrom($hook_type);
  250. }
  251. /**
  252. * @param Minz_HookType $hook_type the hook type or its name
  253. * @return list<Minz_Hook>
  254. */
  255. private static function retrieveHookList(Minz_HookType $hook_type): array {
  256. $list = self::$hook_list[$hook_type->value]['list'] ?? [];
  257. usort($list, static fn (Minz_Hook $a, Minz_Hook $b): int => $a->getPriority() <=> $b->getPriority());
  258. return $list;
  259. }
  260. /**
  261. * Call functions related to a given hook.
  262. *
  263. * The hook name must be a valid one. For the valid list, see Minz_HookType enum.
  264. *
  265. * @param string|Minz_HookType $hook_type the hook to call.
  266. * @param mixed ...$args additional parameters (for signature, please see Minz_HookType enum).
  267. * @return mixed|void|null final result of the called hook.
  268. */
  269. public static function callHook(string|Minz_HookType $hook_type, ...$args) {
  270. if (null === $hook_type = self::extractHookType($hook_type)) {
  271. return;
  272. }
  273. $signature = $hook_type->signature();
  274. if ($signature === Minz_HookSignature::OneToOne) {
  275. return self::callOneToOne($hook_type, $args[0] ?? null);
  276. } elseif ($signature === Minz_HookSignature::PassArguments) {
  277. foreach (self::retrieveHookList($hook_type) as $hook) {
  278. $result = call_user_func($hook->getFunction(), ...$args);
  279. if ($result !== null) {
  280. return $result;
  281. }
  282. }
  283. } elseif ($signature === Minz_HookSignature::NoneToString) {
  284. return self::callHookString($hook_type);
  285. } elseif ($signature === Minz_HookSignature::NoneToNone) {
  286. self::callHookVoid($hook_type);
  287. }
  288. return;
  289. }
  290. /**
  291. * Call a hook which takes one argument and return a result.
  292. *
  293. * The result is chained between the extension, for instance, first extension
  294. * hook will receive the initial argument and return a result which will be
  295. * passed as an argument to the next extension hook and so on.
  296. *
  297. * If a hook return a null or false value, the method is stopped and that value is returned.
  298. *
  299. * @param Minz_HookType $hook_type is the hook type to call.
  300. * @param mixed $arg is the argument to pass to the first extension hook.
  301. * @return mixed|null final chained result of the hooks. If nothing is changed,
  302. * the initial argument is returned.
  303. */
  304. private static function callOneToOne(Minz_HookType $hook_type, mixed $arg): mixed {
  305. $result = $arg;
  306. foreach (self::retrieveHookList($hook_type) as $hook) {
  307. $result = call_user_func($hook->getFunction(), $arg);
  308. if ($result === null || $result === false) {
  309. break;
  310. }
  311. $arg = $result;
  312. }
  313. return $result;
  314. }
  315. /**
  316. * Call a hook which takes no argument and returns a string.
  317. *
  318. * The result is concatenated between each hook and the final string is
  319. * returned.
  320. *
  321. * @param string|Minz_HookType $hook_type is the hook to call.
  322. * @return string concatenated result of the call to all the hooks.
  323. */
  324. public static function callHookString(string|Minz_HookType $hook_type): string {
  325. if (null === $hook_type = self::extractHookType($hook_type)) {
  326. return '';
  327. }
  328. $result = '';
  329. foreach (self::retrieveHookList($hook_type) as $hook) {
  330. $return = call_user_func($hook->getFunction());
  331. if (is_scalar($return)) {
  332. $result .= $return;
  333. }
  334. }
  335. return $result;
  336. }
  337. /**
  338. * Call a hook which takes no argument and returns nothing.
  339. *
  340. * This case is simpler than callOneToOne because hooks are called one by
  341. * one, without any consideration of argument nor result.
  342. *
  343. * @param string|Minz_HookType $hook_type is the hook to call.
  344. */
  345. public static function callHookVoid(string|Minz_HookType $hook_type): void {
  346. if (null === $hook_type = self::extractHookType($hook_type)) {
  347. return;
  348. }
  349. foreach (self::retrieveHookList($hook_type) as $hook) {
  350. call_user_func($hook->getFunction());
  351. }
  352. }
  353. /**
  354. * Call a hook which takes no argument and returns nothing.
  355. * Same as callHookVoid but only calls the first extension.
  356. *
  357. * @param string|Minz_HookType $hook_type is the hook to call.
  358. */
  359. public static function callHookUnique(string|Minz_HookType $hook_type): bool {
  360. if (null === $hook_type = self::extractHookType($hook_type)) {
  361. throw new \RuntimeException("The “{$hook_type}” does not exist!");
  362. }
  363. foreach (self::retrieveHookList($hook_type) as $hook) {
  364. call_user_func($hook->getFunction());
  365. return true;
  366. }
  367. return false;
  368. }
  369. /**
  370. * Check if a extension is enabled
  371. *
  372. * @param string $ext_name is the extension's name as provided in metadata.json
  373. */
  374. public static function isExtensionEnabled(string $ext_name): bool {
  375. return isset(self::$ext_list_enabled[$ext_name]);
  376. }
  377. }