Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.48% covered (success)
90.48%
19 / 21
0.00% covered (danger)
0.00%
0 / 1
CRAP
0.00% covered (danger)
0.00%
0 / 1
SQL_Importer
90.48% covered (success)
90.48%
19 / 21
0.00% covered (danger)
0.00%
0 / 1
8.06
0.00% covered (danger)
0.00%
0 / 1
 import
90.48% covered (success)
90.48%
19 / 21
0.00% covered (danger)
0.00%
0 / 1
8.06
1<?php
2/**
3 * SQL_Importer file.
4 *
5 * @package wpcomsh
6 */
7
8namespace Imports;
9
10use WP_Error;
11
12/**
13 * Import a SQL dump in current database.
14 */
15class SQL_Importer {
16    /**
17     * Import the dump file.
18     *
19     * @param string $sql_file_path The path of the SQL file.
20     * @param bool   $verbose       Whether to run the command in verbose mode.
21     *
22     * @return bool|WP_Error
23     */
24    public static function import( string $sql_file_path, $verbose = false ) {
25        // Bail if the file doesn't exist.
26        if ( ! is_file( $sql_file_path ) || ! is_readable( $sql_file_path ) ) {
27            return new WP_Error( 'sql-file-not-exists', __( 'SQL file not exists', 'wpcomsh' ) );
28        }
29
30        $host = DB_HOST;
31        $port = '';
32        if ( preg_match( '/^(.+):(\d+)$/', $host, $m ) ) {
33            $host = $m[1];
34            $port = $m[2];
35        }
36
37        $output  = null;
38        $ret     = null;
39        $command = sprintf(
40            'mysql -u %s%s -h %s%s %s%s < %s',
41            escapeshellarg( DB_USER ),
42            DB_PASSWORD === '' ? '' : ' -p' . escapeshellarg( DB_PASSWORD ),
43            escapeshellarg( $host ),
44            $port === '' ? '' : ' --port=' . escapeshellarg( $port ),
45            escapeshellarg( DB_NAME ),
46            $verbose ? '' : ' 2>&1',
47            escapeshellarg( $sql_file_path )
48        );
49
50        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.system_calls_exec
51        exec( $command, $output, $ret );
52
53        return $ret === 0 ? true : new WP_Error( 'sql-import-failed', __( 'SQL import failed', 'wpcomsh' ) );
54    }
55}