Completed
Push — master ( 635f45...2230fc )
by dotzero
02:04
created

Catalog::apiDelete()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2.0054

Importance

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