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

Company::apiList()   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\Exception;
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 Company
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 Company extends AbstractModel
25
{
26
    use 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
        'tags',
40
        'modified_user_id',
41
    ];
42
43
    /**
44
     * Список компаний
45
     *
46
     * Метод для получения списка компаний с возможностью фильтрации и постраничной выборки.
47
     * Ограничение по возвращаемым на одной странице (offset) данным - 500 компаний.
48
     *
49
     * @link https://developers.amocrm.ru/rest_api/company_list.php
50
     * @param array $parameters Массив параметров к amoCRM API
51
     * @param null|string $modified Дополнительная фильтрация по (изменено с)
52
     * @return array Ответ amoCRM API
53
     */
54 1
    public function apiList($parameters, $modified = null)
55
    {
56 1
        $response = $this->getRequest('/private/api/v2/json/company/list', $parameters, $modified);
57
58 1
        return isset($response['contacts']) ? $response['contacts'] : [];
59
    }
60
61
    /**
62
     * Добавление компаний
63
     *
64
     * Метод позволяет добавлять компании по одной или пакетно
65
     *
66
     * @link https://developers.amocrm.ru/rest_api/company_set.php
67
     * @param array $companies Массив компаний для пакетного добавления
68
     * @return int|array Уникальный идентификатор компании или массив при пакетном добавлении
69
     */
70 1
    public function apiAdd($companies = [])
71
    {
72 1
        if (empty($companies)) {
73 1
            $companies = [$this];
74 1
        }
75
76
        $parameters = [
77
            'contacts' => [
78 1
                'add' => [],
79 1
            ],
80 1
        ];
81
82 1
        foreach ($companies AS $company) {
83 1
            $parameters['contacts']['add'][] = $company->getValues();
84 1
        }
85
86 1
        $response = $this->postRequest('/private/api/v2/json/company/set', $parameters);
87
88 1
        if (isset($response['contacts']['add'])) {
89 1
            $result = array_map(function($item) {
90 1
				if(!empty($item['id']))
91 1
					return $item['id'];
92
				elseif(!empty($item['error']))
93
					throw new Exception($item['error'],filter_var(mb_strstr($item['error'],".",true), FILTER_SANITIZE_NUMBER_INT));
94
				else
95
					return [];
96 1
            }, $response['contacts']['add']);
97 1
        } else {
98
            return [];
99
        }
100
101 1
        return count($companies) == 1 ? array_shift($result) : $result;
102
    }
103
104
    /**
105
     * Обновление компаний
106
     *
107
     * Метод позволяет обновлять данные по уже существующим компаниям
108
     *
109
     * @link https://developers.amocrm.ru/rest_api/company_set.php
110
     * @param int $id Уникальный идентификатор компании
111
     * @param string $modified Дата последнего изменения данной сущности
112
     * @return bool Флаг успешности выполнения запроса
113
     * @throws \AmoCRM\Exception
114
     */
115 2
    public function apiUpdate($id, $modified = 'now')
116
    {
117 2
        $this->checkId($id);
118
119
        $parameters = [
120
            'contacts' => [
121 1
                'update' => [],
122 1
            ],
123 1
        ];
124
125 1
        $company = $this->getValues();
126 1
        $company['id'] = $id;
127 1
        $company['last_modified'] = strtotime($modified);
128
129 1
        $parameters['contacts']['update'][] = $company;
130
131 1
        $response = $this->postRequest('/private/api/v2/json/company/set', $parameters);
132
133 1
        return empty($response['contacts']['update']['errors']);
134
    }
135
}
136