AbstractModel::getValues()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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