Completed
Push — renovate/mocha-8.x ( 07030e...e8e64c )
by
unknown
28:17 queued 19:09
created

Options_Runner   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 61
Duplicated Lines 11.48 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 7
loc 61
rs 10
c 0
b 0
f 0
wmc 6
lcom 1
cbo 1

4 Methods

Rating   Name   Duplication   Size   Complexity  
A run() 7 7 2
A run_batch() 0 17 2
A get_random_name() 0 3 1
A get_random_value() 0 3 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * The Mocker Runner that creates mock options.
4
 *
5
 * @package Jetpack
6
 */
7
8
namespace Automattic\Jetpack\Debug_Helper\Mocker;
9
10
require_once __DIR__ . '/interface-runner.php';
11
require_once __DIR__ . '/class-tools.php';
12
13
/**
14
 * Creating the mock options.
15
 */
16
class Options_Runner implements Runner_Interface {
17
18
	/**
19
	 * Generate the random options.
20
	 *
21
	 * @param int $number Number of options to generate.
22
	 *
23
	 * @return bool
24
	 */
25 View Code Duplication
	public function run( $number ) {
26
		for ( $i = $number, $per_batch = 500; $i > 0; $i -= $per_batch ) {
27
			$this->run_batch( min( $per_batch, $i ) );
28
		}
29
30
		return true;
31
	}
32
33
	/**
34
	 * Add a batch of mock options.
35
	 *
36
	 * @param int $limit How many options to add.
37
	 *
38
	 * @return bool
39
	 */
40
	private function run_batch( $limit ) {
41
		global $wpdb;
42
43
		$sql = "INSERT INTO {$wpdb->options} (option_name, option_value, autoload) VALUES "
44
			. implode( ', ', array_fill( 0, $limit, '( %s, %s, "no" )' ) );
45
46
		$values_to_insert = array();
47
		for ( $i = 0; $i < $limit; ++$i ) {
48
			$values_to_insert[] = $this->get_random_name();
49
			$values_to_insert[] = $this->get_random_value();
50
		}
51
52
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
53
		$wpdb->query( $wpdb->prepare( $sql, $values_to_insert ) );
54
55
		return true;
56
	}
57
58
	/**
59
	 * Generate a random option name.
60
	 *
61
	 * @return string
62
	 */
63
	private function get_random_name() {
64
		return 'mock_option_' . Tools::get_random_string() . '_' . microtime( true );
65
	}
66
67
	/**
68
	 * Generate a random option value.
69
	 *
70
	 * @return string
71
	 */
72
	private function get_random_value() {
73
		return 'mock_value_' . Tools::get_random_string();
74
	}
75
76
}
77