Completed
Push — master ( 657615...1aff71 )
by Dan
02:27
created

PluginTrait::dispatchMatch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 3
1
<?php
2
3
namespace Nopolabs\Yabot\Plugin;
4
5
use Exception;
6
use Nopolabs\Yabot\Helpers\ConfigTrait;
7
use Nopolabs\Yabot\Helpers\LogTrait;
8
use Nopolabs\Yabot\Message\Message;
9
use Throwable;
10
11
trait PluginTrait
12
{
13
    use LogTrait;
14
    use ConfigTrait;
15
16
    private $pluginId;
17
18
    /** @var PluginMatcher */
19
    private $pluginMatcher;
20
21
    /** @var MethodMatcher[] */
22
    private $methodMatchers;
23
24
    public function help(): string
25
    {
26
        return $this->get('help', 'no help available');
27
    }
28
29
    public function status(): string
30
    {
31
        return 'running';
32
    }
33
34
    public function init(string $pluginId, array $params)
35
    {
36
        $this->pluginId = $pluginId;
37
        $this->overrideConfig($params);
38
        $this->methodMatchers = $this->buildMethodMatchers($this->get('matchers'));
39
        $this->pluginMatcher = new PluginMatcher($pluginId, $this->getIsBot(), $this->getChannels(), $this->getUsers(), $this->getLog());
40
41
        $this->info("inited $pluginId config:", $this->getConfig());
42
    }
43
44
    public function replaceInPatterns($search, $replace, array $matchers): array
45
    {
46
        $replaced = [];
47
        foreach ($matchers as $name => $params) {
48
            $params['patterns'] = array_map(function($pattern) use ($search, $replace) {
49
                return str_replace($search, $replace, $pattern);
50
            }, $params['patterns']);
51
            $replaced[$name] = $params;
52
        }
53
        return $replaced;
54
    }
55
56
    public function getPriority(): int
57
    {
58
        return $this->get('priority');
59
    }
60
61
    public function getPrefix(): string
62
    {
63
        return $this->get('prefix');
64
    }
65
66
    public function handle(Message $message)
67
    {
68
        if (empty($this->pluginMatch($message))) {
69
            return;
70
        }
71
72
        $this->methodMatch($message);
73
    }
74
75
    protected function pluginMatch(Message $message): array
76
    {
77
        return $this->getPluginMatcher()->matches($message);
78
    }
79
80
    protected function getPluginMatcher() : PluginMatcher
81
    {
82
        return $this->pluginMatcher;
83
    }
84
85
    protected function methodMatch(Message $message)
86
    {
87
        foreach ($this->getMethodMatchers() as $methodMatcher) {
88
            /** @var MethodMatcher $methodMatcher */
89
            if ($matches = $methodMatcher->matches($message)) {
90
                $this->dispatchMatch($methodMatcher, $message, $matches);
91
92
                if ($message->isHandled()) {
93
                    return;
94
                }
95
            }
96
        }
97
    }
98
99
    protected function dispatchMatch(MethodMatcher $methodMatcher, Message $message, array $matches)
100
    {
101
        $method = $methodMatcher->getMethod();
102
103
        $this->info("dispatching {$this->pluginId}:{$methodMatcher->getName()}:$method ".json_encode($matches));
104
105
        $this->dispatch($method, $message, $matches);
106
    }
107
108
    protected function getMethodMatchers() : array
109
    {
110
        return $this->methodMatchers;
111
    }
112
113
    protected function dispatch(string $method, Message $message, array $matches)
114
    {
115
        if (!method_exists($this, $method)) {
116
            $this->warning("{$this->pluginId} no method named: $method");
117
            return;
118
        }
119
120
        try {
121
122
            $this->$method($message, $matches);
123
124
        } catch (Throwable $throwable) {
125
            $errmsg = 'Exception in '.static::class.'::'.$method."\n"
126
                .$throwable->getMessage()."\n"
127
                .$throwable->getTraceAsString();
128
            $this->warning($errmsg);
129
        }
130
    }
131
132
    protected function overrideConfig(array $params)
133
    {
134
        $config = $this->canonicalConfig(array_merge($this->getConfig(), $params));
135
136
        $this->setConfig($config);
137
    }
138
139
    protected function setPluginId($pluginId)
140
    {
141
        $this->pluginId = $pluginId;
142
    }
143
144
    protected function getUsers()
145
    {
146
        return $this->get('users');
147
    }
148
149
    protected function getChannels()
150
    {
151
        return $this->get('channels');
152
    }
153
154
    /**
155
     * @return bool|null
156
     */
157
    protected function getIsBot()
158
    {
159
        return $this->get('isBot');
160
    }
161
162
    protected function getMatchers(): array
163
    {
164
        return $this->get('matchers');
165
    }
166
167
    protected function canonicalConfig(array $config): array
168
    {
169
        return [
170
            'priority' => $config['priority'] ?? PluginManager::DEFAULT_PRIORITY,
171
            'prefix' => ($config['prefix'] ?? '') ? $config['prefix'] : PluginManager::NO_PREFIX,
172
            'isBot' => $config['isBot'] ?? null,
173
            'channels' => $config['channels'] ?? array_filter([$config['channel'] ?? null]),
174
            'users' => $config['users'] ?? array_filter([$config['user'] ?? null]),
175
            'matchers' => $this->canonicalMatchers($config['matchers'] ?? []),
176
        ];
177
    }
178
179
    protected function canonicalMatchers(array $matchers): array
180
    {
181
        $expanded = [];
182
183
        foreach ($matchers as $name => $params) {
184
            $expanded[$name] = $this->canonicalMatcher($name, $params);
185
        }
186
187
        if (empty($expanded)) {
188
            $this->warning("{$this->pluginId} has no matchers");
189
        }
190
191
        return $expanded;
192
    }
193
194
    protected function canonicalMatcher(string $name, $params) : array
195
    {
196
        $params = is_array($params) ? $params : ['patterns' => [$params]];
197
198
        $method = $params['method'] ?? $name;
199
200
        if (!method_exists($this, $method)) {
201
            $this->warning("{$this->pluginId} no method named: $method");
202
        }
203
204
        return [
205
            'isBot' => $params['isBot'] ?? null,
206
            'channels' => $params['channels'] ?? array_filter([$params['channel'] ?? null]),
207
            'users' => $params['users'] ?? array_filter([$params['user'] ?? null]),
208
            'patterns' => $params['patterns'] ?? array_filter([$params['pattern'] ?? null]),
209
            'method' => $params['method'] ?? $name,
210
        ];
211
    }
212
213
    protected function buildMethodMatchers(array $matchers) : array
214
    {
215
        $methodMatchers = [];
216
217
        foreach ($matchers as $name => $params) {
218
            $methodMatchers[] = new MethodMatcher(
219
                $name,
220
                $params['isBot'],
221
                $params['channels'],
222
                $params['users'],
223
                $this->validPatterns($params['patterns'], $name),
224
                $params['method'],
225
                $this->getLog()
226
            );
227
        }
228
229
        return $methodMatchers;
230
    }
231
232
    protected function validPatterns(array $patterns, $name) : array
233
    {
234
        $valid = [];
235
        foreach ($patterns as $pattern) {
236
            if ($this->isValidRegExp($pattern, $name)) {
237
                $valid[] = $pattern;
238
            }
239
        }
240
        return $valid;
241
    }
242
243
    protected function isValidRegExp($pattern, $name) : bool
244
    {
245
        try {
246
            preg_match($pattern, '');
247
            return true;
248
        } catch (Throwable $e) {
249
            $this->warning("$name.pattern='$pattern' ".$e->getMessage());
250
            return false;
251
        }
252
    }
253
}