Completed
Push — master ( 6ff583...0835e8 )
by dotzero
01:58
created

CustomField::setDisabled()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
crap 2
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
    ];
30
31
    const TYPE_TEXT = 1;
32
    const TYPE_NUMERIC = 2;
33
    const TYPE_CHECKBOX = 3;
34
    const TYPE_SELECT = 4;
35
    const TYPE_MULTISELECT = 5;
36
    const TYPE_DATE = 6;
37
    const TYPE_URL = 7;
38
    const TYPE_MULTITEXT = 8;
39
    const TYPE_TEXTAREA = 9;
40
    const TYPE_RADIOBUTTON = 10;
41
42
    /**
43
     * @const int Типа сущности Контакт
44
     */
45
    const ENTITY_CONTACT = 1;
46
47
    /**
48
     * @const int Типа сущности Сделка
49
     */
50
    const ENTITY_LEAD = 2;
51
52
    /**
53
     * @const int Типа сущности Компания
54
     */
55
    const ENTITY_COMPANY = 3;
56
57
    /**
58
     * Сеттер для флага, указывающего на то,
59
     * должно ли поле быть редактируемым в веб-интерфейсе
60
     *
61
     * @param string $value Значение флага
62
     * @return $this
63
     */
64 4
    public function setDisabled($value)
65
    {
66 4
        $this->values['disabled'] = (bool)$value ? 1 : 0;
67
68 4
        return $this;
69
    }
70
71
    /**
72
     * Добавление дополнительных полей
73
     *
74
     * Метод позволяет добавлять дополнительные поля по одному или пакетно
75
     *
76
     * @link https://developers.amocrm.ru/rest_api/fields_set.php
77
     * @param $fields array Массив дополнительных полей для пакетного добавления
78
     * @return int|array Уникальный идентификатор поля или массив при пакетном добавлении
79
     */
80 1
    public function apiAdd($fields = [])
81
    {
82 1
        if (empty($fields)) {
83 1
            $fields = [$this];
84 1
        }
85
86
        $parameters = [
87
            'fields' => [
88 1
                'add' => [],
89 1
            ],
90 1
        ];
91
92 1
        foreach ($fields AS $field) {
93 1
            $parameters['fields']['add'][] = $field->getValues();
94 1
        }
95
96 1
        $response = $this->postRequest('/private/api/v2/json/fields/set', $parameters);
97
98 1
        if (isset($response['fields']['add'])) {
99 1
            $result = array_map(function ($item) {
100 1
                return $item['id'];
101 1
            }, $response['fields']['add']);
102 1
        } else {
103
            return [];
104
        }
105
106 1
        return count($fields) == 1 ? array_shift($result) : $result;
107
    }
108
109
    /**
110
     * Удаление дополнительных полей
111
     *
112
     * Метод позволяет удалять дополнительные поля
113
     *
114
     * @link https://developers.amocrm.ru/rest_api/fields_set.php
115
     * @param $id int Уникальный идентификатор дополнительного поля
116
     * @param $origin string Уникальный идентификатор сервиса заданный при создании параметром origin
117
     * @return bool Флаг успешности выполнения запроса
118
     */
119 1
    public function apiDelete($id, $origin)
120
    {
121
        $parameters = [
122
            'fields' => [
123
                'delete' => [
124
                    [
125 1
                        'id' => (int)$id,
126
                        'origin' => $origin
127 1
                    ]
128 1
                ]
129 1
            ]
130 1
        ];
131
132 1
        $response = $this->postRequest('/private/api/v2/json/fields/set', $parameters);
133
134 1
        return isset($response['fields']['delete']) ? true : false;
135
    }
136
}