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

Company::apiUpdateList()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 5.0406

Importance

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