Completed
Push — develop ( 111dce...b8d476 )
by Timothy
02:35
created

Util::backup_data()   B

Complexity

Conditions 7
Paths 20

Size

Total Lines 59
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 25
nc 20
nop 2
dl 0
loc 59
rs 7.5346
c 0
b 0
f 0

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 declare(strict_types=1);
2
/**
3
 * Query
4
 *
5
 * SQL Query Builder / Database Abstraction Layer
6
 *
7
 * PHP version 7
8
 *
9
 * @package     Query
10
 * @author      Timothy J. Warren <[email protected]>
11
 * @copyright   2012 - 2016 Timothy J. Warren
12
 * @license     http://www.opensource.org/licenses/mit-license.html  MIT License
13
 * @link        https://git.timshomepage.net/aviat4ion/Query
14
 */
15
namespace Query\Drivers\Firebird;
16
17
use PDO;
18
use Query\Drivers\AbstractUtil;
19
20
/**
21
 * Firebird-specific backup, import and creation methods
22
 */
23
class Util extends AbstractUtil {
24
25
	/**
26
	 * Convenience public function to generate sql for creating a db table
27
	 *
28
	 * @param string $name
29
	 * @param array $fields
30
	 * @param array $constraints
31
	 * @param bool $ifNotExists
32
	 * @return string
33
	 */
34
	public function createTable($name, $fields, array $constraints=[], $ifNotExists=FALSE)
35
	{
36
		return parent::createTable($name, $fields, $constraints, FALSE);
37
	}
38
39
	/**
40
	 * Drop the selected table
41
	 *
42
	 * @param string $name
43
	 * @return string
44
	 */
45
	public function deleteTable($name)
46
	{
47
		return 'DROP TABLE '.$this->getDriver()->quoteTable($name);
48
	}
49
50
	/**
51
	 * Create an SQL backup file for the current database's structure
52
	 *
53
	 * @return string
54
	 */
55
	public function backupStructure(/* @param string $dbPath, @param string $newFile */)
56
	{
57
		list($dbPath, $newFile) = func_get_args();
58
		return ibase_backup($this->getDriver()->getService(), $dbPath, $newFile, \IBASE_BKP_METADATA_ONLY);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Query\Drivers\DriverInterface as the method getService() does only exist in the following implementations of said interface: Query\Drivers\Firebird\Driver.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
59
	}
60
61
	/**
62
	 * Create an SQL backup file for the current database's data
63
	 *
64
	 * @param array $exclude
65
	 * @param bool $systemTables
66
	 * @return string
67
	 */
68
	public function backupData($exclude=[], $systemTables=FALSE)
69
	{
70
		// Determine which tables to use
71
		$tables = $this->getDriver()->getTables();
72
		if($systemTables == TRUE)
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
73
		{
74
			$tables = array_merge($tables, $this->getDriver()->getSystemTables());
75
		}
76
77
		// Filter out the tables you don't want
78
		if( ! empty($exclude))
79
		{
80
			$tables = array_diff($tables, $exclude);
81
		}
82
83
		$outputSql = '';
84
85
		// Get the data for each object
86
		foreach($tables as $t)
87
		{
88
			$sql = 'SELECT * FROM "'.trim($t).'"';
89
			$res = $this->getDriver()->query($sql);
0 ignored issues
show
Unused Code introduced by
The call to DriverInterface::query() has too many arguments starting with $sql.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
90
			$objRes = $res->fetchAll(PDO::FETCH_ASSOC);
91
92
			// Don't add to the file if the table is empty
93
			if (count($objRes) < 1)
94
			{
95
				continue;
96
			}
97
98
			// Nab the column names by getting the keys of the first row
99
			$columns = @array_keys($objRes[0]);
100
101
			$insertRows = [];
102
103
			// Create the insert statements
104
			foreach($objRes as $row)
105
			{
106
				$row = array_values($row);
107
108
				// Quote values as needed by type
109
				if(stripos($t, 'RDB$') === FALSE)
110
				{
111
					$row = array_map([$this->getDriver(), 'quote'], $row);
112
					$row = array_map('trim', $row);
113
				}
114
115
				$rowString = 'INSERT INTO "'.trim($t).'" ("'.implode('","', $columns).'") VALUES ('.implode(',', $row).');';
116
117
				$row = NULL;
118
119
				$insertRows[] = $rowString;
120
			}
121
122
			$outputSql .= "\n\nSET TRANSACTION;\n".implode("\n", $insertRows)."\nCOMMIT;";
123
		}
124
125
		return $outputSql;
126
	}
127
}