ExportService   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 107
Duplicated Lines 7.48 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 7
dl 8
loc 107
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
B exportIndex() 0 64 3
A getFilePath() 8 8 3
A getWriter() 0 4 1
A getFileCount() 0 11 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
    public function exportIndex(
29
        IndexService $index,
30
        $filename,
31
        $chunkSize,
32
        OutputInterface $output,
33
        $maxLinesInFile = 300000
34
    ) {
35
        $search = new Search();
36
        $search->addQuery(new MatchAllQuery());
37
        $search->setSize($chunkSize);
38
        $search->setScroll('2m');
39
40
        $searchResults = $index->search($search->toArray(), $search->getUriParams());
41
42
        $results = new RawIterator(
43
            $searchResults,
44
            $index,
45
            null,
46
            [
47
                'duration' => '2m',
48
                '_scroll_id' => $searchResults['_scroll_id'],
49
            ]
50
        );
51
52
        $progress = new ProgressBar($output, $results->count());
53
        $progress->setRedrawFrequency(100);
54
        $progress->start();
55
56
        $counter = $fileCounter = 0;
57
        $count = $this->getFileCount($results->count(), $maxLinesInFile, $fileCounter);
58
59
        $date = date(\DateTime::ISO8601);
60
        $metadata = [
61
            'count' => $count,
62
            'date' => $date,
63
        ];
64
65
        $filename = str_replace('.json', '', $filename);
66
        $writer = $this->getWriter($this->getFilePath($filename.'.json'), $metadata['count']);
67
68
        foreach ($results as $data) {
69
            if ($counter >= $maxLinesInFile) {
70
                $writer->finalize();
71
                $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...
72
                $fileCounter++;
73
                $count = $this->getFileCount($results->count(), $maxLinesInFile, $fileCounter);
74
                $metadata = [
75
                    'count' => $count,
76
                    'date' => $date,
77
                ];
78
                $writer = $this->getWriter($this->getFilePath($filename."_".$fileCounter.".json"), $metadata['count']);
79
                $counter = 0;
80
            }
81
82
            $doc = array_intersect_key($data, array_flip(['_id', '_source']));
83
            $writer->push($doc);
84
            $progress->advance();
85
            $counter++;
86
        }
87
88
        $writer->finalize();
89
        $progress->finish();
90
        $output->writeln('');
91
    }
92
93
    /**
94
     * Returns real file path.
95
     *
96
     * @param string $filename
97
     *
98
     * @return string
99
     */
100 View Code Duplication
    protected function getFilePath($filename): string
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...
101
    {
102
        if ($filename[0] == '/' || strstr($filename, ':') !== false) {
103
            return $filename;
104
        }
105
106
        return getcwd() . '/' . $filename;
107
    }
108
109
    protected function getWriter(string $filename, int $count): JsonWriter
110
    {
111
        return new JsonWriter($filename, $count);
112
    }
113
114
    /**
115
     * @param int $resultsCount
116
     * @param int $maxLinesInFile
117
     * @param int $fileCounter
118
     *
119
     * @return int
120
     */
121
    protected function getFileCount($resultsCount, $maxLinesInFile, $fileCounter): int
122
    {
123
        $leftToInsert = $resultsCount - ($fileCounter * $maxLinesInFile);
124
        if ($leftToInsert <= $maxLinesInFile) {
125
            $count = $leftToInsert;
126
        } else {
127
            $count = $maxLinesInFile;
128
        }
129
130
        return (int) $count;
131
    }
132
}
133