Completed
Push — master ( 8368e2...87a527 )
by dotzero
04:04
created

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