Completed
Push — master ( 0c53d4...debbec )
by David
09:08 queued 10s
created

Wordlift_Rebuild_Service::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 2
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
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
		// Whether we should run queries asynchronously, this is handled in `wordlift_constants.php`.
88
		$asynchronous = isset( $_GET['wl-async'] ) && 'true' === $_GET['wl-async'];
89
90
		// If we're starting at offset 0, then delete existing URIs and data from
91
		// the remote dataset.
92
		if ( 0 === $offset ) {
93
94
			// Clear out all generated URIs, since the dataset URI might have changed
95
			// in the process.
96
			$this->uri_service->delete_all();
97
98
			// Delete all the triples in the remote dataset.
99
			$this->sparql_service->execute( 'DELETE { ?s ?p ?o } WHERE { ?s ?p ?o };' );
100
101
		}
102
103
		// Go through the list of published entities and posts and call the (legacy)
104
		// `wl_linked_data_save_post` function for each one. We're using the `process`
105
		// function which is provided by the parent `Wordlift_Listable` abstract class
106
		// and will cycle through all the posts w/ a very small memory footprint
107
		// in order to avoid memory errors.
108
109
		$count = 0;
110
		$log   = $this->log;
111
		$this->process( function ( $post ) use ( &$count, $log ) {
112
			$count ++;
113
			$log->trace( "Going to save post $count, ID $post->ID..." );
114
			wl_linked_data_save_post( $post->ID );
115
		}, array(
116
			'post_status' => 'publish',
117
		), $offset, $max );
118
119
		// Redirect to the next chunk.
120
		if ( $count == $limit ) {
121
			$log->trace( 'Redirecting to post #' . ( $offset + 1 ) . '...' );
122
			$this->redirect( admin_url( 'admin-ajax.php?action=wl_rebuild&offset=' . ( $offset + $limit ) . '&limit=' . $limit . '&wl-async=' . ( $asynchronous ? 'true' : 'false' ) ) );
123
		}
124
125
		// Flush the cache.
126
		Wordlift_File_Cache_Service::flush_all();
127
128
		// Rebuild also the references.
129
		$this->redirect( admin_url( 'admin-ajax.php?action=wl_rebuild_references') );
130
	}
131
132
	/**
133
	 * Redirect using a client-side meta to avoid browsers' redirect restrictions.
134
	 *
135
	 * @since 3.9.8
136
	 *
137
	 * @param string $url The URL to redirect to.
138
	 */
139
	public function redirect( $url ) {
140
141
		ob_clean();
142
143
		@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...
144
		?>
145
		<html>
146
		<head>
147
			<meta http-equiv="refresh"
148
			      content="0; <?php echo esc_attr( $url ); ?>">
149
		</head>
150
		<body>
151
		Rebuilding, please wait...
152
		</body>
153
		</html>
154
		<?php
155
156
		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...
157
158
	}
159
160
	/**
161
	 * List the items starting at the specified offset and up to the specified limit.
162
	 *
163
	 * @since 3.6.0
164
	 *
165
	 * @param int   $offset The start offset.
166
	 * @param int   $limit  The maximum number of items to return.
167
	 * @param array $args   Additional arguments.
168
	 *
169
	 * @return array A array of items (or an empty array if no items are found).
170
	 */
171
	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...
172
		return get_posts( wp_parse_args( $args, Wordlift_Entity_Service::add_criterias( array(
173
			'offset'        => $offset,
174
			'numberposts'   => $limit,
175
			'fields'        => 'all',
176
			'orderby'       => 'ID',
177
			'order'         => 'ASC',
178
			'post_status'   => 'any',
179
			'cache_results' => false,
180
		) ) ) );
181
	}
182
183
}
184