Completed
Push — master ( 1edc76...b79eb4 )
by dotzero
01:28
created

Webhooks::apiUnsubscribe()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 5.1158

Importance

Changes 0
Metric Value
dl 0
loc 29
ccs 15
cts 18
cp 0.8333
rs 8.439
c 0
b 0
f 0
cc 5
eloc 17
nc 8
nop 2
crap 5.1158
1
<?php
2
3
namespace AmoCRM\Models;
4
5
/**
6
 * Class Webhooks
7
 *
8
 * Класс модель для работы с Webhooks
9
 *
10
 * @package AmoCRM\Models
11
 * @author dotzero <[email protected]>
12
 * @link http://www.dotzero.ru/
13
 * @link https://github.com/dotzero/amocrm-php
14
 *
15
 * For the full copyright and license information, please view the LICENSE
16
 * file that was distributed with this source code.
17
 */
18
class Webhooks extends AbstractModel
19
{
20
    /**
21
     * @var array Список доступный полей для модели (исключая кастомные поля)
22
     */
23
    protected $fields = [
24
        'url',
25
        'events',
26
    ];
27
28
    /**
29
     * @var array Список всех доступных событий
30
     */
31
    public $events_list = [
32
        'add_lead', // Добавить сделку
33
        'add_contact', // Добавить контакт
34
        'add_company', // Добавить компанию
35
        'add_customer', // Добавить покупателя
36
        'update_lead', // Изменить сделку
37
        'update_contact', // Изменить контакт
38
        'update_company', // Изменить компанию
39
        'update_customer', // Изменить покупателя
40
        'delete_lead', // Удалить сделку
41
        'delete_contact', // Удалить контакт
42
        'delete_company', // Удалить компанию
43
        'delete_customer', // Удалить покупателя
44
        'status_lead', // Смена статуса сделки
45
        'responsible_lead', // Смена отв-го сделки
46
        'restore_contact', // Восстановить контакт
47
        'restore_company', // Восстановить компанию
48
        'restore_lead', // Восстановить сделку
49
        'note_lead', // Примечание в сделке
50
        'note_contact', // Примечание в контакте
51
        'note_company', // Примечание в компании
52
        'note_customer', // Примечание в покупателе
53
    ];
54
55
    /**
56
     * Сеттер для списка событий
57
     *
58
     * @param string|array $value Название события или массив событий
59
     * @return $this
60
     */
61 5
    public function setEvents($value)
62
    {
63 5
        if (empty($value)) {
64 1
            $value = $this->events_list;
65 5
        } elseif (!is_array($value)) {
66 3
            $value = [$value];
67 3
        }
68
69 5
        $this->values['events'] = $value;
70
71 5
        return $this;
72
    }
73
74
    /**
75
     * Список Webhooks
76
     *
77
     * Метод для получения списка Webhooks.
78
     *
79
     * @link https://developers.amocrm.ru/rest_api/webhooks/list.php
80
     * @return array Ответ amoCRM API
81
     */
82 1
    public function apiList()
83
    {
84 1
        $response = $this->getRequest('/private/api/v2/json/webhooks/list');
85
86 1
        return isset($response['webhooks']) ? $response['webhooks'] : [];
87
    }
88
89
    /**
90
     * Добавление Webhooks
91
     *
92
     * Метод для добавления Webhooks.
93
     *
94
     * @link https://developers.amocrm.ru/rest_api/webhooks/subscribe.php
95
     * @param null|string $url URL на который необходимо присылать уведомления, должен соответствовать стандарту RFC 2396
96
     * @param array|string $events Список событий, при которых должны отправляться Webhooks
97
     * @return array|false Ответ amoCRM API
98
     * @throws \AmoCRM\Exception
99
     */
100 3
    public function apiSubscribe($url = null, $events = [])
101
    {
102
        $parameters = [
103 3
            'url' => $url,
104 3
            'events' => $events,
105 3
        ];
106
107 3
        if ($url === null) {
108 1
            $parameters = $this->getValues();
109 3
        } elseif (!is_array($parameters['events'])) {
110 1
            $parameters['events'] = [$events];
111 2
        } elseif (empty($parameters['events'])) {
112
            $parameters['events'] = $this->events_list;
113
        }
114
115
        $parameters = [
116
            'webhooks' => [
117 3
                'subscribe' => [$parameters],
118 3
            ],
119 3
        ];
120
121 3
        $response = $this->postRequest('/private/api/v2/json/webhooks/subscribe', $parameters);
122
123 3
        if (isset($response['webhooks']['subscribe'][0]['result'])) {
124 3
            return $response['webhooks']['subscribe'][0]['result'];
125
        }
126
127
        return false;
128
    }
129
130
    /**
131
     * Удаления Webhooks
132
     *
133
     * Метод для удаления Webhooks.
134
     *
135
     * @link https://developers.amocrm.ru/rest_api/webhooks/unsubscribe.php
136
     * @param null|string $url URL на который необходимо присылать уведомления, должен соответствовать стандарту RFC 2396
137
     * @param array|string $events Список событий, от которых необходимо отписать WebHook
138
     * @return array|false Ответ amoCRM API
139
     * @throws \AmoCRM\Exception
140
     */
141 3
    public function apiUnsubscribe($url = null, $events = [])
142
    {
143
        $parameters = [
144 3
            'url' => $url,
145 3
            'events' => $events,
146 3
        ];
147
148 3
        if ($url === null) {
149 1
            $parameters = $this->getValues();
150 3
        } elseif (!is_array($parameters['events'])) {
151 1
            $parameters['events'] = [$events];
152 2
        } elseif (empty($parameters['events'])) {
153
            $parameters['events'] = $this->events_list;
154
        }
155
156
        $parameters = [
157
            'webhooks' => [
158 3
                'unsubscribe' => [$parameters],
159 3
            ],
160 3
        ];
161
162 3
        $response = $this->postRequest('/private/api/v2/json/webhooks/unsubscribe', $parameters);
163
164 3
        if (isset($response['webhooks']['unsubscribe'][0]['result'])) {
165 3
            return $response['webhooks']['unsubscribe'][0]['result'];
166
        }
167
168
        return false;
169
    }
170
}
171