Completed
Pull Request — master (#26)
by
unknown
02:20
created

Lead   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 153
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 1

Test Coverage

Coverage 95.65%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 14
c 3
b 0
f 0
lcom 2
cbo 1
dl 0
loc 153
ccs 44
cts 46
cp 0.9565
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A setDateCreate() 0 6 1
A setLastModified() 0 6 1
A setTags() 0 10 2
A apiList() 0 6 2
B apiAdd() 0 28 5
A apiUpdate() 0 23 3
1
<?php
2
3
namespace AmoCRM\Models;
4
5
/**
6
 * Class Lead
7
 *
8
 * Класс модель для работы со Сделками
9
 *
10
 * @package AmoCRM\Models
11
 * @author dotzero <[email protected]>
12
 * @link http://www.dotzero.ru/
13
 * @link https://github.com/dotzero/amocrm-php
14
 *
15
 * For the full copyright and license information, please view the LICENSE
16
 * file that was distributed with this source code.
17
 */
18
class Lead extends AbstractModel
19
{
20
    /**
21
     * @var array Список доступный полей для модели (исключая кастомные поля)
22
     */
23
    protected $fields = [
24
        'name',
25
        'date_create',
26
        'last_modified',
27
        'status_id',
28
        'pipeline_id',
29
        'price',
30
        'responsible_user_id',
31
        'request_id',
32
        'linked_company_id',
33
        'tags',
34
        'visitor_uid',
35
    ];
36
37
    /**
38
     * Сеттер для даты создания сделки
39
     *
40
     * @param string $date Дата в произвольном формате
41
     * @return $this
42
     */
43 1
    public function setDateCreate($date)
44
    {
45 1
        $this->values['date_create'] = strtotime($date);
46
47 1
        return $this;
48
    }
49
50
    /**
51
     * Сеттер для даты последнего изменения сделки
52
     *
53
     * @param string $date Дата в произвольном формате
54
     * @return $this
55
     */
56 1
    public function setLastModified($date)
57
    {
58 1
        $this->values['last_modified'] = strtotime($date);
59
60 1
        return $this;
61
    }
62
63
    /**
64
     * Сеттер для списка тегов сделки
65
     *
66
     * @param int|array $value Название тегов через запятую или массив тегов
67
     * @return $this
68
     */
69 2
    public function setTags($value)
70
    {
71 2
        if (!is_array($value)) {
72 1
            $value = [$value];
73 1
        }
74
75 2
        $this->values['tags'] = implode(',', $value);
76
77 2
        return $this;
78
    }
79
80
    /**
81
     * Список сделок
82
     *
83
     * Метод для получения списка сделок с возможностью фильтрации и постраничной выборки.
84
     * Ограничение по возвращаемым на одной странице (offset) данным - 500 сделок
85
     *
86
     * @link https://developers.amocrm.ru/rest_api/leads_list.php
87
     * @param array $parameters Массив параметров к amoCRM API
88
     * @param null|string $modified Дополнительная фильтрация по (изменено с)
89
     * @return array Ответ amoCRM API
90
     */
91 1
    public function apiList($parameters, $modified = null)
92
    {
93 1
        $response = $this->getRequest('/private/api/v2/json/leads/list', $parameters, $modified);
94
95 1
        return isset($response['leads']) ? $response['leads'] : [];
96
    }
97
98
    /**
99
     * Добавление сделки
100
     *
101
     * Метод позволяет добавлять сделки по одной или пакетно
102
     *
103
     * @link https://developers.amocrm.ru/rest_api/leads_set.php
104
     * @param array $leads Массив сделок для пакетного добавления
105
     * @return int|array Уникальный идентификатор сделки или массив при пакетном добавлении
106
     */
107 1
    public function apiAdd($leads = [])
108
    {
109 1
        if (empty($leads)) {
110 1
            $leads = [$this];
111 1
        }
112
113
        $parameters = [
114
            'leads' => [
115 1
                'add' => [],
116 1
            ],
117 1
        ];
118
119 1
        foreach ($leads AS $lead) {
120 1
            $parameters['leads']['add'][] = $lead->getValues();
121 1
        }
122
123 1
        $response = $this->postRequest('/private/api/v2/json/leads/set', $parameters);
124
125 1
        if (isset($response['leads']['add'])) {
126 1
            $result = array_map(function($item) {
127 1
                return $item['id'];
128 1
            }, $response['leads']['add']);
129 1
        } else {
130
            return [];
131
        }
132
133 1
        return count($leads) == 1 ? array_shift($result) : $result;
134
    }
135
136
    /**
137
     * Обновление сделки
138
     *
139
     * Метод позволяет обновлять данные по уже существующим сделкам
140
     *
141
     * @link https://developers.amocrm.ru/rest_api/leads_set.php
142
     * @param int $id Уникальный идентификатор сделки
143
     * @param string $modified Дата последнего изменения данной сущности
144
     * @return bool Флаг успешности выполнения запроса
145
     * @throws \AmoCRM\Exception
146
     */
147 1
    public function apiUpdate($id, $modified = 'now')
148
    {
149 1
        $this->checkId($id);
150
151
        $parameters = [
152
            'leads' => [
153 1
                'update' => [],
154 1
            ],
155 1
        ];
156
157 1
        $lead = $this->getValues();
158 1
        $lead['id'] = $id;
159 1
        $lead['last_modified'] = strtotime($modified);
160
161 1
        $parameters['leads']['update'][] = $lead;
162
163 1
        $response = $this->postRequest('/private/api/v2/json/leads/set', $parameters);
164 1
        if (isset($response['leads']['update']['errors'][$id])) {
165
            throw new Exception($response['leads']['update']['errors'][$id]);
166
        }
167
168 1
        return isset($response['leads']['update']['id']) ? true : false;
169
    }
170
}
171