Pipelines::setIsMain()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 5
cts 6
cp 0.8333
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2.0185
1
<?php
2
3
namespace AmoCRM\Models;
4
5
/**
6
 * Class Pipelines
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 Pipelines extends AbstractModel
19
{
20
    /**
21
     * @var array Список доступный полей для модели (исключая кастомные поля)
22
     */
23
    protected $fields = [
24
        'name',
25
        'sort',
26
        'is_main',
27
        'statuses',
28
    ];
29
30
    /**
31
     * Сеттер для поля - является ли воронка "главной"
32
     *
33
     * @param string $flag Флаг состояния
34
     * @return $this
35
     */
36 4
    public function setIsMain($flag)
37
    {
38 4
        if ($flag) {
39 4
            $this->values['is_main'] = 'on';
40 4
        } else {
41
            unset($this->values['is_main']);
42
        }
43
44 4
        return $this;
45
    }
46
47
    /**
48
     * Список воронок и этапов продаж
49
     *
50
     * Метод для получения списка воронок и этапов продаж.
51
     *
52
     * @link https://developers.amocrm.ru/rest_api/pipelines/list.php
53
     * @param null|int $id Уникальный идентификатор воронки
54
     * @return array Ответ amoCRM API
55
     * @throws \AmoCRM\Exception
56
     */
57 1
    public function apiList($id = null)
58
    {
59 1
        if ($id !== null) {
60 1
            $this->checkId($id);
61
62 1
            $response = $this->getRequest('/private/api/v2/json/pipelines/list', [
63
                'id' => $id
64 1
            ]);
65
66 1
            return isset($response['pipelines'][$id]) ? $response['pipelines'][$id] : [];
67
        }
68
69 1
        $response = $this->getRequest('/private/api/v2/json/pipelines/list');
70
71 1
        return isset($response['pipelines']) ? $response['pipelines'] : [];
72
    }
73
74
    /**
75
     * Добавление воронок и этапов продаж
76
     *
77
     * Метод позволяет добавлять воронки и этапов продаж по одной или пакетно
78
     *
79
     * @link https://developers.amocrm.ru/rest_api/pipelines/set.php
80
     * @param array $pipelines Массив воронок для пакетного добавления
81
     * @return int|array Уникальный идентификатор воронки или массив при пакетном добавлении
82
     */
83 1
    public function apiAdd($pipelines = [])
84
    {
85 1
        if (empty($pipelines)) {
86 1
            $pipelines = [$this];
87 1
        }
88
89
        $parameters = [
90
            'pipelines' => [
91 1
                'add' => [],
92 1
            ],
93 1
        ];
94
95 1
        foreach ($pipelines AS $pipeline) {
96 1
            $parameters['pipelines']['add'][] = $pipeline->getValues();
97 1
        }
98
99 1
        $response = $this->postRequest('/private/api/v2/json/pipelines/set', $parameters);
100
101 1
        if (isset($response['pipelines']['add']['pipelines'])) {
102 1
            $result = array_map(function ($item) {
103 1
                return $item['id'];
104 1
            }, $response['pipelines']['add']['pipelines']);
105 1
        } else {
106
            return [];
107
        }
108
109 1
        return count($pipelines) == 1 ? array_shift($result) : $result;
110
    }
111
112
    /**
113
     * Обновление воронок и этапов продаж
114
     *
115
     * Метод позволяет обновлять данные по уже существующим воронкам и этапам продаж
116
     *
117
     * @link https://developers.amocrm.ru/rest_api/pipelines/set.php
118
     * @param int $id Уникальный идентификатор воронки
119
     * @return bool Флаг успешности выполнения запроса
120
     * @throws \AmoCRM\Exception
121
     */
122 1
    public function apiUpdate($id)
123
    {
124 1
        $this->checkId($id);
125
126
        $parameters = [
127
            'pipelines' => [
128 1
                'update' => [],
129 1
            ],
130 1
        ];
131
132 1
        $pipeline = $this->getValues();
133 1
        $pipeline['id'] = $id;
134
135 1
        $parameters['pipelines']['update'][$id] = $pipeline;
136
137 1
        $response = $this->postRequest('/private/api/v2/json/pipelines/set', $parameters);
138
139 1
        return isset($response['pipelines']) ? true : false;
140
    }
141
142
    /**
143
     * Удаление воронок
144
     *
145
     * Метод позволяет удалять воронки по одной или пакетно
146
     *
147
     * Удаление последней воронки в аккаунте невозможно,
148
     * при удалении последней воронки выдается ошибка
149
     * "Impossible to delete last pipeline"
150
     *
151
     * @link https://developers.amocrm.ru/rest_api/pipelines/delete.php
152
     * @param int $id Уникальный идентификатор воронки
153
     * @return array Ответ amoCRM API
154
     * @throws \AmoCRM\Exception
155
     */
156 1
    public function apiDelete($id)
157
    {
158
        $parameters = [
159
            'id' => $id
160 1
        ];
161
162 1
        $response = $this->postRequest('/private/api/v2/json/pipelines/delete', $parameters);
163
164 1
        return $response;
165
    }
166
167
    /**
168
     * Добавление этапов воронки, необходимо передать хотя бы один этап,
169
     * кроме успешно/неуспешно завершенного.
170
     *
171
     * Для этапов успешно/неуспешно завершено (id 142/143 соответственно)
172
     * возможно передать только поле name
173
     *
174
     * @param mixed $parameters Параметры этапа воронки
175
     * @param int $id Уникальный идентификатор этапа воронки
176
     * @return $this
177
     */
178 1
    public function addStatusField($parameters, $id = null)
179
    {
180 1
        if ($id === null) {
181 1
            $this->values['statuses'][] = $parameters;
182 1
        } else {
183 1
            $this->checkId($id);
184 1
            $parameters['id'] = $id;
185 1
            $this->values['statuses'][$id] = $parameters;
186
        }
187
188 1
        return $this;
189
    }
190
}
191