Completed
Pull Request — master (#72)
by
unknown
02:19
created

CustomField::setDisabled()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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