Completed
Push — master ( 556987...94c24e )
by ARCANEDEV
9s
created

Webhook   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 48
ccs 10
cts 10
cp 1
rs 10
c 0
b 0
f 0
wmc 3
lcom 0
cbo 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A constructEvent() 0 18 3
1
<?php namespace Arcanedev\Stripe;
2
3
use Arcanedev\Stripe\Resources\Event;
4
use UnexpectedValueException;
5
6
/**
7
 * Class     Webhook
8
 *
9
 * @package  Arcanedev\Stripe
10
 * @author   ARCANEDEV <[email protected]>
11
 */
12
abstract class Webhook
13
{
14
    /* -----------------------------------------------------------------
15
     |  Constants
16
     | -----------------------------------------------------------------
17
     */
18
19
    const DEFAULT_TOLERANCE = 300;
20
21
    /* -----------------------------------------------------------------
22
     |  Main Methods
23
     | -----------------------------------------------------------------
24
     */
25
26
    /**
27
     * Returns an Event instance using the provided JSON payload.
28
     *
29
     * Throws a `UnexpectedValueException` if the payload is not valid JSON,
30
     * and a `SignatureVerificationException` if the signature verification fails for any reason.
31
     *
32
     * @param  string  $payload    The payload sent by Stripe.
33
     * @param  string  $sigHeader  The contents of the signature header sent by Stripe.
34
     * @param  string  $secret     Secret used to generate the signature.
35
     * @param  int     $tolerance  Maximum difference allowed between the header's timestamp and the current time
36
     *
37
     * @return \Arcanedev\Stripe\Resources\Event  the Event instance
38
     *
39
     * @throws UnexpectedValueException
40
     */
41 9
    public static function constructEvent($payload, $sigHeader, $secret, $tolerance = self::DEFAULT_TOLERANCE)
42
    {
43 9
        $data      = json_decode($payload, true);
44 9
        $jsonError = json_last_error();
45
46 9
        if ($data === null && $jsonError !== JSON_ERROR_NONE) {
47 3
            throw new UnexpectedValueException(
48 3
                "Invalid payload: $payload (json_last_error() was $jsonError)"
49 1
            );
50
        }
51
52
        /** @var  \Arcanedev\Stripe\Resources\Event  $event */
53 6
        $event = StripeObject::scopedConstructFrom(Event::class, $data, null);
54
55 6
        WebhookSignature::verifyHeader($payload, $sigHeader, $secret, $tolerance);
56
57 3
        return $event;
58
    }
59
}
60