Completed
Push — master ( 5643cd...35258b )
by Marcel
02:20
created

TriggerWebhooksJob::handle()   B

Complexity

Conditions 8
Paths 4

Size

Total Lines 53
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 16
Bugs 1 Features 1
Metric Value
c 16
b 1
f 1
dl 0
loc 53
rs 7.1199
cc 8
eloc 35
nc 4
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Contracts\Bus\SelfHandling;
10
use Illuminate\Support\Str;
11
use Mpociot\CaptainHook\WebhookLog;
12
use Illuminate\Queue\SerializesModels;
13
use Psr\Http\Message\RequestInterface;
14
use Psr\Http\Message\ResponseInterface;
15
use Illuminate\Queue\InteractsWithQueue;
16
use Illuminate\Contracts\Queue\ShouldQueue;
17
18
class TriggerWebhooksJob implements SelfHandling, ShouldQueue
0 ignored issues
show
Deprecated Code introduced by
The interface Illuminate\Contracts\Bus\SelfHandling has been deprecated with message: since version 5.2. Remove from jobs since self-handling is default.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
19
{
20
    use Queueable, InteractsWithQueue, SerializesModels;
21
22
    /**
23
     * All the webhooks that should be executed.
24
     *
25
     * @var array|\Illuminate\Support\Collection
26
     */
27
    protected $webhooks;
28
29
    /**
30
     * The event data to be posted to our hooks.
31
     *
32
     * @var mixed
33
     */
34
    protected $eventData;
35
36
    /**
37
     * Create a new job instance.
38
     *
39
     * @param array|\Illuminate\Support\Collection $webhooks
40
     * @param mixed $eventData
41
     */
42
    public function __construct($webhooks, $eventData)
43
    {
44
        $this->eventData = $eventData;
45
        $this->webhooks = $webhooks;
46
    }
47
48
    /**
49
     * Resolves
50
     * @param string|callable $transformer
51
     * @return callable
52
     */
53
    private function resolveTransformer($transformer)
54
    {
55
        if (is_string($transformer)) {
56
            return function() use($transformer) {
57
                list($class, $method) = Str::parseCallback($transformer,'transform');
58
                return call_user_func_array([app($class), $method], func_get_args());
59
            };
60
        } elseif (is_callable($transformer)) {
61
            return $transformer;
62
        }
63
    }
64
65
    /**
66
     * Execute the job.
67
     *
68
     * @return void
69
     */
70
    public function handle()
71
    {
72
        $config = app('Illuminate\Contracts\Config\Repository');
73
        $client = app(Client::class);
74
75
        $logging = $config->get('captain_hook.log.active');
76
        $transformer = $this->resolveTransformer($config->get('captain_hook.transformer'));
77
78
        foreach ($this->webhooks as $webhook) {
79
80
            if ($logging) {
81
                if ($config->get('captain_hook.log.storage_quantity') != -1 &&
82
                    $webhook->logs()->count() >= $config->get('captain_hook.log.storage_quantity')) {
83
                    $webhook->logs()->orderBy('updated_at', 'desc')->first()->delete();
84
                }
85
                $log = new WebhookLog([
86
                    'webhook_id' => $webhook[ 'id' ],
87
                    'url' => $webhook[ 'url' ],
88
                ]);
89
                $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...
90
                    $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...
91
                    $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...
92
                }, function ($request, $options, PromiseInterface $response) use ($log) {
93
                    $response->then(function (ResponseInterface $response) use ($log) {
94
                        $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...
95
                        $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...
96
                        $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...
97
98
                        $log->save();
99
100
                        // Retry this job if the webhook response didn't give us a HTTP 200 OK
101
                        if ($response->getStatusCode() != 200) {
102
                            $this->release(30);
103
                        }
104
                    });
105
                });
106
107
                $client->post($webhook[ 'url' ], [
108
                    'exceptions' => false,
109
                    'body' => $transformer($this->eventData, $webhook),
110
                    'verify' => false,
111
                    'handler' => $middleware($client->getConfig('handler')),
112
                ]);
113
            } else {
114
                $client->post($webhook[ 'url' ], [
115
                    'exceptions' => false,
116
                    'body' => $transformer($this->eventData, $webhook),
117
                    'verify' => false,
118
                    'timeout' => 10,
119
                ]);
120
            }
121
        }
122
    }
123
}
124