Completed
Push — master ( f188dd...b917d8 )
by dotzero
02:17
created

WebHooks   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 122
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 81.82%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 1
dl 0
loc 122
ccs 27
cts 33
cp 0.8182
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A apiList() 0 6 2
B apiSubscribe() 0 27 4
B apiUnsubscribe() 0 27 4
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
    public $events = [
24
        'add_lead', // Добавить сделку
25
        'add_contact', // Добавить контакт
26
        'add_company', // Добавить компанию
27
        'add_customer', // Добавить покупателя
28
        'update_lead', // Изменить сделку
29
        'update_contact', // Изменить контакт
30
        'update_company', // Изменить компанию
31
        'update_customer', // Изменить покупателя
32
        'delete_lead', // Удалить сделку
33
        'delete_contact', // Удалить контакт
34
        'delete_company', // Удалить компанию
35
        'delete_customer', // Удалить покупателя
36
        'status_lead', // Смена статуса сделки
37
        'responsible_lead', // Смена отв-го сделки
38
        'restore_contact', // Восстановить контакт
39
        'restore_company', // Восстановить компанию
40
        'restore_lead', // Восстановить сделку
41
        'note_lead', // Примечание в сделке
42
        'note_contact', // Примечание в контакте
43
        'note_company', // Примечание в компании
44
        'note_customer', // Примечание в покупателе
45
    ];
46
47
    /**
48
     * Список WebHooks
49
     *
50
     * Метод для получения списка WebHooks.
51
     *
52
     * @link https://developers.amocrm.ru/rest_api/webhooks/list.php
53
     * @return array Ответ amoCRM API
54
     */
55 1
    public function apiList()
56
    {
57 1
        $response = $this->getRequest('/private/api/v2/json/webhooks/list');
58
59 1
        return isset($response['webhooks']) ? $response['webhooks'] : [];
60
    }
61
62
    /**
63
     * Добавление WebHooks
64
     *
65
     * Метод для добавления WebHooks.
66
     *
67
     * @link https://developers.amocrm.ru/rest_api/webhooks/subscribe.php
68
     * @param string $url URL на который необходимо присылать уведомления, должен соответствоать стандарту RFC 2396
69
     * @param string|array $events Список событий, при которых должны отправляться WebHooks
70
     * @return array Ответ amoCRM API
71
     * @throws \AmoCRM\Exception
72
     */
73 2
    public function apiSubscribe($url, $events = [])
74
    {
75 2
        if (!is_array($events)) {
76 1
            $events = [$events];
77 2
        } elseif (empty($events)) {
78
            $events = $this->events;
79
        }
80
81
        $parameters = [
82
            'webhooks' => [
83
                'subscribe' => [
84
                    [
85 2
                        'url' => $url,
86 2
                        'events' => $events,
87
                    ]
88 2
                ],
89 2
            ],
90 2
        ];
91
92 2
        $response = $this->postRequest('/private/api/v2/json/webhooks/subscribe', $parameters);
93
94 2
        if (isset($response['webhooks']['subscribe'][0]['result'])) {
95 2
            return $response['webhooks']['subscribe'][0]['result'];
96
        }
97
98
        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...
99
    }
100
101
    /**
102
     * Удаления WebHooks
103
     *
104
     * Метод для удаления WebHooks.
105
     *
106
     * @link https://developers.amocrm.ru/rest_api/webhooks/unsubscribe.php
107
     * @param string $url URL на который необходимо присылать уведомления, должен соответствоать стандарту RFC 2396
108
     * @param string|array $events Список событий, от которых необходимо отписать WebHook
109
     * @return array Ответ amoCRM API
110
     * @throws \AmoCRM\Exception
111
     */
112 2
    public function apiUnsubscribe($url, $events = [])
113
    {
114 2
        if (!is_array($events)) {
115 1
            $events = [$events];
116 2
        } elseif (empty($events)) {
117
            $events = $this->events;
118
        }
119
120
        $parameters = [
121
            'webhooks' => [
122
                'unsubscribe' => [
123
                    [
124 2
                        'url' => $url,
125 2
                        'events' => $events,
126
                    ]
127 2
                ],
128 2
            ],
129 2
        ];
130
131 2
        $response = $this->postRequest('/private/api/v2/json/webhooks/unsubscribe', $parameters);
132
133 2
        if (isset($response['webhooks']['unsubscribe'][0]['result'])) {
134 2
            return $response['webhooks']['unsubscribe'][0]['result'];
135
        }
136
137
        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...
138
    }
139
}