Importer::process()   F
last analyzed

Complexity

Conditions 20
Paths 636

Size

Total Lines 75
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 22.1035

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 20
eloc 43
c 4
b 0
f 0
nc 636
nop 1
dl 0
loc 75
ccs 19
cts 23
cp 0.8261
crap 22.1035
rs 0.5054

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
/**
4
 * This file is part of dimtrovich/db-dumper".
5
 *
6
 * (c) 2024 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Dimtrovich\DbDumper;
13
14
use Dimtrovich\DbDumper\Compressor\Factory as CompressorFactory;
15
use Dimtrovich\DbDumper\Exceptions\Exception;
16
use PDOException;
17
18
/**
19
 * @method void onTableCreate(callable(string $tableName) $callback)
20
 * @method void onTableInsert(callable(string $tableName, int $rowCount) $callback)
21
 */
22
class Importer
23
{
24
    use Dumper;
0 ignored issues
show
introduced by
The trait Dimtrovich\DbDumper\Dumper requires some properties which are not provided by Dimtrovich\DbDumper\Importer: $init_commands, $compress
Loading history...
25
26
    /**
27
     * Primary function, triggers restoration.
28
     *
29
     * @param string $filename Name of file to read sql dump to
30
     */
31
    public function process(string $filename): void
32
    {
33 2
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
34
35
        switch ($extension) {
36
            case 'gz':
37
            case 'gzip':
38 2
                $this->compressor = CompressorFactory::create(Option::COMPRESSION_GZIP);
39
                break;
40
41
            case 'bz2':
42
            case 'bzip2':
43 2
                $this->compressor = CompressorFactory::create(Option::COMPRESSION_BZIP2);
44
                break;
45
46
            case 'sql':
47 2
                $this->compressor = CompressorFactory::create(Option::COMPRESSION_NONE);
48 2
                break;
49
50
            default:
51
                throw Exception::unavailableDriverForcompression($extension);
0 ignored issues
show
Bug introduced by
It seems like $extension can also be of type array; however, parameter $extension of Dimtrovich\DbDumper\Exce...eDriverForcompression() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

51
                throw Exception::unavailableDriverForcompression(/** @scrutinizer ignore-type */ $extension);
Loading history...
52
        }
53
54
        if (null === $filename = $this->getFile($filename)) {
55 2
            throw Exception::failledToRead(func_get_arg(0));
56
        }
57
58
        if ($this->option->disable_foreign_keys_check && '' !== $disableForeignKeysCheck = $this->adapter->startDisableForeignKeysCheck()) {
59 2
            $this->pdo->exec($disableForeignKeysCheck);
60
        }
61
62
        /**
63
         * Read backup file line by line
64
         */
65 2
        $handle = fopen($filename, 'rb');
66
67
        if (! $handle) {
0 ignored issues
show
introduced by
$handle is of type resource, thus it always evaluated to false.
Loading history...
68 2
            throw Exception::failledToRead($filename);
69
        }
70
71 2
        $buffer = '';
72
73
        try {
74
            while (! feof($handle)) {
75 2
                $line = fgets($handle);
76
77
                if (substr($line, 0, 2) === '--' || ! $line) {
78 2
                    continue; // skip comments
79
                }
80
81 2
                $buffer .= $line;
82
83
                // if it has a semicolon at the end, it's the end of the query
84
                if (';' === substr(rtrim($line), -1, 1)) {
85
                    if (false !== $affectedRows = $this->pdo->exec($buffer)) {
86
                        if (preg_match('/^CREATE TABLE `([^`]+)`/i', $buffer, $tableName)) {
87 2
                            $this->event->emit('table.create', $tableName[1]);
88
                        }
89
                        if (preg_match('/^INSERT INTO `([^`]+)`/i', $buffer, $tableName)) {
90 2
                            $this->event->emit('table.insert', $tableName[1], $affectedRows);
91
                        }
92
                    }
93
94 2
                    $buffer = '';
95
                }
96
            }
97
        } catch (PDOException $e) {
98
            throw Exception::pdoException($e->getMessage(), $buffer);
99
        } finally {
100 2
            fclose($handle);
101 2
            unlink($filename);
102
        }
103
104
        if ($this->option->disable_foreign_keys_check && '' !== $enableForeignKeysCheck = $this->adapter->endDisableForeignKeysCheck()) {
105 2
            $this->pdo->exec($enableForeignKeysCheck);
106
        }
107
    }
108
109
    /**
110
     * Return unzipped file
111
     */
112
    private function getFile(string $source): ?string
113
    {
114 2
        $pathinfo = pathinfo($source);
115
116 2
        $dest = $pathinfo['dirname'] . '/' . date('Ymd_His', time()) . '_' . $pathinfo['filename'];
117
118
        // Remove $dest file if exists
119
        if (file_exists($dest) && ! unlink($dest)) {
120
            return null;
121
        }
122
123
        // Open gzipped and destination files in binary mode
124 2
        $this->compressor->open($source, 'rb');
125
        if (! $dstFile = fopen($dest, 'wb')) {
126
            return null;
127
        }
128
129
        if (! fwrite($dstFile, $this->compressor->read())) {
130
            return null;
131
        }
132
133 2
        fclose($dstFile);
134 2
        $this->compressor->close();
135
136 2
        return $dest;
137
    }
138
}
139