Failed Conditions
Pull Request — master (#284)
by Maximo
03:23 queued 13s
created

Webhooks   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 131
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 0
loc 131
rs 10
c 0
b 0
f 0
wmc 10
lcom 1
cbo 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A run() 0 32 3
A process() 0 44 3
A formatData() 0 23 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Canvas;
6
7
use Canvas\Models\UserWebhooks;
8
use Throwable;
9
use Phalcon\Http\Response;
10
use GuzzleHttp\Client;
11
use Phalcon\Di;
12
use Canvas\Models\SystemModules;
13
use function Canvas\Core\isJson;
14
15
/**
16
 * Class Validation.
17
 *
18
 * @package Canvas
19
 */
20
class Webhooks
21
{
22
    /**
23
    * Given the weebhook id, we run a test for it.
24
    *
25
    * @param integer $id
26
    * @param mixed $data
27
    * @return Response
28
    */
29
    public static function run(int $id, array $data)
30
    {
31
        /**
32
         * 1- verify it s acorrect url
33
         * 2- verify the method
34
         * 3- get the entity info from one entity of this app and company
35
         * 4- guzzle the request with the info
36
         * 5- verify you got a 200
37
         * 6- return the response from the webhook.
38
         *
39
         * later - add job for all system module to execute a queue when CRUD acction are run, maybe the middleware would do this?
40
         *
41
         */
42
        $userWebhook = UserWebhooks::getById($id);
43
44
        $client = new Client();
45
46
        try {
47
            $clientRequest = $client->request(
48
                $userWebhook->method,
49
                $userWebhook->url,
50
                self::formatData($userWebhook->method, $data)
51
            );
52
53
            $responseContent = $clientRequest->getBody()->getContents();
54
            $response = isJson($responseContent) ? json_decode($responseContent, true) : $responseContent;
55
        } catch (Throwable $error) {
56
            $response = $error->getMessage();
57
        }
58
59
        return $response;
60
    }
61
62
    /**
63
     * Execute the the webhook for the given app company providing the system module
64
     * for the SDK
65
     *  - pass the system module classname or classname\namespace
66
     *  - pass the action you are doing from the CRUD
67
     *  - get all the hooks from the user that match this action
68
     *  - pass the data you are sending
69
     *  - then we send it over to the URl.
70
     *
71
     * @param string $model
0 ignored issues
show
Bug introduced by
There is no parameter named $model. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
72
     * @param mixed $data
73
     * @param string $action
74
     * @throws Exception
75
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be array? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
76
     */
77
    public static function process(string $module, array $data, string $action): array
78
    {
79
        $appId = Di::getDefault()->getApp()->getId();
80
        $company = Di::getDefault()->getUserData()->getDefaultCompany();
81
82
        $systemModule = SystemModules::getByName($module);
83
84
        $webhooks = UserWebhooks::find([
85
            'conditions' => 'apps_id = ?0 AND companies_id = ?1 
86
                            AND webhooks_id in 
87
                                (SELECT Canvas\Models\Webhooks.id FROM Canvas\Models\Webhooks 
88
                                    WHERE Canvas\Models\Webhooks.apps_id = ?0 
89
                                    AND Canvas\Models\Webhooks.system_modules_id = ?2 
90
                                    AND Canvas\Models\Webhooks.action = ?3
91
                                )',
92
            'bind' => [
93
                $appId,
94
                $company->getId(),
95
                $systemModule->getId(),
96
                $action
97
            ]
98
        ]);
99
100
        $results = [];
101
102
        if ($webhooks->count()) {
103
            foreach ($webhooks as $userWebhook) {
104
                $results[$userWebhook->webhook->name][$action][] = [
105
                    $userWebhook->url => [
106
                        'results' => self::run($userWebhook->getId(), $data),
107
                    ]
108
                ];
109
            }
110
111
            return $results;
112
        }
113
114
        return [
115
            'message' => 'No user configure webhooks found for : ',
116
            'module' => $module,
117
            'data' => $data,
118
            'action' => $action
119
        ];
120
    }
121
122
    /**
123
     * Format the data for guzzle correct usage
124
     *
125
     * @return array
126
     */
127
    public static function formatData(string $method, array $data): array
128
    {
129
        switch (ucwords($method)) {
130
            case 'GET':
131
                $updateDataFormat = [
132
                    'query' => $data
133
                ];
134
                break;
135
136
            case 'PUT':
137
            case 'POST':
138
                    $updateDataFormat = [
139
                        'json' => $data,
140
                        'form_params' => $data
141
                    ];
142
                break;
143
            default:
144
                $updateDataFormat = [];
145
                break;
146
        }
147
148
        return $updateDataFormat;
149
    }
150
}
151