Completed
Push — feature/EVO-5751-text-search-j... ( 60a9de...198b26 )
by
unknown
179:20 queued 174:02
created

GenerateBuildIndexesCommand::getMongoDBVersion()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 4
Bugs 0 Features 0
Metric Value
dl 0
loc 9
ccs 0
cts 5
cp 0
rs 9.6666
c 4
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
crap 6
1
<?php
2
/**
3
 * generate MongoDB Fulltext-Search Indexes
4
 */
5
6
namespace Graviton\GeneratorBundle\Command;
7
8
use Doctrine\ODM\MongoDB\DocumentManager;
9
use Symfony\Component\Console\Command\Command;
10
use Symfony\Component\Console\Input\InputInterface;
11
use Symfony\Component\Console\Input\InputOption;
12
use Symfony\Component\Console\Output\OutputInterface;
13
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
14
15
/**
16
 * Here, we generate all MongoDB Fulltext-Search Indexes
17
 *
18
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
19
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
20
 * @link     http://swisscom.ch
21
 */
22
class GenerateBuildIndexesCommand extends Command
23
{
24
    /**
25
     * @var documentManager
26
     */
27
    private $documentManager;
28
29
    /**
30
     * GenerateBuildIndexesCommand constructor.
31
     *
32
     * @param DocumentManager $documentManager The Doctrine Document Manager
33
     * @param String          $name            The Name of this Command
0 ignored issues
show
Documentation introduced by
Should the type for parameter $name not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
34
     */
35 2
    public function __construct(DocumentManager $documentManager, $name = null)
36
    {
37 2
        parent::__construct($name);
38
39 2
        $this->documentManager = $documentManager;
0 ignored issues
show
Documentation Bug introduced by
It seems like $documentManager of type object<Doctrine\ODM\MongoDB\DocumentManager> is incompatible with the declared type object<Graviton\Generato...ommand\documentManager> of property $documentManager.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
40 2
    }
41
42
    /**
43
     * {@inheritDoc}
44
     *
45
     * @return void
46
     */
47 2
    protected function configure()
48
    {
49 2
        parent::configure();
50
51 1
        $this
52 2
            ->setName('graviton:generate:build-indexes')
53 2
            ->setDescription(
54 1
                'Generates Mongo-Text Indexes (MongoDB >= 2.6) for collections as defined'
55 1
            );
56 2
    }
57
58
    /**
59
     * {@inheritDoc}
60
     *
61
     * @param InputInterface  $input  input
62
     * @param OutputInterface $output output
63
     *
64
     * @return void
65
     */
66
    protected function execute(InputInterface $input, OutputInterface $output)
67
    {
68
        // Check mongo db version
69
        $mongoVersion = $this->getMongoDBVersion('Graviton\\CoreBundle\\Document\\App');
70
        if ((float) $mongoVersion < 2.6) {
71
            $output->writeln("MongoDB Version < 2.6 installed: " . $mongoVersion);
72
            exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method execute() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
73
        }
74
75
        $metadatas = $this->documentManager->getMetadataFactory()->getAllMetadata();
76
        /** @var ClassMetadata $metadata */
77
        foreach ($metadatas as $metadata) {
78
            $indexes = $metadata->getIndexes();
79
            $searchName = 'search'.$metadata->getCollection().'Index';
80
            foreach ($indexes as $index) {
81
                if (array_key_exists('keys', $index) && array_key_exists($searchName, $index['keys'])) {
82
                    if (array_key_exists('options', $index) && !empty($index['options'])) {
83
                        $collection = $this->documentManager->getDocumentCollection($metadata->getName());
84
                        if (!$collection) {
85
                            continue;
86
                        }
87
                        $newIndex = [];
88
                        $weights = [];
89
                        foreach ($index['options'] as $optionName => $optionsValue) {
90
                            if (strpos($optionName, 'search_') !== false) {
91
                                $optionName = str_replace('search_', '', $optionName);
92
                                $newIndex[$optionName] = 'text';
93
                                $weights[$optionName] = floatval($optionsValue);
94
                            }
95
                        }
96
                        if (empty($weights)) {
97
                            continue;
98
                        }
99
                        foreach ($collection->getIndexInfo() as $indexInfo) {
100
                            // When using doctrine name may have a _1
101
                            if (strpos($indexInfo['name'], $searchName) !== false) {
102
                                $output->writeln("Deleting Custom Text index {$searchName}");
103
                                $this->documentManager->getDocumentDatabase($metadata->getName())->command(
104
                                    [
105
                                        "deleteIndexes" => $collection->getName(),
106
                                        "index" => $indexInfo['name']
107
                                    ]
108
                                );
109
                                break;
110
                            }
111
                        }
112
                        $output->writeln($metadata->getName().": created custom Text index {$searchName}");
113
                        $collection->ensureIndex(
114
                            $newIndex,
115
                            [
116
                                'weights' => $weights,
117
                                'name'    => $searchName,
118
                                'default_language'  => 'de',
119
                                'language_override' => 'language'
120
                            ]
121
                        );
122
                    }
123
                }
124
            }
125
        }
126
127
    }
128
129
    /**
130
     * Gets the installed MongoDB Version
131
     * @param String $className The Classname of the collection, needed to fetch the right DB connection
132
     * @return String getMongoDBVersion The version of the MongoDB as a string
133
     */
134
    private function getMongoDBVersion($className)
135
    {
136
        $buildInfo = $this->documentManager->getDocumentDatabase($className)->command(['buildinfo' => 1]);
137
        if (isset($buildInfo['version'])) {
138
            return $buildInfo['version'];
139
        } else {
140
            return 'unkown';
141
        }
142
    }
143
}
144