Completed
Pull Request — master (#89)
by
unknown
17:39
created

Contact   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 155
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 93.62%

Importance

Changes 0
Metric Value
wmc 15
lcom 1
cbo 6
dl 0
loc 155
ccs 44
cts 47
cp 0.9362
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A apiList() 0 6 2
A apiAdd() 0 28 5
A apiUpdate() 0 10 1
A apiUpdateList() 0 26 5
A apiLinks() 0 6 2
1
<?php
2
3
namespace AmoCRM\Models;
4
5
use AmoCRM\Models\Traits\SetNote;
6
use AmoCRM\Models\Traits\SetTags;
7
use AmoCRM\Models\Traits\SetDateCreate;
8
use AmoCRM\Models\Traits\SetLastModified;
9
use AmoCRM\Models\Traits\SetLinkedLeadsId;
10
11
/**
12
 * Class Contact
13
 *
14
 * Класс модель для работы с Контактами
15
 *
16
 * @package AmoCRM\Models
17
 * @author dotzero <[email protected]>
18
 * @link http://www.dotzero.ru/
19
 * @link https://github.com/dotzero/amocrm-php
20
 *
21
 * For the full copyright and license information, please view the LICENSE
22
 * file that was distributed with this source code.
23
 */
24
class Contact extends AbstractModel
25
{
26
    use SetNote, SetTags, SetDateCreate, SetLastModified, SetLinkedLeadsId;
27
28
    /**
29
     * @var array Список доступный полей для модели (исключая кастомные поля)
30
     */
31
    protected $fields = [
32
        'name',
33
        'request_id',
34
        'date_create',
35
        'last_modified',
36
        'responsible_user_id',
37
        'created_user_id',
38
        'linked_leads_id',
39
        'company_name',
40
        'linked_company_id',
41
        'tags',
42
        'notes',
43
        'modified_user_id',
44
    ];
45
46
    /**
47
     * Список контактов
48
     *
49
     * Метод для получения списка контактов с возможностью фильтрации и постраничной выборки.
50
     * Ограничение по возвращаемым на одной странице (offset) данным - 500 контактов.
51
     *
52
     * @link https://developers.amocrm.ru/rest_api/contacts_list.php
53
     * @param array $parameters Массив параметров к amoCRM API
54
     * @param null|string $modified Дополнительная фильтрация по (изменено с)
55
     * @return array Ответ amoCRM API
56
     */
57 1
    public function apiList($parameters, $modified = null)
58
    {
59 1
        $response = $this->getRequest('/private/api/v2/json/contacts/list', $parameters, $modified);
60
61 1
        return isset($response['contacts']) ? $response['contacts'] : [];
62
    }
63
64
    /**
65
     * Добавление контактов
66
     *
67
     * Метод позволяет добавлять контакты по одному или пакетно
68
     *
69
     * @link https://developers.amocrm.ru/rest_api/contacts_set.php
70
     * @param array $contacts Массив контактов для пакетного добавления
71
     * @return int|array Уникальный идентификатор контакта или массив при пакетном добавлении
72
     */
73 1
    public function apiAdd($contacts = [])
74
    {
75 1
        if (empty($contacts)) {
76 1
            $contacts = [$this];
77 1
        }
78
79
        $parameters = [
80
            'contacts' => [
81 1
                'add' => [],
82 1
            ],
83 1
        ];
84
85 1
        foreach ($contacts AS $contact) {
86 1
            $parameters['contacts']['add'][] = $contact->getValues();
87 1
        }
88
89 1
        $response = $this->postRequest('/private/api/v2/json/contacts/set', $parameters);
90
91 1
        if (isset($response['contacts']['add'])) {
92 1
            $result = array_map(function ($item) {
93 1
                return $item['id'];
94 1
            }, $response['contacts']['add']);
95 1
        } else {
96
            return [];
97
        }
98
99 1
        return count($contacts) == 1 ? array_shift($result) : $result;
100
    }
101
102
    /**
103
     * Обновление контактов
104
     *
105
     * Метод позволяет обновлять данные по уже существующим контактам
106
     *
107
     * @link https://web.archive.org/web/20140903111912/https://developers.amocrm.ru/rest_api/contacts_set.php
108
     * @param int $id Уникальный идентификатор контакта
109
     * @param string $modified Дата последнего изменения данной сущности
110
     * @return bool Флаг успешности выполнения запроса
111
     * @throws \AmoCRM\Exception
112
     */
113 1
    public function apiUpdate($id, $modified = 'now')
114
    {
115 1
        $this->checkId($id);
116
117 1
        $contact = $this->getValues();
118 1
        $contact['id'] = $id;
119 1
        $contact['last_modified'] = strtotime($modified);
120
121 1
        return $this->apiUpdateList([$contact]);
122
    }
123
124
    /**
125
     * Пакетное обновление контактов
126
     *
127
     * @link https://web.archive.org/web/20140903111912/https://developers.amocrm.ru/rest_api/contacts_set.php
128
     * @param \AmoCRM\Models\Contact[]|array[] $contacts массив контактов для обновления
129
     * @param string $modified
130
     * @return bool
131
     * @throws \AmoCRM\Exception
132
     * @throws \AmoCRM\NetworkException
133
     */
134 1
    public function apiUpdateList($contacts = [], $modified = 'now')
135
    {
136
        $parameters = [
137
            'contacts' => [
138 1
                'update' => [],
139 1
            ],
140 1
        ];
141
142
        /** @var \AmoCRM\Models\Contact|array $contact */
143 1
        foreach ($contacts as $contact) {
144 1
            if ($contact instanceof Contact) {
145
                $contact = $contact->getValues();
146
            }
147 1
            $contact['id'] = isset($contact['id']) ? $contact['id'] : null;
148 1
            $contact['last_modified'] = isset($contact['last_modified'])
149 1
                ? $contact['last_modified']
150 1
                : strtotime($modified);
151
152 1
            $this->checkId($contact['id']);
153 1
            $parameters['contacts']['update'][] = $contact;
154 1
        }
155
156 1
        $response = $this->postRequest('/private/api/v2/json/contacts/set', $parameters);
157
158 1
        return empty($response['contacts']['update']['errors']);
159
    }
160
161
162
    /**
163
     * Связи между сделками и контактами
164
     *
165
     * Метод для получения списка связей между сделками и контактами
166
     *
167
     * @link https://developers.amocrm.ru/rest_api/contacts_links.php
168
     * @param array $parameters Массив параметров к amoCRM API
169
     * @param null|string $modified Дополнительная фильтрация по (изменено с)
170
     * @return array Ответ amoCRM API
171
     */
172 1
    public function apiLinks($parameters, $modified = null)
173
    {
174 1
        $response = $this->getRequest('/private/api/v2/json/contacts/links', $parameters, $modified);
175
176 1
        return isset($response['links']) ? $response['links'] : [];
177
    }
178
}
179