forked from modstart/ModStartBlog
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree.php
More file actions
132 lines (115 loc) · 2.95 KB
/
Copy pathTree.php
File metadata and controls
132 lines (115 loc) · 2.95 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
<?php
namespace ModStart\Field;
use ModStart\Core\Util\ConvertUtil;
use ModStart\Core\Util\SerializeUtil;
use ModStart\Field\Type\FieldRenderMode;
class Tree extends AbstractField
{
private $columnNames = [
'id' => 'id',
'title' => 'title',
'children' => '_child',
];
protected function setup()
{
$this->addVariables([
'spread' => true,
'independentEnable' => false,
'nodes' => [],
]);
}
/**
* 设置id字段映射
* @param $value
* @return $this
*/
public function columnNameId($value)
{
$this->columnNames['id'] = $value;
return $this;
}
/**
* 设置title字段映射
* @param $value
* @return $this
*/
public function columnNameTitle($value)
{
$this->columnNames['title'] = $value;
return $this;
}
/**
* 设置children字段映射
* @param $value
* @return $this
*/
public function columnNameChildren($value)
{
$this->columnNames['children'] = $value;
return $this;
}
/**
* 设置是否展开
* @param $value bool 是否展开
* @return $this
*/
public function spread($value)
{
$this->addVariables(['spread' => $value]);
return $this;
}
/**
* 是否为独立模式,独立模式下,树状的节点父子选项不会做任何关联
* @param $enable bool 是否启用独立模式
* @return $this
*/
public function independentEnable($enable)
{
$this->addVariables(['independentEnable' => $enable]);
return $this;
}
public function unserializeValue($value, AbstractField $field)
{
if (null === $value) {
return $value;
}
return ConvertUtil::toArray($value);
}
public function serializeValue($value, $model)
{
return SerializeUtil::jsonEncode($value);
}
public function prepareInput($value, $model)
{
return ConvertUtil::toArray($value);
}
/**
* 设置树状节点的待选值
*
* @param \Closure|array $tree
* @return $this
*/
public function tree($tree)
{
if ($tree instanceof \Closure) {
$tree = $tree($this);
}
$this->addVariables(['nodes' => $this->formatNodes($tree)]);
return $this;
}
private function formatNodes($tree)
{
$nodes = [];
foreach ($tree as $item) {
$newItem = [];
$newItem['spread'] = $this->getVariable('spread', true);
$newItem['id'] = $item[$this->columnNames['id']];
$newItem['title'] = $item[$this->columnNames['title']];
if (!empty($item[$this->columnNames['children']])) {
$newItem['children'] = $this->formatNodes($item[$this->columnNames['children']]);
}
$nodes[] = $newItem;
}
return $nodes;
}
}