forked from NetCommons3/NetCommons
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetCommonsAppModel.php
More file actions
349 lines (316 loc) · 9.53 KB
/
NetCommonsAppModel.php
File metadata and controls
349 lines (316 loc) · 9.53 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
<?php
/**
* NetCommonsApp Model
*
* @author Jun Nishikawa <topaz2@m0n0m0n0.com>
* @author Takako Miyagawa <nekoget@gmail.com>
* @link http://www.netcommons.org NetCommons Project
* @license http://www.netcommons.org/license.txt NetCommons License
* @copyright Copyright 2014, NetCommons Project
*/
App::uses('Model', 'Model');
/**
* NetCommonsApp Model
*
* CakePHPのModelクラスを継承してます。<br>
* ドキュメントルートのapp.Mode.AppModelはこのクラスを継承しているので、<br>
* 全モデルの基底クラスになります。<br>
* Overrideしているメソッドもあり、CakePHPの通常動作と異なるものがありますので注意して下さい。
*
* #### CakePHPのModel処理をOverrideしているメソッドです。
* [__construct](#__construct)<br>
* [setDataSource](#setdatasource)<br>
* [create](#create)<br>
*
* @author Jun Nishikawa <topaz2@m0n0m0n0.com>
* @author Takako Miyagawa <nekoget@gmail.com>
* @package NetCommons\NetCommons\Model
* @SuppressWarnings(PHPMD.NumberOfChildren)
*/
class NetCommonsAppModel extends Model {
/**
* use behaviors
*
* @var array
*/
public $actsAs = array(
'NetCommons.Trackable',
);
/**
* Validation rules
*
* @var array
*/
public $validate = array();
/**
* 接続先DB master slave変更用
*
* @var string
*/
private static $__changeDbConfig;
/**
* 接続先DB 古いslave保存用
*
* @var string
*/
private static $__oldSlaveDbConfig;
/**
* Constructor. DataSourceの選択
*
* 接続先DBをランダムに選択します。
*
* @param bool|int|string|array $id Set this ID for this model on startup,
* can also be an array of options, see above.
* @param string $table Name of database table to use.
* @param string $ds DataSource connection name.
* @return void
* @SuppressWarnings(PHPMD.BooleanArgumentFlag)
*/
public function __construct($id = false, $table = null, $ds = null) {
// If a datasource is set via params, use it and return
if ((is_array($id) && isset($id['ds'])) || $ds) {
parent::__construct($id, $table, $ds);
return;
}
// Use a static variable, to only use one connection per page-call (otherwise we would get a new handle every time a Model is created)
static $_useDbConfig;
if (!isset($_useDbConfig)) {
$_useDbConfig = $this->__getRandomlySlave();
}
$this->useDbConfig = $_useDbConfig;
parent::__construct($id, $table, $ds);
}
/**
* Find the slaves we have
*
* @return string The name of the DataSource, as defined in app/Config/database.php
*/
private function __getRandomlySlave() {
if ($this->useDbConfig === 'test') {
return $this->useDbConfig;
}
// Get all available database-configs
$sources = ConnectionManager::enumConnectionObjects();
// Find the slaves we have
$slaves = array();
foreach ($sources as $name => $values) {
unset($values);
// Slaves have to be named "slave1", "slave2", etc...
if (preg_match('/^slave[0-9]+$/i', $name) == 1) {
$slaves[] = $name;
}
}
// Randomly use a slave
$dataSource = (count($slaves) !== 0) ? $slaves[rand(0, count($slaves) - 1)] : 'master';
return $dataSource;
}
/**
* Masterの接続先に変更する。
*
* @return void
*/
public function setMasterDataSource() {
self::$__changeDbConfig = 'master';
}
/**
* 以前のSlaveの接続先に戻す。なければ、ランダムに選択
*
* @return void
*/
public function setSlaveDataSource() {
if (self::$__oldSlaveDbConfig) {
self::$__changeDbConfig = self::$__oldSlaveDbConfig;
return;
}
self::$__changeDbConfig = $this->__getRandomlySlave();
}
/**
* Gets the DataSource to which this model is bound.
*
* @return DataSource A DataSource object
*/
public function getDataSource() {
// MasterDBに切り替え処理
$this->__changeDataSource();
return parent::getDataSource();
}
/**
* MasterDBに切り替える処理
*
* @return void
*/
private function __changeDataSource() {
if (!empty(self::$__changeDbConfig) &&
self::$__changeDbConfig !== $this->useDbConfig && $this->useDbConfig !== 'test') {
self::$__oldSlaveDbConfig = $this->useDbConfig;
$this->useDbConfig = self::$__changeDbConfig;
$this->_sourceConfigured = false;
//self::$__changeDbConfig = null;
$associations = Hash::merge(
array_keys($this->hasOne),
array_keys($this->hasMany),
array_keys($this->belongsTo),
array_keys($this->hasAndBelongsToMany)
);
foreach ($associations as $btModelName) {
$this->{$btModelName}->useDbConfig = $this->useDbConfig;
if ($this->{$btModelName}->useTable !== false) {
$this->{$btModelName}->setSource($this->{$btModelName}->useTable);
}
}
}
}
/**
* NetCommonsで使用する共通の値がセットされた結果を返します。<br>
* CakePHPのSchemaは、not null指定されたカラムのdefaultがnullになっているため、<br>
* ''(長さ0の文字列)に書き換えています。<br>
* https://github.com/NetCommons3/NetCommons3/issues/7
*
* #### セットされるデータ
* ```
* 'room_id' => Current::read('Room.id'),
* 'language_id' => Current::read('Language.id'),
* 'block_id' => Current::read('Block.id'),
* 'block_key' => Current::read('Block.key'),
* 'frame_id' => Current::read('Frame.id'),
* 'frame_key' => Current::read('Frame.key'),
* 'plugin_key' => Inflector::underscore($this->plugin),
* ```
*
* @param bool|array $data Optional data array to assign to the model after it is created. If null or false,
* schema data defaults are not merged.
* @param bool $filterKey If true, overwrites any primary key input with an empty value
*
* @return array The current Model::data; after merging $data and/or defaults from database
* @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-create-array-data-array
* @SuppressWarnings(PHPMD.BooleanArgumentFlag)
*/
public function create($data = array(), $filterKey = false) {
if ($data !== null && $data !== false) {
if (empty($data[$this->alias])) {
$data = $this->_setAliasData($data);
}
$options = $this->_getDefaultValue();
$data = Hash::merge($options, $data);
}
return parent::create($data, $filterKey);
}
/**
* Initializes the model for writing a new record, loading the default values
* for those fields that are not defined in $data, and clearing previous validation errors.
* Especially helpful for saving data in loops.
*
* @param bool|array $data Optional data array to assign to the model after it is created. If null or false,
* schema data defaults are not merged.
* @param bool $filterKey If true, overwrites any primary key input with an empty value
*
* @return array The current Model::data; after merging $data and/or defaults from database
* @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-create-array-data-array
* @SuppressWarnings(PHPMD.BooleanArgumentFlag)
*/
public function createAll($data = array(), $filterKey = false) {
$newRecord = $this->create($data, $filterKey);
$associations = Hash::merge(
array_keys($this->hasOne),
array_keys($this->belongsTo)
);
foreach ($associations as $model) {
if ($model === 'TrackableCreator' || $model === 'TrackableUpdater') {
continue;
}
if (isset($data[$model])) {
$options = $data[$model];
} else {
$options = array();
}
$newRecord = Hash::merge($newRecord, $this->$model->create($options, $filterKey));
}
return $newRecord;
}
/**
* transaction begin
*
* @return void
*/
public function begin() {
$this->setMasterDataSource();
$dataSource = $this->getDataSource();
$dataSource->begin();
}
/**
* transaction commit
*
* @return void
*/
public function commit() {
$dataSource = $this->getDataSource();
$dataSource->commit();
}
/**
* transaction rollback
*
* @param mixed $ex Exception
* @return void
* @throws Exception
*/
public function rollback($ex = null) {
$dataSource = $this->getDataSource();
$dataSource->rollback();
if ($ex) {
if ($this->useDbConfig !== 'test') {
CakeLog::error($ex);
}
throw $ex;
}
}
/**
* Load models
*
* @param array $models models to load
* @return void
*/
public function loadModels(array $models = []) {
foreach ($models as $model => $class) {
$this->$model = ClassRegistry::init($class, true);
//if ($this->$model->useDbConfig !== 'test') {
// $this->$model->setDataSource($source);
//}
}
}
/**
* 全カラムのデフォルト値をセットした配列を返す。
*
* @return array デフォルト値をセットした配列
*/
protected function _getDefaultValue() {
$options = array();
$currents = array();
if (class_exists('Current')) {
$currents = array(
'room_id' => Current::read('Room.id'),
'language_id' => Current::read('Language.id'),
'block_id' => Current::read('Block.id'),
'block_key' => Current::read('Block.key'),
'frame_id' => Current::read('Frame.id'),
'frame_key' => Current::read('Frame.key'),
'plugin_key' => Inflector::underscore($this->plugin),
);
}
foreach ($this->schema() as $fieldName => $fieldDetail) {
if ($fieldName !== $this->primaryKey) {
if (($fieldDetail['null'] === false) && ($fieldDetail['default'] === null)) {
// not nullカラムのdefault指定がなかったら空文字にしておく。 @see https://github.com/NetCommons3/NetCommons3/issues/7
$options[$fieldName] = '';
} else {
$options[$fieldName] = $fieldDetail['default'];
}
}
// Currentの値をセット
if (isset($currents[$fieldName])) {
$options[$fieldName] = $currents[$fieldName];
}
}
$options = $this->_setAliasData($options);
return $options;
}
}