Completed
Push — master ( 3e0ee8...072c02 )
by dotzero
03:25
created

Base::offsetGet()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 8
rs 9.4285
ccs 4
cts 4
cp 1
cc 2
eloc 4
nc 2
nop 1
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.1
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 49
    public function offsetGet($offset)
54
    {
55 49
        if (isset($this->values[$offset])) {
56 49
            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 58
    public function offsetSet($offset, $value)
72
    {
73 58
        $setter = 'set' . $this->toCamelCase($offset);
74
75 58
        if (method_exists($this, $setter)) {
76 20
            return $this->$setter($value);
77 39
        } elseif (in_array($offset, $this->fields)) {
78 39
            $this->values[$offset] = $value;
79 39
        }
80 39
    }
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 bool $enum Тип дополнительного поля
111
     * @return $this
112
     */
113 3
    public function addCustomField($id, $value, $enum = false)
114
    {
115
        $field = [
116 3
            'id' => $id,
117 3
            'values' => [],
118 3
        ];
119
120 3
        if (!is_array($value)) {
121 3
            $values = [[$value, $enum]];
122 3
        } else {
123 3
            $values = $value;
124
        }
125
126 3
        foreach ($values AS $val) {
127 3
            list($value, $enum) = $val;
128
129
            $fieldValue = [
130 3
                'value' => $value,
131 3
            ];
132
133 3
            if ($enum !== false) {
134 3
                $fieldValue['enum'] = $enum;
135 3
            }
136
137 3
            $field['values'][] = $fieldValue;
138 3
        }
139
140 3
        $this->values['custom_fields'][] = $field;
141
142 3
        return $this;
143
    }
144
145
    /**
146
     * Добавление кастомного поля типа мультиселект модели
147
     *
148
     * @param int $id Уникальный идентификатор заполняемого дополнительного поля
149
     * @param mixed $values Значения заполняемого дополнительного поля типа мультиселект
150
     * @return $this
151
     */
152 1
    public function addCustomMultiField($id, $values)
153
    {
154
        $field = [
155 1
            'id' => $id,
156 1
            'values' => [],
157 1
        ];
158
159 1
        if (!is_array($values)) {
160 1
            $values = [$values];
161 1
        }
162
163 1
        $field['values'] = $values;
164
165 1
        $this->values['custom_fields'][] = $field;
166
167 1
        return $this;
168
    }
169
170
    /**
171
     * Проверяет ID на валидность
172
     *
173
     * @param mixed $id ID
174
     * @return bool
175
     * @throws Exception
176
     */
177 7
    protected function checkId($id)
178
    {
179 7
        if (intval($id) != $id || $id < 1) {
180 2
            throw new Exception('Id must be integer and positive');
181
        }
182
183 5
        return true;
184
    }
185
186
    /**
187
     * Приведение under_score к CamelCase
188
     *
189
     * @param string $string Строка
190
     * @return string Строка
191
     */
192 58
    private function toCamelCase($string)
193
    {
194 58
        return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
195
    }
196
}
197