Completed
Pull Request — master (#72)
by
unknown
02:19
created

Contact::apiAdd()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 7.2944

Importance

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