Completed
Pull Request — master (#75)
by
unknown
02:52
created

Contact::apiLinks()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
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
		'id',
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
                return $item['id'];
95 1
            }, $response['contacts']['add']);
96 1
        } else {
97
            return [];
98
        }
99
100 1
        return count($contacts) == 1 ? array_shift($result) : $result;
101
    }
102
103
    /**
104
     * Обновление контактов
105
     *
106
     * Метод позволяет обновлять данные по уже существующим контактам
107
     *
108
     * @link https://developers.amocrm.ru/rest_api/contacts_set.php
109
     * @param int $contacts Массив с данными для обновления
110
     * @param string $modified Дата последнего изменения данной сущности
111
     * @return bool Флаг успешности выполнения запроса
112
     * @throws \AmoCRM\Exception
113
     */
114 1
    public function apiUpdate($contacts = [], $modified = 'now')
115
    {
116 1
        if (empty($contacts)) {
117
            $contacts = [$contacts];
118
        }
119
120
        $parameters = [
121
            'contacts' => [
122 1
                'update' => [],
123 1
            ],
124 1
        ];
125
126 1
        foreach ($contacts as $key => $contact) {
0 ignored issues
show
Bug introduced by
The expression $contacts of type integer|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
127
            $parameters['contacts']['update'][$key] = $contact->getValues();
128
            $parameters['contacts']['update'][$key]['last_modified'] = strtotime($modified);
129
        }
130
131
        $response = $this->postRequest('/private/api/v2/json/contacts/set', $parameters);
132
133
        return empty($response['contacts']['update']['errors']);
134
    }
135
136
    /**
137
     * Связи между сделками и контактами
138
     *
139
     * Метод для получения списка связей между сделками и контактами
140
     *
141
     * @link https://developers.amocrm.ru/rest_api/contacts_links.php
142
     * @param array $parameters Массив параметров к amoCRM API
143
     * @param null|string $modified Дополнительная фильтрация по (изменено с)
144
     * @return array Ответ amoCRM API
145
     */
146 1
    public function apiLinks($parameters, $modified = null)
147
    {
148 1
        $response = $this->getRequest('/private/api/v2/json/contacts/links', $parameters, $modified);
149
150 1
        return isset($response['links']) ? $response['links'] : [];
151
    }
152
}
153