GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#936)
by Tom
02:28
created

Zip_File_Backup_Engine::backup()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 40
Code Lines 18

Duplication

Lines 7
Ratio 17.5 %

Importance

Changes 7
Bugs 0 Features 0
Metric Value
c 7
b 0
f 0
dl 7
loc 40
rs 8.439
cc 6
eloc 18
nc 7
nop 0
1
<?php
2
3
namespace HM\BackUpWordPress;
4
5
/**
6
 * Perform a file backup using the zip cli command
7
 */
8
class Zip_File_Backup_Engine extends File_Backup_Engine {
9
10
	/**
11
	 * The path to the zip executable
12
	 *
13
	 * @var string
14
	 */
15
	private $zip_executable_path = '';
16
17
	public function __construct() {
18
		parent::__construct();
19
	}
20
21
	/**
22
	 * Calculate the path to the zip executable.
23
	 *
24
	 * The executable path can be overridden using either the `HMBKP_ZIP_PATH`
25
	 * Constant or the `hmbkp_zip_executable_path` filter.
26
	 *
27
	 * If neither of those are set then we fallback to checking a number of
28
	 * common locations.
29
	 *
30
	 * @return string|false The path to the executable or false.
31
	 */
32
	public function get_zip_executable_path() {
33
34
		if ( defined( 'HMBKP_ZIP_PATH' ) ) {
35
			return HMBKP_ZIP_PATH;
36
		}
37
38
		/**
39
		 * Allow the executable path to be set via a filter
40
		 *
41
		 * @param string The path to the zip executable
42
		 */
43
		$this->zip_executable_path = apply_filters( 'hmbkp_zip_executable_path', '' );
44
45
		if ( ! $this->zip_executable_path ) {
46
47
			// List of possible zip locations
48
			$paths = array(
49
				'zip',
50
				'/usr/bin/zip',
51
				'/opt/local/bin/zip'
52
			);
53
54
			$this->zip_executable_path = Backup_Utilities::get_executable_path( $paths );
0 ignored issues
show
Documentation Bug introduced by
It seems like \HM\BackUpWordPress\Back...executable_path($paths) can also be of type false. However, the property $zip_executable_path is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
55
56
		}
57
58
		return $this->zip_executable_path;
59
60
	}
61
62
	/**
63
	 * Perform the file backup.
64
	 *
65
	 * @return bool Whether the backup completed successfully or not.
66
	 */
67
	public function backup() {
68
69
		if ( ! Backup_Utilities::is_exec_available() || ! $this->get_zip_executable_path() ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->get_zip_executable_path() of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
70
			return false;
71
		}
72
73
		// cd to the site root
74
		$command[] = 'cd ' . escapeshellarg( Path::get_root() );
0 ignored issues
show
Coding Style Comprehensibility introduced by
$command was never initialized. Although not strictly required by PHP, it is generally a good practice to add $command = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
75
76
		// Run the zip command with the recursive and quiet flags
77
		$command[] = '&& ' . escapeshellcmd( $this->get_zip_executable_path() ) . ' -rq';
78
79
		// Save the zip file to the correct path
80
		$command[] = escapeshellarg( $this->get_backup_filepath() ) . ' ./';
81
82
		// Pass exclude rules in if we have them
83
		if ( $this->get_exclude_string() ) {
84
			$command[] = '-x ' . $this->get_exclude_string();
85
		}
86
87
		// Push all output to STDERR
88
		$command[] = '2>&1';
89
90
		$command = implode( ' ', $command );
91
		$output = $return_status = 0;
92
93
		exec( $command, $output, $return_status );
94
95
		// Track any errors
96 View Code Duplication
		if ( $output ) {
1 ignored issue
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...
97
			if ( $return_status === 0 ) {
98
				$this->warning( __CLASS__, implode( ', ', $output ) );
99
			} else {
100
				$this->error( __CLASS__, implode( ', ', $output ) );
101
			}
102
		}
103
104
		return $this->verify_backup();
105
106
	}
107
108
	/**
109
	 * Convert the exclude rules to a format zip accepts
110
	 *
111
	 * @return string The exclude string ready to pass to `zip -x`
112
	 */
113
	public function get_exclude_string() {
114
115
		if ( ! $this->excludes ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->excludes of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
116
			return '';
117
		}
118
119
		$excludes = $this->excludes->get_excludes();
0 ignored issues
show
Bug introduced by
The method get_excludes cannot be called on $this->excludes (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
120
121
		foreach ( $excludes as $key => &$rule ) {
122
123
			$file = $absolute = $fragment = false;
124
125
			// Files don't end with /
126
			if ( ! in_array( substr( $rule, - 1 ), array( '\\', '/' ) ) ) {
127
				$file = true;
128
			}
129
130
			// If rule starts with a / then treat as absolute path
131 View Code Duplication
			elseif ( in_array( substr( $rule, 0, 1 ), array( '\\', '/' ) ) ) {
1 ignored issue
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...
132
				$absolute = true;
133
			}
134
135
			// Otherwise treat as dir fragment
136
			else {
137
				$fragment = true;
138
			}
139
140
			$rule = str_ireplace( Path::get_root(), '', untrailingslashit( wp_normalize_path( $rule ) ) );
141
142
			// Strip the preceeding slash
143 View Code Duplication
			if ( in_array( substr( $rule, 0, 1 ), array( '\\', '/' ) ) ) {
1 ignored issue
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...
144
				$rule = substr( $rule, 1 );
145
			}
146
147
			// Wrap directory fragments and files in wildcards for zip
148
			if ( $fragment || $file ) {
149
				$rule = '*' . $rule . '*';
150
			}
151
152
			// Add a wildcard to the end of absolute url for zips
153
			if ( $absolute ) {
154
				$rule .= '*';
155
			}
156
157
		}
158
159
		// Escape shell args for zip command
160
		$excludes = array_map( 'escapeshellarg', array_unique( $excludes ) );
161
162
		return implode( ' -x ', $excludes );
163
164
	}
165
166
}
167