This repository has been archived by the owner on Apr 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
CustomLinksTable.php
269 lines (252 loc) · 8.04 KB
/
CustomLinksTable.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
<?php
/**
* baserCMS : Based Website Development Project <https://basercms.net>
* Copyright (c) NPO baser foundation <https://baserfoundation.org/>
*
* @copyright Copyright (c) NPO baser foundation
* @link https://basercms.net baserCMS Project
* @since 5.0.0
* @license https://basercms.net/license/index.html MIT License
*/
namespace BcCustomContent\Model\Table;
use ArrayObject;
use BaserCore\Event\BcEventDispatcherTrait;
use BaserCore\Model\Table\AppTable;
use BaserCore\Annotation\UnitTest;
use BaserCore\Annotation\NoTodo;
use BaserCore\Annotation\Checked;
use BcCustomContent\Model\Entity\CustomField;
use Cake\Core\Configure;
use Cake\Datasource\EntityInterface;
use Cake\Event\EventInterface;
use Cake\Utility\Hash;
use Cake\Validation\Validator;
/**
* CustomLinksTable
*
* @property CustomFieldsTable $CustomFields
*/
class CustomLinksTable extends AppTable
{
/**
* Trait
*/
use BcEventDispatcherTrait;
/**
* Initialize
*
* @param array $config
* @checked
* @noTodo
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->addBehavior('Timestamp');
$this->addBehavior('Tree', ['level' => 'level']);
$this->belongsTo('CustomFields')
->setClassName('BcCustomContent.CustomFields')
->setForeignKey('custom_field_id');
$this->belongsTo('CustomTables')
->setClassName('BcCustomContent.CustomTables')
->setForeignKey('custom_table_id');
}
/**
* Validation Default
*
* @param Validator $validator
* @return Validator
*/
public function validationDefault(Validator $validator): Validator
{
$validator
->scalar('name')
->maxLength('name', 255, __d('baser_core', '255文字以内で入力してください。'))
->notEmptyString('name', __d('baser_core', 'フィールド名を入力してください。'))
->regex('name', '/^[a-z0-9_]+$/', __d('baser_core', 'フィールド名は半角英数字とアンダースコアのみで入力してください。'))
->add('name', [[
'rule' => ['validateUnique', ['scope' => 'custom_table_id']],
'provider' => 'table',
'message' => __d('baser_core', '既に登録のあるフィールド名です。')
]])
->add('name', [[
'rule' => ['reserved'],
'provider' => 'bc',
'message' => __d('baser_core', '{0} はシステム予約名称のため利用できません。', implode(', ', Configure::read('BcApp.reservedWords')))
]]);
$validator
->scalar('title')
->maxLength('title', 255, __d('baser_core', '255文字以内で入力してください。'))
->notEmptyString('title', __d('baser_core', 'タイトルを入力してください。'));
return $validator;
}
/**
* イベント定義
*
* scope の設定のため、TreeBehavior より優先度を高くする
*
* @return array
*/
public function implementedEvents(): array
{
$events = parent::implementedEvents();
$events['Model.beforeSave'] = [
'callable' => 'beforeSave',
'priority' => 0,
];
$events['Model.beforeDelete'] = [
'callable' => 'beforeDelete',
'priority' => 0,
];
return $events;
}
/**
* ツリービヘイビアのスコープを設定する
*
* @param int $tableId
*/
public function setTreeScope(int $tableId): void
{
$this->getBehavior('Tree')->setConfig('scope', ['custom_table_id' => $tableId]);
}
/**
* Before Save
* @param EventInterface $event
* @param EntityInterface $entity
* @param ArrayObject $options
* @return bool|void
*/
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)
{
if ($entity->isNew()) {
$entity->name = $this->getUniqueName($entity->name, $entity->custom_table_id);
}
// スコープを設定
$this->setTreeScope($entity->custom_table_id);
}
/**
* Before Delete
* @param EventInterface $event
* @param EntityInterface $entity
* @param ArrayObject $options
*/
public function beforeDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options)
{
// スコープを設定
$this->setTreeScope($entity->custom_table_id);
}
/**
* 並び順を更新する
*
* @param array $customLinks
*/
public function updateSort(array $customLinks)
{
$customLinks = Hash::sort($customLinks, '{n}.sort');
foreach($customLinks as $field) {
$targetSort = $field->sort;
// DBのデータを取得しなおし、lft / rght を最新にする(moveOffset に影響するため)
$field = $this->get($field->id);
$currentSort = $this->getCurentSort($field->id, $field->custom_table_id, $field->parent_id);
$offset = $targetSort - $currentSort;
$this->moveOffset($field, $offset);
}
}
/**
* 同じ階層における並び順を取得
*
* @param int $id
* @param int $tableId
* @param int|null $parentId
* @return bool|int|null
* @checked
* @noTodo
*/
public function getCurentSort(int $id, int $tableId, $parentId)
{
$conditions = ['custom_table_id' => $tableId];
if ($parentId) {
$conditions['parent_id'] = $parentId;
} else {
$conditions['parent_id IS'] = $parentId;
}
$contents = $this->find()
->select(['id', 'parent_id', 'title'])
->where($conditions)
->order('lft');
$order = null;
if (!$contents->all()->isEmpty()) {
foreach($contents as $key => $data) {
if ($id == $data->id) {
$order = $key + 1;
break;
}
}
} else {
return false;
}
return $order;
}
/**
* オフセットを元に関連フィールドを移動する
*
* @param $id
* @param $offset
* @return EntityInterface|bool
* @checked
* @noTodo
*/
public function moveOffset($field, $offset)
{
$offset = (int)$offset;
if ($offset > 0) {
$result = $this->moveDown($field, abs($offset));
} elseif ($offset < 0) {
$result = $this->moveUp($field, abs($offset));
} else {
$result = true;
}
return $result? $field : false;
}
/**
* 一意の name を取得する
*
* @param string $name
* @param int $tableId
* @return string
*/
public function getUniqueName(string $name, int $tableId)
{
// 先頭が同じ名前のリストを取得し、後方プレフィックス付きのフィールド名を取得する
$entities = $this->find()
->select('name')
->where(['name LIKE' => $name . '%', 'custom_table_id' => $tableId])
->order('name')
->all()
->toArray();
if (!$entities) return $name;
$names = Hash::extract($entities, '{n}.name');
$numbers = [];
foreach($names as $value) {
if ($name === $value) {
$numbers[1] = 1;
} elseif (preg_match("/^" . preg_quote($name, '/') . "_([0-9]+)$/s", $value, $matches)) {
$numbers[$matches[1]] = true;
}
}
if ($numbers) {
$prefixNo = 1;
while(true) {
if (!isset($numbers[$prefixNo])) break;
$prefixNo++;
}
if ($prefixNo == 1) {
return $name;
} else {
return $name . '_' . ($prefixNo);
}
} else {
return $name;
}
}
}