-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathActiveRecord.php
285 lines (246 loc) · 8.64 KB
/
ActiveRecord.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
<?php
/**
* Created by PhpStorm.
* User: execut
* Date: 9/20/17
* Time: 2:41 PM
*/
namespace execut\oData;
use Kily\Tools1C\OData\Client;
use yii\db\Exception;
use yii\helpers\ArrayHelper;
class ActiveRecord extends \yii\db\ActiveRecord
{
public $complexRelations = [];
public static function find()
{
return new ActiveQuery(static::class);
}
protected static $attributesCache = [];
/**
* Returns the list of all attribute names of the model.
* The default implementation will return all column names of the table associated with this AR class.
* @return array list of attribute names.
*/
public function attributes()
{
if (array_key_exists(static::tableName(), static::$attributesCache)) {
return static::$attributesCache[static::tableName()];
}
return static::$attributesCache[static::tableName()] = parent::attributes();
}
/**
* @inheritdoc
*/
public function refresh()
{
$pk = [];
// disambiguate column names in case ActiveQuery adds a JOIN
foreach ($this->getPrimaryKey(true) as $key => $value) {
$pk[$key] = $value;
}
/* @var $record BaseActiveRecord */
$record = static::findOne($pk);
return $this->refreshInternal($record);
}
public static function updateAll($attributes, $condition = NULL, $params = []) {
// if ($condition === null || count($condition) != 1 || empty($condition['Ref_Key'])) {
// throw new \yii\base\Exception('updateAll allowed only update by Ref_Key');
// }
//
// $id = $condition['Ref_Key'];
$client = self::getClient();
$attributes = static::filtrateAttributes($attributes);
$result = self::doTries(function () use ($client, $attributes, $condition) {
if (empty($condition['Ref_Key'])) {
$client->{static::tableName() . self::buildIdFilter($condition)}->delete(null);
return $client->{static::tableName()}->create(ArrayHelper::merge($attributes, $condition));
} else {
$id = $condition['Ref_Key'];
return $client->{static::tableName()}->update($id, $attributes);
}
});
return $result;
}
public static function buildFilterByCondition($condition) {
$filterParts = [];
foreach ($condition as $attribute => $value) {
$builder = new ConditionBuilder([
'tableSchema' => static::getTableSchema(),
]);
$filterParts[] = $builder->buildColumnCondition($attribute, $value);
}
return implode(' and ', $filterParts);
}
public static function buildIdFilter($condition) {
$result = [];
foreach ($condition as $attribute => $value) {
$result[] = $attribute . '=\'' . $value . '\'';
}
return '(' . implode(', ', $result) . ')';
}
public static function deleteAll($condition = null, $params = []) {
$client = self::getClient();
self::doTries(function () use ($client, $condition) {
if (empty($condition['Ref_Key'])) {
$client->{static::tableName() . self::buildIdFilter($condition)}->delete(null);
} else {
$id = $condition['Ref_Key'];
$client->{static::tableName()}->update($id, [
'DeletionMark' => true,
]);
}
});
return true;
}
/**
* Inserts an ActiveRecord into DB without considering transaction.
* @param array $attributes list of attributes that need to be saved. Defaults to `null`,
* meaning all attributes that are loaded from DB will be saved.
* @return bool whether the record is inserted successfully.
*/
protected function insertInternal($attributes = null)
{
if (!$this->beforeSave(true)) {
return false;
}
$values = $this->getDirtyAttributes($attributes);
$insertResult = $this->doOperation('create');
unset($insertResult['odata.metadata']);
if (empty($insertResult)) {
return false;
}
foreach ($insertResult as $name => $value) {
if (empty(static::getTableSchema()->columns[$name])) {
continue;
}
$id = static::getTableSchema()->columns[$name]->phpTypecast($value);
$this->setAttribute($name, $id);
$values[$name] = $id;
}
$changedAttributes = array_fill_keys(array_keys($values), null);
$this->setOldAttributes($values);
$this->afterSave(true, $changedAttributes);
return true;
}
protected static function isGuid($attribute) {
return self::getTableSchema()->getColumn($attribute)->dbType === 'Edm.Guid';
}
public static function primaryKey()
{
return self::getTableSchema()->primaryKey;
}
public static function getDb()
{
// throw new Exception(__FUNCTION__ . ' is not implemented');
}
// public static function instantiate($row) {
// var_dump($row);
// exit;
// }
public static function populateRecord($record, $row)
{
foreach ($row as $key => $value) {
if ($value === '00000000-0000-0000-0000-000000000000') {
unset($row[$key]);
}
}
return parent::populateRecord($record, $row); // TODO: Change the autogenerated stub
}
public static function getClient() {
return \yii::$app->oData;
}
public static function getTableSchema()
{
$oDataSchema = new Schema([
'client' => self::getClient(),
]);
return $oDataSchema->getTableSchema(static::tableName()); // TODO: Change the autogenerated stub
}
/**
* @param $value
* @return array
*/
protected static function filtrateAttributes($attributes): array
{
foreach ($attributes as $attribute => &$value) {
if (empty($value) && self::isGuid($attribute)) {
// unset($attributes[$attribute]);
$value = '00000000-0000-0000-0000-000000000000';
} else if (self::getTableSchema()->getColumn($attribute)->dbType === 'Edm.Boolean') {
if ($value === null) {
unset($attributes[$attribute]);
} else {
$value = (boolean) $value;
}
}
}
// unset($attributes[current(self::primaryKey())]);
unset($attributes['DataVersion']);
// unset($attributes['Code']);
return $attributes;
}
/**
* @param $operation
* @return bool
* @throws \yii\base\Exception
*/
protected function doOperation($operation)
{
$client = self::getClient();
$attributes = static::filtrateAttributes($this->attributes);
foreach ($this->complexRelations as $relation) {
$models = $this->$relation;
foreach ($models as $key => $model) {
if (!is_array($model)) {
$models[$key] = $model->attributes;
}
}
$attributes[$relation] = $models;
$this->$relation = [];
}
$try = function () use ($client, $operation, $attributes) {
$client->{static::tableName()};
if ($this->isNewRecord) {
return $client->$operation($attributes);
} else {
return $client->$operation($this->primaryKey, $attributes);
}
};
$result = $this->doTries($try);
return $result;
}
/**
* @param $try
* @return bool
* @throws \execut\oData\Exception
*/
protected static function doTries($try) {
$key = 0;
do {
try {
return $try();
} catch (\execut\oData\Exception $e) {
if (strpos($e->getMessage(), 'ПриЗаписи') !== false) {
\yii::error('Ошибка обработчика при записи ' . $e->getMessage());
if ($key === 2) {
throw $e;
}
$key++;
sleep(1);
continue;
}
throw $e;
}
} while ($key < 3);
}
public function doRequest($request) {
$client = self::getClient();
$client->{static::tableName() . '(guid\'' . $this->primaryKey . '\')/' . $request};
return $client->request('POST');
}
protected static function filterCondition(array $condition, array $aliases = [])
{
return $condition;
}
}