Completed
Push — master ( e5b10a...ef7318 )
by dotzero
02:34 queued 01:01
created

Company::setDateCreate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
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
        $parameters = [
114
            'contacts' => [
115 1
                'update' => [],
116 1
            ],
117 1
        ];
118
119 1
        $company = $this->getValues();
120 1
        $company['id'] = $id;
121 1
        $company['last_modified'] = strtotime($modified);
122
123 1
        $parameters['contacts']['update'][] = $company;
124
125 1
        $response = $this->postRequest('/private/api/v2/json/company/set', $parameters);
126
127 1
        return empty($response['contacts']['update']['errors']);
128
    }
129
}
130