Mysql::executeFile()   A
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.2888
c 0
b 0
f 0
cc 5
nc 6
nop 1
1
<?php
2
3
namespace Fabrica\Tools\Plugin;
4
5
use PDO;
6
use Fabrica\Tools\Builder;
7
use Fabrica\Models\Infra\Ci\Build;
8
use Fabrica\Tools\Plugin;
9
use Fabrica\Tools\Database;
10
11
/**
12
 * MySQL Plugin - Provides access to a MySQL database.
13
 *
14
 * @author Ricardo Sierra <[email protected]>
15
 * @author Steve Kamerman <[email protected]>
16
 */
17
class Mysql extends Plugin
18
{
19
    /**
20
     * @var string
21
     */
22
    protected $host;
23
24
    /**
25
     * @var string
26
     */
27
    protected $user;
28
29
    /**
30
     * @var string
31
     */
32
    protected $pass;
33
34
    /**
35
     * @return string
36
     */
37
    public static function pluginName()
38
    {
39
        return 'mysql';
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function __construct(Builder $builder, Build $build, array $options = [])
46
    {
47
        parent::__construct($builder, $build, $options);
48
49
        $config = Database::getConnection('write')->getDetails();
50
51
        $this->host =(defined('DB_HOST')) ? DB_HOST : null;
52
        $this->user = $config['user'];
53
        $this->pass = $config['pass'];
54
55
        $buildSettings = $this->builder->getConfig('build_settings');
56
        if (!isset($buildSettings['mysql'])) {
57
            return;
58
        }
59
60 View Code Duplication
        if (!empty($buildSettings['mysql']['host'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
61
            $this->host = $this->builder->interpolate($buildSettings['mysql']['host']);
62
        }
63
64 View Code Duplication
        if (!empty($buildSettings['mysql']['user'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
65
            $this->user = $this->builder->interpolate($buildSettings['mysql']['user']);
66
        }
67
68
        if (array_key_exists('pass', $buildSettings['mysql'])) {
69
            $this->pass = $buildSettings['mysql']['pass'];
70
        }
71
    }
72
73
    /**
74
     * Connects to MySQL and runs a specified set of queries.
75
     *
76
     * @return bool
77
     */
78
    public function execute()
79
    {
80
        try {
81
            $opts = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION];
82
            $pdo  = new PDO('mysql:host=' . $this->host, $this->user, $this->pass, $opts);
83
84
            foreach ($this->options as $query) {
85
                if (!is_array($query)) {
86
                    // Simple query
87
                    $pdo->query($this->builder->interpolate($query));
88
                } elseif (isset($query['import'])) {
89
                    // SQL file execution
90
                    $this->executeFile($query['import']);
91
                } else {
92
                    throw new \Exception('Invalid command.');
93
                }
94
            }
95
        } catch (\Exception $ex) {
96
            $this->builder->logFailure($ex->getMessage());
97
            return false;
98
        }
99
        return true;
100
    }
101
102
    /**
103
     * @param array $query
104
     *
105
     * @return bool
106
     *
107
     * @throws \Exception
108
     */
109
    protected function executeFile(array $query)
110
    {
111
        if (!isset($query['file'])) {
112
            throw new \Exception('Import statement must contain a \'file\' key');
113
        }
114
115
        $importFile = $this->builder->buildPath . $this->builder->interpolate($query['file']);
116
        if (!is_readable($importFile)) {
117
            throw new \Exception(sprintf('Cannot open SQL import file: %s', $importFile));
118
        }
119
120
        $database = isset($query['database']) ? $this->builder->interpolate($query['database']) : null;
121
122
        $importCommand = $this->getImportCommand($importFile, $database);
123
        if (!$this->builder->executeCommand($importCommand)) {
124
            throw new \Exception('Unable to execute SQL file');
125
        }
126
127
        return true;
128
    }
129
130
    /**
131
     * Builds the MySQL import command required to import/execute the specified file
132
     *
133
     * @param string $importFile Path to file, relative to the build root
134
     * @param string $database   If specified, this database is selected before execution
135
     *
136
     * @return string
137
     */
138
    protected function getImportCommand($importFile, $database = null)
139
    {
140
        $decompression = [
141
            'bz2' => '| bzip2 --decompress',
142
            'gz'  => '| gzip --decompress',
143
        ];
144
145
        $extension        = strtolower(pathinfo($importFile, PATHINFO_EXTENSION));
146
        $decompressionCmd = '';
147
        if (array_key_exists($extension, $decompression)) {
148
            $decompressionCmd = $decompression[$extension];
149
        }
150
151
        $args = [
152
            ':import_file' => escapeshellarg($importFile),
153
            ':decomp_cmd'  => $decompressionCmd,
154
            ':host'        => escapeshellarg($this->host),
155
            ':user'        => escapeshellarg($this->user),
156
            ':pass'        => (!$this->pass) ? '' : '-p' . escapeshellarg($this->pass),
157
            ':database'    => ($database === null)? '': escapeshellarg($database),
158
        ];
159
160
        return strtr('cat :import_file :decomp_cmd | mysql -h:host -u:user :pass :database', $args);
161
    }
162
}
163