HookManager.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace ModulesGarden\Servers\ProxmoxCloudVps\Core\Hook;
  3. class HookManager
  4. {
  5. protected $hookRegister = [];
  6. protected static $currentName = "";
  7. protected $files = [];
  8. /**
  9. * @var Config
  10. */
  11. protected $config;
  12. public function __construct($dir)
  13. {
  14. $this->config = new Config();
  15. $path = $dir . DS . "app" . DS . "Hooks";
  16. $files = scandir($path, 1);
  17. if (count($files) != 0)
  18. {
  19. foreach ($files as $key => &$value)
  20. {
  21. if ($value === "." || $value === ".." || is_dir($path . DIRECTORY_SEPARATOR . $value))
  22. {
  23. unset($files[$key]);
  24. }
  25. }
  26. }
  27. $this->files = $files;
  28. }
  29. public static function create($dir)
  30. {
  31. $hookManager = new HookManager($dir);
  32. foreach ($hookManager->getFiles() as $file)
  33. {
  34. $path = $dir . DS . "app" . DS . "Hooks" . DS . $file;
  35. try
  36. {
  37. HookManager::$currentName = explode(".", $file)[0];
  38. require $path;
  39. }
  40. catch (\Exception $e)
  41. {
  42. ServiceLocator::call('errorManager')->addError(self::class, $e->getMessage() . " ||||HookPath: {$path}", $e->getTrace());
  43. }
  44. }
  45. $hookManager->start();
  46. return $hookManager;
  47. }
  48. public function getFiles()
  49. {
  50. return $this->files;
  51. }
  52. public function register($callback, $sort = 1)
  53. {
  54. $this->hookRegister[] = [
  55. "name" => HookManager::$currentName,
  56. "function" => $callback,
  57. "sort" => $sort
  58. ];
  59. }
  60. protected function start()
  61. {
  62. foreach ($this->hookRegister as $hook)
  63. {
  64. if ($this->config->checkHook($hook['name']))
  65. {
  66. add_hook(
  67. $hook['name'], $hook['sort'], $hook['function']
  68. );
  69. }
  70. }
  71. }
  72. }