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

Company::apiUpdate()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.679

Importance

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