Completed
Push — feature/add-cache-control-head... ( 0c63ca...d673be )
by Narcotic
14:55
created

GenerateBuildIndexesCommand::execute()   C

Complexity

Conditions 14
Paths 11

Size

Total Lines 66
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 210

Importance

Changes 0
Metric Value
dl 0
loc 66
ccs 0
cts 52
cp 0
rs 5.8815
c 0
b 0
f 0
cc 14
eloc 43
nc 11
nop 2
crap 210

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 2
        $this
55 4
            ->setName('graviton:generate:build-indexes')
56 4
            ->setDescription(
57 2
                'Generates Mongo-Text Indexes (MongoDB >= 2.6) for collections as defined'
58 2
            );
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) &&
85
                    array_key_exists('options', $index) &&
86
                    array_key_exists('name', $index['options']) &&
87
                    $searchName == $index['options']['name'] &&
88
                    is_array($index['keys']) && !empty($index['keys'])
89
                ) {
90
                    $collection = $this->documentManager->getDocumentCollection($metadata->getName());
91
                    if (!$collection) {
92
                        continue;
93
                    }
94
95
                    $newIndex = [];
96
                    $weights = [];
97
                    foreach (array_keys($index['keys']) as $optionKeyName) {
98
                        if (substr($optionKeyName, 0, 7) == 'search_') {
99
                            $options = explode('-', substr($optionKeyName, 7));
100
                            $value = end($options);
101
                            array_pop($options);
102
                            $fieldName = implode('-', $options);
103
                            $newIndex[$fieldName] = 'text';
104
                            $weights[$fieldName] = floatval($value);
105
                        }
106
                    }
107
                    if (empty($weights)) {
108
                        $output->writeln("No Custom Text index for: {$searchName}");
109
                        continue;
110
                    }
111
112
                    $output->writeln("Deleting Custom Text index {$searchName}");
113
                    $this->documentManager->getDocumentDatabase($metadata->getName())->command(
114
                        [
115
                            "deleteIndexes" => $collection->getName(),
116
                            "index" => $searchName
117
                        ]
118
                    );
119
120
                    $newIndexName = str_replace('_', '', $searchName);
121
                    $output->writeln($metadata->getName().": creating custom Text index {$newIndexName}");
122
                    $collection->ensureIndex(
123
                        $newIndex,
124
                        [
125
                            'weights' => $weights,
126
                            'name'    => $newIndexName,
127
                            'default_language'  => 'de',
128
                            'language_override' => 'none'
129
                        ]
130
                    );
131
                }
132
            }
133
        }
134
    }
135
136
    /**
137
     * Gets the installed MongoDB Version
138
     * @param String $className The Classname of the collection, needed to fetch the right DB connection
139
     * @return String getMongoDBVersion The version of the MongoDB as a string
140
     */
141
    private function getMongoDBVersion($className)
142
    {
143
        $buildInfo = $this->documentManager->getDocumentDatabase($className)->command(['buildinfo' => 1]);
144
        if (isset($buildInfo['version'])) {
145
            return $buildInfo['version'];
146
        } else {
147
            return 'unkown';
148
        }
149
    }
150
}
151