Completed
Push — master ( d2fb93...a24186 )
by Narcotic
26:10 queued 11:13
created

GenerateBuildIndexesCommand   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 124
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 2
dl 0
loc 124
ccs 10
cts 10
cp 1
rs 10
c 0
b 0
f 0

4 Methods

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