Catalog::apiDelete()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2.0054

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 8
cts 9
cp 0.8889
rs 9.6666
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2.0054
1
<?php
2
3
namespace AmoCRM\Models;
4
5
/**
6
 * Class Catalog
7
 *
8
 * Класс модель для работы с Каталогами
9
 *
10
 * @package AmoCRM\Models
11
 * @author [email protected]
12
 * @author dotzero <[email protected]>
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 Catalog extends AbstractModel
19
{
20
    /**
21
     * @var array Список доступный полей для модели (исключая кастомные поля)
22
     */
23
    protected $fields = [
24
        'name',
25
        'request_id',
26
    ];
27
28
    /**
29
     * Список каталогов
30
     *
31
     * Метод для получения списка каталогов аккаунта.
32
     *
33
     * @link https://developers.amocrm.ru/rest_api/catalogs/list.php
34
     * @param null|int $id Выбрать элемент с заданным ID
35
     * @return array Ответ amoCRM API
36
     */
37 1
    public function apiList($id = null)
38
    {
39 1
        $parameters = [];
40
41 1
        if ($id !== null) {
42 1
            $parameters['id'] = $id;
43 1
        }
44
45 1
        $response = $this->getRequest('/private/api/v2/json/catalogs/list', $parameters);
46
47 1
        return isset($response['catalogs']) ? $response['catalogs'] : [];
48
    }
49
50
    /**
51
     * Добавление каталогов
52
     *
53
     * Метод позволяет добавлять каталоги по одному или пакетно
54
     *
55
     * @link https://developers.amocrm.ru/rest_api/catalogs/set.php
56
     * @param array $catalogs Массив каталогов для пакетного добавления
57
     * @return int|array Уникальный идентификатор каталога или массив при пакетном добавлении
58
     */
59 1
    public function apiAdd($catalogs = [])
60
    {
61 1
        if (empty($catalogs)) {
62 1
            $catalogs = [$this];
63 1
        }
64
65
        $parameters = [
66
            'catalogs' => [
67 1
                'add' => [],
68 1
            ],
69 1
        ];
70
71 1
        foreach ($catalogs AS $catalog) {
72 1
            $parameters['catalogs']['add'][] = $catalog->getValues();
73 1
        }
74
75 1
        $response = $this->postRequest('/private/api/v2/json/catalogs/set', $parameters);
76
77 1
        if (isset($response['catalogs']['add']['catalogs'])) {
78 1
            $result = array_map(function ($item) {
79 1
                return $item['id'];
80 1
            }, $response['catalogs']['add']['catalogs']);
81 1
        } else {
82
            return [];
83
        }
84
85 1
        return count($catalogs) == 1 ? array_shift($result) : $result;
86
    }
87
88
    /**
89
     * Обновление каталогов
90
     *
91
     * Метод позволяет обновлять данные по уже существующим каталогам
92
     *
93
     * @link https://developers.amocrm.ru/rest_api/catalogs/set.php
94
     * @param int $id Уникальный идентификатор каталога
95
     * @return bool Флаг успешности выполнения запроса
96
     * @throws \AmoCRM\Exception
97
     */
98 1
    public function apiUpdate($id)
99
    {
100 1
        $this->checkId($id);
101
102
        $parameters = [
103
            'catalogs' => [
104 1
                'update' => [],
105 1
            ],
106 1
        ];
107
108 1
        $catalog = $this->getValues();
109 1
        $catalog['id'] = $id;
110
111 1
        $parameters['catalogs']['update'][] = $catalog;
112
113 1
        $response = $this->postRequest('/private/api/v2/json/catalogs/set', $parameters);
114
115 1
        if (!isset($response['catalogs']['update']['errors'])) {
116
            return false;
117
        }
118
119 1
        return empty($response['catalogs']['update']['errors']);
120
    }
121
122
    /**
123
     * Удаление каталогов
124
     *
125
     * Метод позволяет удалять данные по уже существующим каталогам
126
     *
127
     * @link https://developers.amocrm.ru/rest_api/catalogs/set.php
128
     * @param int $id Уникальный идентификатор каталога
129
     * @return bool Флаг успешности выполнения запроса
130
     * @throws \AmoCRM\Exception
131
     */
132 1
    public function apiDelete($id)
133
    {
134 1
        $this->checkId($id);
135
136
        $parameters = [
137
            'catalogs' => [
138 1
                'delete' => [$id],
139 1
            ],
140 1
        ];
141
142 1
        $response = $this->postRequest('/private/api/v2/json/catalogs/set', $parameters);
143
144 1
        if (!isset($response['catalogs']['delete']['errors'])) {
145
            return false;
146
        }
147
148 1
        return empty($response['catalogs']['delete']['errors']);
149
    }
150
}
151