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

Nonces_Runner   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 61
Duplicated Lines 11.48 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A run() 7 7 2
A run_batch() 0 20 3
A get_random_nonce() 0 9 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 nonces.
4
 *
5
 * @package Jetpack
6
 */
7
8
namespace Automattic\Jetpack\Debug_Helper\Mocker;
9
10
require_once __DIR__ . '/class-tools.php';
11
12
/**
13
 * Creating the mock nonces.
14
 */
15
class Nonces_Runner implements Runner_Interface {
16
17
	/**
18
	 * Generate random nonces.
19
	 *
20
	 * @param int $number Number of nonces to generate.
21
	 *
22
	 * @return bool
23
	 */
24 View Code Duplication
	public function run( $number ) {
25
		for ( $i = $number, $per_batch = 500; $i > 0; $i -= $per_batch ) {
26
			$this->run_batch( min( $per_batch, $i ) );
27
		}
28
29
		return true;
30
	}
31
32
	/**
33
	 * Add a batch of mock options.
34
	 *
35
	 * @param int $limit How many options to add.
36
	 *
37
	 * @return bool
38
	 */
39
	private function run_batch( $limit ) {
40
		global $wpdb;
41
42
		if ( ! $limit ) {
43
			return false;
44
		}
45
46
		$sql = "INSERT INTO {$wpdb->options} (option_name, option_value, autoload) VALUES "
47
			. implode( ', ', array_fill( 0, $limit, '( %s, %s, "no" )' ) );
48
49
		$values_to_insert = array();
50
		for ( $i = 0; $i < $limit; ++$i ) {
51
			$values_to_insert = array_merge( $values_to_insert, $this->get_random_nonce() );
52
		}
53
54
		// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
55
		$wpdb->query( $wpdb->prepare( $sql, $values_to_insert ) );
56
57
		return true;
58
	}
59
60
	/**
61
	 * Generate a random nonce
62
	 *
63
	 * @return array [ $option_key, $option_value ]
64
	 */
65
	private function get_random_nonce() {
66
		// phpcs:ignore WordPress.WP.AlternativeFunctions.rand_rand
67
		$time = rand( 1000000000, time() );
68
69
		return array(
70
			'jetpack_nonce_' . $time . '_' . Tools::get_random_string( 10 ),
71
			$time,
72
		);
73
	}
74
75
}
76