Completed
Push — master ( bf6e80...735d1e )
by Dmitry
02:15
created

NestedSet   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 167
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 5
dl 0
loc 167
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A addIndexes() 0 19 4
C beforeCreate() 0 58 9
A beforeRemove() 0 57 4
A isNested() 0 14 4
A resetNestedSpacesCache() 0 4 1
1
<?php
2
3
namespace Tarantool\Mapper\Plugin;
4
5
use Tarantool\Mapper\Entity;
6
use Tarantool\Mapper\Mapper;
7
use Tarantool\Mapper\Plugin;
8
use Tarantool\Mapper\Space;
9
10
class NestedSet extends Plugin
11
{
12
    private $keys = ['id', 'parent', 'root', 'depth', 'left', 'right'];
13
    private $nestedSpaces = [];
14
15
    public function __construct(Mapper $mapper)
16
    {
17
        $this->mapper = $mapper;
18
    }
19
20
    public function addIndexes(Space $space)
21
    {
22
        $indexes = [
23
            ['id'],
24
            [
25
                'fields' => ['parent'],
26
                'unique' => false,
27
            ],
28
            ['root', 'left'],
29
            ['root', 'right'],
30
        ];
31
32
        foreach ($indexes as $index) {
33
            $fields = array_key_exists('fields', $index) ? $index['fields'] : $index;
34
            if ($space->castIndex(array_flip($fields), true) === null) {
35
                $space->createIndex($index);
36
            }
37
        }
38
    }
39
40
    public function beforeCreate(Entity $entity, Space $space)
41
    {
42
        if (!$this->isNested($space)) {
43
            return;
44
        }
45
        $repository = $space->getRepository();
46
47
        if ($entity->parent) {
48
            $parent = $repository->findOne($entity->parent);
0 ignored issues
show
Bug introduced by
The property parent does not seem to exist in Tarantool\Mapper\Entity.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
49
            $entity->depth = $parent->depth + 1;
0 ignored issues
show
Bug introduced by
The property depth does not seem to exist in Tarantool\Mapper\Entity.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
50
51
            $updateLeft = [];
52
            $updateRight = [];
53
            foreach ($repository->find(['root' => $entity->root]) as $node) {
0 ignored issues
show
Bug introduced by
The property root does not seem to exist in Tarantool\Mapper\Entity.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
54
                if ($node->right >= $parent->right) {
55
                    if ($node->left > $parent->right) {
56
                        $updateLeft[$node->left] = $node;
57
                    }
58
                    $updateRight[$node->right] = $node;
59
                }
60
            }
61
62
            $entity->left = $parent->right;
0 ignored issues
show
Bug introduced by
The property left does not seem to exist in Tarantool\Mapper\Entity.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
63
            $entity->right = $entity->left + 1;
0 ignored issues
show
Bug introduced by
The property right does not seem to exist in Tarantool\Mapper\Entity.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
64
65
            krsort($updateRight);
66
            foreach ($updateRight as $node) {
67
                $node->right += 2;
68
                $node->save();
69
            }
70
71
            krsort($updateLeft);
72
            foreach ($updateLeft as $node) {
73
                $node->left += 2;
74
                $node->save();
75
            }
76
        } else {
77
            // new root
78
            $map = $space->getTupleMap();
79
            $spaceName = $space->getName();
80
81
            $entity->root = $entity->root ?: 0;
82
            $max = $this->mapper->getClient()->evaluate("
83
                local max = 0
84
                local root = $entity->root
85
                for i, n in box.space.$spaceName.index.root_right:pairs(root, {iterator = 'le'}) do
86
                    if n[$map->root] == root then
87
                        max = n[$map->right]
88
                    end
89
                    break
90
                end
91
                return max
92
            ")->getData()[0];
93
94
            $entity->left = $max + 1;
95
            $entity->right = $entity->left + 1;
96
        }
97
    }
98
99
    public function beforeRemove(Entity $instance, Space $space)
100
    {
101
        if (!$this->isNested($space)) {
102
            return;
103
        }
104
105
        $spaceName = $space->getName();
106
        $map = $space->getTupleMap();
107
108
        $result = $this->mapper->getClient()->evaluate("
109
            local removed_node = box.space.$spaceName:get($instance->id)
0 ignored issues
show
Bug introduced by
The property id does not seem to exist in Tarantool\Mapper\Entity.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
110
            local remove_list = {}
111
            local update_list = {}
112
            for i, current in box.space.$spaceName.index.root_left:pairs({removed_node[$map->root], removed_node[$map->left]}, 'gt') do
113
                if current[$map->root] ~= removed_node[$map->root] then
114
                    break
115
                end
116
                if current[$map->left] < removed_node[$map->right] then
117
                    table.insert(remove_list, current[$map->id])
118
                else
119
                    table.insert(update_list, current[$map->id])
120
                end
121
            end
122
123
            local delta = removed_node[$map->right] - removed_node[$map->left] + 1
124
125
            for i, id in ipairs(remove_list) do
126
                box.space.$spaceName:delete(id)
127
            end
128
129
            box.space.$spaceName:update($instance->id, {
130
                {'=', $map->left, 0},
131
                {'=', $map->right, 0},
132
            })
133
134
            for i, id in pairs(update_list) do
135
                box.space.$spaceName:update(id, {
136
                    {'-', $map->left, delta},
137
                    {'-', $map->right, delta}
138
                })
139
            end
140
141
            return remove_list, update_list, delta, removed_node
142
        ")->getData();
143
144
        // remove
145
        foreach ($result[0] as $id) {
146
            $space->getRepository()->forget($id);
147
        }
148
149
        // update
150
        foreach ($result[1] as $id) {
151
            $space->getRepository()->sync($id);
152
        }
153
154
        $space->getRepository()->flushCache();
155
    }
156
157
    public function isNested(Space $space, $force = false)
158
    {
159
        $spaceName = $space->getName();
160
        if ($force || !array_key_exists($spaceName, $this->nestedSpaces)) {
161
            $fields = [];
162
            foreach ($space->getFormat() as $field) {
163
                $fields[] = $field['name'];
164
            }
165
166
            $this->nestedSpaces[$spaceName] = !count(array_diff($this->keys, $fields));
167
        }
168
169
        return $this->nestedSpaces[$spaceName];
170
    }
171
172
    public function resetNestedSpacesCache()
173
    {
174
        $this->nestedSpaces = [];
175
    }
176
}
177