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

Lead   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 117
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 88.89%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 6
dl 0
loc 117
ccs 32
cts 36
cp 0.8889
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A apiList() 0 6 2
B apiAdd() 0 33 7
A apiUpdate() 0 20 1
1
<?php
2
3
namespace AmoCRM\Models;
4
5
use AmoCRM\Exception;
6
use AmoCRM\Models\Traits\SetNote;
7
use AmoCRM\Models\Traits\SetTags;
8
use AmoCRM\Models\Traits\SetDateCreate;
9
use AmoCRM\Models\Traits\SetLastModified;
10
11
/**
12
 * Class Lead
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 Lead extends AbstractModel
25
{
26
    use SetNote, SetTags, SetDateCreate, SetLastModified;
27
28
    /**
29
     * @var array Список доступный полей для модели (исключая кастомные поля)
30
     */
31
    protected $fields = [
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
				if(!empty($item['id']))
96 1
					return $item['id'];
97
				elseif(!empty($item['error']))
98
					throw new Exception($item['error'],filter_var(mb_strstr($item['error'],".",true), FILTER_SANITIZE_NUMBER_INT));
99
				else
100
					return [];
101 1
            }, $response['leads']['add']);
102 1
        } else {
103
            return [];
104
        }
105
106 1
        return count($leads) == 1 ? array_shift($result) : $result;
107
    }
108
109
    /**
110
     * Обновление сделки
111
     *
112
     * Метод позволяет обновлять данные по уже существующим сделкам
113
     *
114
     * @link https://developers.amocrm.ru/rest_api/leads_set.php
115
     * @param int $id Уникальный идентификатор сделки
116
     * @param string $modified Дата последнего изменения данной сущности
117
     * @return bool Флаг успешности выполнения запроса
118
     * @throws \AmoCRM\Exception
119
     */
120 1
    public function apiUpdate($id, $modified = 'now')
121
    {
122 1
        $this->checkId($id);
123
124
        $parameters = [
125
            'leads' => [
126 1
                'update' => [],
127 1
            ],
128 1
        ];
129
130 1
        $lead = $this->getValues();
131 1
        $lead['id'] = $id;
132 1
        $lead['last_modified'] = strtotime($modified);
133
134 1
        $parameters['leads']['update'][] = $lead;
135
136 1
        $response = $this->postRequest('/private/api/v2/json/leads/set', $parameters);
137
138 1
        return empty($response['leads']['update']['errors']);
139
    }
140
}
141