Completed
Pull Request — master (#72)
by
unknown
04:20
created

Contact   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 132
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 89.74%

Importance

Changes 0
Metric Value
wmc 12
c 0
b 0
f 0
lcom 1
cbo 6
dl 0
loc 132
ccs 35
cts 39
cp 0.8974
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A apiList() 0 6 2
C apiAdd() 0 33 7
A apiUpdate() 0 20 1
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
				if(!empty($item['id']))
94 1
					return $item['id'];
95
				elseif(!empty($item['error']))
96
					throw new Exception($item['error'],filter_var(mb_strstr($item['error'],".",true), FILTER_SANITIZE_NUMBER_INT));
97
				else
98
					return [];
99 1
            }, $response['contacts']['add']);
100 1
        } else {
101
            return [];
102
        }
103
104 1
        return count($contacts) == 1 ? array_shift($result) : $result;
105
    }
106
107
    /**
108
     * Обновление контактов
109
     *
110
     * Метод позволяет обновлять данные по уже существующим контактам
111
     *
112
     * @link https://developers.amocrm.ru/rest_api/contacts_set.php
113
     * @param int $id Уникальный идентификатор контакта
114
     * @param string $modified Дата последнего изменения данной сущности
115
     * @return bool Флаг успешности выполнения запроса
116
     * @throws \AmoCRM\Exception
117
     */
118 1
    public function apiUpdate($id, $modified = 'now')
119
    {
120 1
        $this->checkId($id);
121
122
        $parameters = [
123
            'contacts' => [
124 1
                'update' => [],
125 1
            ],
126 1
        ];
127
128 1
        $contact = $this->getValues();
129 1
        $contact['id'] = $id;
130 1
        $contact['last_modified'] = strtotime($modified);
131
132 1
        $parameters['contacts']['update'][] = $contact;
133
134 1
        $response = $this->postRequest('/private/api/v2/json/contacts/set', $parameters);
135
136 1
        return empty($response['contacts']['update']['errors']);
137
    }
138
139
    /**
140
     * Связи между сделками и контактами
141
     *
142
     * Метод для получения списка связей между сделками и контактами
143
     *
144
     * @link https://developers.amocrm.ru/rest_api/contacts_links.php
145
     * @param array $parameters Массив параметров к amoCRM API
146
     * @param null|string $modified Дополнительная фильтрация по (изменено с)
147
     * @return array Ответ amoCRM API
148
     */
149 1
    public function apiLinks($parameters, $modified = null)
150
    {
151 1
        $response = $this->getRequest('/private/api/v2/json/contacts/links', $parameters, $modified);
152
153 1
        return isset($response['links']) ? $response['links'] : [];
154
    }
155
}
156