TriggerWebhooksJob   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 117
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 6
Bugs 2 Features 0
Metric Value
wmc 15
c 6
b 2
f 0
lcom 1
cbo 10
dl 0
loc 117
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A resolveCallable() 0 15 3
C handle() 0 59 11
1
<?php
2
3
namespace Mpociot\CaptainHook\Jobs;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Middleware;
7
use GuzzleHttp\Promise\PromiseInterface;
8
use Illuminate\Bus\Queueable;
9
use Illuminate\Support\Str;
10
use Mpociot\CaptainHook\WebhookLog;
11
use Illuminate\Queue\SerializesModels;
12
use Psr\Http\Message\RequestInterface;
13
use Psr\Http\Message\ResponseInterface;
14
use Illuminate\Queue\InteractsWithQueue;
15
use Illuminate\Contracts\Queue\ShouldQueue;
16
17
class TriggerWebhooksJob implements ShouldQueue
18
{
19
    use Queueable, InteractsWithQueue, SerializesModels;
20
21
    /**
22
     * All the webhooks that should be executed.
23
     *
24
     * @var array|\Illuminate\Support\Collection
25
     */
26
    protected $webhooks;
27
28
    /**
29
     * The event data to be posted to our hooks.
30
     *
31
     * @var mixed
32
     */
33
    protected $eventData;
34
35
    /**
36
     * Create a new job instance.
37
     *
38
     * @param array|\Illuminate\Support\Collection $webhooks
39
     * @param mixed $eventData
40
     */
41
    public function __construct($webhooks, $eventData)
42
    {
43
        $this->eventData = $eventData;
44
        $this->webhooks = $webhooks;
45
    }
46
47
    /**
48
     * Resolves a string or callable to a valid callable.
49
     * @param string|callable $transformer
50
     * @param $defaultMethodName
51
     * @return callable
52
     */
53
    private function resolveCallable($transformer, $defaultMethodName)
54
    {
55
        if (is_string($transformer)) {
56
            return function () use ($transformer, $defaultMethodName) {
57
                list($class, $method) = Str::parseCallback($transformer, $defaultMethodName);
58
59
                return call_user_func_array([app($class), $method], func_get_args());
60
            };
61
        } elseif (is_callable($transformer)) {
62
            return $transformer;
63
        }
64
65
        return function () {
66
        };
67
    }
68
69
    /**
70
     * Execute the job.
71
     *
72
     * @return void
73
     */
74
    public function handle()
75
    {
76
        $config = app('Illuminate\Contracts\Config\Repository');
77
        $client = app(Client::class);
78
79
        if ($config->get('captain_hook.log.max_attempts', -1) !== -1 && $this->attempts() > $config->get('captain_hook.log.max_attempts')) {
80
            return;
81
        }
82
83
        $logging = $config->get('captain_hook.log.active');
84
        $transformer = $this->resolveCallable($config->get('captain_hook.transformer'), 'transform');
85
        $responseCallback = $this->resolveCallable($config->get('captain_hook.response_callback'), 'handle');
86
87
        foreach ($this->webhooks as $webhook) {
88
            if ($logging) {
89
                if ($config->get('captain_hook.log.storage_quantity') != -1 &&
90
                    $webhook->logs()->count() >= $config->get('captain_hook.log.storage_quantity')) {
91
                    $webhook->logs()->orderBy('updated_at', 'asc')->first()->delete();
92
                }
93
                $log = new WebhookLog([
94
                    'webhook_id' => $webhook['id'],
95
                    'url' => $webhook['url'],
96
                ]);
97
                $middleware = Middleware::tap(function (RequestInterface $request, $options) use ($log) {
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
98
                    $log->payload_format = isset($request->getHeader('Content-Type')[0]) ? $request->getHeader('Content-Type')[0] : null;
0 ignored issues
show
Documentation introduced by
The property payload_format does not exist on object<Mpociot\CaptainHook\WebhookLog>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
99
                    $log->payload = $request->getBody()->getContents();
0 ignored issues
show
Documentation introduced by
The property payload does not exist on object<Mpociot\CaptainHook\WebhookLog>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
100
                }, function ($request, $options, PromiseInterface $response) use ($log, $webhook, $responseCallback) {
101
                    $response->then(function (ResponseInterface $response) use ($log, $webhook, $responseCallback) {
102
                        $log->status = $response->getStatusCode();
0 ignored issues
show
Documentation introduced by
The property status does not exist on object<Mpociot\CaptainHook\WebhookLog>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
103
                        $log->response = $response->getBody()->getContents();
0 ignored issues
show
Documentation introduced by
The property response does not exist on object<Mpociot\CaptainHook\WebhookLog>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
104
                        $log->response_format = $log->payload_format = isset($response->getHeader('Content-Type')[0]) ? $response->getHeader('Content-Type')[0] : null;
0 ignored issues
show
Documentation introduced by
The property response_format does not exist on object<Mpociot\CaptainHook\WebhookLog>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Documentation introduced by
The property payload_format does not exist on object<Mpociot\CaptainHook\WebhookLog>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
105
106
                        $log->save();
107
108
                        // Retry this job if the webhook response didn't give us a HTTP 200 OK
109
                        if ($response->getStatusCode() >= 300 || $response->getStatusCode() < 200) {
110
                            $this->release(30);
111
                        }
112
113
                        $responseCallback($webhook, $response);
114
                    });
115
                });
116
117
                $client->post($webhook['url'], [
118
                    'exceptions' => false,
119
                    'body' => $transformer($this->eventData, $webhook),
120
                    'verify' => false,
121
                    'handler' => $middleware($client->getConfig('handler')),
122
                ]);
123
            } else {
124
                $client->post($webhook['url'], [
125
                    'exceptions' => false,
126
                    'body' => $transformer($this->eventData, $webhook),
127
                    'verify' => false,
128
                    'timeout' => 10,
129
                ]);
130
            }
131
        }
132
    }
133
}
134