Completed
Push — feature/EVO-5751-text-search-j... ( c6ed70...86d6f0 )
by
unknown
293:11 queued 287:20
created

GenerateBuildIndexesCommand::configure()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 10
ccs 8
cts 8
cp 1
rs 9.4285
cc 1
eloc 6
nc 1
nop 0
crap 1
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 Graviton\GeneratorBundle\Definition\Loader\LoaderInterface;
10
use Symfony\Component\Console\Command\Command;
11
use Symfony\Component\Console\Input\InputInterface;
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
    /**
26
     * @var documentManager
27
     */
28
    private $documentManager;
29
30
    /**
31
     * GenerateBuildIndexesCommand constructor.
32
     *
33
     * @param LoaderInterface $definitionLoader The definition Loader - loads Definitions from JSON-Files
0 ignored issues
show
Bug introduced by
There is no parameter named $definitionLoader. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
34
     * @param DocumentManager $documentManager  The Doctrine Document Manager
35
     * @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...
36
     */
37 2
    public function __construct(
38
        DocumentManager $documentManager,
39
        $name = null
40
    ) {
41 2
        parent::__construct($name);
42
43 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...
44 2
    }
45
46
    /**
47
     * {@inheritDoc}
48
     *
49
     * @return void
50
     */
51 2
    protected function configure()
52
    {
53 2
        parent::configure();
54
55 1
        $this
56 2
            ->setName('graviton:generate:build-indexes')
57 2
            ->setDescription(
58 1
                'Generates Mongo-Text Indexes (MongoDB >= 2.6) for collections as defined'
59 1
            );
60 2
    }
61
62
    /**
63
     * {@inheritDoc}
64
     *
65
     * @param InputInterface  $input  input
66
     * @param OutputInterface $output output
67
     *
68
     * @return void
69
     */
70
    protected function execute(InputInterface $input, OutputInterface $output)
71
    {
72
        // Check mongo db version
73
        $mongoVersion = $this->getMongoDBVersion('Graviton\\CoreBundle\\Document\\App');
74
        if ((float) $mongoVersion < 2.6) {
75
            $output->writeln("MongoDB Version < 2.6 installed: " . $mongoVersion);
76
            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...
77
        }
78
79
        $metadatas = $this->documentManager->getMetadataFactory()->getAllMetadata();
80
        /** @var ClassMetadata $metadata */
81
        foreach ($metadatas as $metadata) {
82
            $indexes = $metadata->getIndexes();
83
            $searchName = 'search'.$metadata->getCollection().'Index';
84
            foreach ($indexes as $index) {
85
                if (array_key_exists('keys', $index) && array_key_exists($searchName, $index['keys'])) {
86
                    if (array_key_exists('options', $index) && !empty($index['options'])) {
87
                        $collection = $this->documentManager->getDocumentCollection($metadata->getName());
88
                        if (!$collection) {
89
                            continue;
90
                        }
91
                        $newIndex = [];
92
                        $weights = [];
93
                        foreach ($index['options'] as $optionName => $optionsValue) {
94
                            if (strpos($optionName, 'search_') !== false) {
95
                                $optionName = str_replace('search_', '', $optionName);
96
                                $newIndex[$optionName] = 'text';
97
                                $weights[$optionName] = floatval($optionsValue);
98
                            }
99
                        }
100
                        if (empty($weights)) {
101
                            continue;
102
                        }
103
                        foreach ($collection->getIndexInfo() as $indexInfo) {
104
                            // When using doctrine name may have a _1
105
                            if (strpos($indexInfo['name'], $searchName) !== false) {
106
                                $output->writeln("Deleting Custom Text index {$searchName}");
107
                                $this->documentManager->getDocumentDatabase($metadata->getName())->command(
108
                                    [
109
                                        "deleteIndexes" => $collection->getName(),
110
                                        "index" => $indexInfo['name']
111
                                    ]
112
                                );
113
                                break;
114
                            }
115
                        }
116
                        $output->writeln($metadata->getName().": created custom Text index {$searchName}");
117
                        $collection->ensureIndex(
118
                            $newIndex,
119
                            [
120
                                'weights' => $weights,
121
                                'name'    => $searchName,
122
                                'default_language'  => 'de',
123
                                'language_override' => 'dummy'
124
                            ]
125
                        );
126
                    }
127
                }
128
            }
129
        }
130
131
    }
132
133
    /**
134
     * Gets the installed MongoDB Version
135
     * @param String $className The Classname of the collection, needed to fetch the right DB connection
136
     * @return String getMongoDBVersion The version of the MongoDB as a string
137
     */
138
    private function getMongoDBVersion($className)
139
    {
140
        $buildInfo = $this->documentManager->getDocumentDatabase($className)->command(['buildinfo' => 1]);
141
        if (isset($buildInfo['version'])) {
142
            return $buildInfo['version'];
143
        } else {
144
            return 'unkown';
145
        }
146
    }
147
}
148