1 | <?php |
||
30 | trait SimpleTreeTrait |
||
31 | { |
||
32 | |||
33 | use WithParentTrait; |
||
34 | |||
35 | /** |
||
36 | * @RelatedArray('join' = {'_id' = 'parentId'}, 'updatable' = true) |
||
37 | * @RelatedOrdering('order') |
||
38 | * @var AnnotatedInterface[] |
||
39 | */ |
||
40 | public $children = []; |
||
41 | |||
42 | /** |
||
43 | * @Label('Manual sort') |
||
44 | * @var int |
||
45 | */ |
||
46 | public $order = 0; |
||
47 | |||
48 | /** |
||
49 | * NOTE: This must be called by class using this trait |
||
50 | * TODO Move event initializer to some other global event init, as events now handle traits too. |
||
51 | * @Ignored |
||
52 | */ |
||
53 | 7 | public function initTree() |
|
54 | { |
||
55 | 7 | if ($this instanceof TrashInterface) |
|
56 | { |
||
57 | // Trash related events |
||
58 | $onBeforeTrash = function(ModelEvent $event) |
||
59 | { |
||
60 | $event->isValid = true; |
||
61 | }; |
||
62 | Event::on($this, TrashInterface::EventBeforeTrash, $onBeforeTrash); |
||
63 | |||
64 | |||
65 | $onAfterTrash = function(ModelEvent $event) |
||
66 | { |
||
67 | foreach ($event->sender->children as $child) |
||
68 | { |
||
69 | $child->trash(); |
||
70 | } |
||
71 | }; |
||
72 | |||
73 | Event::on($this, TrashInterface::EventAfterTrash, $onAfterTrash); |
||
74 | |||
75 | |||
76 | $onAfterRestore = function(ModelEvent $event) |
||
77 | { |
||
78 | // Root nodes does not have parentId |
||
79 | if ($this->parentId) |
||
80 | { |
||
81 | // Put node to root if parent does not exists |
||
82 | // RawFinder is used for performance reasons here |
||
83 | // and to skip filters |
||
84 | /** |
||
85 | * TODO Similar mechanism should be used to detect orphaned tree items. |
||
86 | * TODO Use exists here instead of raw finder. |
||
87 | * |
||
88 | */ |
||
89 | if (!(new RawFinder($this))->findByPk(new MongoId($this->parentId))) |
||
90 | { |
||
91 | $this->parentId = null; |
||
92 | (new EntityManager($this))->update(['parentId']); |
||
93 | } |
||
94 | } |
||
95 | }; |
||
96 | $onAfterRestore->bindTo($this); |
||
97 | Event::on($this, TrashInterface::EventAfterRestore, $onAfterRestore); |
||
98 | } |
||
99 | 7 | } |
|
100 | |||
101 | /** |
||
102 | * Move to a new parent |
||
103 | * @param string|MongoId $parentId |
||
104 | * @param string[]|MongoId[] $order |
||
105 | * @Ignored |
||
106 | */ |
||
107 | public function moveTo($parentId, $order = []) |
||
124 | |||
125 | } |
||
126 |