Skip to content

Commit 367fc06

Browse files
committed
Extract VAPID header caching logic
1 parent bc465f7 commit 367fc06

File tree

1 file changed

+35
-23
lines changed

1 file changed

+35
-23
lines changed

src/WebPush.php

Lines changed: 35 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -262,34 +262,12 @@ private function prepare(array $notifications): array
262262
}
263263
// if VAPID (GCM doesn't support it but FCM does)
264264
elseif (array_key_exists('VAPID', $auth)) {
265-
$vapid = $auth['VAPID'];
266-
267265
$audience = parse_url($endpoint, PHP_URL_SCHEME).'://'.parse_url($endpoint, PHP_URL_HOST);
268-
269266
if (!parse_url($audience)) {
270267
throw new \ErrorException('Audience "'.$audience.'"" could not be generated.');
271268
}
272269

273-
$vapidHeaders = null;
274-
$cache_key = null;
275-
if ($this->reuseVAPIDHeaders) {
276-
$cache_key = implode('#', [$audience, $contentEncoding, crc32(serialize($vapid))]);
277-
if (array_key_exists($cache_key, $this->vapidHeaders)) {
278-
$vapidHeaders = $this->vapidHeaders[$cache_key];
279-
}
280-
}
281-
282-
if (!$vapidHeaders) {
283-
if (!$contentEncoding) {
284-
throw new \ErrorException('Subscription should have a content encoding');
285-
}
286-
287-
$vapidHeaders = VAPID::getVapidHeaders($audience, $vapid['subject'], $vapid['publicKey'], $vapid['privateKey'], $contentEncoding);
288-
}
289-
290-
if ($this->reuseVAPIDHeaders) {
291-
$this->vapidHeaders[$cache_key] = $vapidHeaders;
292-
}
270+
$vapidHeaders = $this->getVAPIDHeaders($audience, $contentEncoding, $auth['VAPID']);
293271

294272
$headers['Authorization'] = $vapidHeaders['Authorization'];
295273

@@ -391,4 +369,38 @@ public function setDefaultOptions(array $defaultOptions)
391369
public function countPendingNotifications(): int {
392370
return null !== $this->notifications ? count($this->notifications) : 0;
393371
}
372+
373+
/**
374+
* @param string $audience
375+
* @param string|null $contentEncoding
376+
* @param array $vapid
377+
* @return array
378+
* @throws \ErrorException
379+
*/
380+
private function getVAPIDHeaders(string $audience, ?string $contentEncoding, array $vapid)
381+
{
382+
$vapidHeaders = null;
383+
384+
$cache_key = null;
385+
if ($this->reuseVAPIDHeaders) {
386+
$cache_key = implode('#', [$audience, $contentEncoding, crc32(serialize($vapid))]);
387+
if (array_key_exists($cache_key, $this->vapidHeaders)) {
388+
$vapidHeaders = $this->vapidHeaders[$cache_key];
389+
}
390+
}
391+
392+
if (!$vapidHeaders) {
393+
if (!$contentEncoding) {
394+
throw new \ErrorException('Subscription should have a content encoding');
395+
}
396+
397+
$vapidHeaders = VAPID::getVapidHeaders($audience, $vapid['subject'], $vapid['publicKey'], $vapid['privateKey'], $contentEncoding);
398+
}
399+
400+
if ($this->reuseVAPIDHeaders) {
401+
$this->vapidHeaders[$cache_key] = $vapidHeaders;
402+
}
403+
404+
return $vapidHeaders;
405+
}
394406
}

0 commit comments

Comments
 (0)