Failed Conditions
Pull Request — master (#284)
by Maximo
02:56
created

Webhooks::run()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 5
nop 3
dl 0
loc 35
rs 9.36
c 0
b 0
f 0
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
use Canvas\Http\Exception\UnprocessableEntityException;
15
16
/**
17
 * Class Validation.
18
 *
19
 * @package Canvas
20
 */
21
class Webhooks
22
{
23
    /**
24
    * Given the weebhook id, we run a test for it.
25
    *
26
    * @param integer $id
27
    * @param mixed $data
28
    * @return Response
29
    */
30
    public static function run(int $id, array $data, array $headers = [])
31
    {
32
        /**
33
         * 1- verify it s acorrect url
34
         * 2- verify the method
35
         * 3- get the entity info from one entity of this app and company
36
         * 4- guzzle the request with the info
37
         * 5- verify you got a 200
38
         * 6- return the response from the webhook.
39
         *
40
         * later - add job for all system module to execute a queue when CRUD acction are run, maybe the middleware would do this?
41
         *
42
         */
43
        $userWebhook = UserWebhooks::getById($id);
44
45
        $client = new Client();
46
47
        try {
48
            /**
49
             * @todo move the guzzle reqeust to Async for faster performance
50
             */
51
            $clientRequest = $client->request(
52
                $userWebhook->method,
53
                $userWebhook->url,
54
                self::formatData($userWebhook->method, $data, $headers)
55
            );
56
57
            $responseContent = $clientRequest->getBody()->getContents();
58
            $response = isJson($responseContent) ? json_decode($responseContent, true) : $responseContent;
59
        } catch (Throwable $error) {
60
            $response = $error->getMessage();
61
        }
62
63
        return $response;
64
    }
65
66
    /**
67
     * Execute the the webhook for the given app company providing the system module
68
     * for the SDK
69
     *  - pass the system module classname or classname\namespace
70
     *  - pass the action you are doing from the CRUD
71
     *  - get all the hooks from the user that match this action
72
     *  - pass the data you are sending
73
     *  - then we send it over to the URl.
74
     *
75
     * @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...
76
     * @param mixed $data
77
     * @param string $action
78
     * @throws Exception
79
     * @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...
80
     */
81
    public static function process(string $module, array $data, string $action, array $headers = []): array
82
    {
83
        $appId = Di::getDefault()->getApp()->getId();
84
        $company = Di::getDefault()->getUserData()->getDefaultCompany();
85
86
        $systemModule = SystemModules::getByName($module);
87
88
        $webhooks = UserWebhooks::find([
89
            'conditions' => 'apps_id = ?0 AND companies_id = ?1 
90
                            AND webhooks_id in 
91
                                (SELECT Canvas\Models\Webhooks.id FROM Canvas\Models\Webhooks 
92
                                    WHERE Canvas\Models\Webhooks.apps_id = ?0 
93
                                    AND Canvas\Models\Webhooks.system_modules_id = ?2 
94
                                    AND Canvas\Models\Webhooks.action = ?3
95
                                )',
96
            'bind' => [
97
                $appId,
98
                $company->getId(),
99
                $systemModule->getId(),
100
                $action
101
            ]
102
        ]);
103
104
        $results = [];
105
106
        if ($webhooks->count()) {
107
            foreach ($webhooks as $userWebhook) {
108
                $results[$userWebhook->webhook->name][$action][] = [
109
                    $userWebhook->url => [
110
                        'results' => self::run($userWebhook->getId(), $data, $headers),
111
                    ]
112
                ];
113
            }
114
115
            return $results;
116
        }
117
118
        return [
119
            'message' => 'No user configure webhooks found for : ',
120
            'module' => $module,
121
            'data' => $data,
122
            'action' => $action
123
        ];
124
    }
125
126
    /**
127
     * Format the data for guzzle correct usage.
128
     *
129
     * @return array
130
     */
131
    public static function formatData(string $method, array $data, array $headers = []): array
132
    {
133
        switch (ucwords($method)) {
134
            case 'GET':
135
                $updateDataFormat = [
136
                    'query' => $data
137
                ];
138
                break;
139
140
            case 'PUT':
141
            case 'POST':
142
                    $updateDataFormat = [
143
                        'json' => $data,
144
                        'form_params' => $data
145
                    ];
146
                break;
147
            default:
148
                $updateDataFormat = [];
149
                break;
150
        }
151
152
        if (!empty($headers)) {
153
            $updateDataFormat['headers'] = $headers;
154
        }
155
156
        return $updateDataFormat;
157
    }
158
}
159