Completed
Pull Request — master (#72)
by
unknown
04:20
created

Lead::apiAdd()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 33
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 7.2944

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 33
ccs 18
cts 22
cp 0.8182
rs 6.7272
cc 7
eloc 21
nc 12
nop 1
crap 7.2944
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
        'name',
32
        'date_create',
33
        'last_modified',
34
        'status_id',
35
        'pipeline_id',
36
        'price',
37
        'responsible_user_id',
38
        'created_user_id',
39
        'request_id',
40
        'linked_company_id',
41
        'tags',
42
        'visitor_uid',
43
        'notes',
44
        'modified_user_id',
45
    ];
46
47
    /**
48
     * Список сделок
49
     *
50
     * Метод для получения списка сделок с возможностью фильтрации и постраничной выборки.
51
     * Ограничение по возвращаемым на одной странице (offset) данным - 500 сделок
52
     *
53
     * @link https://developers.amocrm.ru/rest_api/leads_list.php
54
     * @param array $parameters Массив параметров к amoCRM API
55
     * @param null|string $modified Дополнительная фильтрация по (изменено с)
56
     * @return array Ответ amoCRM API
57
     */
58 1
    public function apiList($parameters, $modified = null)
59
    {
60 1
        $response = $this->getRequest('/private/api/v2/json/leads/list', $parameters, $modified);
61
62 1
        return isset($response['leads']) ? $response['leads'] : [];
63
    }
64
65
    /**
66
     * Добавление сделки
67
     *
68
     * Метод позволяет добавлять сделки по одной или пакетно
69
     *
70
     * @link https://developers.amocrm.ru/rest_api/leads_set.php
71
     * @param array $leads Массив сделок для пакетного добавления
72
     * @return int|array Уникальный идентификатор сделки или массив при пакетном добавлении
73
     */
74 1
    public function apiAdd($leads = [])
75
    {
76 1
        if (empty($leads)) {
77 1
            $leads = [$this];
78 1
        }
79
80
        $parameters = [
81
            'leads' => [
82 1
                'add' => [],
83 1
            ],
84 1
        ];
85
86 1
        foreach ($leads AS $lead) {
87 1
            $parameters['leads']['add'][] = $lead->getValues();
88 1
        }
89
90 1
        $response = $this->postRequest('/private/api/v2/json/leads/set', $parameters);
91
92 1
        if (isset($response['leads']['add'])) {
93 1
            $result = array_map(function($item) {
94 1
				if(!empty($item['id']))
95 1
					return $item['id'];
96
				elseif(!empty($item['error']))
97
					throw new Exception($item['error'],filter_var(mb_strstr($item['error'],".",true), FILTER_SANITIZE_NUMBER_INT));
98
				else
99
					return [];
100 1
            }, $response['leads']['add']);
101 1
        } else {
102
            return [];
103
        }
104
105 1
        return count($leads) == 1 ? array_shift($result) : $result;
106
    }
107
108
    /**
109
     * Обновление сделки
110
     *
111
     * Метод позволяет обновлять данные по уже существующим сделкам
112
     *
113
     * @link https://developers.amocrm.ru/rest_api/leads_set.php
114
     * @param int $id Уникальный идентификатор сделки
115
     * @param string $modified Дата последнего изменения данной сущности
116
     * @return bool Флаг успешности выполнения запроса
117
     * @throws \AmoCRM\Exception
118
     */
119 1
    public function apiUpdate($id, $modified = 'now')
120
    {
121 1
        $this->checkId($id);
122
123
        $parameters = [
124
            'leads' => [
125 1
                'update' => [],
126 1
            ],
127 1
        ];
128
129 1
        $lead = $this->getValues();
130 1
        $lead['id'] = $id;
131 1
        $lead['last_modified'] = strtotime($modified);
132
133 1
        $parameters['leads']['update'][] = $lead;
134
135 1
        $response = $this->postRequest('/private/api/v2/json/leads/set', $parameters);
136
137 1
        return empty($response['leads']['update']['errors']);
138
    }
139
}
140