forked from vtsykun/packeton
-
Notifications
You must be signed in to change notification settings - Fork 0
/
WebhookExtension.php
259 lines (227 loc) · 7.11 KB
/
WebhookExtension.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
<?php
namespace Packagist\WebBundle\Webhook\Twig;
use Doctrine\Persistence\ManagerRegistry;
use Packagist\WebBundle\Entity\Package;
use Packagist\WebBundle\Entity\Version;
use Packagist\WebBundle\Entity\Webhook;
use Packagist\WebBundle\Util\ChangelogUtils;
use Predis\Client as Redis;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\NullLogger;
use Symfony\Component\HttpClient\HttpClient;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* This extension only apply for webhook sandbox env.
*/
class WebhookExtension extends AbstractExtension implements ContextAwareInterface, LoggerAwareInterface
{
use LoggerAwareTrait;
private $registry;
private $changelogUtils;
private $redis;
/** @var WebhookContext */
private $context;
public function __construct(
ManagerRegistry $registry,
ChangelogUtils $changelogUtils,
Redis $redis
) {
$this->registry = $registry;
$this->changelogUtils = $changelogUtils;
$this->redis = $redis;
$this->logger = new NullLogger();
}
/**
* {@inheritdoc}
*/
public function getFunctions()
{
$functions = [];
$reflect = new \ReflectionClass(__CLASS__);
foreach ($reflect->getMethods() as $method) {
if ($method->isPublic() && strpos($method->getName(), 'hook_function_') === 0) {
$functions[] = new TwigFunction(substr($method->getName(), 14), [$this, $method->getName()]);
}
}
return $functions;
}
/**
* Get commit messages between two tags
*
* {@inheritDoc}
*/
public function hook_function_get_changelog($package, $fromVersion = null, $toVersion = null, $maxCount = 100)
{
$repo = $this->registry->getRepository(Package::class);
if (is_int($package)) {
$package = $repo->find($package);
} elseif (is_string($package)) {
$package = $repo->findOneBy(['name' => $package]);
}
if (!is_string($toVersion) || !$package instanceof Package) {
return [];
}
if (!is_int($maxCount)) {
$maxCount = 100;
}
if (!is_string($fromVersion)) {
$fromVersion = $this->registry->getRepository(Version::class)
->getPreviousRelease($package->getName(), $toVersion);
}
if ($toVersion && $fromVersion) {
return $this->changelogUtils->getChangelog($package, $fromVersion, $toVersion, $maxCount);
}
return [];
}
public function hook_function_preg_match_all($regex, $content, $matchOffset = null)
{
try {
preg_match_all($regex, $content, $matches);
$this->logger->debug(sprintf('preg_match_all result "%s": "%s"', $regex, json_encode($matches)));
} catch (\Throwable $e) {
$this->logger->error(sprintf('Error in regex "%s": %s', $regex, $e->getMessage()));
return [];
}
return is_int($matchOffset) ? $matches[$matchOffset] ?? [] : $matches;
}
/**
* Key value storage. Set value
*
* {@inheritDoc}
*/
public function hook_function_keyvalue_set(string $key, $value, $expire = 86400)
{
$key = 'hook.' . md5($key);
if ($expire) {
$this->redis->setex($key, $expire, $value);
} else {
$this->redis->set($key, $value);
}
}
/**
* Key value storage. Get value
*
* {@inheritDoc}
*/
public function hook_function_keyvalue_get(string $key)
{
$key = 'hook.' . md5($key);
return $this->redis->get($key);
}
/**
* Json decode function.
*
* {@inheritDoc}
*/
public function hook_function_json_decode($value)
{
return json_decode($value, true);
}
/**
* PHP hash_mac.
*
* {@inheritDoc}
*/
public function hook_function_hash_mac($algo, $value, $key)
{
try {
return hash_hmac($algo, $value, $key);
} catch (\Throwable $exception) {
$this->logger->error('hash_hmac error: ' . $exception->getMessage());
}
return null;
}
/**
* Simple wrapper for HttpClient.
* Allow make get http request from twig code (ONLY for webhooks).
* Don't recommended to use, but this hack can be very useful
*
* Return decoded as array body, if JSON response.
* {@inheritDoc}
*/
public function hook_function_http_request(string $url, array $options = [])
{
$method = $options['method'] ?? 'GET';
$isRaw = $options['raw'] ?? false;
unset($options['method'], $options['raw']);
$client = HttpClient::create(['max_duration' => 60]);
try {
$response = $client->request($method, $url, $options);
} catch (\Throwable $exception) {
$this->logger->error('Http request failed: ' . $exception->getMessage());
return null;
}
$array = $info = $statusCode = $content = $headers = $array = null;
try {
$info = $response->getInfo();
$statusCode = $response->getStatusCode();
$headers = $response->getHeaders(false);
$content = $response->getContent(false);
$array = $content ? @json_decode($content, true) : null;
} catch (\Throwable $exception) {
$this->logger->warning('Http get response failed: ' . $exception->getMessage());
}
if (false === $isRaw) {
return $array ?: $content;
}
return [
'info' => $info,
'statusCode' => $statusCode,
'content' => $content,
'toArray' => $array,
'headers' => $headers,
];
}
public function hook_function_array_unique($value)
{
return is_array($value) ? array_unique($value) : null;
}
/**
* Interrupt request
*
* {@inheritDoc}
*/
public function hook_function_interrupt($reason = null)
{
throw new InterruptException('This request was interrupt by user from twig code. ' . $reason);
}
/**
* Trigger other webhook by ID
*
* {@inheritdoc}
*/
public function hook_function_trigger_webhook($hookId, array $context = [])
{
if (!$this->context instanceof WebhookContext) {
return;
}
$hook = $hookId instanceof Webhook ? $hookId :
$this->registry->getRepository(Webhook::class)->find((int) $hookId);
if (null !== $hook) {
$this->context[WebhookContext::CHILD_WEBHOOK][] = [$hook, $context];
} else {
$this->logger->warning(sprintf('webhook %s not found', $hookId));
}
}
/**
* Log event from webhook.
*
* {@inheritdoc}
*/
public function hook_function_log($level, $value)
{
if (!is_string($value)) {
$value = json_encode($value);
}
$this->logger->log($level, $value);
}
/**
* @inheritDoc
*/
public function setContext(WebhookContext $context = null): void
{
$this->context = $context;
}
}