Completed
Push — master ( d14dcd...4333fc )
by dotzero
11s
created

Base::addCustomMultiField()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
ccs 10
cts 10
cp 1
cc 2
eloc 9
nc 2
nop 2
crap 2
1
<?php
2
3
namespace AmoCRM\Models;
4
5
use AmoCRM\Exception;
6
use AmoCRM\Request\Request;
7
8
/**
9
 * Class Base
10
 *
11
 * Базовый класс всех моделей
12
 *
13
 * @package AmoCRM\Models
14
 * @version 0.3.4
15
 * @author dotzero <[email protected]>
16
 * @link http://www.dotzero.ru/
17
 * @link https://github.com/dotzero/amocrm-php
18
 *
19
 * For the full copyright and license information, please view the LICENSE
20
 * file that was distributed with this source code.
21
 */
22
class Base extends Request implements \ArrayAccess
23
{
24
    /**
25
     * @var array Список доступный полей для модели (исключая кастомные поля)
26
     */
27
    protected $fields = [];
28
29
    /**
30
     * @var array Список значений полей для модели
31
     */
32
    protected $values = [];
33
34
    /**
35
     * Определяет, существует ли заданное поле модели
36
     *
37
     * @link http://php.net/manual/en/arrayaccess.offsetexists.php
38
     * @param mixed $offset Название поля для проверки
39
     * @return boolean Возвращает true или false
40
     */
41 1
    public function offsetExists($offset)
42
    {
43 1
        return isset($this->values[$offset]);
44
    }
45
46
    /**
47
     * Возвращает заданное поле модели
48
     *
49
     * @link http://php.net/manual/en/arrayaccess.offsetget.php
50
     * @param mixed $offset Название поля для возврата
51
     * @return mixed Значение поля
52
     */
53 52
    public function offsetGet($offset)
54
    {
55 52
        if (isset($this->values[$offset])) {
56 52
            return $this->values[$offset];
57
        }
58
59 2
        return null;
60
    }
61
62
    /**
63
     * Устанавливает заданное поле модели
64
     *
65
     * Если есть сеттер модели, то будет использовать сеттер
66
     *
67
     * @link http://php.net/manual/en/arrayaccess.offsetset.php
68
     * @param mixed $offset Название поля, которому будет присваиваться значение
69
     * @param mixed $value Значение для присвоения
70
     */
71 61
    public function offsetSet($offset, $value)
72
    {
73 61
        $setter = 'set' . $this->toCamelCase($offset);
74
75 61
        if (method_exists($this, $setter)) {
76 22
            return $this->$setter($value);
77 40
        } elseif (in_array($offset, $this->fields)) {
78 40
            $this->values[$offset] = $value;
79 40
        }
80 40
    }
81
82
    /**
83
     * Удаляет поле модели
84
     *
85
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
86
     * @param mixed $offset Название поля для удаления
87
     */
88 1
    public function offsetUnset($offset)
89
    {
90 1
        if (isset($this->values[$offset])) {
91 1
            unset($this->values[$offset]);
92 1
        }
93 1
    }
94
95
    /**
96
     * Получение списока значений полей модели
97
     *
98
     * @return array Список значений полей модели
99
     */
100 11
    public function getValues()
101
    {
102 11
        return $this->values;
103
    }
104
105
    /**
106
     * Добавление кастомного поля модели
107
     *
108
     * @param int $id Уникальный идентификатор заполняемого дополнительного поля
109
     * @param mixed $value Значение заполняемого дополнительного поля
110
     * @param string $enum Тип дополнительного поля
111
     * @param string $subtype Тип подтипа поля
112
     * @return $this
113
     */
114 3
    public function addCustomField($id, $value, $enum = false, $subtype = false)
115
    {
116
        $field = [
117 3
            'id' => $id,
118 3
            'values' => [],
119 3
        ];
120
121 3
        if (!is_array($value)) {
122 3
            $values = [[$value, $enum]];
123 3
        } else {
124 3
            $values = $value;
125
        }
126
127 3
        foreach ($values as $val) {
128 3
            list($value, $enum) = $val;
129
130
            $fieldValue = [
131 3
                'value' => $value,
132 3
            ];
133
134 3
            if ($enum !== false) {
135 3
                $fieldValue['enum'] = $enum;
136 3
            }
137
            
138 3
            if ($subtype !== false) {
139
                $fieldValue['subtype'] = $subtype;
140
            }
141
142 3
            $field['values'][] = $fieldValue;
143 3
        }
144
145 3
        $this->values['custom_fields'][] = $field;
146
147 3
        return $this;
148
    }
149
150
    /**
151
     * Добавление кастомного поля типа мультиселект модели
152
     *
153
     * @param int $id Уникальный идентификатор заполняемого дополнительного поля
154
     * @param mixed $values Значения заполняемого дополнительного поля типа мультиселект
155
     * @return $this
156
     */
157 1
    public function addCustomMultiField($id, $values)
158
    {
159
        $field = [
160 1
            'id' => $id,
161 1
            'values' => [],
162 1
        ];
163
164 1
        if (!is_array($values)) {
165 1
            $values = [$values];
166 1
        }
167
168 1
        $field['values'] = $values;
169
170 1
        $this->values['custom_fields'][] = $field;
171
172 1
        return $this;
173
    }
174
175
    /**
176
     * Проверяет ID на валидность
177
     *
178
     * @param mixed $id ID
179
     * @return bool
180
     * @throws Exception
181
     */
182 7
    protected function checkId($id)
183
    {
184 7
        if (intval($id) != $id || $id < 1) {
185 2
            throw new Exception('Id must be integer and positive');
186
        }
187
188 5
        return true;
189
    }
190
191
    /**
192
     * Приведение under_score к CamelCase
193
     *
194
     * @param string $string Строка
195
     * @return string Строка
196
     */
197 61
    private function toCamelCase($string)
198
    {
199 61
        return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
200
    }
201
}
202