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

Webhooks::formatData()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 2
dl 0
loc 23
rs 9.552
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
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
            /**
48
             * @todo move the guzzle reqeust to Async for faster performance
49
             */
50
            $clientRequest = $client->request(
51
                $userWebhook->method,
52
                $userWebhook->url,
53
                self::formatData($userWebhook->method, $data)
54
            );
55
56
            $responseContent = $clientRequest->getBody()->getContents();
57
            $response = isJson($responseContent) ? json_decode($responseContent, true) : $responseContent;
58
        } catch (Throwable $error) {
59
            $response = $error->getMessage();
60
        }
61
62
        return $response;
63
    }
64
65
    /**
66
     * Execute the the webhook for the given app company providing the system module
67
     * for the SDK
68
     *  - pass the system module classname or classname\namespace
69
     *  - pass the action you are doing from the CRUD
70
     *  - get all the hooks from the user that match this action
71
     *  - pass the data you are sending
72
     *  - then we send it over to the URl.
73
     *
74
     * @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...
75
     * @param mixed $data
76
     * @param string $action
77
     * @throws Exception
78
     * @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...
79
     */
80
    public static function process(string $module, array $data, string $action): array
81
    {
82
        $appId = Di::getDefault()->getApp()->getId();
83
        $company = Di::getDefault()->getUserData()->getDefaultCompany();
84
85
        $systemModule = SystemModules::getByName($module);
86
87
        $webhooks = UserWebhooks::find([
88
            'conditions' => 'apps_id = ?0 AND companies_id = ?1 
89
                            AND webhooks_id in 
90
                                (SELECT Canvas\Models\Webhooks.id FROM Canvas\Models\Webhooks 
91
                                    WHERE Canvas\Models\Webhooks.apps_id = ?0 
92
                                    AND Canvas\Models\Webhooks.system_modules_id = ?2 
93
                                    AND Canvas\Models\Webhooks.action = ?3
94
                                )',
95
            'bind' => [
96
                $appId,
97
                $company->getId(),
98
                $systemModule->getId(),
99
                $action
100
            ]
101
        ]);
102
103
        $results = [];
104
105
        if ($webhooks->count()) {
106
            foreach ($webhooks as $userWebhook) {
107
                $results[$userWebhook->webhook->name][$action][] = [
108
                    $userWebhook->url => [
109
                        'results' => self::run($userWebhook->getId(), $data),
110
                    ]
111
                ];
112
            }
113
114
            return $results;
115
        }
116
117
        return [
118
            'message' => 'No user configure webhooks found for : ',
119
            'module' => $module,
120
            'data' => $data,
121
            'action' => $action
122
        ];
123
    }
124
125
    /**
126
     * Format the data for guzzle correct usage
127
     *
128
     * @return array
129
     */
130
    public static function formatData(string $method, array $data): array
131
    {
132
        switch (ucwords($method)) {
133
            case 'GET':
134
                $updateDataFormat = [
135
                    'query' => $data
136
                ];
137
                break;
138
139
            case 'PUT':
140
            case 'POST':
141
                    $updateDataFormat = [
142
                        'json' => $data,
143
                        'form_params' => $data
144
                    ];
145
                break;
146
            default:
147
                $updateDataFormat = [];
148
                break;
149
        }
150
151
        return $updateDataFormat;
152
    }
153
}
154