Completed
Push — master ( 5db201...585add )
by David
08:20
created

Wordlift_Rebuild_Service::rebuild()   B

Complexity

Conditions 6
Paths 32

Size

Total Lines 55
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 22
nc 32
nop 0
dl 0
loc 55
rs 8.7752
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
2
/**
3
 * Services: Rebuild Service.
4
 *
5
 * The Wordlift_Rebuild_Service allows to rebuild the Linked Data dataset from
6
 * scratch by clearing out data on the remote dataset, parsing all data in WordPress
7
 * and resending data to the remote dataset.
8
 *
9
 * @since      3.6.0
10
 * @package    Wordlift
11
 * @subpackage Wordlift/includes
12
 */
13
14
/**
15
 * Define the {@link Wordlift_Rebuild_Service} class.
16
 *
17
 * @since      3.6.0
18
 * @package    Wordlift
19
 * @subpackage Wordlift/includes
20
 */
21
class Wordlift_Rebuild_Service extends Wordlift_Listable {
22
23
	/**
24
	 * A {@link Wordlift_Log_Service} instance.
25
	 *
26
	 * @since  3.6.0
27
	 * @access private
28
	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
29
	 */
30
	private $log;
31
32
	/**
33
	 * A {@link Wordlift_Sparql_Service} instance.
34
	 *
35
	 * @since  3.6.0
36
	 * @access private
37
	 * @var \Wordlift_Sparql_Service $sparql_service A {@link Wordlift_Sparql_Service} instance.
38
	 */
39
	private $sparql_service;
40
41
	/**
42
	 * The {@link Wordlift_Uri_Service} instance.
43
	 *
44
	 * @since  3.15.0
45
	 * @access private
46
	 * @var \Wordlift_Uri_Service $uri_service The {@link Wordlift_Uri_Service} instance.
47
	 */
48
	private $uri_service;
49
50
	/**
51
	 * Create an instance of Wordlift_Rebuild_Service.
52
	 *
53
	 * @since 3.6.0
54
	 *
55
	 * @param \Wordlift_Sparql_Service $sparql_service A {@link Wordlift_Sparql_Service} instance used to query the remote dataset.
56
	 * @param \Wordlift_Uri_Service    $uri_service
57
	 */
58
	public function __construct( $sparql_service, $uri_service ) {
59
60
		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Rebuild_Service' );
61
62
		$this->sparql_service = $sparql_service;
63
		$this->uri_service    = $uri_service;
64
	}
65
66
	/**
67
	 * Rebuild the Linked Data remote dataset by clearing it out and repopulating
68
	 * it with local data.
69
	 *
70
	 * @since 3.6.0
71
	 */
72
	public function rebuild() {
0 ignored issues
show
Coding Style introduced by
rebuild uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
73
74
		ob_clean();
75
76
		// Give ourselves some time to process the data.
77
		set_time_limit( 21600 ); // 6 hours
78
79
		// Send textual output.
80
		header( 'Content-type: text/plain; charset=utf-8' );
81
82
		// We start at 0 by default and get to max.
83
		$offset = $_GET['offset'] ?: 0;
84
		$limit  = $_GET['limit'] ?: 1;
85
		$max    = $offset + $limit;
86
87
		// If we're starting at offset 0, then delete existing URIs and data from
88
		// the remote dataset.
89
		if ( 0 === $offset ) {
90
91
			// Clear out all generated URIs, since the dataset URI might have changed
92
			// in the process.
93
			$this->uri_service->delete_all();
94
95
			// Delete all the triples in the remote dataset.
96
			$this->sparql_service->execute( 'DELETE { ?s ?p ?o } WHERE { ?s ?p ?o };' );
97
98
		}
99
100
		// Go through the list of published entities and posts and call the (legacy)
101
		// `wl_linked_data_save_post` function for each one. We're using the `process`
102
		// function which is provided by the parent `Wordlift_Listable` abstract class
103
		// and will cycle through all the posts w/ a very small memory footprint
104
		// in order to avoid memory errors.
105
106
		$count = 0;
107
		$this->process( function ( $post ) use ( &$count ) {
108
			$count ++;
109
			wl_linked_data_save_post( $post->ID );
110
		}, array(
111
			'post_status' => 'publish',
112
		), $offset, $max );
113
114
		// Redirect to the next chunk.
115
		if ( $count == $limit ) {
116
			$this->redirect( admin_url( 'admin-ajax.php?action=wl_rebuild&offset=' . ( $offset + $limit ) . '&limit=' . $limit ) );
117
		}
118
119
		echo( "Rebuild complete [ count :: $count ][ limit :: $limit ]" );
120
121
		// If we're being called as AJAX, die here.
122
		if ( DOING_AJAX ) {
123
			wp_die();
124
		}
125
126
	}
127
128
	/**
129
	 * Redirect using a client-side meta to avoid browsers' redirect restrictions.
130
	 *
131
	 * @since 3.9.8
132
	 *
133
	 * @param string $url The URL to redirect to.
134
	 */
135
	private function redirect( $url ) {
136
137
		ob_clean();
138
139
		@header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
140
		?>
141
		<html>
142
		<head>
143
			<meta http-equiv="refresh"
144
			      content="0; <?php echo esc_attr( $url ); ?>">
145
		</head>
146
		<body>
147
		Rebuilding, please wait...
148
		</body>
149
		</html>
150
		<?php
151
152
		exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method redirect() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
153
154
	}
155
156
	/**
157
	 * List the items starting at the specified offset and up to the specified limit.
158
	 *
159
	 * @since 3.6.0
160
	 *
161
	 * @param int   $offset The start offset.
162
	 * @param int   $limit  The maximum number of items to return.
163
	 * @param array $args   Additional arguments.
164
	 *
165
	 * @return array A array of items (or an empty array if no items are found).
166
	 */
167
	function find( $offset = 0, $limit = 10, $args = array() ) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
168
169
		return get_posts( wp_parse_args( $args, Wordlift_Entity_Service::add_criterias( array(
170
			'offset'      => $offset,
171
			'numberposts' => $limit,
172
			'fields'      => 'all',
173
			'orderby'     => 'ID',
174
			'order'       => 'ASC',
175
			'post_status' => 'any',
176
		) ) ) );
177
	}
178
179
}
180