Completed
Push — master ( 9e3151...cdc91c )
by dotzero
02:29
created

Base::addCustomField()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 31
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 31
rs 8.5806
cc 4
eloc 17
nc 6
nop 3
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.1.0
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
    public function offsetExists($offset)
42
    {
43
        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
    public function offsetGet($offset)
54
    {
55
        if (isset($this->values[$offset])) {
56
            return $this->values[$offset];
57
        }
58
59
        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
    public function offsetSet($offset, $value)
72
    {
73
        $setter = 'set' . $this->toCamelCase($offset);
74
75
        if (method_exists($this, $setter)) {
76
            return $this->$setter($value);
77
        } elseif (in_array($offset, $this->fields)) {
78
            $this->values[$offset] = $value;
79
        }
80
    }
81
82
    /**
83
     * Удаляет поле модели
84
     *
85
     * @link http://php.net/manual/en/arrayaccess.offsetunset.php
86
     * @param mixed $offset Название поля для удаления
87
     */
88
    public function offsetUnset($offset)
89
    {
90
        if (isset($this->values[$offset])) {
91
            unset($this->values[$offset]);
92
        }
93
    }
94
95
    /**
96
     * Получение списока значений полей модели
97
     *
98
     * @return array Список значений полей модели
99
     */
100
    public function getValues()
101
    {
102
        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
    public function addCustomField($id, $value, $enum = false)
114
    {
115
        $field = [
116
            'id' => $id,
117
            'values' => [],
118
        ];
119
120
        if (!is_array($value)) {
121
            $values = [[$value, $enum]];
122
        } else {
123
            $values = $value;
124
        }
125
126
        foreach ($values AS $val) {
127
            list($value, $enum) = $val;
128
129
            $fieldValue = [
130
                'value' => $value,
131
            ];
132
133
            if ($enum !== false) {
134
                $fieldValue['enum'] = $enum;
135
            }
136
137
            $field['values'][] = $fieldValue;
138
        }
139
140
        $this->values['custom_fields'][] = $field;
141
142
        return $this;
143
    }
144
145
    /**
146
     * Проверяет ID на валидность
147
     *
148
     * @param mixed $id ID
149
     * @return bool
150
     * @throws Exception
151
     */
152
    protected function checkId($id)
153
    {
154
        if (intval($id) != $id OR $id < 1) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
155
            throw new Exception('Id must be integer and positive');
156
        }
157
158
        return true;
159
    }
160
161
    /**
162
     * Приведение under_score к CamelCase
163
     *
164
     * @param string $string Строка
165
     * @return string Строка
166
     */
167
    private function toCamelCase($string)
168
    {
169
        return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
170
    }
171
}
172