Completed
Push — master ( dc5034...dd736e )
by dotzero
02:29
created

Lead   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 129
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 1

Test Coverage

Coverage 97.37%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 11
c 3
b 0
f 1
lcom 2
cbo 1
dl 0
loc 129
ccs 37
cts 38
cp 0.9737
rs 10

5 Methods

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