Completed
Push — master ( 2aab0a...440703 )
by Raffael
19:06 queued 15:05
created

CreateUniqueNodeIndex::start()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 43
ccs 0
cts 39
cp 0
rs 9.232
c 0
b 0
f 0
cc 2
nc 2
nop 0
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * balloon
7
 *
8
 * @copyright   Copryright (c) 2012-2018 gyselroth GmbH (https://gyselroth.com)
9
 * @license     GPL-3.0 https://opensource.org/licenses/GPL-3.0
10
 */
11
12
namespace Balloon\Migration\Delta;
13
14
use MongoDB\Database;
15
16
class CreateUniqueNodeIndex implements DeltaInterface
17
{
18
    /**
19
     * Database.
20
     *
21
     * @var Database
22
     */
23
    protected $db;
24
25
    /**
26
     * Construct.
27
     */
28
    public function __construct(Database $db)
29
    {
30
        $this->db = $db;
31
    }
32
33
    /**
34
     * Start.
35
     */
36
    public function start(): bool
37
    {
38
        $pipeline = [
39
            ['$group' => [
40
                '_id' => [
41
                    'name' => '$name',
42
                    'parent' => '$parent',
43
                    'owner' => '$owner',
44
                    'deleted' => '$deleted',
45
                ],
46
                'count' => [
47
                    '$sum' => 1,
48
                ],
49
                'nodes' => [
50
                    '$addToSet' => '$_id',
51
                ],
52
            ]],
53
            ['$match' => [
54
                '_id' => ['$ne' => null],
55
                'count' => ['$gt' => 1],
56
            ]],
57
        ];
58
59
        $cursor = $this->db->storage->aggregate($pipeline, [
60
            'allowDiskUse' => true,
61
        ]);
62
63
        foreach ($cursor as $object) {
64
            $id = array_pop($object['nodes']);
65
            $this->db->storage->deleteOne(['_id' => $id]);
66
        }
67
68
        $this->db->storage->createIndex([
69
            'name' => 1,
70
            'owner' => 1,
71
            'parent' => 1,
72
            'deleted' => 1,
73
        ], [
74
            'unique' => true,
75
        ]);
76
77
        return true;
78
    }
79
}
80