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

CustomField::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 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
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
/**
6
 * Class CustomField
7
 *
8
 * Класс модель для работы с Дополнительными полями
9
 *
10
 * @package AmoCRM\Models
11
 * @author mihasichechek <[email protected]>
12
 * @link https://github.com/dotzero/amocrm-php
13
 *
14
 * For the full copyright and license information, please view the LICENSE
15
 * file that was distributed with this source code.
16
 */
17
class CustomField extends AbstractModel
18
{
19
    /**
20
     * @var array Список доступный полей для модели (исключая кастомные поля)
21
     */
22
    protected $fields = [
23
        'name',
24
        'request_id',
25
        'disabled',
26
        'type',
27
        'element_type',
28
        'origin',
29
        'enums',
30
    ];
31
32
    const TYPE_TEXT = 1;
33
    const TYPE_NUMERIC = 2;
34
    const TYPE_CHECKBOX = 3;
35
    const TYPE_SELECT = 4;
36
    const TYPE_MULTISELECT = 5;
37
    const TYPE_DATE = 6;
38
    const TYPE_URL = 7;
39
    const TYPE_MULTITEXT = 8;
40
    const TYPE_TEXTAREA = 9;
41
    const TYPE_RADIOBUTTON = 10;
42
43
    /**
44
     * @const int Типа сущности Контакт
45
     */
46
    const ENTITY_CONTACT = 1;
47
48
    /**
49
     * @const int Типа сущности Сделка
50
     */
51
    const ENTITY_LEAD = 2;
52
53
    /**
54
     * @const int Типа сущности Компания
55
     */
56
    const ENTITY_COMPANY = 3;
57
58
    /**
59
     * Сеттер для флага, указывающего на то,
60
     * должно ли поле быть редактируемым в веб-интерфейсе
61
     *
62
     * @param string $value Значение флага
63
     * @return $this
64
     */
65 4
    public function setDisabled($value)
66
    {
67 4
        $this->values['disabled'] = (bool)$value ? 1 : 0;
68
69 4
        return $this;
70
    }
71
72
    /**
73
     * Добавление дополнительных полей
74
     *
75
     * Метод позволяет добавлять дополнительные поля по одному или пакетно
76
     *
77
     * @link https://developers.amocrm.ru/rest_api/fields_set.php
78
     * @param $fields array Массив дополнительных полей для пакетного добавления
79
     * @return int|array Уникальный идентификатор поля или массив при пакетном добавлении
80
     */
81 1
    public function apiAdd($fields = [])
82
    {
83 1
        if (empty($fields)) {
84 1
            $fields = [$this];
85 1
        }
86
87
        $parameters = [
88
            'fields' => [
89 1
                'add' => [],
90 1
            ],
91 1
        ];
92
93 1
        foreach ($fields AS $field) {
94 1
            $parameters['fields']['add'][] = $field->getValues();
95 1
        }
96
97 1
        $response = $this->postRequest('/private/api/v2/json/fields/set', $parameters);
98
99 1
        if (isset($response['fields']['add'])) {
100 1
            $result = array_map(function ($item) {
101 1
				if(!empty($item['id']))
102 1
					return $item['id'];
103
				elseif(!empty($item['error']))
104
					throw new Exception($item['error'],filter_var(mb_strstr($item['error'],".",true), FILTER_SANITIZE_NUMBER_INT));
105
				else
106
					return [];
107 1
            }, $response['fields']['add']);
108 1
        } else {
109
            return [];
110
        }
111
112 1
        return count($fields) == 1 ? array_shift($result) : $result;
113
    }
114
115
    /**
116
     * Удаление дополнительных полей
117
     *
118
     * Метод позволяет удалять дополнительные поля
119
     *
120
     * @link https://developers.amocrm.ru/rest_api/fields_set.php
121
     * @param $id int Уникальный идентификатор дополнительного поля
122
     * @param $origin string Уникальный идентификатор сервиса заданный при создании параметром origin
123
     * @return bool Флаг успешности выполнения запроса
124
     */
125 1
    public function apiDelete($id, $origin)
126
    {
127
        $parameters = [
128
            'fields' => [
129
                'delete' => [
130
                    [
131 1
                        'id' => (int)$id,
132
                        'origin' => $origin
133 1
                    ]
134 1
                ]
135 1
            ]
136 1
        ];
137
138 1
        $response = $this->postRequest('/private/api/v2/json/fields/set', $parameters);
139
140 1
        return isset($response['fields']['delete']) ? true : false;
141
    }
142
}