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

Company::apiAdd()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 33
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 7.2944

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 33
ccs 18
cts 22
cp 0.8182
rs 6.7272
cc 7
eloc 21
nc 12
nop 1
crap 7.2944
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
				if(!empty($item['id']))
90 1
					return $item['id'];
91
				elseif(!empty($item['error']))
92
					throw new Exception($item['error'],filter_var(mb_strstr($item['error'],".",true), FILTER_SANITIZE_NUMBER_INT));
93
				else
94
					return [];
95 1
            }, $response['contacts']['add']);
96 1
        } else {
97
            return [];
98
        }
99
100 1
        return count($companies) == 1 ? array_shift($result) : $result;
101
    }
102
103
    /**
104
     * Обновление компаний
105
     *
106
     * Метод позволяет обновлять данные по уже существующим компаниям
107
     *
108
     * @link https://developers.amocrm.ru/rest_api/company_set.php
109
     * @param int $id Уникальный идентификатор компании
110
     * @param string $modified Дата последнего изменения данной сущности
111
     * @return bool Флаг успешности выполнения запроса
112
     * @throws \AmoCRM\Exception
113
     */
114 2
    public function apiUpdate($id, $modified = 'now')
115
    {
116 2
        $this->checkId($id);
117
118
        $parameters = [
119
            'contacts' => [
120 1
                'update' => [],
121 1
            ],
122 1
        ];
123
124 1
        $company = $this->getValues();
125 1
        $company['id'] = $id;
126 1
        $company['last_modified'] = strtotime($modified);
127
128 1
        $parameters['contacts']['update'][] = $company;
129
130 1
        $response = $this->postRequest('/private/api/v2/json/company/set', $parameters);
131
132 1
        return empty($response['contacts']['update']['errors']);
133
    }
134
}
135