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

Lead   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 114
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Test Coverage

Coverage 76.47%

Importance

Changes 0
Metric Value
wmc 10
lcom 0
cbo 5
dl 0
loc 114
ccs 26
cts 34
cp 0.7647
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A apiList() 0 6 2
A apiAdd() 0 28 5
A apiUpdate() 0 21 3
1
<?php
2
3
namespace AmoCRM\Models;
4
5
use AmoCRM\Models\Traits\SetNote;
6
use AmoCRM\Models\Traits\SetTags;
7
use AmoCRM\Models\Traits\SetDateCreate;
8
use AmoCRM\Models\Traits\SetLastModified;
9
10
/**
11
 * Class Lead
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 Lead extends AbstractModel
24
{
25
    use SetNote, SetTags, SetDateCreate, SetLastModified;
26
27
    /**
28
     * @var array Список доступный полей для модели (исключая кастомные поля)
29
     */
30
    protected $fields = [
31
        'id',
32
        'name',
33
        'date_create',
34
        'last_modified',
35
        'status_id',
36
        'pipeline_id',
37
        'price',
38
        'responsible_user_id',
39
        'created_user_id',
40
        'request_id',
41
        'linked_company_id',
42
        'tags',
43
        'visitor_uid',
44
        'notes',
45
        'modified_user_id',
46
    ];
47
48
    /**
49
     * Список сделок
50
     *
51
     * Метод для получения списка сделок с возможностью фильтрации и постраничной выборки.
52
     * Ограничение по возвращаемым на одной странице (offset) данным - 500 сделок
53
     *
54
     * @link https://developers.amocrm.ru/rest_api/leads_list.php
55
     * @param array $parameters Массив параметров к amoCRM API
56
     * @param null|string $modified Дополнительная фильтрация по (изменено с)
57
     * @return array Ответ amoCRM API
58
     */
59 1
    public function apiList($parameters, $modified = null)
60
    {
61 1
        $response = $this->getRequest('/private/api/v2/json/leads/list', $parameters, $modified);
62
63 1
        return isset($response['leads']) ? $response['leads'] : [];
64
    }
65
66
    /**
67
     * Добавление сделки
68
     *
69
     * Метод позволяет добавлять сделки по одной или пакетно
70
     *
71
     * @link https://developers.amocrm.ru/rest_api/leads_set.php
72
     * @param array $leads Массив сделок для пакетного добавления
73
     * @return int|array Уникальный идентификатор сделки или массив при пакетном добавлении
74
     */
75 1
    public function apiAdd($leads = [])
76
    {
77 1
        if (empty($leads)) {
78 1
            $leads = [$this];
79 1
        }
80
81
        $parameters = [
82
            'leads' => [
83 1
                'add' => [],
84 1
            ],
85 1
        ];
86
87 1
        foreach ($leads AS $lead) {
88 1
            $parameters['leads']['add'][] = $lead->getValues();
89 1
        }
90
91 1
        $response = $this->postRequest('/private/api/v2/json/leads/set', $parameters);
92
93 1
        if (isset($response['leads']['add'])) {
94 1
            $result = array_map(function($item) {
95 1
                return $item['id'];
96 1
            }, $response['leads']['add']);
97 1
        } else {
98
            return [];
99
        }
100
101 1
        return count($leads) == 1 ? array_shift($result) : $result;
102
    }
103
104
    /**
105
     * Обновление сделки
106
     *
107
     * Метод позволяет обновлять данные по уже существующим сделкам
108
     *
109
     * @link https://developers.amocrm.ru/rest_api/leads_set.php
110
     * @param int $leads Массив с данными для обновления
111
     * @param string $modified Дата последнего изменения данной сущности
112
     * @return bool Флаг успешности выполнения запроса
113
     * @throws \AmoCRM\Exception
114
     */
115 1
    public function apiUpdate($leads = [], $modified = 'now')
116
    {
117 1
        if (empty($leads)) {
118
            $leads = [$this];
119
        }
120
121
        $parameters = [
122
            'leads' => [
123 1
                'update' => [],
124 1
            ],
125 1
        ];
126
127 1
        foreach ($leads as $key => $lead) {
0 ignored issues
show
Bug introduced by
The expression $leads 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...
128
            $parameters['leads']['update'][$key] = $lead->getValues();
129
            $parameters['leads']['update'][$key]['last_modified'] = strtotime($modified);
130
        }
131
132
        $response = $this->postRequest('/private/api/v2/json/leads/set', $parameters);
133
134
        return empty($response['leads']['update']['errors']);
135
    }
136
}
137