Completed
Push — master ( 3a80c3...bb241f )
by Simonas
03:00 queued 01:04
created

ExportService::exportIndex()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 71
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 71
rs 9.1369
cc 3
eloc 50
nc 3
nop 6

How to fix   Long Method   

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
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ONGR\ElasticsearchBundle\Service;
13
14
use Elasticsearch\Helper\Iterators\SearchHitIterator;
15
use Elasticsearch\Helper\Iterators\SearchResponseIterator;
16
use ONGR\ElasticsearchBundle\Result\RawIterator;
17
use ONGR\ElasticsearchBundle\Service\Json\JsonWriter;
18
use ONGR\ElasticsearchDSL\Query\MatchAllQuery;
19
use ONGR\ElasticsearchDSL\Search;
20
use Symfony\Component\Console\Helper\ProgressBar;
21
use Symfony\Component\Console\Output\OutputInterface;
22
23
/**
24
 * ExportService class.
25
 */
26
class ExportService
27
{
28
    /**
29
     * Exports es index to provided file.
30
     *
31
     * @param Manager         $manager
32
     * @param string          $filename
33
     * @param array           $types
34
     * @param int             $chunkSize
35
     * @param int             $maxLinesInFile
36
     * @param OutputInterface $output
37
     */
38
    public function exportIndex(
39
        Manager $manager,
40
        $filename,
41
        $types,
42
        $chunkSize,
43
        OutputInterface $output,
44
        $maxLinesInFile = 300000
45
    ) {
46
47
        $search = new Search();
48
        $search->addQuery(new MatchAllQuery());
49
        $search->setSize($chunkSize);
50
51
        $queryParameters = [
52
                '_source' => true,
53
                'scroll' => '10m',
54
            ];
55
56
        $searchResults = $manager->search($types, $search->toArray(), $queryParameters);
57
58
        $results = new RawIterator(
59
            $searchResults,
0 ignored issues
show
Documentation introduced by
$searchResults is of type callable, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
60
            $manager,
61
            [
62
                'duration' => $queryParameters['scroll'],
63
                '_scroll_id' => $searchResults['_scroll_id'],
64
            ]
65
        );
66
67
        $progress = new ProgressBar($output, $results->count());
68
        $progress->setRedrawFrequency(100);
69
        $progress->start();
70
71
        $counter = $fileCounter = 0;
72
        $count = $this->getFileCount($results->count(), $maxLinesInFile, $fileCounter);
73
74
        $date = date(\DateTime::ISO8601);
75
        $metadata = [
76
            'count' => $count,
77
            'date' => $date,
78
        ];
79
80
        $filename = str_replace('.json', '', $filename);
81
        $writer = $this->getWriter($this->getFilePath($filename.'.json'), $metadata);
82
83
        $file = [];
84
        foreach ($results as $data) {
85
            if ($counter >= $maxLinesInFile) {
86
                $writer->finalize();
87
                $writer = null;
0 ignored issues
show
Unused Code introduced by
$writer is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
88
                $fileCounter++;
89
                $count = $this->getFileCount($results->count(), $maxLinesInFile, $fileCounter);
90
                $metadata = [
91
                    'count' => $count,
92
                    'date' => $date,
93
                ];
94
                $writer = $this->getWriter($this->getFilePath($filename."_".$fileCounter.".json"), $metadata);
95
                $counter = 0;
96
            }
97
98
            $doc = array_intersect_key($data, array_flip(['_id', '_type', '_source']));
99
            $writer->push($doc);
100
            $file[] = $doc;
101
            $progress->advance();
102
            $counter++;
103
        }
104
105
        $writer->finalize();
106
        $progress->finish();
107
        $output->writeln('');
108
    }
109
110
    /**
111
     * Returns real file path.
112
     *
113
     * @param string $filename
114
     *
115
     * @return string
116
     */
117 View Code Duplication
    protected function getFilePath($filename)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
118
    {
119
        if ($filename{0} == '/' || strstr($filename, ':') !== false) {
120
            return $filename;
121
        }
122
123
        return getcwd() . '/' . $filename;
124
    }
125
126
    /**
127
     * Prepares JSON writer.
128
     *
129
     * @param string $filename
130
     * @param array  $metadata
131
     *
132
     * @return JsonWriter
133
     */
134
    protected function getWriter($filename, $metadata)
135
    {
136
        return new JsonWriter($filename, $metadata);
137
    }
138
139
    /**
140
     * @param int $resultsCount
141
     * @param int $maxLinesInFile
142
     * @param int $fileCounter
143
     *
144
     * @return int
145
     */
146
    protected function getFileCount($resultsCount, $maxLinesInFile, $fileCounter)
147
    {
148
        $leftToInsert = $resultsCount - ($fileCounter * $maxLinesInFile);
149
        if ($leftToInsert <= $maxLinesInFile) {
150
            $count = $leftToInsert;
151
        } else {
152
            $count = $maxLinesInFile;
153
        }
154
155
        return $count;
156
    }
157
}
158