Completed
Push — master ( b917d8...537358 )
by dotzero
01:54
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 Base
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 Ответ 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;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by AmoCRM\Models\WebHooks::apiSubscribe of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
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 Ответ 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;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by AmoCRM\Models\WebHooks::apiUnsubscribe of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
169
    }
170
}