Completed
Push — master ( e5b10a...ef7318 )
by dotzero
02:34 queued 01:01
created

Contact::setTags()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
ccs 6
cts 6
cp 1
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
crap 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://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
        $parameters = [
118
            'contacts' => [
119 1
                'update' => [],
120 1
            ],
121 1
        ];
122
123 1
        $contact = $this->getValues();
124 1
        $contact['id'] = $id;
125 1
        $contact['last_modified'] = strtotime($modified);
126
127 1
        $parameters['contacts']['update'][] = $contact;
128
129 1
        $response = $this->postRequest('/private/api/v2/json/contacts/set', $parameters);
130
131 1
        return empty($response['contacts']['update']['errors']);
132
    }
133
134
    /**
135
     * Связи между сделками и контактами
136
     *
137
     * Метод для получения списка связей между сделками и контактами
138
     *
139
     * @link https://developers.amocrm.ru/rest_api/contacts_links.php
140
     * @param array $parameters Массив параметров к amoCRM API
141
     * @param null|string $modified Дополнительная фильтрация по (изменено с)
142
     * @return array Ответ amoCRM API
143
     */
144 1
    public function apiLinks($parameters, $modified = null)
145
    {
146 1
        $response = $this->getRequest('/private/api/v2/json/contacts/links', $parameters, $modified);
147
148 1
        return isset($response['links']) ? $response['links'] : [];
149
    }
150
}
151