1 <?php
2
3 4 5 6 7 8
9
10 namespace frankmayer\ArangoDbPhpCore\Plugins;
11
12 use frankmayer\ArangoDbPhpCore\Client;
13 use frankmayer\ArangoDbPhpCore\ClientException;
14
15
16 17 18 19 20
21 class PluginManager
22 {
23 24 25
26 public $pluginStorage;
27 28 29
30 public $client;
31 32 33
34 public $options;
35
36
37 38 39 40 41
42 public function __construct($client, $plugins = [], $options = ['notificationsEnabled' => true])
43 {
44 $options['notificationsEnabled'] = true;
45
46 $this->client = $client;
47 $this->pluginStorage = [];
48 $this->options = $options;
49 $this->setPluginsFromPluginArray($plugins);
50 }
51
52
53 54 55 56 57 58
59 public function setPluginsFromPluginArray($plugins = null)
60 {
61 if (is_array($plugins) && count($plugins) > 0) {
62 foreach ($plugins as $key => $plugin) {
63 if (is_subclass_of($plugin, 'frankmayer\ArangoDbPhpCore\Plugins\Plugin')) {
64 $this->pluginStorage[$key]['plugin'] = $plugin;
65 $this->pluginStorage[$key]['priority'] = $plugin->priority;
66 } else {
67 throw new ClientException('Could not initialize plugin. Is not a subclass of frankmayer\ArangoDbPhpCore\Plugins\PluginPlugin');
68 }
69 }
70 }
71 uksort($this->pluginStorage, [$this, 'comparePluginPriorities']);
72
73 return true;
74 }
75
76
77 78 79 80
81 public function notifyPlugins($eventName, $eventData = [])
82 {
83 if ($this->options['notificationsEnabled'] === true) {
84 if (count($this->pluginStorage) > 0) {
85 foreach ($this->pluginStorage as $key => $priority) {
86 $plugin = $this->pluginStorage[$key]['plugin'];
87
88 $plugin->notify($eventName, $this->client, $eventData);
89 }
90 }
91 }
92 }
93
94
95 96 97 98 99 100
101 protected function comparePluginPriorities($a, $b)
102 {
103 if ($this->pluginStorage[$a]['priority'] === $this->pluginStorage[$b]['priority']) {
104 return 0;
105 }
106
107 return ($this->pluginStorage[$a]['priority'] > $this->pluginStorage[$b]['priority']) ? -1 : 1;
108 }
109
110 111 112
113 public function removePluginInstance($instanceName)
114 {
115 unset ($this->pluginStorage[$instanceName]);
116
117 return;
118 }
119 }