Completed
Pull Request — develop (#900)
by William
04:03
created
src/includes/rebuild/class-wordlift-reference-rebuild-service.php 3 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -33,6 +33,7 @@
 block discarded – undo
33 33
 	 *
34 34
 	 * @param \Wordlift_Entity_Service       $entity_service       The {@link Wordlift_Entity_Service} instance.
35 35
 	 * @param \Wordlift_Linked_Data_Service  $linked_data_service  The {@link Wordlift_Linked_Data_Service} instance.
36
+	 * @param Wordlift_Relation_Service $relation_service
36 37
 	 */
37 38
 	public function __construct( $linked_data_service, $entity_service, $relation_service ) {
38 39
 
Please login to merge, or discard this patch.
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -2,119 +2,119 @@
 block discarded – undo
2 2
 
3 3
 class Wordlift_Reference_Rebuild_Service extends Wordlift_Rebuild_Service {
4 4
 
5
-	/**
6
-	 * @since  3.18.0
7
-	 * @access private
8
-	 * @var \Wordlift_Linked_Data_Service $log A {@link Wordlift_Linked_Data_Service} instance.
9
-	 */
10
-	private $linked_data_service;
11
-
12
-	/**
13
-	 * The {@link Wordlift_Entity_Service} instance.
14
-	 *
15
-	 * @since  3.18.0
16
-	 * @access private
17
-	 * @var \Wordlift_Entity_Service $entity_service The {@link Wordlift_Entity_Service} instance.
18
-	 */
19
-	private $entity_service;
20
-
21
-	/**
22
-	 * A {@link Wordlift_Log_Service} instance.
23
-	 *
24
-	 * @since  3.18.0
25
-	 * @access private
26
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
27
-	 */
28
-	private $log;
29
-
30
-
31
-	/**
32
-	 * Wordlift_Reference_Rebuild_Service constructor.
33
-	 *
34
-	 * @param \Wordlift_Entity_Service       $entity_service       The {@link Wordlift_Entity_Service} instance.
35
-	 * @param \Wordlift_Linked_Data_Service  $linked_data_service  The {@link Wordlift_Linked_Data_Service} instance.
36
-	 */
37
-	public function __construct( $linked_data_service, $entity_service, $relation_service ) {
38
-
39
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Reference_Rebuild_Service' );
40
-
41
-		$this->linked_data_service = $linked_data_service;
42
-		$this->entity_service      = $entity_service;
43
-	}
44
-
45
-	public function rebuild() {
46
-		set_time_limit( 21600 ); // 6 hours
47
-
48
-		// Send textual output.
49
-		header( 'Content-type: text/plain; charset=utf-8' );
50
-
51
-		// We start at 0 by default and get to max.
52
-		$offset = $_GET['offset'] ?: 0;
53
-		$limit  = $_GET['limit'] ?: 1;
54
-		$max    = $offset + $limit;
55
-
56
-		$this->log->debug( 'Processing references...' );
57
-
58
-		// Go through the list of published entities and posts and call the (legacy)
59
-		// `wl_linked_data_save_post` function for each one. We're using the `process`
60
-		// function which is provided by the parent `Wordlift_Listable` abstract class
61
-		// and will cycle through all the posts w/ a very small memory footprint
62
-		// in order to avoid memory errors.
63
-
64
-		$count               = 0;
65
-		$log                 = $this->log;
66
-		$entity_service      = $this->entity_service;
67
-		$linked_data_service = $this->linked_data_service;
68
-
69
-		$this->process(
70
-			function ( $post_id ) use ( &$count, $log, $entity_service, $linked_data_service ) {
71
-				$count ++;
72
-
73
-				if ( $entity_service->is_entity( $post_id ) ) {
74
-					$log->trace( "Post $post_id is an entity, skipping..." );
75
-					return;
76
-				}
77
-
78
-				$log->trace( "Going to save post $count, ID $post_id..." );
79
-				$linked_data_service->push( $post_id );
80
-			},
81
-			array(),
82
-			$offset,
83
-			$max
84
-		);
85
-
86
-		// Redirect to the next chunk.
87
-		if ( $count == $limit ) {
88
-			$log->trace( 'Redirecting to post #' . ( $offset + 1 ) . '...' );
89
-			$url = admin_url( 'admin-ajax.php?action=wl_rebuild_references&offset=' . ( $offset + $limit ) . '&limit=' . $limit );
90
-			$this->redirect( $url );
91
-		}
92
-
93
-		$this->log->info( "Rebuild complete" );
94
-		echo( "Rebuild complete" );
95
-
96
-		// If we're being called as AJAX, die here.
97
-		if ( DOING_AJAX ) {
98
-			wp_die();
99
-		}
100
-	}
101
-
102
-	/**
103
-	 * @inheritdoc
104
-	 */
105
-	function find( $offset = 0, $limit = 10, $args = array() ) {
106
-		global $wpdb;
107
-
108
-		return $wpdb->get_col( $wpdb->prepare(
109
-			"
5
+    /**
6
+     * @since  3.18.0
7
+     * @access private
8
+     * @var \Wordlift_Linked_Data_Service $log A {@link Wordlift_Linked_Data_Service} instance.
9
+     */
10
+    private $linked_data_service;
11
+
12
+    /**
13
+     * The {@link Wordlift_Entity_Service} instance.
14
+     *
15
+     * @since  3.18.0
16
+     * @access private
17
+     * @var \Wordlift_Entity_Service $entity_service The {@link Wordlift_Entity_Service} instance.
18
+     */
19
+    private $entity_service;
20
+
21
+    /**
22
+     * A {@link Wordlift_Log_Service} instance.
23
+     *
24
+     * @since  3.18.0
25
+     * @access private
26
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
27
+     */
28
+    private $log;
29
+
30
+
31
+    /**
32
+     * Wordlift_Reference_Rebuild_Service constructor.
33
+     *
34
+     * @param \Wordlift_Entity_Service       $entity_service       The {@link Wordlift_Entity_Service} instance.
35
+     * @param \Wordlift_Linked_Data_Service  $linked_data_service  The {@link Wordlift_Linked_Data_Service} instance.
36
+     */
37
+    public function __construct( $linked_data_service, $entity_service, $relation_service ) {
38
+
39
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Reference_Rebuild_Service' );
40
+
41
+        $this->linked_data_service = $linked_data_service;
42
+        $this->entity_service      = $entity_service;
43
+    }
44
+
45
+    public function rebuild() {
46
+        set_time_limit( 21600 ); // 6 hours
47
+
48
+        // Send textual output.
49
+        header( 'Content-type: text/plain; charset=utf-8' );
50
+
51
+        // We start at 0 by default and get to max.
52
+        $offset = $_GET['offset'] ?: 0;
53
+        $limit  = $_GET['limit'] ?: 1;
54
+        $max    = $offset + $limit;
55
+
56
+        $this->log->debug( 'Processing references...' );
57
+
58
+        // Go through the list of published entities and posts and call the (legacy)
59
+        // `wl_linked_data_save_post` function for each one. We're using the `process`
60
+        // function which is provided by the parent `Wordlift_Listable` abstract class
61
+        // and will cycle through all the posts w/ a very small memory footprint
62
+        // in order to avoid memory errors.
63
+
64
+        $count               = 0;
65
+        $log                 = $this->log;
66
+        $entity_service      = $this->entity_service;
67
+        $linked_data_service = $this->linked_data_service;
68
+
69
+        $this->process(
70
+            function ( $post_id ) use ( &$count, $log, $entity_service, $linked_data_service ) {
71
+                $count ++;
72
+
73
+                if ( $entity_service->is_entity( $post_id ) ) {
74
+                    $log->trace( "Post $post_id is an entity, skipping..." );
75
+                    return;
76
+                }
77
+
78
+                $log->trace( "Going to save post $count, ID $post_id..." );
79
+                $linked_data_service->push( $post_id );
80
+            },
81
+            array(),
82
+            $offset,
83
+            $max
84
+        );
85
+
86
+        // Redirect to the next chunk.
87
+        if ( $count == $limit ) {
88
+            $log->trace( 'Redirecting to post #' . ( $offset + 1 ) . '...' );
89
+            $url = admin_url( 'admin-ajax.php?action=wl_rebuild_references&offset=' . ( $offset + $limit ) . '&limit=' . $limit );
90
+            $this->redirect( $url );
91
+        }
92
+
93
+        $this->log->info( "Rebuild complete" );
94
+        echo( "Rebuild complete" );
95
+
96
+        // If we're being called as AJAX, die here.
97
+        if ( DOING_AJAX ) {
98
+            wp_die();
99
+        }
100
+    }
101
+
102
+    /**
103
+     * @inheritdoc
104
+     */
105
+    function find( $offset = 0, $limit = 10, $args = array() ) {
106
+        global $wpdb;
107
+
108
+        return $wpdb->get_col( $wpdb->prepare(
109
+            "
110 110
 			SELECT DISTINCT subject_id AS id
111 111
 			FROM {$wpdb->prefix}wl_relation_instances
112 112
 			LIMIT %d OFFSET %d
113 113
 			",
114
-			$limit,
115
-			$offset
116
-		) );
114
+            $limit,
115
+            $offset
116
+        ) );
117 117
 
118
-	}
118
+    }
119 119
 
120 120
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -34,26 +34,26 @@  discard block
 block discarded – undo
34 34
 	 * @param \Wordlift_Entity_Service       $entity_service       The {@link Wordlift_Entity_Service} instance.
35 35
 	 * @param \Wordlift_Linked_Data_Service  $linked_data_service  The {@link Wordlift_Linked_Data_Service} instance.
36 36
 	 */
37
-	public function __construct( $linked_data_service, $entity_service, $relation_service ) {
37
+	public function __construct($linked_data_service, $entity_service, $relation_service) {
38 38
 
39
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Reference_Rebuild_Service' );
39
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Reference_Rebuild_Service');
40 40
 
41 41
 		$this->linked_data_service = $linked_data_service;
42 42
 		$this->entity_service      = $entity_service;
43 43
 	}
44 44
 
45 45
 	public function rebuild() {
46
-		set_time_limit( 21600 ); // 6 hours
46
+		set_time_limit(21600); // 6 hours
47 47
 
48 48
 		// Send textual output.
49
-		header( 'Content-type: text/plain; charset=utf-8' );
49
+		header('Content-type: text/plain; charset=utf-8');
50 50
 
51 51
 		// We start at 0 by default and get to max.
52 52
 		$offset = $_GET['offset'] ?: 0;
53 53
 		$limit  = $_GET['limit'] ?: 1;
54 54
 		$max    = $offset + $limit;
55 55
 
56
-		$this->log->debug( 'Processing references...' );
56
+		$this->log->debug('Processing references...');
57 57
 
58 58
 		// Go through the list of published entities and posts and call the (legacy)
59 59
 		// `wl_linked_data_save_post` function for each one. We're using the `process`
@@ -67,16 +67,16 @@  discard block
 block discarded – undo
67 67
 		$linked_data_service = $this->linked_data_service;
68 68
 
69 69
 		$this->process(
70
-			function ( $post_id ) use ( &$count, $log, $entity_service, $linked_data_service ) {
71
-				$count ++;
70
+			function($post_id) use (&$count, $log, $entity_service, $linked_data_service) {
71
+				$count++;
72 72
 
73
-				if ( $entity_service->is_entity( $post_id ) ) {
74
-					$log->trace( "Post $post_id is an entity, skipping..." );
73
+				if ($entity_service->is_entity($post_id)) {
74
+					$log->trace("Post $post_id is an entity, skipping...");
75 75
 					return;
76 76
 				}
77 77
 
78
-				$log->trace( "Going to save post $count, ID $post_id..." );
79
-				$linked_data_service->push( $post_id );
78
+				$log->trace("Going to save post $count, ID $post_id...");
79
+				$linked_data_service->push($post_id);
80 80
 			},
81 81
 			array(),
82 82
 			$offset,
@@ -84,17 +84,17 @@  discard block
 block discarded – undo
84 84
 		);
85 85
 
86 86
 		// Redirect to the next chunk.
87
-		if ( $count == $limit ) {
88
-			$log->trace( 'Redirecting to post #' . ( $offset + 1 ) . '...' );
89
-			$url = admin_url( 'admin-ajax.php?action=wl_rebuild_references&offset=' . ( $offset + $limit ) . '&limit=' . $limit );
90
-			$this->redirect( $url );
87
+		if ($count == $limit) {
88
+			$log->trace('Redirecting to post #'.($offset + 1).'...');
89
+			$url = admin_url('admin-ajax.php?action=wl_rebuild_references&offset='.($offset + $limit).'&limit='.$limit);
90
+			$this->redirect($url);
91 91
 		}
92 92
 
93
-		$this->log->info( "Rebuild complete" );
94
-		echo( "Rebuild complete" );
93
+		$this->log->info("Rebuild complete");
94
+		echo("Rebuild complete");
95 95
 
96 96
 		// If we're being called as AJAX, die here.
97
-		if ( DOING_AJAX ) {
97
+		if (DOING_AJAX) {
98 98
 			wp_die();
99 99
 		}
100 100
 	}
@@ -102,10 +102,10 @@  discard block
 block discarded – undo
102 102
 	/**
103 103
 	 * @inheritdoc
104 104
 	 */
105
-	function find( $offset = 0, $limit = 10, $args = array() ) {
105
+	function find($offset = 0, $limit = 10, $args = array()) {
106 106
 		global $wpdb;
107 107
 
108
-		return $wpdb->get_col( $wpdb->prepare(
108
+		return $wpdb->get_col($wpdb->prepare(
109 109
 			"
110 110
 			SELECT DISTINCT subject_id AS id
111 111
 			FROM {$wpdb->prefix}wl_relation_instances
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
 			",
114 114
 			$limit,
115 115
 			$offset
116
-		) );
116
+		));
117 117
 
118 118
 	}
119 119
 
Please login to merge, or discard this patch.
src/includes/rebuild/class-wordlift-relation-rebuild-service.php 2 patches
Indentation   +85 added lines, -85 removed lines patch added patch discarded remove patch
@@ -2,133 +2,133 @@
 block discarded – undo
2 2
 
3 3
 class Wordlift_Relation_Rebuild_Service extends Wordlift_Listable {
4 4
 
5
-	/**
6
-	 * @var Wordlift_Content_Filter_Service
7
-	 */
8
-	private $content_filter_service;
5
+    /**
6
+     * @var Wordlift_Content_Filter_Service
7
+     */
8
+    private $content_filter_service;
9 9
 
10
-	/**
11
-	 * @var Wordlift_Entity_Service
12
-	 */
13
-	private $entity_service;
10
+    /**
11
+     * @var Wordlift_Entity_Service
12
+     */
13
+    private $entity_service;
14 14
 
15
-	/**
16
-	 * A {@link Wordlift_Log_Service} instance.
17
-	 *
18
-	 * @since  3.14.3
19
-	 * @access private
20
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
21
-	 */
22
-	private $log;
15
+    /**
16
+     * A {@link Wordlift_Log_Service} instance.
17
+     *
18
+     * @since  3.14.3
19
+     * @access private
20
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
21
+     */
22
+    private $log;
23 23
 
24 24
 
25
-	/**
26
-	 * Wordlift_Relation_Rebuild_Service constructor.
27
-	 *
28
-	 * @param \Wordlift_Content_Filter_Service $content_filter_service
29
-	 * @param \Wordlift_Entity_Service         $entity_service
30
-	 */
31
-	public function __construct( $content_filter_service, $entity_service ) {
25
+    /**
26
+     * Wordlift_Relation_Rebuild_Service constructor.
27
+     *
28
+     * @param \Wordlift_Content_Filter_Service $content_filter_service
29
+     * @param \Wordlift_Entity_Service         $entity_service
30
+     */
31
+    public function __construct( $content_filter_service, $entity_service ) {
32 32
 
33
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Relation_Rebuild_Service' );
33
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Relation_Rebuild_Service' );
34 34
 
35
-		$this->content_filter_service = $content_filter_service;
36
-		$this->entity_service         = $entity_service;
35
+        $this->content_filter_service = $content_filter_service;
36
+        $this->entity_service         = $entity_service;
37 37
 
38
-	}
38
+    }
39 39
 
40
-	public function process_all() {
41
-		global $wpdb;
40
+    public function process_all() {
41
+        global $wpdb;
42 42
 
43
-		set_time_limit( 21600 ); // 6 hours
43
+        set_time_limit( 21600 ); // 6 hours
44 44
 
45
-		$this->log->debug( 'Deleting all existing relations...' );
45
+        $this->log->debug( 'Deleting all existing relations...' );
46 46
 
47
-		// Delete existing data.
48
-		$wpdb->query( "TRUNCATE TABLE {$wpdb->prefix}wl_relation_instances" );
47
+        // Delete existing data.
48
+        $wpdb->query( "TRUNCATE TABLE {$wpdb->prefix}wl_relation_instances" );
49 49
 
50
-		$this->log->debug( 'Processing contents...' );
50
+        $this->log->debug( 'Processing contents...' );
51 51
 
52
-		$this->process( array( $this, 'process_single' ) );
52
+        $this->process( array( $this, 'process_single' ) );
53 53
 
54
-	}
54
+    }
55 55
 
56
-	public function process_single( $post_id ) {
56
+    public function process_single( $post_id ) {
57 57
 
58
-		$this->log->debug( "Processing post $post_id..." );
58
+        $this->log->debug( "Processing post $post_id..." );
59 59
 
60
-		// Bail out if the post is not found.
61
-		$post = get_post( $post_id );
60
+        // Bail out if the post is not found.
61
+        $post = get_post( $post_id );
62 62
 
63
-		if ( null === $post ) {
64
-			$this->log->error( "Post $post_id not found." );
63
+        if ( null === $post ) {
64
+            $this->log->error( "Post $post_id not found." );
65 65
 
66
-			return;
67
-		}
66
+            return;
67
+        }
68 68
 
69
-		// Get the URIs from the post content.
70
-		$uris = $this->content_filter_service->get_entity_uris( $post->post_content );
69
+        // Get the URIs from the post content.
70
+        $uris = $this->content_filter_service->get_entity_uris( $post->post_content );
71 71
 
72
-		// Map the URIs to post IDs.
73
-		$ids = $this->uri_to_post_id( $uris );
72
+        // Map the URIs to post IDs.
73
+        $ids = $this->uri_to_post_id( $uris );
74 74
 
75
-		$this->log->info( 'Found ' . count( $uris ) . ' annotation(s) and ' . count( $ids ) . ' unique relation(s).' );
75
+        $this->log->info( 'Found ' . count( $uris ) . ' annotation(s) and ' . count( $ids ) . ' unique relation(s).' );
76 76
 
77
-		// Create the relations.
78
-		$this->create_relations( $post_id, $ids );
77
+        // Create the relations.
78
+        $this->create_relations( $post_id, $ids );
79 79
 
80
-	}
80
+    }
81 81
 
82
-	private function create_relations( $subject_id, $object_ids ) {
82
+    private function create_relations( $subject_id, $object_ids ) {
83 83
 
84
-		$this->log->info( "Creating relations for post $subject_id..." );
84
+        $this->log->info( "Creating relations for post $subject_id..." );
85 85
 
86
-		$entity_service = $this->entity_service;
86
+        $entity_service = $this->entity_service;
87 87
 
88
-		array_walk( $object_ids, function ( $item ) use ( $subject_id, $entity_service ) {
89
-			wl_core_add_relation_instance(
90
-				$subject_id,
91
-				$entity_service->get_classification_scope_for( $item ),
92
-				$item
93
-			);
94
-		} );
88
+        array_walk( $object_ids, function ( $item ) use ( $subject_id, $entity_service ) {
89
+            wl_core_add_relation_instance(
90
+                $subject_id,
91
+                $entity_service->get_classification_scope_for( $item ),
92
+                $item
93
+            );
94
+        } );
95 95
 
96
-	}
96
+    }
97 97
 
98
-	private function uri_to_post_id( $uris ) {
98
+    private function uri_to_post_id( $uris ) {
99 99
 
100
-		$entity_service = $this->entity_service;
100
+        $entity_service = $this->entity_service;
101 101
 
102
-		$ids = array_unique( array_map( function ( $item ) use ( $entity_service ) {
103
-			$post = $entity_service->get_entity_post_by_uri( $item );
102
+        $ids = array_unique( array_map( function ( $item ) use ( $entity_service ) {
103
+            $post = $entity_service->get_entity_post_by_uri( $item );
104 104
 
105
-			return null === $post ? null : $post->ID;
106
-		}, (array) $uris ) );
105
+            return null === $post ? null : $post->ID;
106
+        }, (array) $uris ) );
107 107
 
108
-		return array_filter( $ids, function ( $item ) {
109
-			return null !== $item;
110
-		} );
111
-	}
108
+        return array_filter( $ids, function ( $item ) {
109
+            return null !== $item;
110
+        } );
111
+    }
112 112
 
113
-	/**
114
-	 * @inheritdoc
115
-	 */
116
-	function find( $offset = 0, $limit = 10, $args = array() ) {
117
-		global $wpdb;
113
+    /**
114
+     * @inheritdoc
115
+     */
116
+    function find( $offset = 0, $limit = 10, $args = array() ) {
117
+        global $wpdb;
118 118
 
119
-		return $wpdb->get_col( $wpdb->prepare(
120
-			"
119
+        return $wpdb->get_col( $wpdb->prepare(
120
+            "
121 121
 			SELECT id
122 122
 			FROM $wpdb->posts
123 123
 			WHERE post_type NOT IN ( 'attachment', 'revision' )
124 124
 				AND post_content REGEXP %s
125 125
 			LIMIT %d OFFSET %d
126 126
 			",
127
-			'<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">',
128
-			$limit,
129
-			$offset
130
-		) );
127
+            '<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">',
128
+            $limit,
129
+            $offset
130
+        ) );
131 131
 
132
-	}
132
+    }
133 133
 
134 134
 }
Please login to merge, or discard this patch.
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -27,9 +27,9 @@  discard block
 block discarded – undo
27 27
 	 * @param \Wordlift_Content_Filter_Service $content_filter_service
28 28
 	 * @param \Wordlift_Entity_Service         $entity_service
29 29
 	 */
30
-	public function __construct( $content_filter_service, $entity_service ) {
30
+	public function __construct($content_filter_service, $entity_service) {
31 31
 
32
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Relation_Rebuild_Service' );
32
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Relation_Rebuild_Service');
33 33
 
34 34
 		$this->content_filter_service = $content_filter_service;
35 35
 		$this->entity_service         = $entity_service;
@@ -39,72 +39,72 @@  discard block
 block discarded – undo
39 39
 	public function process_all() {
40 40
 		global $wpdb;
41 41
 
42
-		set_time_limit( 21600 ); // 6 hours
42
+		set_time_limit(21600); // 6 hours
43 43
 
44
-		$this->log->debug( 'Deleting all existing relations...' );
44
+		$this->log->debug('Deleting all existing relations...');
45 45
 
46 46
 		// Delete existing data.
47
-		$wpdb->query( "TRUNCATE TABLE {$wpdb->prefix}wl_relation_instances" );
47
+		$wpdb->query("TRUNCATE TABLE {$wpdb->prefix}wl_relation_instances");
48 48
 
49
-		$this->log->debug( 'Processing contents...' );
49
+		$this->log->debug('Processing contents...');
50 50
 
51
-		$this->process( array( $this, 'process_single' ) );
51
+		$this->process(array($this, 'process_single'));
52 52
 
53 53
 	}
54 54
 
55
-	public function process_single( $post_id ) {
55
+	public function process_single($post_id) {
56 56
 
57
-		$this->log->debug( "Processing post $post_id..." );
57
+		$this->log->debug("Processing post $post_id...");
58 58
 
59 59
 		// Bail out if the post is not found.
60
-		$post = get_post( $post_id );
60
+		$post = get_post($post_id);
61 61
 
62
-		if ( null === $post ) {
63
-			$this->log->error( "Post $post_id not found." );
62
+		if (null === $post) {
63
+			$this->log->error("Post $post_id not found.");
64 64
 
65 65
 			return;
66 66
 		}
67 67
 
68 68
 		// Get the URIs from the post content.
69
-		$uris = $this->content_filter_service->get_entity_uris( $post->post_content );
69
+		$uris = $this->content_filter_service->get_entity_uris($post->post_content);
70 70
 
71 71
 		// Map the URIs to post IDs.
72
-		$ids = $this->uri_to_post_id( $uris );
72
+		$ids = $this->uri_to_post_id($uris);
73 73
 
74
-		$this->log->info( 'Found ' . count( $uris ) . ' annotation(s) and ' . count( $ids ) . ' unique relation(s).' );
74
+		$this->log->info('Found '.count($uris).' annotation(s) and '.count($ids).' unique relation(s).');
75 75
 
76 76
 		// Create the relations.
77
-		$this->create_relations( $post_id, $ids );
77
+		$this->create_relations($post_id, $ids);
78 78
 
79 79
 	}
80 80
 
81
-	private function create_relations( $subject_id, $object_ids ) {
81
+	private function create_relations($subject_id, $object_ids) {
82 82
 
83
-		$this->log->info( "Creating relations for post $subject_id..." );
83
+		$this->log->info("Creating relations for post $subject_id...");
84 84
 
85 85
 		$entity_service = $this->entity_service;
86 86
 
87
-		array_walk( $object_ids, function ( $item ) use ( $subject_id, $entity_service ) {
87
+		array_walk($object_ids, function($item) use ($subject_id, $entity_service) {
88 88
 			wl_core_add_relation_instance(
89 89
 				$subject_id,
90
-				$entity_service->get_classification_scope_for( $item ),
90
+				$entity_service->get_classification_scope_for($item),
91 91
 				$item
92 92
 			);
93 93
 		} );
94 94
 
95 95
 	}
96 96
 
97
-	private function uri_to_post_id( $uris ) {
97
+	private function uri_to_post_id($uris) {
98 98
 
99 99
 		$entity_service = $this->entity_service;
100 100
 
101
-		$ids = array_unique( array_map( function ( $item ) use ( $entity_service ) {
102
-			$post = $entity_service->get_entity_post_by_uri( $item );
101
+		$ids = array_unique(array_map(function($item) use ($entity_service) {
102
+			$post = $entity_service->get_entity_post_by_uri($item);
103 103
 
104 104
 			return null === $post ? null : $post->ID;
105
-		}, (array) $uris ) );
105
+		}, (array) $uris));
106 106
 
107
-		return array_filter( $ids, function ( $item ) {
107
+		return array_filter($ids, function($item) {
108 108
 			return null !== $item;
109 109
 		} );
110 110
 	}
@@ -112,10 +112,10 @@  discard block
 block discarded – undo
112 112
 	/**
113 113
 	 * @inheritdoc
114 114
 	 */
115
-	function find( $offset = 0, $limit = 10, $args = array() ) {
115
+	function find($offset = 0, $limit = 10, $args = array()) {
116 116
 		global $wpdb;
117 117
 
118
-		return $wpdb->get_col( $wpdb->prepare(
118
+		return $wpdb->get_col($wpdb->prepare(
119 119
 			"
120 120
 			SELECT id
121 121
 			FROM $wpdb->posts
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 			'<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">',
127 127
 			$limit,
128 128
 			$offset
129
-		) );
129
+		));
130 130
 
131 131
 	}
132 132
 
Please login to merge, or discard this patch.
src/includes/rebuild/class-wordlift-listable.php 2 patches
Indentation   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -4,54 +4,54 @@
 block discarded – undo
4 4
  */
5 5
 abstract class Wordlift_Listable {
6 6
 
7
-	private $count = 0;
8
-
9
-	/**
10
-	 * List the items starting at the specified offset and up to the specified limit.
11
-	 *
12
-	 * @param int   $offset The start offset.
13
-	 * @param int   $limit  The maximum number of items to return.
14
-	 * @param array $args   Additional arguments.
15
-	 *
16
-	 * @return array A array of items (or an empty array if no items are found).
17
-	 */
18
-	abstract function find( $offset = 0, $limit = 10, $args = array() );
19
-
20
-	/**
21
-	 * @param callable $callback
22
-	 * @param array    $args
23
-	 * @param int      $offset
24
-	 * @param int      $max
25
-	 */
26
-	public function process( $callback, $args = array(), $offset = 0, $max = PHP_INT_MAX ) {
27
-
28
-		// We process chunks in order to avoid using too much memory,
29
-		// starting at offset 0.
30
-		while ( 0 < sizeof( $items = $this->find( $offset, 1, $args ) ) && $offset < $max ) {
31
-
32
-			// Cycle through items and call the callback function.
33
-			foreach ( $items as $item ) {
34
-				call_user_func_array( $callback, array( $item ) );
35
-			}
36
-
37
-			// Remove the flush of the cache.
38
-			//
39
-			// See https://github.com/insideout10/wordlift-plugin/issues/686.
40
-			// Clean the cache to avoid memory errors.
41
-			// wp_cache_flush();
42
-
43
-			// Move to the next offset.
44
-			$offset += 1;
45
-
46
-			$this->count ++;
47
-
48
-		}
49
-
50
-	}
51
-
52
-	public function get_count() {
53
-
54
-		return $this->count;
55
-	}
7
+    private $count = 0;
8
+
9
+    /**
10
+     * List the items starting at the specified offset and up to the specified limit.
11
+     *
12
+     * @param int   $offset The start offset.
13
+     * @param int   $limit  The maximum number of items to return.
14
+     * @param array $args   Additional arguments.
15
+     *
16
+     * @return array A array of items (or an empty array if no items are found).
17
+     */
18
+    abstract function find( $offset = 0, $limit = 10, $args = array() );
19
+
20
+    /**
21
+     * @param callable $callback
22
+     * @param array    $args
23
+     * @param int      $offset
24
+     * @param int      $max
25
+     */
26
+    public function process( $callback, $args = array(), $offset = 0, $max = PHP_INT_MAX ) {
27
+
28
+        // We process chunks in order to avoid using too much memory,
29
+        // starting at offset 0.
30
+        while ( 0 < sizeof( $items = $this->find( $offset, 1, $args ) ) && $offset < $max ) {
31
+
32
+            // Cycle through items and call the callback function.
33
+            foreach ( $items as $item ) {
34
+                call_user_func_array( $callback, array( $item ) );
35
+            }
36
+
37
+            // Remove the flush of the cache.
38
+            //
39
+            // See https://github.com/insideout10/wordlift-plugin/issues/686.
40
+            // Clean the cache to avoid memory errors.
41
+            // wp_cache_flush();
42
+
43
+            // Move to the next offset.
44
+            $offset += 1;
45
+
46
+            $this->count ++;
47
+
48
+        }
49
+
50
+    }
51
+
52
+    public function get_count() {
53
+
54
+        return $this->count;
55
+    }
56 56
 
57 57
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
 	 *
16 16
 	 * @return array A array of items (or an empty array if no items are found).
17 17
 	 */
18
-	abstract function find( $offset = 0, $limit = 10, $args = array() );
18
+	abstract function find($offset = 0, $limit = 10, $args = array());
19 19
 
20 20
 	/**
21 21
 	 * @param callable $callback
@@ -23,15 +23,15 @@  discard block
 block discarded – undo
23 23
 	 * @param int      $offset
24 24
 	 * @param int      $max
25 25
 	 */
26
-	public function process( $callback, $args = array(), $offset = 0, $max = PHP_INT_MAX ) {
26
+	public function process($callback, $args = array(), $offset = 0, $max = PHP_INT_MAX) {
27 27
 
28 28
 		// We process chunks in order to avoid using too much memory,
29 29
 		// starting at offset 0.
30
-		while ( 0 < sizeof( $items = $this->find( $offset, 1, $args ) ) && $offset < $max ) {
30
+		while (0 < sizeof($items = $this->find($offset, 1, $args)) && $offset < $max) {
31 31
 
32 32
 			// Cycle through items and call the callback function.
33
-			foreach ( $items as $item ) {
34
-				call_user_func_array( $callback, array( $item ) );
33
+			foreach ($items as $item) {
34
+				call_user_func_array($callback, array($item));
35 35
 			}
36 36
 
37 37
 			// Remove the flush of the cache.
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
 			// Move to the next offset.
44 44
 			$offset += 1;
45 45
 
46
-			$this->count ++;
46
+			$this->count++;
47 47
 
48 48
 		}
49 49
 
Please login to merge, or discard this patch.
src/includes/rebuild/class-wordlift-relation-rebuild-adapter.php 2 patches
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -1,31 +1,31 @@
 block discarded – undo
1 1
 <?php
2 2
 
3 3
 class Wordlift_Relation_Rebuild_Adapter {
4
-	/**
5
-	 * @var Wordlift_Relation_Rebuild_Service
6
-	 */
7
-	private $relation_rebuild_service;
4
+    /**
5
+     * @var Wordlift_Relation_Rebuild_Service
6
+     */
7
+    private $relation_rebuild_service;
8 8
 
9 9
 
10
-	/**
11
-	 * Wordlift_Relation_Rebuild_Adapter constructor.
12
-	 *
13
-	 * @param \Wordlift_Relation_Rebuild_Service $relation_rebuild_service
14
-	 */
15
-	public function __construct( $relation_rebuild_service ) {
16
-		$this->relation_rebuild_service = $relation_rebuild_service;
17
-	}
10
+    /**
11
+     * Wordlift_Relation_Rebuild_Adapter constructor.
12
+     *
13
+     * @param \Wordlift_Relation_Rebuild_Service $relation_rebuild_service
14
+     */
15
+    public function __construct( $relation_rebuild_service ) {
16
+        $this->relation_rebuild_service = $relation_rebuild_service;
17
+    }
18 18
 
19
-	public function process_all() {
19
+    public function process_all() {
20 20
 
21
-		$this->relation_rebuild_service->process_all();
21
+        $this->relation_rebuild_service->process_all();
22 22
 
23
-		ob_clean();
23
+        ob_clean();
24 24
 
25
-		wp_send_json_success( array(
26
-			'count' => $this->relation_rebuild_service->get_count(),
27
-		) );
25
+        wp_send_json_success( array(
26
+            'count' => $this->relation_rebuild_service->get_count(),
27
+        ) );
28 28
 
29
-	}
29
+    }
30 30
 
31 31
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -12,7 +12,7 @@  discard block
 block discarded – undo
12 12
 	 *
13 13
 	 * @param \Wordlift_Relation_Rebuild_Service $relation_rebuild_service
14 14
 	 */
15
-	public function __construct( $relation_rebuild_service ) {
15
+	public function __construct($relation_rebuild_service) {
16 16
 		$this->relation_rebuild_service = $relation_rebuild_service;
17 17
 	}
18 18
 
@@ -22,9 +22,9 @@  discard block
 block discarded – undo
22 22
 
23 23
 		ob_clean();
24 24
 
25
-		wp_send_json_success( array(
25
+		wp_send_json_success(array(
26 26
 			'count' => $this->relation_rebuild_service->get_count(),
27
-		) );
27
+		));
28 28
 
29 29
 	}
30 30
 
Please login to merge, or discard this patch.
src/includes/batch-analysis/class-wordlift-batch-analysis-sql-helper.php 2 patches
Indentation   +177 added lines, -177 removed lines patch added patch discarded remove patch
@@ -11,25 +11,25 @@  discard block
 block discarded – undo
11 11
 
12 12
 class Wordlift_Batch_Analysis_Sql_Helper {
13 13
 
14
-	/**
15
-	 * Get the base SQL statement to submit a post for Batch Analysis.
16
-	 *
17
-	 * Functions may use this base SQL and add their own filters. This function
18
-	 * should be `private` and only used by the {@link Wordlift_Batch_Analysis_Service}
19
-	 * `submit` function. But since we want to maintain compatibility with PHP 5.3
20
-	 * and we couldn't use traits to hide the function from the Wordlift_Batch_Analysis_Service
21
-	 * we used a Helper function.
22
-	 *
23
-	 * @since 3.14.2
24
-	 *
25
-	 * @param array $args An array of parameters, see {@link submit}.
26
-	 *
27
-	 * @return string The base SQL.
28
-	 */
29
-	public static function get_sql( $args ) {
30
-		global $wpdb;
31
-
32
-		/*
14
+    /**
15
+     * Get the base SQL statement to submit a post for Batch Analysis.
16
+     *
17
+     * Functions may use this base SQL and add their own filters. This function
18
+     * should be `private` and only used by the {@link Wordlift_Batch_Analysis_Service}
19
+     * `submit` function. But since we want to maintain compatibility with PHP 5.3
20
+     * and we couldn't use traits to hide the function from the Wordlift_Batch_Analysis_Service
21
+     * we used a Helper function.
22
+     *
23
+     * @since 3.14.2
24
+     *
25
+     * @param array $args An array of parameters, see {@link submit}.
26
+     *
27
+     * @return string The base SQL.
28
+     */
29
+    public static function get_sql( $args ) {
30
+        global $wpdb;
31
+
32
+        /*
33 33
 		Prepare the statement:
34 34
 			1. Insert into `postmeta` the meta keys and values:
35 35
 				a) state meta, with value of SUBMIT (0),
@@ -45,21 +45,21 @@  discard block
 block discarded – undo
45 45
 			9. Filter by `post_id` where `exclude` is the posts id to exclude.
46 46
 		*/
47 47
 
48
-		// @codingStandardsIgnoreStart, Ignore phpcs sanitation errors.
49
-		return "SELECT p.ID FROM $wpdb->posts p"
50
-			   . " WHERE p.post_type IN ('" . join( "', '", array_map( 'esc_sql', (array) $args['post_type'] ) ) . "')"
51
-			   . "  AND p.post_status = 'publish'"
52
-			   . Wordlift_Batch_Analysis_Sql_Helper::and_include_annotated( $args['include_annotated'] )
53
-			   . Wordlift_Batch_Analysis_Sql_Helper::and_post_date_from( $args['from'] )
54
-			   . Wordlift_Batch_Analysis_Sql_Helper::and_post_date_to( $args['to'] )
55
-			   . Wordlift_Batch_Analysis_Sql_Helper::and_exclude_posts( $args['exclude'] );
56
-		// @codingStandardsIgnoreEnd
57
-	}
58
-
59
-	public static function get_sql_for_ids( $args ) {
60
-		global $wpdb;
61
-
62
-		/*
48
+        // @codingStandardsIgnoreStart, Ignore phpcs sanitation errors.
49
+        return "SELECT p.ID FROM $wpdb->posts p"
50
+                . " WHERE p.post_type IN ('" . join( "', '", array_map( 'esc_sql', (array) $args['post_type'] ) ) . "')"
51
+                . "  AND p.post_status = 'publish'"
52
+                . Wordlift_Batch_Analysis_Sql_Helper::and_include_annotated( $args['include_annotated'] )
53
+                . Wordlift_Batch_Analysis_Sql_Helper::and_post_date_from( $args['from'] )
54
+                . Wordlift_Batch_Analysis_Sql_Helper::and_post_date_to( $args['to'] )
55
+                . Wordlift_Batch_Analysis_Sql_Helper::and_exclude_posts( $args['exclude'] );
56
+        // @codingStandardsIgnoreEnd
57
+    }
58
+
59
+    public static function get_sql_for_ids( $args ) {
60
+        global $wpdb;
61
+
62
+        /*
63 63
 		Prepare the statement:
64 64
 			1. Insert into `postmeta` the meta keys and values:
65 65
 				a) state meta, with value of SUBMIT (0),
@@ -75,148 +75,148 @@  discard block
 block discarded – undo
75 75
 			9. Filter by `post_id` where `exclude` is the posts id to exclude.
76 76
 		*/
77 77
 
78
-		// @codingStandardsIgnoreStart, Ignore phpcs sanitation errors.
79
-
80
-		return "SELECT p.ID FROM $wpdb->posts p WHERE p.id IN (" . implode( ', ', wp_parse_id_list( $args['ids'] ) ) . ")";
81
-		// @codingStandardsIgnoreEnd
82
-	}
83
-
84
-	/**
85
-	 * Add a clause to analyze all auto selected posts, i.e. non annotated posts.
86
-	 *
87
-	 * @param bool $include Whether to include annotated posts in selection.
88
-	 *
89
-	 * @since  3.17.0
90
-	 *
91
-	 * @return string The `post_content` clause.
92
-	 */
93
-	private static function and_include_annotated( $include ) {
94
-
95
-		// Bail out with an empty string if we include all the posts.
96
-		if ( true === $include ) {
97
-			return '';
98
-		}
99
-
100
-		// Filter out already annotated posts.
101
-		return " AND p.post_content NOT REGEXP '<[a-z]+ id=\"urn:[^\"]+\" class=\"[^\"]+\" itemid=\"[^\"]+\">'";
102
-	}
103
-
104
-	/**
105
-	 * Add the start date clause.
106
-	 *
107
-	 * @param  DateTime|null $value The date where the analysis should start.
108
-	 *
109
-	 * @since  3.17.0
110
-	 *
111
-	 * @return string The start `post_date_gmt` clause
112
-	 */
113
-	private static function and_post_date_from( $value ) {
114
-
115
-		// Bail out if the `from` isn't specified.
116
-		if ( null === $value ) {
117
-			return '';
118
-		}
119
-
120
-		// Try to convert the value to a date, GMT timezone.
121
-		$date = self::get_mysql_date_string( $value );
122
-
123
-		// Return the clause.
124
-		return " AND p.post_date_gmt >= '$date'";
125
-	}
126
-
127
-	/**
128
-	 * Add the `to` date clause.
129
-	 *
130
-	 * @param  DateTime|null $value The `to` date clause.
131
-	 *
132
-	 * @since  3.17.0
133
-	 *
134
-	 * @return string The end `post_date_gmt` clause
135
-	 */
136
-	private static function and_post_date_to( $value ) {
137
-
138
-		// Bail out if the `from` isn't specified.
139
-		if ( null === $value ) {
140
-			return '';
141
-		}
142
-
143
-		// Try to convert the value to a date, GMT timezone.
144
-		$date = self::get_mysql_date_string( $value );
145
-
146
-		// Return the clause.
147
-		return " AND p.post_date_gmt <= '$date'";
148
-	}
149
-
150
-	/**
151
-	 * Include specific posts by their id in the analysis.
152
-	 *
153
-	 * @param array $include Array of post ids to include.
154
-	 *
155
-	 * @since  3.17.0
156
-	 *
157
-	 * @return string The posts IN clause.
158
-	 */
159
-	private static function and_include_posts( $include ) {
160
-
161
-		// Bail if the param is not set.
162
-		if ( empty( $include ) ) {
163
-			return '';
164
-		}
165
-
166
-		return ' AND p.ID IN ( ' . implode( ',', wp_parse_id_list( $include ) ) . ' )';
167
-	}
168
-
169
-	/**
170
-	 * Exclude specific posts by ids.
171
-	 *
172
-	 * @param array $exclude Array of post ids to exclude.
173
-	 *
174
-	 * @since  3.17.0
175
-	 *
176
-	 * @return string The posts NOT IN clause.
177
-	 */
178
-	private static function and_exclude_posts( $exclude ) {
179
-
180
-		// Bail if the param is not set.
181
-		if ( empty( $exclude ) ) {
182
-			return '';
183
-		}
184
-
185
-		return ' AND p.ID NOT IN ( ' . implode( ',', wp_parse_id_list( $exclude ) ) . ' )';
186
-	}
187
-
188
-
189
-	/**
190
-	 * Convert a `Y-m-d'T'H:i:sT` string representation of a date to a MySQL
191
-	 * date string, taking into consideration the time zone.
192
-	 *
193
-	 * If the date string cannot be converted, the processing is stopped.
194
-	 *
195
-	 * @since 3.17.0
196
-	 *
197
-	 * @param string $value A date represented as `Y-m-d'T'H:i:sT`.
198
-	 *
199
-	 * @return string A MySQL string representation of the date.
200
-	 */
201
-	private static function get_mysql_date_string( $value ) {
202
-
203
-		// Try to convert the value to a date, GMT timezone.
204
-		$date = date_create_from_format( 'Y-m-d\TH:i:sT', $value );
205
-
206
-		if ( false === $date ) {
207
-			wp_die( "Invalid date format, use `Y-m-d'T'H:i:sT`." );
208
-		}
209
-
210
-		// Convert the DateTime timezone to `GMT`.
211
-		$date->setTimezone( timezone_open( 'GMT' ) );
212
-
213
-		// Stop if the conversion failed.
214
-		if ( false === $date ) {
215
-			wp_die( "Invalid date format, date must be in Y-m-d'T'H:i:sT format." );
216
-		}
217
-
218
-		// Return the clause.
219
-		return $date->format( 'Y-m-d H:i:s' );
220
-	}
78
+        // @codingStandardsIgnoreStart, Ignore phpcs sanitation errors.
79
+
80
+        return "SELECT p.ID FROM $wpdb->posts p WHERE p.id IN (" . implode( ', ', wp_parse_id_list( $args['ids'] ) ) . ")";
81
+        // @codingStandardsIgnoreEnd
82
+    }
83
+
84
+    /**
85
+     * Add a clause to analyze all auto selected posts, i.e. non annotated posts.
86
+     *
87
+     * @param bool $include Whether to include annotated posts in selection.
88
+     *
89
+     * @since  3.17.0
90
+     *
91
+     * @return string The `post_content` clause.
92
+     */
93
+    private static function and_include_annotated( $include ) {
94
+
95
+        // Bail out with an empty string if we include all the posts.
96
+        if ( true === $include ) {
97
+            return '';
98
+        }
99
+
100
+        // Filter out already annotated posts.
101
+        return " AND p.post_content NOT REGEXP '<[a-z]+ id=\"urn:[^\"]+\" class=\"[^\"]+\" itemid=\"[^\"]+\">'";
102
+    }
103
+
104
+    /**
105
+     * Add the start date clause.
106
+     *
107
+     * @param  DateTime|null $value The date where the analysis should start.
108
+     *
109
+     * @since  3.17.0
110
+     *
111
+     * @return string The start `post_date_gmt` clause
112
+     */
113
+    private static function and_post_date_from( $value ) {
114
+
115
+        // Bail out if the `from` isn't specified.
116
+        if ( null === $value ) {
117
+            return '';
118
+        }
119
+
120
+        // Try to convert the value to a date, GMT timezone.
121
+        $date = self::get_mysql_date_string( $value );
122
+
123
+        // Return the clause.
124
+        return " AND p.post_date_gmt >= '$date'";
125
+    }
126
+
127
+    /**
128
+     * Add the `to` date clause.
129
+     *
130
+     * @param  DateTime|null $value The `to` date clause.
131
+     *
132
+     * @since  3.17.0
133
+     *
134
+     * @return string The end `post_date_gmt` clause
135
+     */
136
+    private static function and_post_date_to( $value ) {
137
+
138
+        // Bail out if the `from` isn't specified.
139
+        if ( null === $value ) {
140
+            return '';
141
+        }
142
+
143
+        // Try to convert the value to a date, GMT timezone.
144
+        $date = self::get_mysql_date_string( $value );
145
+
146
+        // Return the clause.
147
+        return " AND p.post_date_gmt <= '$date'";
148
+    }
149
+
150
+    /**
151
+     * Include specific posts by their id in the analysis.
152
+     *
153
+     * @param array $include Array of post ids to include.
154
+     *
155
+     * @since  3.17.0
156
+     *
157
+     * @return string The posts IN clause.
158
+     */
159
+    private static function and_include_posts( $include ) {
160
+
161
+        // Bail if the param is not set.
162
+        if ( empty( $include ) ) {
163
+            return '';
164
+        }
165
+
166
+        return ' AND p.ID IN ( ' . implode( ',', wp_parse_id_list( $include ) ) . ' )';
167
+    }
168
+
169
+    /**
170
+     * Exclude specific posts by ids.
171
+     *
172
+     * @param array $exclude Array of post ids to exclude.
173
+     *
174
+     * @since  3.17.0
175
+     *
176
+     * @return string The posts NOT IN clause.
177
+     */
178
+    private static function and_exclude_posts( $exclude ) {
179
+
180
+        // Bail if the param is not set.
181
+        if ( empty( $exclude ) ) {
182
+            return '';
183
+        }
184
+
185
+        return ' AND p.ID NOT IN ( ' . implode( ',', wp_parse_id_list( $exclude ) ) . ' )';
186
+    }
187
+
188
+
189
+    /**
190
+     * Convert a `Y-m-d'T'H:i:sT` string representation of a date to a MySQL
191
+     * date string, taking into consideration the time zone.
192
+     *
193
+     * If the date string cannot be converted, the processing is stopped.
194
+     *
195
+     * @since 3.17.0
196
+     *
197
+     * @param string $value A date represented as `Y-m-d'T'H:i:sT`.
198
+     *
199
+     * @return string A MySQL string representation of the date.
200
+     */
201
+    private static function get_mysql_date_string( $value ) {
202
+
203
+        // Try to convert the value to a date, GMT timezone.
204
+        $date = date_create_from_format( 'Y-m-d\TH:i:sT', $value );
205
+
206
+        if ( false === $date ) {
207
+            wp_die( "Invalid date format, use `Y-m-d'T'H:i:sT`." );
208
+        }
209
+
210
+        // Convert the DateTime timezone to `GMT`.
211
+        $date->setTimezone( timezone_open( 'GMT' ) );
212
+
213
+        // Stop if the conversion failed.
214
+        if ( false === $date ) {
215
+            wp_die( "Invalid date format, date must be in Y-m-d'T'H:i:sT format." );
216
+        }
217
+
218
+        // Return the clause.
219
+        return $date->format( 'Y-m-d H:i:s' );
220
+    }
221 221
 
222 222
 }
Please login to merge, or discard this patch.
Spacing   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@  discard block
 block discarded – undo
26 26
 	 *
27 27
 	 * @return string The base SQL.
28 28
 	 */
29
-	public static function get_sql( $args ) {
29
+	public static function get_sql($args) {
30 30
 		global $wpdb;
31 31
 
32 32
 		/*
@@ -47,16 +47,16 @@  discard block
 block discarded – undo
47 47
 
48 48
 		// @codingStandardsIgnoreStart, Ignore phpcs sanitation errors.
49 49
 		return "SELECT p.ID FROM $wpdb->posts p"
50
-			   . " WHERE p.post_type IN ('" . join( "', '", array_map( 'esc_sql', (array) $args['post_type'] ) ) . "')"
50
+			   . " WHERE p.post_type IN ('".join("', '", array_map('esc_sql', (array) $args['post_type']))."')"
51 51
 			   . "  AND p.post_status = 'publish'"
52
-			   . Wordlift_Batch_Analysis_Sql_Helper::and_include_annotated( $args['include_annotated'] )
53
-			   . Wordlift_Batch_Analysis_Sql_Helper::and_post_date_from( $args['from'] )
54
-			   . Wordlift_Batch_Analysis_Sql_Helper::and_post_date_to( $args['to'] )
55
-			   . Wordlift_Batch_Analysis_Sql_Helper::and_exclude_posts( $args['exclude'] );
52
+			   . Wordlift_Batch_Analysis_Sql_Helper::and_include_annotated($args['include_annotated'])
53
+			   . Wordlift_Batch_Analysis_Sql_Helper::and_post_date_from($args['from'])
54
+			   . Wordlift_Batch_Analysis_Sql_Helper::and_post_date_to($args['to'])
55
+			   . Wordlift_Batch_Analysis_Sql_Helper::and_exclude_posts($args['exclude']);
56 56
 		// @codingStandardsIgnoreEnd
57 57
 	}
58 58
 
59
-	public static function get_sql_for_ids( $args ) {
59
+	public static function get_sql_for_ids($args) {
60 60
 		global $wpdb;
61 61
 
62 62
 		/*
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 
78 78
 		// @codingStandardsIgnoreStart, Ignore phpcs sanitation errors.
79 79
 
80
-		return "SELECT p.ID FROM $wpdb->posts p WHERE p.id IN (" . implode( ', ', wp_parse_id_list( $args['ids'] ) ) . ")";
80
+		return "SELECT p.ID FROM $wpdb->posts p WHERE p.id IN (".implode(', ', wp_parse_id_list($args['ids'])).")";
81 81
 		// @codingStandardsIgnoreEnd
82 82
 	}
83 83
 
@@ -90,10 +90,10 @@  discard block
 block discarded – undo
90 90
 	 *
91 91
 	 * @return string The `post_content` clause.
92 92
 	 */
93
-	private static function and_include_annotated( $include ) {
93
+	private static function and_include_annotated($include) {
94 94
 
95 95
 		// Bail out with an empty string if we include all the posts.
96
-		if ( true === $include ) {
96
+		if (true === $include) {
97 97
 			return '';
98 98
 		}
99 99
 
@@ -110,15 +110,15 @@  discard block
 block discarded – undo
110 110
 	 *
111 111
 	 * @return string The start `post_date_gmt` clause
112 112
 	 */
113
-	private static function and_post_date_from( $value ) {
113
+	private static function and_post_date_from($value) {
114 114
 
115 115
 		// Bail out if the `from` isn't specified.
116
-		if ( null === $value ) {
116
+		if (null === $value) {
117 117
 			return '';
118 118
 		}
119 119
 
120 120
 		// Try to convert the value to a date, GMT timezone.
121
-		$date = self::get_mysql_date_string( $value );
121
+		$date = self::get_mysql_date_string($value);
122 122
 
123 123
 		// Return the clause.
124 124
 		return " AND p.post_date_gmt >= '$date'";
@@ -133,15 +133,15 @@  discard block
 block discarded – undo
133 133
 	 *
134 134
 	 * @return string The end `post_date_gmt` clause
135 135
 	 */
136
-	private static function and_post_date_to( $value ) {
136
+	private static function and_post_date_to($value) {
137 137
 
138 138
 		// Bail out if the `from` isn't specified.
139
-		if ( null === $value ) {
139
+		if (null === $value) {
140 140
 			return '';
141 141
 		}
142 142
 
143 143
 		// Try to convert the value to a date, GMT timezone.
144
-		$date = self::get_mysql_date_string( $value );
144
+		$date = self::get_mysql_date_string($value);
145 145
 
146 146
 		// Return the clause.
147 147
 		return " AND p.post_date_gmt <= '$date'";
@@ -156,14 +156,14 @@  discard block
 block discarded – undo
156 156
 	 *
157 157
 	 * @return string The posts IN clause.
158 158
 	 */
159
-	private static function and_include_posts( $include ) {
159
+	private static function and_include_posts($include) {
160 160
 
161 161
 		// Bail if the param is not set.
162
-		if ( empty( $include ) ) {
162
+		if (empty($include)) {
163 163
 			return '';
164 164
 		}
165 165
 
166
-		return ' AND p.ID IN ( ' . implode( ',', wp_parse_id_list( $include ) ) . ' )';
166
+		return ' AND p.ID IN ( '.implode(',', wp_parse_id_list($include)).' )';
167 167
 	}
168 168
 
169 169
 	/**
@@ -175,14 +175,14 @@  discard block
 block discarded – undo
175 175
 	 *
176 176
 	 * @return string The posts NOT IN clause.
177 177
 	 */
178
-	private static function and_exclude_posts( $exclude ) {
178
+	private static function and_exclude_posts($exclude) {
179 179
 
180 180
 		// Bail if the param is not set.
181
-		if ( empty( $exclude ) ) {
181
+		if (empty($exclude)) {
182 182
 			return '';
183 183
 		}
184 184
 
185
-		return ' AND p.ID NOT IN ( ' . implode( ',', wp_parse_id_list( $exclude ) ) . ' )';
185
+		return ' AND p.ID NOT IN ( '.implode(',', wp_parse_id_list($exclude)).' )';
186 186
 	}
187 187
 
188 188
 
@@ -198,25 +198,25 @@  discard block
 block discarded – undo
198 198
 	 *
199 199
 	 * @return string A MySQL string representation of the date.
200 200
 	 */
201
-	private static function get_mysql_date_string( $value ) {
201
+	private static function get_mysql_date_string($value) {
202 202
 
203 203
 		// Try to convert the value to a date, GMT timezone.
204
-		$date = date_create_from_format( 'Y-m-d\TH:i:sT', $value );
204
+		$date = date_create_from_format('Y-m-d\TH:i:sT', $value);
205 205
 
206
-		if ( false === $date ) {
207
-			wp_die( "Invalid date format, use `Y-m-d'T'H:i:sT`." );
206
+		if (false === $date) {
207
+			wp_die("Invalid date format, use `Y-m-d'T'H:i:sT`.");
208 208
 		}
209 209
 
210 210
 		// Convert the DateTime timezone to `GMT`.
211
-		$date->setTimezone( timezone_open( 'GMT' ) );
211
+		$date->setTimezone(timezone_open('GMT'));
212 212
 
213 213
 		// Stop if the conversion failed.
214
-		if ( false === $date ) {
215
-			wp_die( "Invalid date format, date must be in Y-m-d'T'H:i:sT format." );
214
+		if (false === $date) {
215
+			wp_die("Invalid date format, date must be in Y-m-d'T'H:i:sT format.");
216 216
 		}
217 217
 
218 218
 		// Return the clause.
219
-		return $date->format( 'Y-m-d H:i:s' );
219
+		return $date->format('Y-m-d H:i:s');
220 220
 	}
221 221
 
222 222
 }
Please login to merge, or discard this patch.
src/includes/batch-analysis/class-wordlift-batch-analysis-service.php 2 patches
Indentation   +751 added lines, -751 removed lines patch added patch discarded remove patch
@@ -51,558 +51,558 @@  discard block
 block discarded – undo
51 51
  */
52 52
 class Wordlift_Batch_Analysis_Service {
53 53
 
54
-	/**
55
-	 * The list of states for the Batch Analysis:
56
-	 *  - STATE_META_KEY: the batch analysis state meta key,
57
-	 *  - STATE_SUBMIT: a post/page has been submitted for analysis,
58
-	 *  - STATE_REQUEST: the plugin requested an analysis for the submitted
59
-	 *      post/page,
60
-	 *  - STATE_SUCCESS: the analysis has completed successfully,
61
-	 *  - STATE_ERROR: the analysis returned an error.
62
-	 *
63
-	 * @since 3.14.2
64
-	 */
65
-	const STATE_META_KEY = '_wl_batch_analysis_state';
66
-	const STATE_SUBMIT = 0;
67
-	const STATE_REQUEST = 1;
68
-	// ### COMPLETE states.
69
-	const STATE_SUCCESS = 2;
70
-	const STATE_ERROR = 2;
71
-
72
-	/**
73
-	 * The submit timestamp meta key. A post may have more than one timestamp.
74
-	 *
75
-	 * @since 3.14.2
76
-	 */
77
-	const SUBMIT_TIMESTAMP_META_KEY = '_wl_batch_analysis_submit_timestamp';
78
-
79
-	/**
80
-	 * The request timestamp meta key. A post may have more than one timestamp.
81
-	 *
82
-	 * @since 3.14.2
83
-	 */
84
-	const REQUEST_TIMESTAMP_META_KEY = '_wl_batch_analysis_request_timestamp';
85
-
86
-	/**
87
-	 * The complete (success or error) timestamp meta key. A post may have more
88
-	 * than one timestamp.
89
-	 *
90
-	 * @since 3.14.2
91
-	 */
92
-	const COMPLETE_TIMESTAMP_META_KEY = '_wl_batch_analysis_complete_timestamp';
93
-
94
-	/**
95
-	 * The options setting meta key. A post may have more than one setting.
96
-	 *
97
-	 * @since 3.14.2
98
-	 */
99
-	const BATCH_ANALYSIS_OPTIONS_META_KEY = '_wl_batch_analysis_options';
100
-
101
-	/**
102
-	 * The warning timestamp meta key. A post has only zero/one value.
103
-	 *
104
-	 * @since 3.14.2
105
-	 */
106
-	const WARNING_META_KEY = '_wl_batch_analysis_warning';
107
-
108
-	/**
109
-	 * Option name.
110
-	 *
111
-	 * @since  3.14.0
112
-	 */
113
-	const OPTION_NAME = 'wl_analyze_batch';
114
-
115
-	/**
116
-	 * Name of waiting to be processed queue array inside the option.
117
-	 *
118
-	 * @since  3.14.0
119
-	 */
120
-	const ANALYZE_QUEUE = 'queue';
121
-
122
-	/**
123
-	 * Name of waiting for response queue array inside the option.
124
-	 *
125
-	 * @since  3.14.0
126
-	 */
127
-	const RESPONSE_QUEUE = 'processing';
128
-
129
-	/**
130
-	 * Regular expressions that match interpolation errors.
131
-	 *
132
-	 * @since  3.17.0
133
-	 */
134
-	private static $interpolation_patterns = array(
135
-		// Matches word before the annotation.
136
-		'~(\w)<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">(.*?)<\/[a-z]+>~',
137
-		// Matches word after the annotation.
138
-		'~<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">(.*?)<\/[a-z]+>(\w)~',
139
-		// Matches space in the beginning of annotation name.
140
-		'~<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">(\s)(.*?)<\/[a-z]+>~',
141
-	);
142
-
143
-	/**
144
-	 * The {@link Wordlift} plugin instance.
145
-	 *
146
-	 * @since  3.14.0
147
-	 * @access private
148
-	 * @var \Wordlift $plugin The {@link Wordlift} plugin instance.
149
-	 */
150
-	private $plugin;
151
-
152
-	/**
153
-	 * The {@link Wordlift_Configuration_Service} instance.
154
-	 *
155
-	 * @since  3.14.0
156
-	 * @access private
157
-	 * @var \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
158
-	 */
159
-	private $configuration_service;
160
-
161
-	/**
162
-	 * The {@link Wordlift_Cache_Service} instance.
163
-	 *
164
-	 * @since  3.17.0
165
-	 * @access protected
166
-	 * @var \Wordlift_Cache_Service $cache_service The {@link Wordlift_Cache_Service} instance.
167
-	 */
168
-	private $cache_service;
169
-
170
-	/**
171
-	 * A {@link Wordlift_Log_Service} instance.
172
-	 *
173
-	 * @since  3.14.2
174
-	 * @access private
175
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
176
-	 */
177
-	private $log;
178
-
179
-	/**
180
-	 * The {@link Class_Wordlift_Batch_Analys_Service} instance.
181
-	 *
182
-	 * @since 3.14.0
183
-	 *
184
-	 * @param \Wordlift                       $plugin                The {@link Wordlift} plugin instance.
185
-	 * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
186
-	 * @param \Wordlift_Cache_Service         $cache_service         The {@link Wordlift_Cache_Service} instance.
187
-	 */
188
-	public function __construct( $plugin, $configuration_service, $cache_service ) {
189
-
190
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Batch_Analysis_Service' );
191
-
192
-		$this->plugin                = $plugin;
193
-		$this->configuration_service = $configuration_service;
194
-		$this->cache_service         = $cache_service;
195
-
196
-		add_action( 'wl_async_wl_batch_analysis_request', array(
197
-			$this,
198
-			'request',
199
-		) );
200
-		add_action( 'wl_async_wl_batch_analysis_complete', array(
201
-			$this,
202
-			'complete',
203
-		) );
204
-
205
-	}
206
-
207
-	/**
208
-	 * Submit posts for Batch Analysis.
209
-	 *
210
-	 * @since 3.14.2
211
-	 *
212
-	 * @param array       $args               {
213
-	 *                                        A list of options for the Batch Analysis.
214
-	 *
215
-	 * @type string       $link               Either `default`, `no` or `yes` (`default` is used if not specified):
216
-	 *                                        * `default` doesn't set the link option - entities
217
-	 *                                           will be linked if configured so in WordLift settings.
218
-	 *                                        * `yes` links the entities.
219
-	 *                                        * `no` doesn't link the entities.
220
-	 *                                        This value is forwarded to WLS' Batch Analysis end-point.
221
-	 * @type int          $min_occurrences    The minimum number of occurrences to select
222
-	 *                                        an entity. Default `1`.
223
-	 * @type bool         $include_annotated  Whether to include annotated posts in selection.
224
-	 *                                        Default `false`.
225
-	 * @type array|int    $include            Explicitly include the specified {@link WP_Post}s.
226
-	 * @type array|int    $exclude            Explicitly exclude the specified {@link WP_Post}s.
227
-	 * @type string|null  $from               An optional date from filter (used in `post_date_gmt`).
228
-	 * @type string|null  $to                 An optional date from filter (used in `post_date_gmt`).
229
-	 * @type array|string $post_type          Specify the post type(s), by default only `post`.
230
-	 *                      }
231
-	 *
232
-	 * @return int The number of submitted {@link WP_Post}s or false on error.
233
-	 */
234
-	public function submit( $args ) {
235
-		// Parse the parameters.
236
-		$params = wp_parse_args( $args, array(
237
-			'links'             => 'default',
238
-			'min_occurrences'   => 1,
239
-			'include_annotated' => false,
240
-			'exclude'           => array(),
241
-			'from'              => null,
242
-			'to'                => null,
243
-			'post_type'         => 'post',
244
-		) );
245
-
246
-		// Validation.
247
-		if ( ! in_array( $params['links'], array( 'default', 'yes', 'no' ) ) ) {
248
-			wp_die( '`link` must be one of the following: `default`, `yes` or `no`.' );
249
-		}
250
-
251
-		if ( ! is_numeric( $params['min_occurrences'] ) || 1 > $params['min_occurrences'] ) {
252
-			wp_die( '`min_occurrences` must greater or equal 1.' );
253
-		}
254
-
255
-		// Get the sql query.
256
-		$query = Wordlift_Batch_Analysis_Sql_Helper::get_sql( $params );
257
-
258
-		// Set the post metas and get the value of the posts.
259
-		$submitted_posts = $this->update_posts_meta( $params, $query );
260
-
261
-		// Request Batch Analysis (the operation is handled asynchronously).
262
-		do_action( 'wl_batch_analysis_request' );
263
-
264
-		// Return the count of the posts.
265
-		return $submitted_posts;
266
-	}
267
-
268
-	/**
269
-	 * Submit one or more {@link WP_Posts} for Batch Analysis.
270
-	 *
271
-	 * @param array    $args            {
272
-	 *                                  An array of arguments.
273
-	 *
274
-	 * @type string    $link            The link option: `default`, `yes` or
275
-	 *                                  `no`. If not set `default`.
276
-	 * @type int       $min_occurrences The minimum number of occurrences. If
277
-	 *                                  not set `1`.
278
-	 * @type array|int $ids             An array of {@link WP_Post}s' ids or one
279
-	 *                                  single numeric {@link WP_Post} id.
280
-	 *                    }
281
-	 *
282
-	 * @return float|int
283
-	 */
284
-	public function submit_posts( $args ) {
285
-		// Parse the parameters.
286
-		$params = wp_parse_args( $args, array(
287
-			'links'           => 'default',
288
-			'min_occurrences' => 1,
289
-			'ids'             => array(),
290
-		) );
291
-
292
-		// Validation.
293
-		if ( empty( $params['ids'] ) ) {
294
-			wp_die( '`ids` cannot be empty.' );
295
-		}
296
-
297
-		// Get the query,
298
-		$query = Wordlift_Batch_Analysis_Sql_Helper::get_sql_for_ids( $params );
299
-
300
-		// Set the post metas and get the value of the posts.
301
-		$submitted_posts = $this->update_posts_meta( $params, $query );
302
-
303
-		// Request Batch Analysis (the operation is handled asynchronously).
304
-		do_action( 'wl_batch_analysis_request' );
305
-
306
-		// Return the count of the posts.
307
-		return $submitted_posts;
308
-	}
309
-
310
-	/**
311
-	 * Add metas to the posts that should be analysed.
312
-	 *
313
-	 * @param array  $params The request params.
314
-	 * @param string $query  The mysql query.
315
-	 *
316
-	 * @since 3.18.0
317
-	 *
318
-	 * @return int The number of posts found/submitted.
319
-	 */
320
-	public function update_posts_meta( $params, $query ) {
321
-		global $wpdb;
322
-
323
-		// Get the link options.
324
-		$link_options = array(
325
-			'links'           => $params['links'],
326
-			'min_occurrences' => $params['min_occurrences'],
327
-		);
328
-
329
-		// Get the posts that should be submitted for analysis.
330
-		$posts = $wpdb->get_results( $query ); // WPCS: cache ok, db call ok.
331
-
332
-		// Bail if there are no posts found.
333
-		if ( empty( $posts ) ) {
334
-			return 0;
335
-		}
336
-
337
-		// Add the post metas.
338
-		foreach ( $posts as $p ) {
339
-			add_post_meta( $p->ID, self::STATE_META_KEY, 0 );
340
-			add_post_meta( $p->ID, self::SUBMIT_TIMESTAMP_META_KEY, gmdate( 'Y-m-d H:i:s' ) );
341
-			add_post_meta( $p->ID, self::BATCH_ANALYSIS_OPTIONS_META_KEY, $link_options );
342
-		}
343
-
344
-		// Finally return the posts count.
345
-		return count( $posts );
346
-	}
347
-
348
-	/**
349
-	 * Cancel the Batch Analysis request for the specified {@link WP_Post}s.
350
-	 *
351
-	 * @since 3.14.2
352
-	 *
353
-	 * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
354
-	 *                            {@link WP_Post}s' ids.
355
-	 *
356
-	 * @return false|int The number of cancelled {@link WP_Post}s or false on
357
-	 *                   error.
358
-	 */
359
-	public function cancel( $post_ids ) {
360
-		global $wpdb;
361
-
362
-		return $wpdb->query( $wpdb->prepare(
363
-			"
54
+    /**
55
+     * The list of states for the Batch Analysis:
56
+     *  - STATE_META_KEY: the batch analysis state meta key,
57
+     *  - STATE_SUBMIT: a post/page has been submitted for analysis,
58
+     *  - STATE_REQUEST: the plugin requested an analysis for the submitted
59
+     *      post/page,
60
+     *  - STATE_SUCCESS: the analysis has completed successfully,
61
+     *  - STATE_ERROR: the analysis returned an error.
62
+     *
63
+     * @since 3.14.2
64
+     */
65
+    const STATE_META_KEY = '_wl_batch_analysis_state';
66
+    const STATE_SUBMIT = 0;
67
+    const STATE_REQUEST = 1;
68
+    // ### COMPLETE states.
69
+    const STATE_SUCCESS = 2;
70
+    const STATE_ERROR = 2;
71
+
72
+    /**
73
+     * The submit timestamp meta key. A post may have more than one timestamp.
74
+     *
75
+     * @since 3.14.2
76
+     */
77
+    const SUBMIT_TIMESTAMP_META_KEY = '_wl_batch_analysis_submit_timestamp';
78
+
79
+    /**
80
+     * The request timestamp meta key. A post may have more than one timestamp.
81
+     *
82
+     * @since 3.14.2
83
+     */
84
+    const REQUEST_TIMESTAMP_META_KEY = '_wl_batch_analysis_request_timestamp';
85
+
86
+    /**
87
+     * The complete (success or error) timestamp meta key. A post may have more
88
+     * than one timestamp.
89
+     *
90
+     * @since 3.14.2
91
+     */
92
+    const COMPLETE_TIMESTAMP_META_KEY = '_wl_batch_analysis_complete_timestamp';
93
+
94
+    /**
95
+     * The options setting meta key. A post may have more than one setting.
96
+     *
97
+     * @since 3.14.2
98
+     */
99
+    const BATCH_ANALYSIS_OPTIONS_META_KEY = '_wl_batch_analysis_options';
100
+
101
+    /**
102
+     * The warning timestamp meta key. A post has only zero/one value.
103
+     *
104
+     * @since 3.14.2
105
+     */
106
+    const WARNING_META_KEY = '_wl_batch_analysis_warning';
107
+
108
+    /**
109
+     * Option name.
110
+     *
111
+     * @since  3.14.0
112
+     */
113
+    const OPTION_NAME = 'wl_analyze_batch';
114
+
115
+    /**
116
+     * Name of waiting to be processed queue array inside the option.
117
+     *
118
+     * @since  3.14.0
119
+     */
120
+    const ANALYZE_QUEUE = 'queue';
121
+
122
+    /**
123
+     * Name of waiting for response queue array inside the option.
124
+     *
125
+     * @since  3.14.0
126
+     */
127
+    const RESPONSE_QUEUE = 'processing';
128
+
129
+    /**
130
+     * Regular expressions that match interpolation errors.
131
+     *
132
+     * @since  3.17.0
133
+     */
134
+    private static $interpolation_patterns = array(
135
+        // Matches word before the annotation.
136
+        '~(\w)<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">(.*?)<\/[a-z]+>~',
137
+        // Matches word after the annotation.
138
+        '~<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">(.*?)<\/[a-z]+>(\w)~',
139
+        // Matches space in the beginning of annotation name.
140
+        '~<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">(\s)(.*?)<\/[a-z]+>~',
141
+    );
142
+
143
+    /**
144
+     * The {@link Wordlift} plugin instance.
145
+     *
146
+     * @since  3.14.0
147
+     * @access private
148
+     * @var \Wordlift $plugin The {@link Wordlift} plugin instance.
149
+     */
150
+    private $plugin;
151
+
152
+    /**
153
+     * The {@link Wordlift_Configuration_Service} instance.
154
+     *
155
+     * @since  3.14.0
156
+     * @access private
157
+     * @var \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
158
+     */
159
+    private $configuration_service;
160
+
161
+    /**
162
+     * The {@link Wordlift_Cache_Service} instance.
163
+     *
164
+     * @since  3.17.0
165
+     * @access protected
166
+     * @var \Wordlift_Cache_Service $cache_service The {@link Wordlift_Cache_Service} instance.
167
+     */
168
+    private $cache_service;
169
+
170
+    /**
171
+     * A {@link Wordlift_Log_Service} instance.
172
+     *
173
+     * @since  3.14.2
174
+     * @access private
175
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
176
+     */
177
+    private $log;
178
+
179
+    /**
180
+     * The {@link Class_Wordlift_Batch_Analys_Service} instance.
181
+     *
182
+     * @since 3.14.0
183
+     *
184
+     * @param \Wordlift                       $plugin                The {@link Wordlift} plugin instance.
185
+     * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
186
+     * @param \Wordlift_Cache_Service         $cache_service         The {@link Wordlift_Cache_Service} instance.
187
+     */
188
+    public function __construct( $plugin, $configuration_service, $cache_service ) {
189
+
190
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Batch_Analysis_Service' );
191
+
192
+        $this->plugin                = $plugin;
193
+        $this->configuration_service = $configuration_service;
194
+        $this->cache_service         = $cache_service;
195
+
196
+        add_action( 'wl_async_wl_batch_analysis_request', array(
197
+            $this,
198
+            'request',
199
+        ) );
200
+        add_action( 'wl_async_wl_batch_analysis_complete', array(
201
+            $this,
202
+            'complete',
203
+        ) );
204
+
205
+    }
206
+
207
+    /**
208
+     * Submit posts for Batch Analysis.
209
+     *
210
+     * @since 3.14.2
211
+     *
212
+     * @param array       $args               {
213
+     *                                        A list of options for the Batch Analysis.
214
+     *
215
+     * @type string       $link               Either `default`, `no` or `yes` (`default` is used if not specified):
216
+     *                                        * `default` doesn't set the link option - entities
217
+     *                                           will be linked if configured so in WordLift settings.
218
+     *                                        * `yes` links the entities.
219
+     *                                        * `no` doesn't link the entities.
220
+     *                                        This value is forwarded to WLS' Batch Analysis end-point.
221
+     * @type int          $min_occurrences    The minimum number of occurrences to select
222
+     *                                        an entity. Default `1`.
223
+     * @type bool         $include_annotated  Whether to include annotated posts in selection.
224
+     *                                        Default `false`.
225
+     * @type array|int    $include            Explicitly include the specified {@link WP_Post}s.
226
+     * @type array|int    $exclude            Explicitly exclude the specified {@link WP_Post}s.
227
+     * @type string|null  $from               An optional date from filter (used in `post_date_gmt`).
228
+     * @type string|null  $to                 An optional date from filter (used in `post_date_gmt`).
229
+     * @type array|string $post_type          Specify the post type(s), by default only `post`.
230
+     *                      }
231
+     *
232
+     * @return int The number of submitted {@link WP_Post}s or false on error.
233
+     */
234
+    public function submit( $args ) {
235
+        // Parse the parameters.
236
+        $params = wp_parse_args( $args, array(
237
+            'links'             => 'default',
238
+            'min_occurrences'   => 1,
239
+            'include_annotated' => false,
240
+            'exclude'           => array(),
241
+            'from'              => null,
242
+            'to'                => null,
243
+            'post_type'         => 'post',
244
+        ) );
245
+
246
+        // Validation.
247
+        if ( ! in_array( $params['links'], array( 'default', 'yes', 'no' ) ) ) {
248
+            wp_die( '`link` must be one of the following: `default`, `yes` or `no`.' );
249
+        }
250
+
251
+        if ( ! is_numeric( $params['min_occurrences'] ) || 1 > $params['min_occurrences'] ) {
252
+            wp_die( '`min_occurrences` must greater or equal 1.' );
253
+        }
254
+
255
+        // Get the sql query.
256
+        $query = Wordlift_Batch_Analysis_Sql_Helper::get_sql( $params );
257
+
258
+        // Set the post metas and get the value of the posts.
259
+        $submitted_posts = $this->update_posts_meta( $params, $query );
260
+
261
+        // Request Batch Analysis (the operation is handled asynchronously).
262
+        do_action( 'wl_batch_analysis_request' );
263
+
264
+        // Return the count of the posts.
265
+        return $submitted_posts;
266
+    }
267
+
268
+    /**
269
+     * Submit one or more {@link WP_Posts} for Batch Analysis.
270
+     *
271
+     * @param array    $args            {
272
+     *                                  An array of arguments.
273
+     *
274
+     * @type string    $link            The link option: `default`, `yes` or
275
+     *                                  `no`. If not set `default`.
276
+     * @type int       $min_occurrences The minimum number of occurrences. If
277
+     *                                  not set `1`.
278
+     * @type array|int $ids             An array of {@link WP_Post}s' ids or one
279
+     *                                  single numeric {@link WP_Post} id.
280
+     *                    }
281
+     *
282
+     * @return float|int
283
+     */
284
+    public function submit_posts( $args ) {
285
+        // Parse the parameters.
286
+        $params = wp_parse_args( $args, array(
287
+            'links'           => 'default',
288
+            'min_occurrences' => 1,
289
+            'ids'             => array(),
290
+        ) );
291
+
292
+        // Validation.
293
+        if ( empty( $params['ids'] ) ) {
294
+            wp_die( '`ids` cannot be empty.' );
295
+        }
296
+
297
+        // Get the query,
298
+        $query = Wordlift_Batch_Analysis_Sql_Helper::get_sql_for_ids( $params );
299
+
300
+        // Set the post metas and get the value of the posts.
301
+        $submitted_posts = $this->update_posts_meta( $params, $query );
302
+
303
+        // Request Batch Analysis (the operation is handled asynchronously).
304
+        do_action( 'wl_batch_analysis_request' );
305
+
306
+        // Return the count of the posts.
307
+        return $submitted_posts;
308
+    }
309
+
310
+    /**
311
+     * Add metas to the posts that should be analysed.
312
+     *
313
+     * @param array  $params The request params.
314
+     * @param string $query  The mysql query.
315
+     *
316
+     * @since 3.18.0
317
+     *
318
+     * @return int The number of posts found/submitted.
319
+     */
320
+    public function update_posts_meta( $params, $query ) {
321
+        global $wpdb;
322
+
323
+        // Get the link options.
324
+        $link_options = array(
325
+            'links'           => $params['links'],
326
+            'min_occurrences' => $params['min_occurrences'],
327
+        );
328
+
329
+        // Get the posts that should be submitted for analysis.
330
+        $posts = $wpdb->get_results( $query ); // WPCS: cache ok, db call ok.
331
+
332
+        // Bail if there are no posts found.
333
+        if ( empty( $posts ) ) {
334
+            return 0;
335
+        }
336
+
337
+        // Add the post metas.
338
+        foreach ( $posts as $p ) {
339
+            add_post_meta( $p->ID, self::STATE_META_KEY, 0 );
340
+            add_post_meta( $p->ID, self::SUBMIT_TIMESTAMP_META_KEY, gmdate( 'Y-m-d H:i:s' ) );
341
+            add_post_meta( $p->ID, self::BATCH_ANALYSIS_OPTIONS_META_KEY, $link_options );
342
+        }
343
+
344
+        // Finally return the posts count.
345
+        return count( $posts );
346
+    }
347
+
348
+    /**
349
+     * Cancel the Batch Analysis request for the specified {@link WP_Post}s.
350
+     *
351
+     * @since 3.14.2
352
+     *
353
+     * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
354
+     *                            {@link WP_Post}s' ids.
355
+     *
356
+     * @return false|int The number of cancelled {@link WP_Post}s or false on
357
+     *                   error.
358
+     */
359
+    public function cancel( $post_ids ) {
360
+        global $wpdb;
361
+
362
+        return $wpdb->query( $wpdb->prepare(
363
+            "
364 364
 			DELETE FROM $wpdb->postmeta
365 365
 			WHERE meta_key = %s
366 366
 				AND meta_value IN ( %d, %d )
367 367
 				AND post_id IN( " . implode( ',', wp_parse_id_list( $post_ids ) ) . " )
368 368
 			",
369
-			self::STATE_META_KEY,
370
-			self::STATE_SUBMIT,
371
-			self::STATE_REQUEST
372
-		) ); // WPCS: cache ok, db call ok.
369
+            self::STATE_META_KEY,
370
+            self::STATE_SUBMIT,
371
+            self::STATE_REQUEST
372
+        ) ); // WPCS: cache ok, db call ok.
373 373
 
374
-	}
374
+    }
375 375
 
376
-	/**
377
-	 * Request the batch analysis for submitted posts.
378
-	 *
379
-	 * @since 3.14.2
380
-	 */
381
-	public function request() {
376
+    /**
377
+     * Request the batch analysis for submitted posts.
378
+     *
379
+     * @since 3.14.2
380
+     */
381
+    public function request() {
382 382
 
383
-		$this->log->debug( 'Requesting analysis...' );
383
+        $this->log->debug( 'Requesting analysis...' );
384 384
 
385
-		// By default 5 posts of any post type are returned.
386
-		$posts = get_posts( array(
387
-			'fields'     => 'ids',
388
-			'meta_key'   => self::STATE_META_KEY,
389
-			'meta_value' => self::STATE_SUBMIT,
390
-			'orderby'    => 'ID',
391
-			'post_type'  => 'any',
392
-		) );
385
+        // By default 5 posts of any post type are returned.
386
+        $posts = get_posts( array(
387
+            'fields'     => 'ids',
388
+            'meta_key'   => self::STATE_META_KEY,
389
+            'meta_value' => self::STATE_SUBMIT,
390
+            'orderby'    => 'ID',
391
+            'post_type'  => 'any',
392
+        ) );
393 393
 
394
-		// Bail out if there are no submitted posts.
395
-		if ( empty( $posts ) ) {
396
-			$this->log->debug( 'No posts to submit found, checking for completed requests...' );
397
-
398
-			do_action( 'wl_batch_analysis_complete' );
394
+        // Bail out if there are no submitted posts.
395
+        if ( empty( $posts ) ) {
396
+            $this->log->debug( 'No posts to submit found, checking for completed requests...' );
397
+
398
+            do_action( 'wl_batch_analysis_complete' );
399 399
 
400
-			return;
401
-		}
400
+            return;
401
+        }
402 402
 
403
-		// Send a request for each post.
404
-		foreach ( $posts as $id ) {
403
+        // Send a request for each post.
404
+        foreach ( $posts as $id ) {
405 405
 
406
-			$this->log->debug( "Requesting analysis for post $id..." );
406
+            $this->log->debug( "Requesting analysis for post $id..." );
407 407
 
408
-			// Send the actual request to the remote service.
409
-			$result = $this->do_request( $id );
408
+            // Send the actual request to the remote service.
409
+            $result = $this->do_request( $id );
410 410
 
411
-			// Set an error if we received an error.
412
-			if ( is_wp_error( $result ) ) {
413
-				$this->log->error( "An error occurred while requesting a batch analysis for post $id: " . $result->get_error_message() );
411
+            // Set an error if we received an error.
412
+            if ( is_wp_error( $result ) ) {
413
+                $this->log->error( "An error occurred while requesting a batch analysis for post $id: " . $result->get_error_message() );
414 414
 
415
-				$this->set_state( $id, self::STATE_ERROR );
416
-			}
415
+                $this->set_state( $id, self::STATE_ERROR );
416
+            }
417 417
 
418
-		}
418
+        }
419 419
 
420
-		// Call the `wl_batch_analysis_request` action again. This is going
421
-		// to be handled by the async task.
422
-		do_action( 'wl_batch_analysis_request' );
420
+        // Call the `wl_batch_analysis_request` action again. This is going
421
+        // to be handled by the async task.
422
+        do_action( 'wl_batch_analysis_request' );
423 423
 
424
-	}
424
+    }
425 425
 
426
-	/**
427
-	 * Get the results for the Batch Analysis.
428
-	 *
429
-	 * @since 3.14.2
430
-	 */
431
-	public function complete() {
432
-
433
-		$this->log->debug( 'Requesting results...' );
426
+    /**
427
+     * Get the results for the Batch Analysis.
428
+     *
429
+     * @since 3.14.2
430
+     */
431
+    public function complete() {
432
+
433
+        $this->log->debug( 'Requesting results...' );
434 434
 
435
-		// By default 5 posts of any post type are returned.
436
-		$posts = get_posts( array(
437
-			'fields'     => 'ids',
438
-			'meta_key'   => self::STATE_META_KEY,
439
-			'meta_value' => self::STATE_REQUEST,
440
-			'orderby'    => 'ID',
441
-			'post_type'  => 'any',
442
-		) );
435
+        // By default 5 posts of any post type are returned.
436
+        $posts = get_posts( array(
437
+            'fields'     => 'ids',
438
+            'meta_key'   => self::STATE_META_KEY,
439
+            'meta_value' => self::STATE_REQUEST,
440
+            'orderby'    => 'ID',
441
+            'post_type'  => 'any',
442
+        ) );
443 443
 
444
-		// Bail out if there are no submitted posts.
445
-		if ( empty( $posts ) ) {
446
-			$this->log->debug( 'No posts in request state found.' );
444
+        // Bail out if there are no submitted posts.
445
+        if ( empty( $posts ) ) {
446
+            $this->log->debug( 'No posts in request state found.' );
447 447
 
448
-			return;
449
-		}
448
+            return;
449
+        }
450 450
 
451
-		// Send a request for each post.
452
-		foreach ( $posts as $id ) {
453
-			$this->log->debug( "Requesting results for post $id..." );
451
+        // Send a request for each post.
452
+        foreach ( $posts as $id ) {
453
+            $this->log->debug( "Requesting results for post $id..." );
454 454
 
455
-			// Send the actual request to the remote service.
456
-			$response = $this->do_complete( $id );
457
-
458
-			// Move to the next item if we don't have a reply for this one.
459
-			if ( is_wp_error( $response ) || 200 !== (int) $response['response']['code'] || ! isset( $response['body'] ) ) {
460
-				continue;
461
-			}
462
-
463
-			$this->log->debug( "Results received for post $id." );
464
-
465
-			// Save the returned content as new revision.
466
-			$json = json_decode( $response['body'] );
467
-
468
-			// Continue if the content isn't set.
469
-			if ( empty( $json->content ) ) {
470
-				// The post content is empty, so is should be marked as completed.
471
-				$this->log->error( "An error occurred while decoding the batch analysis response for post $id: {$response['body']}" );
455
+            // Send the actual request to the remote service.
456
+            $response = $this->do_complete( $id );
457
+
458
+            // Move to the next item if we don't have a reply for this one.
459
+            if ( is_wp_error( $response ) || 200 !== (int) $response['response']['code'] || ! isset( $response['body'] ) ) {
460
+                continue;
461
+            }
462
+
463
+            $this->log->debug( "Results received for post $id." );
464
+
465
+            // Save the returned content as new revision.
466
+            $json = json_decode( $response['body'] );
467
+
468
+            // Continue if the content isn't set.
469
+            if ( empty( $json->content ) ) {
470
+                // The post content is empty, so is should be marked as completed.
471
+                $this->log->error( "An error occurred while decoding the batch analysis response for post $id: {$response['body']}" );
472 472
 
473
-				$this->set_state( $id, self::STATE_ERROR );
474
-				continue;
475
-			}
476
-
477
-			// Set the warning flag if needed.
478
-			$this->set_warning_based_on_content( $json->content, $id );
479
-
480
-			// Get the content, cleaned up if there are interpolation errors.
481
-			$pre_content = $this->fix_interpolation_errors( $json->content, $id );
482
-
483
-			/**
484
-			 * Filter: 'wl_batch_analysis_update_post_content' - Allow third
485
-			 * parties to perform additional actions when the post content is
486
-			 * updated.
487
-			 *
488
-			 * @since  3.17.0
489
-			 * @api    string $data The {@link WP_Post}'s content.
490
-			 * @api    int    $id   The {@link WP_Post}'s id.
491
-			 */
492
-			$content = apply_filters( 'wl_batch_analysis_update_post_content', $pre_content, $id );
473
+                $this->set_state( $id, self::STATE_ERROR );
474
+                continue;
475
+            }
476
+
477
+            // Set the warning flag if needed.
478
+            $this->set_warning_based_on_content( $json->content, $id );
479
+
480
+            // Get the content, cleaned up if there are interpolation errors.
481
+            $pre_content = $this->fix_interpolation_errors( $json->content, $id );
482
+
483
+            /**
484
+             * Filter: 'wl_batch_analysis_update_post_content' - Allow third
485
+             * parties to perform additional actions when the post content is
486
+             * updated.
487
+             *
488
+             * @since  3.17.0
489
+             * @api    string $data The {@link WP_Post}'s content.
490
+             * @api    int    $id   The {@link WP_Post}'s id.
491
+             */
492
+            $content = apply_filters( 'wl_batch_analysis_update_post_content', $pre_content, $id );
493 493
 
494
-			// Update the post content.
495
-			wp_update_post( array(
496
-				'ID'           => $id,
497
-				'post_content' => wp_slash( $content ),
498
-			) );
499
-
500
-			// Update the status.
501
-			$this->set_state( $id, self::STATE_SUCCESS );
502
-
503
-			// Invalidating the cache for the current post.
504
-			$this->cache_service->delete_cache( $id );
505
-
506
-			$this->log->debug( "Post $id updated with batch analysis results." );
507
-
508
-			// Set default entity type term for posts that didn't have any.
509
-			$this->maybe_set_default_term( $id );
510
-
511
-			// @todo: implement a kind of timeout that sets an error if the
512
-			// results haven't been received after a long time.
513
-		}
514
-
515
-		// Call the `wl_batch_analysis_request` action again. This is going
516
-		// to be handled by the async task.
517
-		do_action( 'wl_batch_analysis_complete' );
518
-
519
-	}
520
-
521
-	/**
522
-	 * Set a warning flag on the {@link WP_Post} if its content has suspicious
523
-	 * interpolations.
524
-	 *
525
-	 * @since 3.14.2
526
-	 *
527
-	 * @param string $content The {@link WP_Post}'s content.
528
-	 * @param int    $post_id The {@link WP_Post}'s id.
529
-	 */
530
-	protected function set_warning_based_on_content( $content, $post_id ) {
531
-
532
-		// Check for suspicious interpolations.
533
-		$is_warning = $this->has_interpolation_errors( $content );
534
-
535
-		// Set the warning flag accordingly.
536
-		$this->set_warning( $post_id, $is_warning );
537
-
538
-	}
539
-
540
-	private function has_interpolation_errors( $content ) {
541
-		$matches = array();
542
-
543
-		// eg:
544
-		// r-pro<span id="urn:local-text-annotation-oxbgy6139gnjgk1n0oxnq9zg62py29pf" class="textannotation disambiguated wl-thing" itemid="http://data.wordlift.it/be2/entity/developing_country">ne region, has shoul</span>dere
545
-
546
-		return 0 < preg_match_all( '/\w<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches )
547
-			   || 0 < preg_match_all( ' /<[a-z]+ id="urn:[^"]+ " class="[^"]+" itemid="[^"]+">\s/', $content, $matches );
548
-	}
549
-
550
-	/**
551
-	 * Fix interpolation errors raised by Batch Analysis
552
-	 *
553
-	 * @param string $content The {@link WP_Post}'s content.
554
-	 * @param int    $id      The {@link WP_Post}'s id.
555
-	 *
556
-	 * @since 3.17.0
557
-	 *
558
-	 * @return string Post content without interpolations.
559
-	 */
560
-	private function fix_interpolation_errors( $content, $id ) {
561
-
562
-		// Bail out if there are no interpolation errors.
563
-		if ( ! $this->has_interpolation_errors( $content ) ) {
564
-			$this->log->trace( "No interpolation errors found for post $id." );
565
-
566
-			return $content;
567
-		}
568
-
569
-		$this->log->debug( "Fixing post $id interpolations..." );
570
-
571
-		// Remove all interpolations from the content.
572
-		return preg_replace( self::$interpolation_patterns, '$1$2', $content );
573
-	}
574
-
575
-	/**
576
-	 * Clear the warning flag for the specified {@link WP_Post}s.
577
-	 *
578
-	 * @since 3.14.2
579
-	 *
580
-	 * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
581
-	 *                            {@link WP_Post}s' ids.
582
-	 */
583
-	public function clear_warning( $post_ids ) {
584
-
585
-		foreach ( (array) $post_ids as $post_id ) {
586
-			delete_post_meta( $post_id, self::WARNING_META_KEY );
587
-		}
588
-
589
-	}
590
-
591
-	/**
592
-	 * Set the warning flag for the specified {@link WP_Post}.
593
-	 *
594
-	 * @since 3.14.2
595
-	 *
596
-	 * @param int  $post_id The {@link WP_Post}'s id.
597
-	 * @param bool $value   The flag's value.
598
-	 *
599
-	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
600
-	 *                  false on failure.
601
-	 */
602
-	private function set_warning( $post_id, $value ) {
603
-
604
-		return update_post_meta( $post_id, self::WARNING_META_KEY, ( true === $value ? 'yes' : 'no' ) );
605
-	}
494
+            // Update the post content.
495
+            wp_update_post( array(
496
+                'ID'           => $id,
497
+                'post_content' => wp_slash( $content ),
498
+            ) );
499
+
500
+            // Update the status.
501
+            $this->set_state( $id, self::STATE_SUCCESS );
502
+
503
+            // Invalidating the cache for the current post.
504
+            $this->cache_service->delete_cache( $id );
505
+
506
+            $this->log->debug( "Post $id updated with batch analysis results." );
507
+
508
+            // Set default entity type term for posts that didn't have any.
509
+            $this->maybe_set_default_term( $id );
510
+
511
+            // @todo: implement a kind of timeout that sets an error if the
512
+            // results haven't been received after a long time.
513
+        }
514
+
515
+        // Call the `wl_batch_analysis_request` action again. This is going
516
+        // to be handled by the async task.
517
+        do_action( 'wl_batch_analysis_complete' );
518
+
519
+    }
520
+
521
+    /**
522
+     * Set a warning flag on the {@link WP_Post} if its content has suspicious
523
+     * interpolations.
524
+     *
525
+     * @since 3.14.2
526
+     *
527
+     * @param string $content The {@link WP_Post}'s content.
528
+     * @param int    $post_id The {@link WP_Post}'s id.
529
+     */
530
+    protected function set_warning_based_on_content( $content, $post_id ) {
531
+
532
+        // Check for suspicious interpolations.
533
+        $is_warning = $this->has_interpolation_errors( $content );
534
+
535
+        // Set the warning flag accordingly.
536
+        $this->set_warning( $post_id, $is_warning );
537
+
538
+    }
539
+
540
+    private function has_interpolation_errors( $content ) {
541
+        $matches = array();
542
+
543
+        // eg:
544
+        // r-pro<span id="urn:local-text-annotation-oxbgy6139gnjgk1n0oxnq9zg62py29pf" class="textannotation disambiguated wl-thing" itemid="http://data.wordlift.it/be2/entity/developing_country">ne region, has shoul</span>dere
545
+
546
+        return 0 < preg_match_all( '/\w<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches )
547
+               || 0 < preg_match_all( ' /<[a-z]+ id="urn:[^"]+ " class="[^"]+" itemid="[^"]+">\s/', $content, $matches );
548
+    }
549
+
550
+    /**
551
+     * Fix interpolation errors raised by Batch Analysis
552
+     *
553
+     * @param string $content The {@link WP_Post}'s content.
554
+     * @param int    $id      The {@link WP_Post}'s id.
555
+     *
556
+     * @since 3.17.0
557
+     *
558
+     * @return string Post content without interpolations.
559
+     */
560
+    private function fix_interpolation_errors( $content, $id ) {
561
+
562
+        // Bail out if there are no interpolation errors.
563
+        if ( ! $this->has_interpolation_errors( $content ) ) {
564
+            $this->log->trace( "No interpolation errors found for post $id." );
565
+
566
+            return $content;
567
+        }
568
+
569
+        $this->log->debug( "Fixing post $id interpolations..." );
570
+
571
+        // Remove all interpolations from the content.
572
+        return preg_replace( self::$interpolation_patterns, '$1$2', $content );
573
+    }
574
+
575
+    /**
576
+     * Clear the warning flag for the specified {@link WP_Post}s.
577
+     *
578
+     * @since 3.14.2
579
+     *
580
+     * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
581
+     *                            {@link WP_Post}s' ids.
582
+     */
583
+    public function clear_warning( $post_ids ) {
584
+
585
+        foreach ( (array) $post_ids as $post_id ) {
586
+            delete_post_meta( $post_id, self::WARNING_META_KEY );
587
+        }
588
+
589
+    }
590
+
591
+    /**
592
+     * Set the warning flag for the specified {@link WP_Post}.
593
+     *
594
+     * @since 3.14.2
595
+     *
596
+     * @param int  $post_id The {@link WP_Post}'s id.
597
+     * @param bool $value   The flag's value.
598
+     *
599
+     * @return int|bool Meta ID if the key didn't exist, true on successful update,
600
+     *                  false on failure.
601
+     */
602
+    private function set_warning( $post_id, $value ) {
603
+
604
+        return update_post_meta( $post_id, self::WARNING_META_KEY, ( true === $value ? 'yes' : 'no' ) );
605
+    }
606 606
 
607 607
 //	/**
608 608
 //	 * Get the post/page batch analysis state.
@@ -618,231 +618,231 @@  discard block
 block discarded – undo
618 618
 //		return get_post_meta( $post_id, self::STATE_META_KEY, true );
619 619
 //	}
620 620
 
621
-	/**
622
-	 * Set the post/page batch analysis state.
623
-	 *
624
-	 * @since 3.14.2
625
-	 *
626
-	 * @param int $post_id The {@link WP_Post}'s id.
627
-	 * @param int $value   The new state.
628
-	 *
629
-	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
630
-	 *                  false on failure.
631
-	 */
632
-	private function set_state( $post_id, $value ) {
633
-
634
-		// Update the state.
635
-		$result = update_post_meta( $post_id, self::STATE_META_KEY, $value );
636
-
637
-		// Update timestamps as required.
638
-		switch ( $value ) {
639
-
640
-			// ### REQUEST state.
641
-			case self::STATE_REQUEST:
642
-				add_post_meta( $post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
643
-				break;
644
-
645
-			// ### SUCCESS/ERROR state.
646
-			case self::STATE_SUCCESS:
647
-			case self::STATE_ERROR:
648
-				add_post_meta( $post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
649
-				break;
650
-		}
651
-
652
-		// Finally return the result.
653
-		return $result;
654
-	}
655
-
656
-	/**
657
-	 * Get the options setting for a {@link WP_Post}.
658
-	 *
659
-	 * If there are multiple link settings, only the last one is returned.
660
-	 *
661
-	 * @since 3.14.2
662
-	 *
663
-	 * @param int $post_id The {@link WP_Post}'s id.
664
-	 *
665
-	 * @return array The link settings.
666
-	 */
667
-	private function get_options( $post_id ) {
668
-
669
-		$values = get_post_meta( $post_id, self::BATCH_ANALYSIS_OPTIONS_META_KEY );
670
-
671
-		return end( $values ) ?: array(
672
-			'links'           => 'default',
673
-			'min_occurrences' => 1,
674
-		);
675
-	}
676
-
677
-	/**
678
-	 * Get the array of post IDS waiting in the queue to start processing.
679
-	 *
680
-	 * @since 3.14.0
681
-	 *
682
-	 * @return array The waiting to be processed post ids queue.
683
-	 */
684
-	public function waiting_for_analysis() {
685
-
686
-		return get_posts( array(
687
-			'posts_per_page' => - 1,
688
-			'fields'         => 'ids',
689
-			'post_status'    => 'any',
690
-			'meta_key'       => self::STATE_META_KEY,
691
-			'meta_value'     => self::STATE_SUBMIT,
692
-			'orderby'        => 'ID',
693
-			'post_type'      => 'any',
694
-			// Add any because posts from multiple posts types may be waiting.
695
-		) );
696
-	}
697
-
698
-	/**
699
-	 * Get the array of post IDS waiting for response.
700
-	 *
701
-	 * @deprecated
702
-	 * @since 3.14.0
703
-	 *
704
-	 * @return array The waiting for response post ids queue.
705
-	 */
706
-	public function waiting_for_response() {
707
-
708
-		return get_posts( array(
709
-			'posts_per_page' => - 1,
710
-			'fields'         => 'ids',
711
-			'post_status'    => 'any',
712
-			'meta_key'       => self::STATE_META_KEY,
713
-			'meta_value'     => self::STATE_REQUEST,
714
-			'orderby'        => 'ID',
715
-			'post_type'      => 'any',
716
-			// Add any because posts from multiple posts types may be waiting.
717
-		) );
718
-	}
719
-
720
-	/**
721
-	 * Request the analysis for the specified {@link WP_Post}.
722
-	 *
723
-	 * @since 3.14.2
724
-	 *
725
-	 * @param int $post_id The {@link WP_Post}'s id.
726
-	 *
727
-	 * @return WP_Error|array The response or WP_Error on failure.
728
-	 */
729
-	private function do_request( $post_id ) {
730
-
731
-		// Change the state to `REQUEST`.
732
-		$this->set_state( $post_id, self::STATE_REQUEST );
733
-
734
-		// Get the post.
735
-		$post = get_post( $post_id );
736
-
737
-		// Bail out if the post isn't found.
738
-		if ( null === $post ) {
739
-			$this->log->warn( "Post $post_id not found." );
740
-
741
-			return new WP_Error( 0, "Cannot find post $post_id." );
742
-		}
743
-
744
-		// Get the link setting.
745
-		$options = $this->get_options( $post_id );
746
-
747
-		$this->log->debug( 'Sending analysis request for post $post_id [ links :: ' . $options['links'] . ', min_occurrences :: ' . $options['min_occurrences'] . ' ] ...' );
748
-
749
-		// Get the batch analysis URL.
750
-		$url = $this->configuration_service->get_batch_analysis_url();
751
-
752
-		// Prepare the POST parameters.
753
-		$params = array(
754
-			'id'              => $post->ID,
755
-			'key'             => $this->configuration_service->get_key(),
756
-			'content'         => $post->post_content,
757
-			'contentLanguage' => $this->configuration_service->get_language_code(),
758
-			'version'         => $this->plugin->get_version(),
759
-			'scope'           => 'local',
760
-			'links'           => $options['links'],
761
-			'minOccurrences'  => $options['min_occurrences'],
762
-		);
763
-
764
-		// Get the HTTP options.
765
-		$args = array_merge_recursive( unserialize( WL_REDLINK_API_HTTP_OPTIONS ), array(
766
-			'method'      => 'POST',
767
-			'headers'     => array(
768
-				'Accept'       => 'application/json',
769
-				'Content-type' => 'application/json; charset=UTF-8',
770
-			),
771
-			// we need to downgrade the HTTP version in this case since chunked encoding is dumping numbers in the response.
772
-			'httpversion' => '1.0',
773
-			'body'        => wp_json_encode( $params ),
774
-		) );
775
-
776
-		$this->log->debug( "Posting analysis request for post $post_id to $url..." );
777
-
778
-		// Post the parameter.
779
-		return wp_remote_post( $url, $args );
780
-	}
781
-
782
-	/**
783
-	 * Get the Batch Analysis results for the specified {@link WP_Post}.
784
-	 *
785
-	 * @since 3.14.2
786
-	 *
787
-	 * @param int $post_id The {@link WP_Post}'s id.
788
-	 *
789
-	 * @return WP_Error|array The response or WP_Error on failure.
790
-	 */
791
-	private function do_complete( $post_id ) {
792
-
793
-		$post = get_post( $post_id );
794
-
795
-		if ( null === $post ) {
796
-			// Post was possibly deleted, just bailout.
797
-			return new WP_Error( 0, "Post $post_id not found . " );
798
-		}
799
-
800
-		$url = $this->configuration_service->get_batch_analysis_url();
801
-		$key = $this->configuration_service->get_key();
802
-		$url = $url . '/' . $post->ID . '?key=' . $key;
803
-
804
-		return wp_remote_get( $url, unserialize( WL_REDLINK_API_HTTP_OPTIONS ) );
805
-	}
806
-
807
-	/**
808
-	 * Get the {@link WP_Post}s' ids flagged with warnings.
809
-	 *
810
-	 * @since 3.14.2
811
-	 *
812
-	 * @return array An array of {@link WP_Post}s' ids.
813
-	 */
814
-	public function get_warnings() {
815
-
816
-		return get_posts( array(
817
-			'fields'      => 'ids',
818
-			'numberposts' => - 1,
819
-			'post_status' => 'any',
820
-			'meta_key'    => self::WARNING_META_KEY,
821
-			'meta_value'  => 'yes',
822
-			'post_type'   => 'any',
823
-			// Add any because posts from multiple posts types may be waiting.
824
-		) );
825
-	}
826
-
827
-	/**
828
-	 * Check whether the term has entity type associated and set default term if it hasn't.
829
-	 *
830
-	 * @since 3.17.0
831
-	 *
832
-	 * @param int $id The {@link WP_Post}'s id.
833
-	 */
834
-	private function maybe_set_default_term( $id ) {
835
-		// Check whether the post has any of the WordLift entity types.
836
-		$has_term = has_term( '', Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME, $id );
837
-
838
-		// Bail if the term is associated with entity types already.
839
-		if ( ! empty( $has_term ) ) {
840
-			return;
841
-		}
842
-
843
-		// Set the default `article` term.
844
-		wp_set_object_terms( $id, 'article', Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
845
-
846
-	}
621
+    /**
622
+     * Set the post/page batch analysis state.
623
+     *
624
+     * @since 3.14.2
625
+     *
626
+     * @param int $post_id The {@link WP_Post}'s id.
627
+     * @param int $value   The new state.
628
+     *
629
+     * @return int|bool Meta ID if the key didn't exist, true on successful update,
630
+     *                  false on failure.
631
+     */
632
+    private function set_state( $post_id, $value ) {
633
+
634
+        // Update the state.
635
+        $result = update_post_meta( $post_id, self::STATE_META_KEY, $value );
636
+
637
+        // Update timestamps as required.
638
+        switch ( $value ) {
639
+
640
+            // ### REQUEST state.
641
+            case self::STATE_REQUEST:
642
+                add_post_meta( $post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
643
+                break;
644
+
645
+            // ### SUCCESS/ERROR state.
646
+            case self::STATE_SUCCESS:
647
+            case self::STATE_ERROR:
648
+                add_post_meta( $post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
649
+                break;
650
+        }
651
+
652
+        // Finally return the result.
653
+        return $result;
654
+    }
655
+
656
+    /**
657
+     * Get the options setting for a {@link WP_Post}.
658
+     *
659
+     * If there are multiple link settings, only the last one is returned.
660
+     *
661
+     * @since 3.14.2
662
+     *
663
+     * @param int $post_id The {@link WP_Post}'s id.
664
+     *
665
+     * @return array The link settings.
666
+     */
667
+    private function get_options( $post_id ) {
668
+
669
+        $values = get_post_meta( $post_id, self::BATCH_ANALYSIS_OPTIONS_META_KEY );
670
+
671
+        return end( $values ) ?: array(
672
+            'links'           => 'default',
673
+            'min_occurrences' => 1,
674
+        );
675
+    }
676
+
677
+    /**
678
+     * Get the array of post IDS waiting in the queue to start processing.
679
+     *
680
+     * @since 3.14.0
681
+     *
682
+     * @return array The waiting to be processed post ids queue.
683
+     */
684
+    public function waiting_for_analysis() {
685
+
686
+        return get_posts( array(
687
+            'posts_per_page' => - 1,
688
+            'fields'         => 'ids',
689
+            'post_status'    => 'any',
690
+            'meta_key'       => self::STATE_META_KEY,
691
+            'meta_value'     => self::STATE_SUBMIT,
692
+            'orderby'        => 'ID',
693
+            'post_type'      => 'any',
694
+            // Add any because posts from multiple posts types may be waiting.
695
+        ) );
696
+    }
697
+
698
+    /**
699
+     * Get the array of post IDS waiting for response.
700
+     *
701
+     * @deprecated
702
+     * @since 3.14.0
703
+     *
704
+     * @return array The waiting for response post ids queue.
705
+     */
706
+    public function waiting_for_response() {
707
+
708
+        return get_posts( array(
709
+            'posts_per_page' => - 1,
710
+            'fields'         => 'ids',
711
+            'post_status'    => 'any',
712
+            'meta_key'       => self::STATE_META_KEY,
713
+            'meta_value'     => self::STATE_REQUEST,
714
+            'orderby'        => 'ID',
715
+            'post_type'      => 'any',
716
+            // Add any because posts from multiple posts types may be waiting.
717
+        ) );
718
+    }
719
+
720
+    /**
721
+     * Request the analysis for the specified {@link WP_Post}.
722
+     *
723
+     * @since 3.14.2
724
+     *
725
+     * @param int $post_id The {@link WP_Post}'s id.
726
+     *
727
+     * @return WP_Error|array The response or WP_Error on failure.
728
+     */
729
+    private function do_request( $post_id ) {
730
+
731
+        // Change the state to `REQUEST`.
732
+        $this->set_state( $post_id, self::STATE_REQUEST );
733
+
734
+        // Get the post.
735
+        $post = get_post( $post_id );
736
+
737
+        // Bail out if the post isn't found.
738
+        if ( null === $post ) {
739
+            $this->log->warn( "Post $post_id not found." );
740
+
741
+            return new WP_Error( 0, "Cannot find post $post_id." );
742
+        }
743
+
744
+        // Get the link setting.
745
+        $options = $this->get_options( $post_id );
746
+
747
+        $this->log->debug( 'Sending analysis request for post $post_id [ links :: ' . $options['links'] . ', min_occurrences :: ' . $options['min_occurrences'] . ' ] ...' );
748
+
749
+        // Get the batch analysis URL.
750
+        $url = $this->configuration_service->get_batch_analysis_url();
751
+
752
+        // Prepare the POST parameters.
753
+        $params = array(
754
+            'id'              => $post->ID,
755
+            'key'             => $this->configuration_service->get_key(),
756
+            'content'         => $post->post_content,
757
+            'contentLanguage' => $this->configuration_service->get_language_code(),
758
+            'version'         => $this->plugin->get_version(),
759
+            'scope'           => 'local',
760
+            'links'           => $options['links'],
761
+            'minOccurrences'  => $options['min_occurrences'],
762
+        );
763
+
764
+        // Get the HTTP options.
765
+        $args = array_merge_recursive( unserialize( WL_REDLINK_API_HTTP_OPTIONS ), array(
766
+            'method'      => 'POST',
767
+            'headers'     => array(
768
+                'Accept'       => 'application/json',
769
+                'Content-type' => 'application/json; charset=UTF-8',
770
+            ),
771
+            // we need to downgrade the HTTP version in this case since chunked encoding is dumping numbers in the response.
772
+            'httpversion' => '1.0',
773
+            'body'        => wp_json_encode( $params ),
774
+        ) );
775
+
776
+        $this->log->debug( "Posting analysis request for post $post_id to $url..." );
777
+
778
+        // Post the parameter.
779
+        return wp_remote_post( $url, $args );
780
+    }
781
+
782
+    /**
783
+     * Get the Batch Analysis results for the specified {@link WP_Post}.
784
+     *
785
+     * @since 3.14.2
786
+     *
787
+     * @param int $post_id The {@link WP_Post}'s id.
788
+     *
789
+     * @return WP_Error|array The response or WP_Error on failure.
790
+     */
791
+    private function do_complete( $post_id ) {
792
+
793
+        $post = get_post( $post_id );
794
+
795
+        if ( null === $post ) {
796
+            // Post was possibly deleted, just bailout.
797
+            return new WP_Error( 0, "Post $post_id not found . " );
798
+        }
799
+
800
+        $url = $this->configuration_service->get_batch_analysis_url();
801
+        $key = $this->configuration_service->get_key();
802
+        $url = $url . '/' . $post->ID . '?key=' . $key;
803
+
804
+        return wp_remote_get( $url, unserialize( WL_REDLINK_API_HTTP_OPTIONS ) );
805
+    }
806
+
807
+    /**
808
+     * Get the {@link WP_Post}s' ids flagged with warnings.
809
+     *
810
+     * @since 3.14.2
811
+     *
812
+     * @return array An array of {@link WP_Post}s' ids.
813
+     */
814
+    public function get_warnings() {
815
+
816
+        return get_posts( array(
817
+            'fields'      => 'ids',
818
+            'numberposts' => - 1,
819
+            'post_status' => 'any',
820
+            'meta_key'    => self::WARNING_META_KEY,
821
+            'meta_value'  => 'yes',
822
+            'post_type'   => 'any',
823
+            // Add any because posts from multiple posts types may be waiting.
824
+        ) );
825
+    }
826
+
827
+    /**
828
+     * Check whether the term has entity type associated and set default term if it hasn't.
829
+     *
830
+     * @since 3.17.0
831
+     *
832
+     * @param int $id The {@link WP_Post}'s id.
833
+     */
834
+    private function maybe_set_default_term( $id ) {
835
+        // Check whether the post has any of the WordLift entity types.
836
+        $has_term = has_term( '', Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME, $id );
837
+
838
+        // Bail if the term is associated with entity types already.
839
+        if ( ! empty( $has_term ) ) {
840
+            return;
841
+        }
842
+
843
+        // Set the default `article` term.
844
+        wp_set_object_terms( $id, 'article', Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
845
+
846
+    }
847 847
 
848 848
 }
Please login to merge, or discard this patch.
Spacing   +130 added lines, -130 removed lines patch added patch discarded remove patch
@@ -185,22 +185,22 @@  discard block
 block discarded – undo
185 185
 	 * @param \Wordlift_Configuration_Service $configuration_service The {@link Wordlift_Configuration_Service} instance.
186 186
 	 * @param \Wordlift_Cache_Service         $cache_service         The {@link Wordlift_Cache_Service} instance.
187 187
 	 */
188
-	public function __construct( $plugin, $configuration_service, $cache_service ) {
188
+	public function __construct($plugin, $configuration_service, $cache_service) {
189 189
 
190
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Batch_Analysis_Service' );
190
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Batch_Analysis_Service');
191 191
 
192 192
 		$this->plugin                = $plugin;
193 193
 		$this->configuration_service = $configuration_service;
194 194
 		$this->cache_service         = $cache_service;
195 195
 
196
-		add_action( 'wl_async_wl_batch_analysis_request', array(
196
+		add_action('wl_async_wl_batch_analysis_request', array(
197 197
 			$this,
198 198
 			'request',
199
-		) );
200
-		add_action( 'wl_async_wl_batch_analysis_complete', array(
199
+		));
200
+		add_action('wl_async_wl_batch_analysis_complete', array(
201 201
 			$this,
202 202
 			'complete',
203
-		) );
203
+		));
204 204
 
205 205
 	}
206 206
 
@@ -231,9 +231,9 @@  discard block
 block discarded – undo
231 231
 	 *
232 232
 	 * @return int The number of submitted {@link WP_Post}s or false on error.
233 233
 	 */
234
-	public function submit( $args ) {
234
+	public function submit($args) {
235 235
 		// Parse the parameters.
236
-		$params = wp_parse_args( $args, array(
236
+		$params = wp_parse_args($args, array(
237 237
 			'links'             => 'default',
238 238
 			'min_occurrences'   => 1,
239 239
 			'include_annotated' => false,
@@ -241,25 +241,25 @@  discard block
 block discarded – undo
241 241
 			'from'              => null,
242 242
 			'to'                => null,
243 243
 			'post_type'         => 'post',
244
-		) );
244
+		));
245 245
 
246 246
 		// Validation.
247
-		if ( ! in_array( $params['links'], array( 'default', 'yes', 'no' ) ) ) {
248
-			wp_die( '`link` must be one of the following: `default`, `yes` or `no`.' );
247
+		if ( ! in_array($params['links'], array('default', 'yes', 'no'))) {
248
+			wp_die('`link` must be one of the following: `default`, `yes` or `no`.');
249 249
 		}
250 250
 
251
-		if ( ! is_numeric( $params['min_occurrences'] ) || 1 > $params['min_occurrences'] ) {
252
-			wp_die( '`min_occurrences` must greater or equal 1.' );
251
+		if ( ! is_numeric($params['min_occurrences']) || 1 > $params['min_occurrences']) {
252
+			wp_die('`min_occurrences` must greater or equal 1.');
253 253
 		}
254 254
 
255 255
 		// Get the sql query.
256
-		$query = Wordlift_Batch_Analysis_Sql_Helper::get_sql( $params );
256
+		$query = Wordlift_Batch_Analysis_Sql_Helper::get_sql($params);
257 257
 
258 258
 		// Set the post metas and get the value of the posts.
259
-		$submitted_posts = $this->update_posts_meta( $params, $query );
259
+		$submitted_posts = $this->update_posts_meta($params, $query);
260 260
 
261 261
 		// Request Batch Analysis (the operation is handled asynchronously).
262
-		do_action( 'wl_batch_analysis_request' );
262
+		do_action('wl_batch_analysis_request');
263 263
 
264 264
 		// Return the count of the posts.
265 265
 		return $submitted_posts;
@@ -281,27 +281,27 @@  discard block
 block discarded – undo
281 281
 	 *
282 282
 	 * @return float|int
283 283
 	 */
284
-	public function submit_posts( $args ) {
284
+	public function submit_posts($args) {
285 285
 		// Parse the parameters.
286
-		$params = wp_parse_args( $args, array(
286
+		$params = wp_parse_args($args, array(
287 287
 			'links'           => 'default',
288 288
 			'min_occurrences' => 1,
289 289
 			'ids'             => array(),
290
-		) );
290
+		));
291 291
 
292 292
 		// Validation.
293
-		if ( empty( $params['ids'] ) ) {
294
-			wp_die( '`ids` cannot be empty.' );
293
+		if (empty($params['ids'])) {
294
+			wp_die('`ids` cannot be empty.');
295 295
 		}
296 296
 
297 297
 		// Get the query,
298
-		$query = Wordlift_Batch_Analysis_Sql_Helper::get_sql_for_ids( $params );
298
+		$query = Wordlift_Batch_Analysis_Sql_Helper::get_sql_for_ids($params);
299 299
 
300 300
 		// Set the post metas and get the value of the posts.
301
-		$submitted_posts = $this->update_posts_meta( $params, $query );
301
+		$submitted_posts = $this->update_posts_meta($params, $query);
302 302
 
303 303
 		// Request Batch Analysis (the operation is handled asynchronously).
304
-		do_action( 'wl_batch_analysis_request' );
304
+		do_action('wl_batch_analysis_request');
305 305
 
306 306
 		// Return the count of the posts.
307 307
 		return $submitted_posts;
@@ -317,7 +317,7 @@  discard block
 block discarded – undo
317 317
 	 *
318 318
 	 * @return int The number of posts found/submitted.
319 319
 	 */
320
-	public function update_posts_meta( $params, $query ) {
320
+	public function update_posts_meta($params, $query) {
321 321
 		global $wpdb;
322 322
 
323 323
 		// Get the link options.
@@ -327,22 +327,22 @@  discard block
 block discarded – undo
327 327
 		);
328 328
 
329 329
 		// Get the posts that should be submitted for analysis.
330
-		$posts = $wpdb->get_results( $query ); // WPCS: cache ok, db call ok.
330
+		$posts = $wpdb->get_results($query); // WPCS: cache ok, db call ok.
331 331
 
332 332
 		// Bail if there are no posts found.
333
-		if ( empty( $posts ) ) {
333
+		if (empty($posts)) {
334 334
 			return 0;
335 335
 		}
336 336
 
337 337
 		// Add the post metas.
338
-		foreach ( $posts as $p ) {
339
-			add_post_meta( $p->ID, self::STATE_META_KEY, 0 );
340
-			add_post_meta( $p->ID, self::SUBMIT_TIMESTAMP_META_KEY, gmdate( 'Y-m-d H:i:s' ) );
341
-			add_post_meta( $p->ID, self::BATCH_ANALYSIS_OPTIONS_META_KEY, $link_options );
338
+		foreach ($posts as $p) {
339
+			add_post_meta($p->ID, self::STATE_META_KEY, 0);
340
+			add_post_meta($p->ID, self::SUBMIT_TIMESTAMP_META_KEY, gmdate('Y-m-d H:i:s'));
341
+			add_post_meta($p->ID, self::BATCH_ANALYSIS_OPTIONS_META_KEY, $link_options);
342 342
 		}
343 343
 
344 344
 		// Finally return the posts count.
345
-		return count( $posts );
345
+		return count($posts);
346 346
 	}
347 347
 
348 348
 	/**
@@ -356,20 +356,20 @@  discard block
 block discarded – undo
356 356
 	 * @return false|int The number of cancelled {@link WP_Post}s or false on
357 357
 	 *                   error.
358 358
 	 */
359
-	public function cancel( $post_ids ) {
359
+	public function cancel($post_ids) {
360 360
 		global $wpdb;
361 361
 
362
-		return $wpdb->query( $wpdb->prepare(
362
+		return $wpdb->query($wpdb->prepare(
363 363
 			"
364 364
 			DELETE FROM $wpdb->postmeta
365 365
 			WHERE meta_key = %s
366 366
 				AND meta_value IN ( %d, %d )
367
-				AND post_id IN( " . implode( ',', wp_parse_id_list( $post_ids ) ) . " )
367
+				AND post_id IN( ".implode(',', wp_parse_id_list($post_ids))." )
368 368
 			",
369 369
 			self::STATE_META_KEY,
370 370
 			self::STATE_SUBMIT,
371 371
 			self::STATE_REQUEST
372
-		) ); // WPCS: cache ok, db call ok.
372
+		)); // WPCS: cache ok, db call ok.
373 373
 
374 374
 	}
375 375
 
@@ -380,46 +380,46 @@  discard block
 block discarded – undo
380 380
 	 */
381 381
 	public function request() {
382 382
 
383
-		$this->log->debug( 'Requesting analysis...' );
383
+		$this->log->debug('Requesting analysis...');
384 384
 
385 385
 		// By default 5 posts of any post type are returned.
386
-		$posts = get_posts( array(
386
+		$posts = get_posts(array(
387 387
 			'fields'     => 'ids',
388 388
 			'meta_key'   => self::STATE_META_KEY,
389 389
 			'meta_value' => self::STATE_SUBMIT,
390 390
 			'orderby'    => 'ID',
391 391
 			'post_type'  => 'any',
392
-		) );
392
+		));
393 393
 
394 394
 		// Bail out if there are no submitted posts.
395
-		if ( empty( $posts ) ) {
396
-			$this->log->debug( 'No posts to submit found, checking for completed requests...' );
395
+		if (empty($posts)) {
396
+			$this->log->debug('No posts to submit found, checking for completed requests...');
397 397
 
398
-			do_action( 'wl_batch_analysis_complete' );
398
+			do_action('wl_batch_analysis_complete');
399 399
 
400 400
 			return;
401 401
 		}
402 402
 
403 403
 		// Send a request for each post.
404
-		foreach ( $posts as $id ) {
404
+		foreach ($posts as $id) {
405 405
 
406
-			$this->log->debug( "Requesting analysis for post $id..." );
406
+			$this->log->debug("Requesting analysis for post $id...");
407 407
 
408 408
 			// Send the actual request to the remote service.
409
-			$result = $this->do_request( $id );
409
+			$result = $this->do_request($id);
410 410
 
411 411
 			// Set an error if we received an error.
412
-			if ( is_wp_error( $result ) ) {
413
-				$this->log->error( "An error occurred while requesting a batch analysis for post $id: " . $result->get_error_message() );
412
+			if (is_wp_error($result)) {
413
+				$this->log->error("An error occurred while requesting a batch analysis for post $id: ".$result->get_error_message());
414 414
 
415
-				$this->set_state( $id, self::STATE_ERROR );
415
+				$this->set_state($id, self::STATE_ERROR);
416 416
 			}
417 417
 
418 418
 		}
419 419
 
420 420
 		// Call the `wl_batch_analysis_request` action again. This is going
421 421
 		// to be handled by the async task.
422
-		do_action( 'wl_batch_analysis_request' );
422
+		do_action('wl_batch_analysis_request');
423 423
 
424 424
 	}
425 425
 
@@ -430,55 +430,55 @@  discard block
 block discarded – undo
430 430
 	 */
431 431
 	public function complete() {
432 432
 
433
-		$this->log->debug( 'Requesting results...' );
433
+		$this->log->debug('Requesting results...');
434 434
 
435 435
 		// By default 5 posts of any post type are returned.
436
-		$posts = get_posts( array(
436
+		$posts = get_posts(array(
437 437
 			'fields'     => 'ids',
438 438
 			'meta_key'   => self::STATE_META_KEY,
439 439
 			'meta_value' => self::STATE_REQUEST,
440 440
 			'orderby'    => 'ID',
441 441
 			'post_type'  => 'any',
442
-		) );
442
+		));
443 443
 
444 444
 		// Bail out if there are no submitted posts.
445
-		if ( empty( $posts ) ) {
446
-			$this->log->debug( 'No posts in request state found.' );
445
+		if (empty($posts)) {
446
+			$this->log->debug('No posts in request state found.');
447 447
 
448 448
 			return;
449 449
 		}
450 450
 
451 451
 		// Send a request for each post.
452
-		foreach ( $posts as $id ) {
453
-			$this->log->debug( "Requesting results for post $id..." );
452
+		foreach ($posts as $id) {
453
+			$this->log->debug("Requesting results for post $id...");
454 454
 
455 455
 			// Send the actual request to the remote service.
456
-			$response = $this->do_complete( $id );
456
+			$response = $this->do_complete($id);
457 457
 
458 458
 			// Move to the next item if we don't have a reply for this one.
459
-			if ( is_wp_error( $response ) || 200 !== (int) $response['response']['code'] || ! isset( $response['body'] ) ) {
459
+			if (is_wp_error($response) || 200 !== (int) $response['response']['code'] || ! isset($response['body'])) {
460 460
 				continue;
461 461
 			}
462 462
 
463
-			$this->log->debug( "Results received for post $id." );
463
+			$this->log->debug("Results received for post $id.");
464 464
 
465 465
 			// Save the returned content as new revision.
466
-			$json = json_decode( $response['body'] );
466
+			$json = json_decode($response['body']);
467 467
 
468 468
 			// Continue if the content isn't set.
469
-			if ( empty( $json->content ) ) {
469
+			if (empty($json->content)) {
470 470
 				// The post content is empty, so is should be marked as completed.
471
-				$this->log->error( "An error occurred while decoding the batch analysis response for post $id: {$response['body']}" );
471
+				$this->log->error("An error occurred while decoding the batch analysis response for post $id: {$response['body']}");
472 472
 
473
-				$this->set_state( $id, self::STATE_ERROR );
473
+				$this->set_state($id, self::STATE_ERROR);
474 474
 				continue;
475 475
 			}
476 476
 
477 477
 			// Set the warning flag if needed.
478
-			$this->set_warning_based_on_content( $json->content, $id );
478
+			$this->set_warning_based_on_content($json->content, $id);
479 479
 
480 480
 			// Get the content, cleaned up if there are interpolation errors.
481
-			$pre_content = $this->fix_interpolation_errors( $json->content, $id );
481
+			$pre_content = $this->fix_interpolation_errors($json->content, $id);
482 482
 
483 483
 			/**
484 484
 			 * Filter: 'wl_batch_analysis_update_post_content' - Allow third
@@ -489,24 +489,24 @@  discard block
 block discarded – undo
489 489
 			 * @api    string $data The {@link WP_Post}'s content.
490 490
 			 * @api    int    $id   The {@link WP_Post}'s id.
491 491
 			 */
492
-			$content = apply_filters( 'wl_batch_analysis_update_post_content', $pre_content, $id );
492
+			$content = apply_filters('wl_batch_analysis_update_post_content', $pre_content, $id);
493 493
 
494 494
 			// Update the post content.
495
-			wp_update_post( array(
495
+			wp_update_post(array(
496 496
 				'ID'           => $id,
497
-				'post_content' => wp_slash( $content ),
498
-			) );
497
+				'post_content' => wp_slash($content),
498
+			));
499 499
 
500 500
 			// Update the status.
501
-			$this->set_state( $id, self::STATE_SUCCESS );
501
+			$this->set_state($id, self::STATE_SUCCESS);
502 502
 
503 503
 			// Invalidating the cache for the current post.
504
-			$this->cache_service->delete_cache( $id );
504
+			$this->cache_service->delete_cache($id);
505 505
 
506
-			$this->log->debug( "Post $id updated with batch analysis results." );
506
+			$this->log->debug("Post $id updated with batch analysis results.");
507 507
 
508 508
 			// Set default entity type term for posts that didn't have any.
509
-			$this->maybe_set_default_term( $id );
509
+			$this->maybe_set_default_term($id);
510 510
 
511 511
 			// @todo: implement a kind of timeout that sets an error if the
512 512
 			// results haven't been received after a long time.
@@ -514,7 +514,7 @@  discard block
 block discarded – undo
514 514
 
515 515
 		// Call the `wl_batch_analysis_request` action again. This is going
516 516
 		// to be handled by the async task.
517
-		do_action( 'wl_batch_analysis_complete' );
517
+		do_action('wl_batch_analysis_complete');
518 518
 
519 519
 	}
520 520
 
@@ -527,24 +527,24 @@  discard block
 block discarded – undo
527 527
 	 * @param string $content The {@link WP_Post}'s content.
528 528
 	 * @param int    $post_id The {@link WP_Post}'s id.
529 529
 	 */
530
-	protected function set_warning_based_on_content( $content, $post_id ) {
530
+	protected function set_warning_based_on_content($content, $post_id) {
531 531
 
532 532
 		// Check for suspicious interpolations.
533
-		$is_warning = $this->has_interpolation_errors( $content );
533
+		$is_warning = $this->has_interpolation_errors($content);
534 534
 
535 535
 		// Set the warning flag accordingly.
536
-		$this->set_warning( $post_id, $is_warning );
536
+		$this->set_warning($post_id, $is_warning);
537 537
 
538 538
 	}
539 539
 
540
-	private function has_interpolation_errors( $content ) {
540
+	private function has_interpolation_errors($content) {
541 541
 		$matches = array();
542 542
 
543 543
 		// eg:
544 544
 		// r-pro<span id="urn:local-text-annotation-oxbgy6139gnjgk1n0oxnq9zg62py29pf" class="textannotation disambiguated wl-thing" itemid="http://data.wordlift.it/be2/entity/developing_country">ne region, has shoul</span>dere
545 545
 
546
-		return 0 < preg_match_all( '/\w<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches )
547
-			   || 0 < preg_match_all( ' /<[a-z]+ id="urn:[^"]+ " class="[^"]+" itemid="[^"]+">\s/', $content, $matches );
546
+		return 0 < preg_match_all('/\w<[a-z]+ id="urn:[^"]+" class="[^"]+" itemid="[^"]+">/', $content, $matches)
547
+			   || 0 < preg_match_all(' /<[a-z]+ id="urn:[^"]+ " class="[^"]+" itemid="[^"]+">\s/', $content, $matches);
548 548
 	}
549 549
 
550 550
 	/**
@@ -557,19 +557,19 @@  discard block
 block discarded – undo
557 557
 	 *
558 558
 	 * @return string Post content without interpolations.
559 559
 	 */
560
-	private function fix_interpolation_errors( $content, $id ) {
560
+	private function fix_interpolation_errors($content, $id) {
561 561
 
562 562
 		// Bail out if there are no interpolation errors.
563
-		if ( ! $this->has_interpolation_errors( $content ) ) {
564
-			$this->log->trace( "No interpolation errors found for post $id." );
563
+		if ( ! $this->has_interpolation_errors($content)) {
564
+			$this->log->trace("No interpolation errors found for post $id.");
565 565
 
566 566
 			return $content;
567 567
 		}
568 568
 
569
-		$this->log->debug( "Fixing post $id interpolations..." );
569
+		$this->log->debug("Fixing post $id interpolations...");
570 570
 
571 571
 		// Remove all interpolations from the content.
572
-		return preg_replace( self::$interpolation_patterns, '$1$2', $content );
572
+		return preg_replace(self::$interpolation_patterns, '$1$2', $content);
573 573
 	}
574 574
 
575 575
 	/**
@@ -580,10 +580,10 @@  discard block
 block discarded – undo
580 580
 	 * @param int|array $post_ids A single {@link WP_Post}'s id or an array of
581 581
 	 *                            {@link WP_Post}s' ids.
582 582
 	 */
583
-	public function clear_warning( $post_ids ) {
583
+	public function clear_warning($post_ids) {
584 584
 
585
-		foreach ( (array) $post_ids as $post_id ) {
586
-			delete_post_meta( $post_id, self::WARNING_META_KEY );
585
+		foreach ((array) $post_ids as $post_id) {
586
+			delete_post_meta($post_id, self::WARNING_META_KEY);
587 587
 		}
588 588
 
589 589
 	}
@@ -599,9 +599,9 @@  discard block
 block discarded – undo
599 599
 	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
600 600
 	 *                  false on failure.
601 601
 	 */
602
-	private function set_warning( $post_id, $value ) {
602
+	private function set_warning($post_id, $value) {
603 603
 
604
-		return update_post_meta( $post_id, self::WARNING_META_KEY, ( true === $value ? 'yes' : 'no' ) );
604
+		return update_post_meta($post_id, self::WARNING_META_KEY, (true === $value ? 'yes' : 'no'));
605 605
 	}
606 606
 
607 607
 //	/**
@@ -629,23 +629,23 @@  discard block
 block discarded – undo
629 629
 	 * @return int|bool Meta ID if the key didn't exist, true on successful update,
630 630
 	 *                  false on failure.
631 631
 	 */
632
-	private function set_state( $post_id, $value ) {
632
+	private function set_state($post_id, $value) {
633 633
 
634 634
 		// Update the state.
635
-		$result = update_post_meta( $post_id, self::STATE_META_KEY, $value );
635
+		$result = update_post_meta($post_id, self::STATE_META_KEY, $value);
636 636
 
637 637
 		// Update timestamps as required.
638
-		switch ( $value ) {
638
+		switch ($value) {
639 639
 
640 640
 			// ### REQUEST state.
641 641
 			case self::STATE_REQUEST:
642
-				add_post_meta( $post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
642
+				add_post_meta($post_id, self::REQUEST_TIMESTAMP_META_KEY, current_time('mysql', true));
643 643
 				break;
644 644
 
645 645
 			// ### SUCCESS/ERROR state.
646 646
 			case self::STATE_SUCCESS:
647 647
 			case self::STATE_ERROR:
648
-				add_post_meta( $post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time( 'mysql', true ) );
648
+				add_post_meta($post_id, self::COMPLETE_TIMESTAMP_META_KEY, current_time('mysql', true));
649 649
 				break;
650 650
 		}
651 651
 
@@ -664,11 +664,11 @@  discard block
 block discarded – undo
664 664
 	 *
665 665
 	 * @return array The link settings.
666 666
 	 */
667
-	private function get_options( $post_id ) {
667
+	private function get_options($post_id) {
668 668
 
669
-		$values = get_post_meta( $post_id, self::BATCH_ANALYSIS_OPTIONS_META_KEY );
669
+		$values = get_post_meta($post_id, self::BATCH_ANALYSIS_OPTIONS_META_KEY);
670 670
 
671
-		return end( $values ) ?: array(
671
+		return end($values) ?: array(
672 672
 			'links'           => 'default',
673 673
 			'min_occurrences' => 1,
674 674
 		);
@@ -683,8 +683,8 @@  discard block
 block discarded – undo
683 683
 	 */
684 684
 	public function waiting_for_analysis() {
685 685
 
686
-		return get_posts( array(
687
-			'posts_per_page' => - 1,
686
+		return get_posts(array(
687
+			'posts_per_page' => -1,
688 688
 			'fields'         => 'ids',
689 689
 			'post_status'    => 'any',
690 690
 			'meta_key'       => self::STATE_META_KEY,
@@ -692,7 +692,7 @@  discard block
 block discarded – undo
692 692
 			'orderby'        => 'ID',
693 693
 			'post_type'      => 'any',
694 694
 			// Add any because posts from multiple posts types may be waiting.
695
-		) );
695
+		));
696 696
 	}
697 697
 
698 698
 	/**
@@ -705,8 +705,8 @@  discard block
 block discarded – undo
705 705
 	 */
706 706
 	public function waiting_for_response() {
707 707
 
708
-		return get_posts( array(
709
-			'posts_per_page' => - 1,
708
+		return get_posts(array(
709
+			'posts_per_page' => -1,
710 710
 			'fields'         => 'ids',
711 711
 			'post_status'    => 'any',
712 712
 			'meta_key'       => self::STATE_META_KEY,
@@ -714,7 +714,7 @@  discard block
 block discarded – undo
714 714
 			'orderby'        => 'ID',
715 715
 			'post_type'      => 'any',
716 716
 			// Add any because posts from multiple posts types may be waiting.
717
-		) );
717
+		));
718 718
 	}
719 719
 
720 720
 	/**
@@ -726,25 +726,25 @@  discard block
 block discarded – undo
726 726
 	 *
727 727
 	 * @return WP_Error|array The response or WP_Error on failure.
728 728
 	 */
729
-	private function do_request( $post_id ) {
729
+	private function do_request($post_id) {
730 730
 
731 731
 		// Change the state to `REQUEST`.
732
-		$this->set_state( $post_id, self::STATE_REQUEST );
732
+		$this->set_state($post_id, self::STATE_REQUEST);
733 733
 
734 734
 		// Get the post.
735
-		$post = get_post( $post_id );
735
+		$post = get_post($post_id);
736 736
 
737 737
 		// Bail out if the post isn't found.
738
-		if ( null === $post ) {
739
-			$this->log->warn( "Post $post_id not found." );
738
+		if (null === $post) {
739
+			$this->log->warn("Post $post_id not found.");
740 740
 
741
-			return new WP_Error( 0, "Cannot find post $post_id." );
741
+			return new WP_Error(0, "Cannot find post $post_id.");
742 742
 		}
743 743
 
744 744
 		// Get the link setting.
745
-		$options = $this->get_options( $post_id );
745
+		$options = $this->get_options($post_id);
746 746
 
747
-		$this->log->debug( 'Sending analysis request for post $post_id [ links :: ' . $options['links'] . ', min_occurrences :: ' . $options['min_occurrences'] . ' ] ...' );
747
+		$this->log->debug('Sending analysis request for post $post_id [ links :: '.$options['links'].', min_occurrences :: '.$options['min_occurrences'].' ] ...');
748 748
 
749 749
 		// Get the batch analysis URL.
750 750
 		$url = $this->configuration_service->get_batch_analysis_url();
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
 		);
763 763
 
764 764
 		// Get the HTTP options.
765
-		$args = array_merge_recursive( unserialize( WL_REDLINK_API_HTTP_OPTIONS ), array(
765
+		$args = array_merge_recursive(unserialize(WL_REDLINK_API_HTTP_OPTIONS), array(
766 766
 			'method'      => 'POST',
767 767
 			'headers'     => array(
768 768
 				'Accept'       => 'application/json',
@@ -770,13 +770,13 @@  discard block
 block discarded – undo
770 770
 			),
771 771
 			// we need to downgrade the HTTP version in this case since chunked encoding is dumping numbers in the response.
772 772
 			'httpversion' => '1.0',
773
-			'body'        => wp_json_encode( $params ),
774
-		) );
773
+			'body'        => wp_json_encode($params),
774
+		));
775 775
 
776
-		$this->log->debug( "Posting analysis request for post $post_id to $url..." );
776
+		$this->log->debug("Posting analysis request for post $post_id to $url...");
777 777
 
778 778
 		// Post the parameter.
779
-		return wp_remote_post( $url, $args );
779
+		return wp_remote_post($url, $args);
780 780
 	}
781 781
 
782 782
 	/**
@@ -788,20 +788,20 @@  discard block
 block discarded – undo
788 788
 	 *
789 789
 	 * @return WP_Error|array The response or WP_Error on failure.
790 790
 	 */
791
-	private function do_complete( $post_id ) {
791
+	private function do_complete($post_id) {
792 792
 
793
-		$post = get_post( $post_id );
793
+		$post = get_post($post_id);
794 794
 
795
-		if ( null === $post ) {
795
+		if (null === $post) {
796 796
 			// Post was possibly deleted, just bailout.
797
-			return new WP_Error( 0, "Post $post_id not found . " );
797
+			return new WP_Error(0, "Post $post_id not found . ");
798 798
 		}
799 799
 
800 800
 		$url = $this->configuration_service->get_batch_analysis_url();
801 801
 		$key = $this->configuration_service->get_key();
802
-		$url = $url . '/' . $post->ID . '?key=' . $key;
802
+		$url = $url.'/'.$post->ID.'?key='.$key;
803 803
 
804
-		return wp_remote_get( $url, unserialize( WL_REDLINK_API_HTTP_OPTIONS ) );
804
+		return wp_remote_get($url, unserialize(WL_REDLINK_API_HTTP_OPTIONS));
805 805
 	}
806 806
 
807 807
 	/**
@@ -813,15 +813,15 @@  discard block
 block discarded – undo
813 813
 	 */
814 814
 	public function get_warnings() {
815 815
 
816
-		return get_posts( array(
816
+		return get_posts(array(
817 817
 			'fields'      => 'ids',
818
-			'numberposts' => - 1,
818
+			'numberposts' => -1,
819 819
 			'post_status' => 'any',
820 820
 			'meta_key'    => self::WARNING_META_KEY,
821 821
 			'meta_value'  => 'yes',
822 822
 			'post_type'   => 'any',
823 823
 			// Add any because posts from multiple posts types may be waiting.
824
-		) );
824
+		));
825 825
 	}
826 826
 
827 827
 	/**
@@ -831,17 +831,17 @@  discard block
 block discarded – undo
831 831
 	 *
832 832
 	 * @param int $id The {@link WP_Post}'s id.
833 833
 	 */
834
-	private function maybe_set_default_term( $id ) {
834
+	private function maybe_set_default_term($id) {
835 835
 		// Check whether the post has any of the WordLift entity types.
836
-		$has_term = has_term( '', Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME, $id );
836
+		$has_term = has_term('', Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME, $id);
837 837
 
838 838
 		// Bail if the term is associated with entity types already.
839
-		if ( ! empty( $has_term ) ) {
839
+		if ( ! empty($has_term)) {
840 840
 			return;
841 841
 		}
842 842
 
843 843
 		// Set the default `article` term.
844
-		wp_set_object_terms( $id, 'article', Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
844
+		wp_set_object_terms($id, 'article', Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME);
845 845
 
846 846
 	}
847 847
 
Please login to merge, or discard this patch.
src/includes/linked-data/storage/class-wordlift-storage-factory.php 2 patches
Indentation   +205 added lines, -205 removed lines patch added patch discarded remove patch
@@ -18,210 +18,210 @@
 block discarded – undo
18 18
  */
19 19
 class Wordlift_Storage_Factory {
20 20
 
21
-	/**
22
-	 * The {@link Wordlift_Entity_Service} instance.
23
-	 *
24
-	 * @since  3.15.0
25
-	 * @access private
26
-	 * @var \Wordlift_Entity_Service $entity_service The {@link Wordlift_Entity_Service} instance.
27
-	 */
28
-	private $entity_service;
29
-
30
-	/**
31
-	 * The {@link Wordlift_User_Service} instance.
32
-	 *
33
-	 * @since  3.15.0
34
-	 * @access private
35
-	 * @var \Wordlift_User_Service $user_service The {@link Wordlift_User_Service} instance.
36
-	 */
37
-	private $user_service;
38
-
39
-	/**
40
-	 * The {@link Wordlift_Property_Getter} instance.
41
-	 *
42
-	 * @since  3.15.0
43
-	 * @access private
44
-	 * @var \Wordlift_Property_Getter The {@link Wordlift_Property_Getter} instance.
45
-	 */
46
-	private $property_getter;
47
-
48
-	/**
49
-	 * The singleton instance.
50
-	 *
51
-	 * @since  3.15.0
52
-	 * @access private
53
-	 * @var \Wordlift_Storage_Factory $instance The singleton instance.
54
-	 */
55
-	private static $instance;
56
-
57
-	/**
58
-	 * Create a {@link Wordlift_Storage_Factory} instance.
59
-	 *
60
-	 * @since 3.15.0
61
-	 *
62
-	 * @param \Wordlift_Entity_Service  $entity_service  The {@link Wordlift_Entity_Service} instance.
63
-	 * @param \Wordlift_User_Service    $user_service    The {@link Wordlift_User_Service} instance.
64
-	 * @param \Wordlift_Property_Getter $property_getter The {@link Wordlift_Property_Getter} instance.
65
-	 */
66
-	public function __construct( $entity_service, $user_service, $property_getter ) {
67
-
68
-		$this->entity_service  = $entity_service;
69
-		$this->user_service    = $user_service;
70
-		$this->property_getter = $property_getter;
71
-
72
-		self::$instance = $this;
73
-	}
74
-
75
-	/**
76
-	 * Get the singleton instance.
77
-	 *
78
-	 * @since 3.15.0
79
-	 *
80
-	 * @return \Wordlift_Storage_Factory The singleton instance.
81
-	 */
82
-	public static function get_instance() {
83
-
84
-		return self::$instance;
85
-	}
86
-
87
-	/**
88
-	 * Get a {@link Wordlift_Post_Property_Storage} to read {@link WP_Post}s'
89
-	 * titles.
90
-	 *
91
-	 * @since 3.15.0
92
-	 *
93
-	 * @return \Wordlift_Post_Property_Storage A {@link Wordlift_Post_Property_Storage}
94
-	 *                                         instance.
95
-	 */
96
-	public function post_title() {
97
-
98
-		return new Wordlift_Post_Property_Storage( Wordlift_Post_Property_Storage::TITLE );
99
-	}
100
-
101
-	/**
102
-	 * Get a {@link Wordlift_Post_Property_Storage} to read {@link WP_Post}s'
103
-	 * descriptions stripped of tags and shortcodes.
104
-	 *
105
-	 * @since 3.15.0
106
-	 *
107
-	 * @return \Wordlift_Post_Property_Storage A {@link Wordlift_Post_Property_Storage}
108
-	 *                                         instance.
109
-	 */
110
-	public function post_description_no_tags_no_shortcodes() {
111
-
112
-		return new Wordlift_Post_Property_Storage( Wordlift_Post_Property_Storage::DESCRIPTION_NO_TAGS_NO_SHORTCODES );
113
-	}
114
-
115
-	/**
116
-	 * Get a {@link Wordlift_Post_Property_Storage} to read {@link WP_Post}s'
117
-	 * authors.
118
-	 *
119
-	 * @since 3.15.0
120
-	 *
121
-	 * @return \Wordlift_Post_Property_Storage A {@link Wordlift_Post_Property_Storage}
122
-	 *                                         instance.
123
-	 */
124
-	public function post_author() {
125
-
126
-		return new Wordlift_Post_Property_Storage( Wordlift_Post_Property_Storage::AUTHOR );
127
-	}
128
-
129
-	/**
130
-	 * Get a {@link Wordlift_Post_Property_Storage} to read {@link WP_Post}s'
131
-	 * metas.
132
-	 *
133
-	 * @since 3.15.0
134
-	 *
135
-	 * @param string $meta_key The meta key to read.
136
-	 *
137
-	 * @return Wordlift_Post_Meta_Storage A {@link Wordlift_Post_Meta_Storage}
138
-	 *                                    instance.
139
-	 */
140
-	public function post_meta( $meta_key ) {
141
-
142
-		return new Wordlift_Post_Meta_Storage( $meta_key );
143
-	}
144
-
145
-	/**
146
-	 * Get a {@link Wordlift_Post_Schema_Class_Storage} to read {@link WP_Post}s'
147
-	 * entity type class.
148
-	 *
149
-	 * @since 3.15.0
150
-	 *
151
-	 * @return Wordlift_Post_Schema_Class_Storage A {@link Wordlift_Post_Schema_Class_Storage}
152
-	 *                                    instance.
153
-	 */
154
-	public function schema_class() {
155
-
156
-		return new Wordlift_Post_Schema_Class_Storage();
157
-	}
158
-
159
-	/**
160
-	 * Get a {@link Wordlift_Post_Author_Storage} instance able to turn an author
161
-	 * id into a URI.
162
-	 *
163
-	 * @since 3.15.0
164
-	 *
165
-	 * @return \Wordlift_Post_Author_Storage A {@link Wordlift_Post_Author_Storage}
166
-	 *                                       instance.
167
-	 */
168
-	public function author_uri() {
169
-
170
-		return new Wordlift_Post_Author_Storage( $this->entity_service, $this->user_service );
171
-	}
172
-
173
-	/**
174
-	 * Get a {@link Wordlift_Post_Meta_Uri_Storage} instance which reads {@link WP_Post}
175
-	 * ids and maps them to URI.
176
-	 *
177
-	 * @param string $meta_key The {@link WP_Post}'s meta key.
178
-	 *
179
-	 * @return \Wordlift_Post_Meta_Uri_Storage A {@link Wordlift_Post_Meta_Uri_Storage}
180
-	 *                                         instance.
181
-	 */
182
-	public function post_meta_to_uri( $meta_key ) {
183
-
184
-		return new Wordlift_Post_Meta_Uri_Storage( $meta_key, $this->entity_service );
185
-	}
186
-
187
-	/**
188
-	 * Get a list of {@link WP_Post}'s images URI.
189
-	 *
190
-	 * @since 3.15.0
191
-	 *
192
-	 * @return \Wordlift_Post_Image_Storage A {@link Wordlift_Post_Image_Storage}
193
-	 *                                      instance.
194
-	 */
195
-	public function post_images() {
196
-
197
-		return new Wordlift_Post_Image_Storage();
198
-	}
199
-
200
-	/**
201
-	 * Get a {@link Wordlift_Post_Related_Storage} instance to get related
202
-	 * {@link WP_Post}s.
203
-	 *
204
-	 * @since 3.15.0
205
-	 *
206
-	 * @return \Wordlift_Post_Related_Storage A {@link Wordlift_Post_Related_Storage}
207
-	 *                                        instance.
208
-	 */
209
-	public function relations() {
210
-
211
-		return new Wordlift_Post_Related_Storage( $this->entity_service );
212
-	}
213
-
214
-	/**
215
-	 * Get the {@link Wordlift_Url_Property_Storage} instance.
216
-	 *
217
-	 * @since 3.15.0
218
-	 *
219
-	 * @return \Wordlift_Url_Property_Storage The {@link Wordlift_Url_Property_Storage}
220
-	 *                                        instance.
221
-	 */
222
-	public function url_property() {
223
-
224
-		return new Wordlift_Url_Property_Storage( $this->property_getter );
225
-	}
21
+    /**
22
+     * The {@link Wordlift_Entity_Service} instance.
23
+     *
24
+     * @since  3.15.0
25
+     * @access private
26
+     * @var \Wordlift_Entity_Service $entity_service The {@link Wordlift_Entity_Service} instance.
27
+     */
28
+    private $entity_service;
29
+
30
+    /**
31
+     * The {@link Wordlift_User_Service} instance.
32
+     *
33
+     * @since  3.15.0
34
+     * @access private
35
+     * @var \Wordlift_User_Service $user_service The {@link Wordlift_User_Service} instance.
36
+     */
37
+    private $user_service;
38
+
39
+    /**
40
+     * The {@link Wordlift_Property_Getter} instance.
41
+     *
42
+     * @since  3.15.0
43
+     * @access private
44
+     * @var \Wordlift_Property_Getter The {@link Wordlift_Property_Getter} instance.
45
+     */
46
+    private $property_getter;
47
+
48
+    /**
49
+     * The singleton instance.
50
+     *
51
+     * @since  3.15.0
52
+     * @access private
53
+     * @var \Wordlift_Storage_Factory $instance The singleton instance.
54
+     */
55
+    private static $instance;
56
+
57
+    /**
58
+     * Create a {@link Wordlift_Storage_Factory} instance.
59
+     *
60
+     * @since 3.15.0
61
+     *
62
+     * @param \Wordlift_Entity_Service  $entity_service  The {@link Wordlift_Entity_Service} instance.
63
+     * @param \Wordlift_User_Service    $user_service    The {@link Wordlift_User_Service} instance.
64
+     * @param \Wordlift_Property_Getter $property_getter The {@link Wordlift_Property_Getter} instance.
65
+     */
66
+    public function __construct( $entity_service, $user_service, $property_getter ) {
67
+
68
+        $this->entity_service  = $entity_service;
69
+        $this->user_service    = $user_service;
70
+        $this->property_getter = $property_getter;
71
+
72
+        self::$instance = $this;
73
+    }
74
+
75
+    /**
76
+     * Get the singleton instance.
77
+     *
78
+     * @since 3.15.0
79
+     *
80
+     * @return \Wordlift_Storage_Factory The singleton instance.
81
+     */
82
+    public static function get_instance() {
83
+
84
+        return self::$instance;
85
+    }
86
+
87
+    /**
88
+     * Get a {@link Wordlift_Post_Property_Storage} to read {@link WP_Post}s'
89
+     * titles.
90
+     *
91
+     * @since 3.15.0
92
+     *
93
+     * @return \Wordlift_Post_Property_Storage A {@link Wordlift_Post_Property_Storage}
94
+     *                                         instance.
95
+     */
96
+    public function post_title() {
97
+
98
+        return new Wordlift_Post_Property_Storage( Wordlift_Post_Property_Storage::TITLE );
99
+    }
100
+
101
+    /**
102
+     * Get a {@link Wordlift_Post_Property_Storage} to read {@link WP_Post}s'
103
+     * descriptions stripped of tags and shortcodes.
104
+     *
105
+     * @since 3.15.0
106
+     *
107
+     * @return \Wordlift_Post_Property_Storage A {@link Wordlift_Post_Property_Storage}
108
+     *                                         instance.
109
+     */
110
+    public function post_description_no_tags_no_shortcodes() {
111
+
112
+        return new Wordlift_Post_Property_Storage( Wordlift_Post_Property_Storage::DESCRIPTION_NO_TAGS_NO_SHORTCODES );
113
+    }
114
+
115
+    /**
116
+     * Get a {@link Wordlift_Post_Property_Storage} to read {@link WP_Post}s'
117
+     * authors.
118
+     *
119
+     * @since 3.15.0
120
+     *
121
+     * @return \Wordlift_Post_Property_Storage A {@link Wordlift_Post_Property_Storage}
122
+     *                                         instance.
123
+     */
124
+    public function post_author() {
125
+
126
+        return new Wordlift_Post_Property_Storage( Wordlift_Post_Property_Storage::AUTHOR );
127
+    }
128
+
129
+    /**
130
+     * Get a {@link Wordlift_Post_Property_Storage} to read {@link WP_Post}s'
131
+     * metas.
132
+     *
133
+     * @since 3.15.0
134
+     *
135
+     * @param string $meta_key The meta key to read.
136
+     *
137
+     * @return Wordlift_Post_Meta_Storage A {@link Wordlift_Post_Meta_Storage}
138
+     *                                    instance.
139
+     */
140
+    public function post_meta( $meta_key ) {
141
+
142
+        return new Wordlift_Post_Meta_Storage( $meta_key );
143
+    }
144
+
145
+    /**
146
+     * Get a {@link Wordlift_Post_Schema_Class_Storage} to read {@link WP_Post}s'
147
+     * entity type class.
148
+     *
149
+     * @since 3.15.0
150
+     *
151
+     * @return Wordlift_Post_Schema_Class_Storage A {@link Wordlift_Post_Schema_Class_Storage}
152
+     *                                    instance.
153
+     */
154
+    public function schema_class() {
155
+
156
+        return new Wordlift_Post_Schema_Class_Storage();
157
+    }
158
+
159
+    /**
160
+     * Get a {@link Wordlift_Post_Author_Storage} instance able to turn an author
161
+     * id into a URI.
162
+     *
163
+     * @since 3.15.0
164
+     *
165
+     * @return \Wordlift_Post_Author_Storage A {@link Wordlift_Post_Author_Storage}
166
+     *                                       instance.
167
+     */
168
+    public function author_uri() {
169
+
170
+        return new Wordlift_Post_Author_Storage( $this->entity_service, $this->user_service );
171
+    }
172
+
173
+    /**
174
+     * Get a {@link Wordlift_Post_Meta_Uri_Storage} instance which reads {@link WP_Post}
175
+     * ids and maps them to URI.
176
+     *
177
+     * @param string $meta_key The {@link WP_Post}'s meta key.
178
+     *
179
+     * @return \Wordlift_Post_Meta_Uri_Storage A {@link Wordlift_Post_Meta_Uri_Storage}
180
+     *                                         instance.
181
+     */
182
+    public function post_meta_to_uri( $meta_key ) {
183
+
184
+        return new Wordlift_Post_Meta_Uri_Storage( $meta_key, $this->entity_service );
185
+    }
186
+
187
+    /**
188
+     * Get a list of {@link WP_Post}'s images URI.
189
+     *
190
+     * @since 3.15.0
191
+     *
192
+     * @return \Wordlift_Post_Image_Storage A {@link Wordlift_Post_Image_Storage}
193
+     *                                      instance.
194
+     */
195
+    public function post_images() {
196
+
197
+        return new Wordlift_Post_Image_Storage();
198
+    }
199
+
200
+    /**
201
+     * Get a {@link Wordlift_Post_Related_Storage} instance to get related
202
+     * {@link WP_Post}s.
203
+     *
204
+     * @since 3.15.0
205
+     *
206
+     * @return \Wordlift_Post_Related_Storage A {@link Wordlift_Post_Related_Storage}
207
+     *                                        instance.
208
+     */
209
+    public function relations() {
210
+
211
+        return new Wordlift_Post_Related_Storage( $this->entity_service );
212
+    }
213
+
214
+    /**
215
+     * Get the {@link Wordlift_Url_Property_Storage} instance.
216
+     *
217
+     * @since 3.15.0
218
+     *
219
+     * @return \Wordlift_Url_Property_Storage The {@link Wordlift_Url_Property_Storage}
220
+     *                                        instance.
221
+     */
222
+    public function url_property() {
223
+
224
+        return new Wordlift_Url_Property_Storage( $this->property_getter );
225
+    }
226 226
 
227 227
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
 	 * @param \Wordlift_User_Service    $user_service    The {@link Wordlift_User_Service} instance.
64 64
 	 * @param \Wordlift_Property_Getter $property_getter The {@link Wordlift_Property_Getter} instance.
65 65
 	 */
66
-	public function __construct( $entity_service, $user_service, $property_getter ) {
66
+	public function __construct($entity_service, $user_service, $property_getter) {
67 67
 
68 68
 		$this->entity_service  = $entity_service;
69 69
 		$this->user_service    = $user_service;
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 	 */
96 96
 	public function post_title() {
97 97
 
98
-		return new Wordlift_Post_Property_Storage( Wordlift_Post_Property_Storage::TITLE );
98
+		return new Wordlift_Post_Property_Storage(Wordlift_Post_Property_Storage::TITLE);
99 99
 	}
100 100
 
101 101
 	/**
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 	 */
110 110
 	public function post_description_no_tags_no_shortcodes() {
111 111
 
112
-		return new Wordlift_Post_Property_Storage( Wordlift_Post_Property_Storage::DESCRIPTION_NO_TAGS_NO_SHORTCODES );
112
+		return new Wordlift_Post_Property_Storage(Wordlift_Post_Property_Storage::DESCRIPTION_NO_TAGS_NO_SHORTCODES);
113 113
 	}
114 114
 
115 115
 	/**
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 	 */
124 124
 	public function post_author() {
125 125
 
126
-		return new Wordlift_Post_Property_Storage( Wordlift_Post_Property_Storage::AUTHOR );
126
+		return new Wordlift_Post_Property_Storage(Wordlift_Post_Property_Storage::AUTHOR);
127 127
 	}
128 128
 
129 129
 	/**
@@ -137,9 +137,9 @@  discard block
 block discarded – undo
137 137
 	 * @return Wordlift_Post_Meta_Storage A {@link Wordlift_Post_Meta_Storage}
138 138
 	 *                                    instance.
139 139
 	 */
140
-	public function post_meta( $meta_key ) {
140
+	public function post_meta($meta_key) {
141 141
 
142
-		return new Wordlift_Post_Meta_Storage( $meta_key );
142
+		return new Wordlift_Post_Meta_Storage($meta_key);
143 143
 	}
144 144
 
145 145
 	/**
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 	 */
168 168
 	public function author_uri() {
169 169
 
170
-		return new Wordlift_Post_Author_Storage( $this->entity_service, $this->user_service );
170
+		return new Wordlift_Post_Author_Storage($this->entity_service, $this->user_service);
171 171
 	}
172 172
 
173 173
 	/**
@@ -179,9 +179,9 @@  discard block
 block discarded – undo
179 179
 	 * @return \Wordlift_Post_Meta_Uri_Storage A {@link Wordlift_Post_Meta_Uri_Storage}
180 180
 	 *                                         instance.
181 181
 	 */
182
-	public function post_meta_to_uri( $meta_key ) {
182
+	public function post_meta_to_uri($meta_key) {
183 183
 
184
-		return new Wordlift_Post_Meta_Uri_Storage( $meta_key, $this->entity_service );
184
+		return new Wordlift_Post_Meta_Uri_Storage($meta_key, $this->entity_service);
185 185
 	}
186 186
 
187 187
 	/**
@@ -208,7 +208,7 @@  discard block
 block discarded – undo
208 208
 	 */
209 209
 	public function relations() {
210 210
 
211
-		return new Wordlift_Post_Related_Storage( $this->entity_service );
211
+		return new Wordlift_Post_Related_Storage($this->entity_service);
212 212
 	}
213 213
 
214 214
 	/**
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
 	 */
222 222
 	public function url_property() {
223 223
 
224
-		return new Wordlift_Url_Property_Storage( $this->property_getter );
224
+		return new Wordlift_Url_Property_Storage($this->property_getter);
225 225
 	}
226 226
 
227 227
 }
Please login to merge, or discard this patch.
src/includes/wp-async-task/class-wordlift-push-references-async-task.php 2 patches
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -18,59 +18,59 @@
 block discarded – undo
18 18
  */
19 19
 class Wordlift_Push_References_Async_Task extends Wordlift_Async_Task {
20 20
 
21
-	/**
22
-	 * The protected $action property should be set to the action to which you
23
-	 * wish to attach the asynchronous task. For example, if you want to spin
24
-	 * off an asynchronous task whenever a post gets saved, you would set this
25
-	 * to save_post.
26
-	 *
27
-	 * @since  3.18.0
28
-	 * @access protected
29
-	 * @var string $action The action to which you wish to attach the
30
-	 *                     asynchronous task.
31
-	 */
32
-	protected $action = 'wl_push_references';
21
+    /**
22
+     * The protected $action property should be set to the action to which you
23
+     * wish to attach the asynchronous task. For example, if you want to spin
24
+     * off an asynchronous task whenever a post gets saved, you would set this
25
+     * to save_post.
26
+     *
27
+     * @since  3.18.0
28
+     * @access protected
29
+     * @var string $action The action to which you wish to attach the
30
+     *                     asynchronous task.
31
+     */
32
+    protected $action = 'wl_push_references';
33 33
 
34
-	/**
35
-	 * A {@link Wordlift_Log_Service} instance.
36
-	 *
37
-	 * @since  3.18.0
38
-	 * @access private
39
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
40
-	 */
41
-	private $log;
34
+    /**
35
+     * A {@link Wordlift_Log_Service} instance.
36
+     *
37
+     * @since  3.18.0
38
+     * @access private
39
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
40
+     */
41
+    private $log;
42 42
 
43
-	/**
44
-	 * Create a {@link Wordlift_Push_References_Async_Task} instance.
45
-	 *
46
-	 * @since 3.18.0
47
-	 *
48
-	 * @param int $auth_level The authentication level to use (see above)
49
-	 */
50
-	public function __construct( $auth_level = self::BOTH ) {
51
-		parent::__construct( $auth_level );
43
+    /**
44
+     * Create a {@link Wordlift_Push_References_Async_Task} instance.
45
+     *
46
+     * @since 3.18.0
47
+     *
48
+     * @param int $auth_level The authentication level to use (see above)
49
+     */
50
+    public function __construct( $auth_level = self::BOTH ) {
51
+        parent::__construct( $auth_level );
52 52
 
53
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Push_References_Async_Task' );
53
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Push_References_Async_Task' );
54 54
 
55
-	}
55
+    }
56 56
 
57
-	/**
58
-	 * @inheritdoc
59
-	 */
60
-	protected function prepare_data( $data ) {
57
+    /**
58
+     * @inheritdoc
59
+     */
60
+    protected function prepare_data( $data ) {
61 61
 
62
-		// Return the link setting.
63
-		return array();
64
-	}
62
+        // Return the link setting.
63
+        return array();
64
+    }
65 65
 
66
-	/**
67
-	 * @inheritdoc
68
-	 */
69
-	protected function run_action() {
66
+    /**
67
+     * @inheritdoc
68
+     */
69
+    protected function run_action() {
70 70
 
71
-		// Run the asynchronous action.
72
-		do_action( "wl_async_$this->action" );
71
+        // Run the asynchronous action.
72
+        do_action( "wl_async_$this->action" );
73 73
 
74
-	}
74
+    }
75 75
 
76 76
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -47,17 +47,17 @@  discard block
 block discarded – undo
47 47
 	 *
48 48
 	 * @param int $auth_level The authentication level to use (see above)
49 49
 	 */
50
-	public function __construct( $auth_level = self::BOTH ) {
51
-		parent::__construct( $auth_level );
50
+	public function __construct($auth_level = self::BOTH) {
51
+		parent::__construct($auth_level);
52 52
 
53
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Push_References_Async_Task' );
53
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Push_References_Async_Task');
54 54
 
55 55
 	}
56 56
 
57 57
 	/**
58 58
 	 * @inheritdoc
59 59
 	 */
60
-	protected function prepare_data( $data ) {
60
+	protected function prepare_data($data) {
61 61
 
62 62
 		// Return the link setting.
63 63
 		return array();
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
 	protected function run_action() {
70 70
 
71 71
 		// Run the asynchronous action.
72
-		do_action( "wl_async_$this->action" );
72
+		do_action("wl_async_$this->action");
73 73
 
74 74
 	}
75 75
 
Please login to merge, or discard this patch.
src/includes/class-wordlift-query-builder.php 2 patches
Spacing   +20 added lines, -22 removed lines patch added patch discarded remove patch
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 	 *
200 200
 	 * @return $this \Wordlift_Query_Builder The Query builder.
201 201
 	 */
202
-	public function select( $props = '*' ) {
202
+	public function select($props = '*') {
203 203
 
204 204
 		$this->template = "SELECT $props WHERE { %s }";
205 205
 
@@ -220,38 +220,36 @@  discard block
 block discarded – undo
220 220
 	 *
221 221
 	 * @return $this \Wordlift_Query_Builder The Query builder.
222 222
 	 */
223
-	public function statement( $subject, $predicate, $object, $object_type = self::OBJECT_AUTO, $data_type = null, $language = null ) {
223
+	public function statement($subject, $predicate, $object, $object_type = self::OBJECT_AUTO, $data_type = null, $language = null) {
224 224
 
225 225
 		// If no value has been provided, we don't set any statement.
226
-		if ( empty( $object ) ) {
226
+		if (empty($object)) {
227 227
 			return $this;
228 228
 		}
229 229
 
230 230
 		// Guess the subject type.
231
-		$subject_value_type = $this->guess_subject_type( $subject );
231
+		$subject_value_type = $this->guess_subject_type($subject);
232 232
 
233 233
 		// Get the object type if set, otherwise try to guess it.
234
-		$object_value_type = ( self::OBJECT_AUTO === $object_type ? $this->guess_object_type( $predicate, $object ) : $object_type );
234
+		$object_value_type = (self::OBJECT_AUTO === $object_type ? $this->guess_object_type($predicate, $object) : $object_type);
235 235
 
236 236
 		// Prepare the statement template.
237 237
 		$template =
238 238
 			// Subject as a parameter, no `<`, `>`.
239
-			( self::OBJECT_PARAMETER === $subject_value_type ? '%1$s' : '<%1$s>' ) .
239
+			(self::OBJECT_PARAMETER === $subject_value_type ? '%1$s' : '<%1$s>').
240 240
 			// Predicate.
241
-			' <%2$s> ' .
241
+			' <%2$s> '.
242 242
 			// Object.
243
-			( self::OBJECT_URI === $object_value_type ? '<%3$s>' :
244
-				( self::OBJECT_PARAMETER === $object_value_type ? '%3$s' :
245
-					// self::OBJECT_VALUE === $object_value_type
246
-					'"%3$s"' . ( isset( $data_type ) ? '^^%4$s' : '' ) . ( isset( $language ) ? '@%5$s' : '' ) ) );
243
+			(self::OBJECT_URI === $object_value_type ? '<%3$s>' : (self::OBJECT_PARAMETER === $object_value_type ? '%3$s' : // self::OBJECT_VALUE === $object_value_type
244
+					'"%3$s"'.(isset($data_type) ? '^^%4$s' : '').(isset($language) ? '@%5$s' : '')));
247 245
 
248 246
 		// Escape the subject, predicate and object.
249
-		$escaped_subject   = Wordlift_Sparql_Service::escape_uri( $subject );
250
-		$escaped_predicate = Wordlift_Sparql_Service::escape_uri( $predicate );
251
-		$escaped_object    = ( self::OBJECT_URI === $object_value_type ? Wordlift_Sparql_Service::escape_uri( $object ) : Wordlift_Sparql_Service::escape( $object ) );
247
+		$escaped_subject   = Wordlift_Sparql_Service::escape_uri($subject);
248
+		$escaped_predicate = Wordlift_Sparql_Service::escape_uri($predicate);
249
+		$escaped_object    = (self::OBJECT_URI === $object_value_type ? Wordlift_Sparql_Service::escape_uri($object) : Wordlift_Sparql_Service::escape($object));
252 250
 
253 251
 		// Prepare the statement and add it to the list of statements.
254
-		$this->statements[] = sprintf( $template, $escaped_subject, $escaped_predicate, $escaped_object, $data_type, $language );
252
+		$this->statements[] = sprintf($template, $escaped_subject, $escaped_predicate, $escaped_object, $data_type, $language);
255 253
 
256 254
 		return $this;
257 255
 	}
@@ -265,11 +263,11 @@  discard block
 block discarded – undo
265 263
 	public function build() {
266 264
 
267 265
 		// If there are no statements return an empty string.
268
-		if ( empty( $this->statements ) ) {
266
+		if (empty($this->statements)) {
269 267
 			return '';
270 268
 		}
271 269
 
272
-		return sprintf( $this->template, implode( ' . ', $this->statements ) ) . "\n";
270
+		return sprintf($this->template, implode(' . ', $this->statements))."\n";
273 271
 	}
274 272
 
275 273
 	/**
@@ -282,15 +280,15 @@  discard block
 block discarded – undo
282 280
 	 *
283 281
 	 * @return int {@link Wordlift_Query_Builder::OBJECT_URI} if the Query builder thinks the object must be an URI, {@link Wordlift_Query_Builder::OBJECT_VALUE} otherwise.
284 282
 	 */
285
-	private function guess_object_type( $predicate, $object ) {
283
+	private function guess_object_type($predicate, $object) {
286 284
 
287 285
 		// If the object starts with a question mark, it's a parameter.
288
-		if ( 0 === strpos( $object, '?' ) ) {
286
+		if (0 === strpos($object, '?')) {
289 287
 			return self::OBJECT_PARAMETER;
290 288
 		}
291 289
 
292 290
 		// Guess based on the predicate.
293
-		switch ( $predicate ) {
291
+		switch ($predicate) {
294 292
 
295 293
 			case self::DCTERMS_REFERENCES_URI:
296 294
 			case self::DCTERMS_SUBJECT_URI:
@@ -315,10 +313,10 @@  discard block
 block discarded – undo
315 313
 	 *
316 314
 	 * @return int {@link Wordlift_Query_Builder::OBJECT_PARAMETER} if the Query builder thinks the subject is a parameter (starts with ?), otherwise {@link Wordlift_Query_Builder::OBJECT_URI}.
317 315
 	 */
318
-	private function guess_subject_type( $subject ) {
316
+	private function guess_subject_type($subject) {
319 317
 
320 318
 		// If the object starts with a question mark, it's a parameter.
321
-		if ( 0 === strpos( $subject, '?' ) ) {
319
+		if (0 === strpos($subject, '?')) {
322 320
 			return self::OBJECT_PARAMETER;
323 321
 		}
324 322
 
Please login to merge, or discard this patch.
Indentation   +324 added lines, -324 removed lines patch added patch discarded remove patch
@@ -7,329 +7,329 @@
 block discarded – undo
7 7
  */
8 8
 class Wordlift_Query_Builder {
9 9
 
10
-	/**
11
-	 * The INSERT statement template.
12
-	 *
13
-	 * @since 3.1.7
14
-	 */
15
-	const INSERT = 'INSERT DATA { %s };';
16
-
17
-	/**
18
-	 * The DELETE statement template (it repeats the statements in the WHERE clause.
19
-	 *
20
-	 * @since 3.1.7
21
-	 */
22
-	const DELETE = 'DELETE { %s } WHERE { %1$s };';
23
-
24
-	/**
25
-	 * Tell the statement function to guess the object type (URI, value or parameter).
26
-	 *
27
-	 * @since 3.1.7
28
-	 */
29
-	const OBJECT_AUTO = - 1;
30
-
31
-	/**
32
-	 * Tell the statement function that the object is a URI.
33
-	 *
34
-	 * @since 3.1.7
35
-	 */
36
-	const OBJECT_URI = 0;
37
-
38
-	/**
39
-	 * Tell the statement function that the object is a value.
40
-	 *
41
-	 * @since 3.1.7
42
-	 */
43
-	const OBJECT_VALUE = 1;
44
-
45
-	/**
46
-	 * Tell the statement function that the object is a parameter.
47
-	 *
48
-	 * @since 3.1.7
49
-	 */
50
-	const OBJECT_PARAMETER = 2;
51
-
52
-	/**
53
-	 * The RDFS type.
54
-	 *
55
-	 * @since 3.1.7
56
-	 */
57
-	const RDFS_TYPE_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
58
-
59
-	/**
60
-	 * The schema.org/Person type.
61
-	 *
62
-	 * @since 3.1.7
63
-	 */
64
-	const SCHEMA_PERSON_URI = 'http://schema.org/Person';
65
-
66
-	/**
67
-	 * The schema.org given name predicate.
68
-	 *
69
-	 * @since 3.1.7
70
-	 */
71
-	const SCHEMA_GIVEN_NAME_URI = 'http://schema.org/givenName';
72
-
73
-	/**
74
-	 * The schema.org family name predicate.
75
-	 *
76
-	 * @since 3.1.7
77
-	 */
78
-	const SCHEMA_FAMILY_NAME_URI = 'http://schema.org/familyName';
79
-
80
-	/**
81
-	 * The schema.org url predicate.
82
-	 *
83
-	 * @since 3.1.7
84
-	 */
85
-	const SCHEMA_URL_URI = 'http://schema.org/url';
86
-
87
-	/**
88
-	 * @since 3.14.0
89
-	 */
90
-	const SCHEMA_IMAGE_URI = 'http://schema.org/image';
91
-
92
-	/**
93
-	 * The location created predicate.
94
-	 *
95
-	 * @since 3.14.0
96
-	 */
97
-	const SCHEMA_LOCATION_CREATED_URI = 'http://schema.org/locationCreated';
98
-
99
-	/**
100
-	 * @since 3.14.0
101
-	 */
102
-	const SCHEMA_AUTHOR_URI = 'http://schema.org/author';
103
-
104
-	/**
105
-	 * @since 3.14.0
106
-	 */
107
-	const SCHEMA_INTERACTION_COUNT_URI = 'http://schema.org/interactionCount';
108
-
109
-	/**
110
-	 * @since 3.14.0
111
-	 */
112
-	const DCTERMS_SUBJECT_URI = 'http://purl.org/dc/terms/subject';
113
-
114
-	/**
115
-	 * @since 3.14.0
116
-	 */
117
-	const DCTERMS_REFERENCES_URI = 'http://purl.org/dc/terms/references';
118
-
119
-	/**
120
-	 * @since 3.15.0
121
-	 */
122
-	const DCTERMS_RELATION_URI = 'http://purl.org/dc/terms/relation';
123
-
124
-	/**
125
-	 * The RDF label.
126
-	 *
127
-	 * @since 3.1.7
128
-	 */
129
-	const RDFS_LABEL_URI = 'http://www.w3.org/2000/01/rdf-schema#label';
130
-
131
-	/**
132
-	 * The schema.org `streetAddress` property.
133
-	 *
134
-	 * @since 3.18.0
135
-	 */
136
-	const SCHEMA_STREET_ADDRESS = 'http://schema.org/streetAddress';
137
-
138
-	/**
139
-	 * The schema.org headline.
140
-	 *
141
-	 * @since 3.18.0
142
-	 */
143
-	const SCHEMA_HEADLINE_URI = 'http://schema.org/headline';
144
-
145
-	/**
146
-	 * Hold the template (INSERT or DELETE).
147
-	 *
148
-	 * @since  3.1.7
149
-	 * @access private
150
-	 * @var string $template The query template.
151
-	 */
152
-	private $template;
153
-
154
-	/**
155
-	 * An array of statements (in the form of subject, predicate, object).
156
-	 *
157
-	 * @since  3.1.7
158
-	 * @access private
159
-	 * @var array $statements An array of statements.
160
-	 */
161
-	private $statements = array();
162
-
163
-	/**
164
-	 * Create a new instance of the Query builder (compatible with PHP 5.3).
165
-	 *
166
-	 * @since 3.1.7
167
-	 * @return Wordlift_Query_Builder A new instance of the Query builder.
168
-	 */
169
-	public static function new_instance() {
170
-
171
-		return new Wordlift_Query_Builder();
172
-	}
173
-
174
-	/**
175
-	 * Set the query to INSERT.
176
-	 *
177
-	 * @since 3.1.7
178
-	 * @return Wordlift_Query_Builder The Query builder.
179
-	 */
180
-	public function insert() {
181
-
182
-		$this->template = self::INSERT;
183
-
184
-		return $this;
185
-	}
186
-
187
-	/**
188
-	 * Set the query to DELETE.
189
-	 *
190
-	 * @since 3.1.7
191
-	 * @return $this \Wordlift_Query_Builder The Query builder.
192
-	 */
193
-	public function delete() {
194
-
195
-		$this->template = self::DELETE;
196
-
197
-		return $this;
198
-	}
199
-
200
-	/**
201
-	 * Set the query to SELECT.
202
-	 *
203
-	 * @since 3.12.2
204
-	 *
205
-	 * @param string $props The list of properties to read.
206
-	 *
207
-	 * @return $this \Wordlift_Query_Builder The Query builder.
208
-	 */
209
-	public function select( $props = '*' ) {
210
-
211
-		$this->template = "SELECT $props WHERE { %s }";
212
-
213
-		return $this;
214
-	}
215
-
216
-	/**
217
-	 * Add a statement.
218
-	 *
219
-	 * @since 3.1.7
220
-	 *
221
-	 * @param string      $subject     The subject of the statement (must be a URI).
222
-	 * @param string      $predicate   The predicate (must be a URI).
223
-	 * @param string      $object      The object, can be a URI or a value.
224
-	 * @param int         $object_type The object type, either a {@link OBJECT_URI} or a value {@link OBJECT_VALUE}. If set to {@link OBJECT_AUTO}, the Query builder will try to guess.
225
-	 * @param string|null $data_type   The data type (or null).
226
-	 * @param string|null $language    The language code (or null).
227
-	 *
228
-	 * @return $this \Wordlift_Query_Builder The Query builder.
229
-	 */
230
-	public function statement( $subject, $predicate, $object, $object_type = self::OBJECT_AUTO, $data_type = null, $language = null ) {
231
-
232
-		// If no value has been provided, we don't set any statement.
233
-		if ( empty( $object ) ) {
234
-			return $this;
235
-		}
236
-
237
-		// Guess the subject type.
238
-		$subject_value_type = $this->guess_subject_type( $subject );
239
-
240
-		// Get the object type if set, otherwise try to guess it.
241
-		$object_value_type = ( self::OBJECT_AUTO === $object_type ? $this->guess_object_type( $predicate, $object ) : $object_type );
242
-
243
-		// Prepare the statement template.
244
-		$template =
245
-			// Subject as a parameter, no `<`, `>`.
246
-			( self::OBJECT_PARAMETER === $subject_value_type ? '%1$s' : '<%1$s>' ) .
247
-			// Predicate.
248
-			' <%2$s> ' .
249
-			// Object.
250
-			( self::OBJECT_URI === $object_value_type ? '<%3$s>' :
251
-				( self::OBJECT_PARAMETER === $object_value_type ? '%3$s' :
252
-					// self::OBJECT_VALUE === $object_value_type
253
-					'"%3$s"' . ( isset( $data_type ) ? '^^%4$s' : '' ) . ( isset( $language ) ? '@%5$s' : '' ) ) );
254
-
255
-		// Escape the subject, predicate and object.
256
-		$escaped_subject   = Wordlift_Sparql_Service::escape_uri( $subject );
257
-		$escaped_predicate = Wordlift_Sparql_Service::escape_uri( $predicate );
258
-		$escaped_object    = ( self::OBJECT_URI === $object_value_type ? Wordlift_Sparql_Service::escape_uri( $object ) : Wordlift_Sparql_Service::escape( $object ) );
259
-
260
-		// Prepare the statement and add it to the list of statements.
261
-		$this->statements[] = sprintf( $template, $escaped_subject, $escaped_predicate, $escaped_object, $data_type, $language );
262
-
263
-		return $this;
264
-	}
265
-
266
-	/**
267
-	 * Build the query.
268
-	 *
269
-	 * @since 3.1.7
270
-	 * @return string The query string.
271
-	 */
272
-	public function build() {
273
-
274
-		// If there are no statements return an empty string.
275
-		if ( empty( $this->statements ) ) {
276
-			return '';
277
-		}
278
-
279
-		return sprintf( $this->template, implode( ' . ', $this->statements ) ) . "\n";
280
-	}
281
-
282
-	/**
283
-	 * Guess the statement object type.
284
-	 *
285
-	 * @since 3.1.7
286
-	 *
287
-	 * @param string $predicate The predicate.
288
-	 * @param string $object    The object.
289
-	 *
290
-	 * @return int {@link Wordlift_Query_Builder::OBJECT_URI} if the Query builder thinks the object must be an URI, {@link Wordlift_Query_Builder::OBJECT_VALUE} otherwise.
291
-	 */
292
-	private function guess_object_type( $predicate, $object ) {
293
-
294
-		// If the object starts with a question mark, it's a parameter.
295
-		if ( 0 === strpos( $object, '?' ) ) {
296
-			return self::OBJECT_PARAMETER;
297
-		}
298
-
299
-		// Guess based on the predicate.
300
-		switch ( $predicate ) {
301
-
302
-			case self::DCTERMS_REFERENCES_URI:
303
-			case self::DCTERMS_SUBJECT_URI:
304
-			case self::RDFS_TYPE_URI:
305
-			case self::SCHEMA_AUTHOR_URI:
306
-			case self::SCHEMA_LOCATION_CREATED_URI:
307
-			case self::SCHEMA_URL_URI:
308
-			case self::SCHEMA_IMAGE_URI:
309
-				return self::OBJECT_URI;
310
-
311
-		}
312
-
313
-		return self::OBJECT_VALUE;
314
-	}
315
-
316
-	/**
317
-	 * Guess the subject type.
318
-	 *
319
-	 * @since 3.12.3
320
-	 *
321
-	 * @param string $subject The subject string.
322
-	 *
323
-	 * @return int {@link Wordlift_Query_Builder::OBJECT_PARAMETER} if the Query builder thinks the subject is a parameter (starts with ?), otherwise {@link Wordlift_Query_Builder::OBJECT_URI}.
324
-	 */
325
-	private function guess_subject_type( $subject ) {
326
-
327
-		// If the object starts with a question mark, it's a parameter.
328
-		if ( 0 === strpos( $subject, '?' ) ) {
329
-			return self::OBJECT_PARAMETER;
330
-		}
331
-
332
-		return self::OBJECT_URI;
333
-	}
10
+    /**
11
+     * The INSERT statement template.
12
+     *
13
+     * @since 3.1.7
14
+     */
15
+    const INSERT = 'INSERT DATA { %s };';
16
+
17
+    /**
18
+     * The DELETE statement template (it repeats the statements in the WHERE clause.
19
+     *
20
+     * @since 3.1.7
21
+     */
22
+    const DELETE = 'DELETE { %s } WHERE { %1$s };';
23
+
24
+    /**
25
+     * Tell the statement function to guess the object type (URI, value or parameter).
26
+     *
27
+     * @since 3.1.7
28
+     */
29
+    const OBJECT_AUTO = - 1;
30
+
31
+    /**
32
+     * Tell the statement function that the object is a URI.
33
+     *
34
+     * @since 3.1.7
35
+     */
36
+    const OBJECT_URI = 0;
37
+
38
+    /**
39
+     * Tell the statement function that the object is a value.
40
+     *
41
+     * @since 3.1.7
42
+     */
43
+    const OBJECT_VALUE = 1;
44
+
45
+    /**
46
+     * Tell the statement function that the object is a parameter.
47
+     *
48
+     * @since 3.1.7
49
+     */
50
+    const OBJECT_PARAMETER = 2;
51
+
52
+    /**
53
+     * The RDFS type.
54
+     *
55
+     * @since 3.1.7
56
+     */
57
+    const RDFS_TYPE_URI = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
58
+
59
+    /**
60
+     * The schema.org/Person type.
61
+     *
62
+     * @since 3.1.7
63
+     */
64
+    const SCHEMA_PERSON_URI = 'http://schema.org/Person';
65
+
66
+    /**
67
+     * The schema.org given name predicate.
68
+     *
69
+     * @since 3.1.7
70
+     */
71
+    const SCHEMA_GIVEN_NAME_URI = 'http://schema.org/givenName';
72
+
73
+    /**
74
+     * The schema.org family name predicate.
75
+     *
76
+     * @since 3.1.7
77
+     */
78
+    const SCHEMA_FAMILY_NAME_URI = 'http://schema.org/familyName';
79
+
80
+    /**
81
+     * The schema.org url predicate.
82
+     *
83
+     * @since 3.1.7
84
+     */
85
+    const SCHEMA_URL_URI = 'http://schema.org/url';
86
+
87
+    /**
88
+     * @since 3.14.0
89
+     */
90
+    const SCHEMA_IMAGE_URI = 'http://schema.org/image';
91
+
92
+    /**
93
+     * The location created predicate.
94
+     *
95
+     * @since 3.14.0
96
+     */
97
+    const SCHEMA_LOCATION_CREATED_URI = 'http://schema.org/locationCreated';
98
+
99
+    /**
100
+     * @since 3.14.0
101
+     */
102
+    const SCHEMA_AUTHOR_URI = 'http://schema.org/author';
103
+
104
+    /**
105
+     * @since 3.14.0
106
+     */
107
+    const SCHEMA_INTERACTION_COUNT_URI = 'http://schema.org/interactionCount';
108
+
109
+    /**
110
+     * @since 3.14.0
111
+     */
112
+    const DCTERMS_SUBJECT_URI = 'http://purl.org/dc/terms/subject';
113
+
114
+    /**
115
+     * @since 3.14.0
116
+     */
117
+    const DCTERMS_REFERENCES_URI = 'http://purl.org/dc/terms/references';
118
+
119
+    /**
120
+     * @since 3.15.0
121
+     */
122
+    const DCTERMS_RELATION_URI = 'http://purl.org/dc/terms/relation';
123
+
124
+    /**
125
+     * The RDF label.
126
+     *
127
+     * @since 3.1.7
128
+     */
129
+    const RDFS_LABEL_URI = 'http://www.w3.org/2000/01/rdf-schema#label';
130
+
131
+    /**
132
+     * The schema.org `streetAddress` property.
133
+     *
134
+     * @since 3.18.0
135
+     */
136
+    const SCHEMA_STREET_ADDRESS = 'http://schema.org/streetAddress';
137
+
138
+    /**
139
+     * The schema.org headline.
140
+     *
141
+     * @since 3.18.0
142
+     */
143
+    const SCHEMA_HEADLINE_URI = 'http://schema.org/headline';
144
+
145
+    /**
146
+     * Hold the template (INSERT or DELETE).
147
+     *
148
+     * @since  3.1.7
149
+     * @access private
150
+     * @var string $template The query template.
151
+     */
152
+    private $template;
153
+
154
+    /**
155
+     * An array of statements (in the form of subject, predicate, object).
156
+     *
157
+     * @since  3.1.7
158
+     * @access private
159
+     * @var array $statements An array of statements.
160
+     */
161
+    private $statements = array();
162
+
163
+    /**
164
+     * Create a new instance of the Query builder (compatible with PHP 5.3).
165
+     *
166
+     * @since 3.1.7
167
+     * @return Wordlift_Query_Builder A new instance of the Query builder.
168
+     */
169
+    public static function new_instance() {
170
+
171
+        return new Wordlift_Query_Builder();
172
+    }
173
+
174
+    /**
175
+     * Set the query to INSERT.
176
+     *
177
+     * @since 3.1.7
178
+     * @return Wordlift_Query_Builder The Query builder.
179
+     */
180
+    public function insert() {
181
+
182
+        $this->template = self::INSERT;
183
+
184
+        return $this;
185
+    }
186
+
187
+    /**
188
+     * Set the query to DELETE.
189
+     *
190
+     * @since 3.1.7
191
+     * @return $this \Wordlift_Query_Builder The Query builder.
192
+     */
193
+    public function delete() {
194
+
195
+        $this->template = self::DELETE;
196
+
197
+        return $this;
198
+    }
199
+
200
+    /**
201
+     * Set the query to SELECT.
202
+     *
203
+     * @since 3.12.2
204
+     *
205
+     * @param string $props The list of properties to read.
206
+     *
207
+     * @return $this \Wordlift_Query_Builder The Query builder.
208
+     */
209
+    public function select( $props = '*' ) {
210
+
211
+        $this->template = "SELECT $props WHERE { %s }";
212
+
213
+        return $this;
214
+    }
215
+
216
+    /**
217
+     * Add a statement.
218
+     *
219
+     * @since 3.1.7
220
+     *
221
+     * @param string      $subject     The subject of the statement (must be a URI).
222
+     * @param string      $predicate   The predicate (must be a URI).
223
+     * @param string      $object      The object, can be a URI or a value.
224
+     * @param int         $object_type The object type, either a {@link OBJECT_URI} or a value {@link OBJECT_VALUE}. If set to {@link OBJECT_AUTO}, the Query builder will try to guess.
225
+     * @param string|null $data_type   The data type (or null).
226
+     * @param string|null $language    The language code (or null).
227
+     *
228
+     * @return $this \Wordlift_Query_Builder The Query builder.
229
+     */
230
+    public function statement( $subject, $predicate, $object, $object_type = self::OBJECT_AUTO, $data_type = null, $language = null ) {
231
+
232
+        // If no value has been provided, we don't set any statement.
233
+        if ( empty( $object ) ) {
234
+            return $this;
235
+        }
236
+
237
+        // Guess the subject type.
238
+        $subject_value_type = $this->guess_subject_type( $subject );
239
+
240
+        // Get the object type if set, otherwise try to guess it.
241
+        $object_value_type = ( self::OBJECT_AUTO === $object_type ? $this->guess_object_type( $predicate, $object ) : $object_type );
242
+
243
+        // Prepare the statement template.
244
+        $template =
245
+            // Subject as a parameter, no `<`, `>`.
246
+            ( self::OBJECT_PARAMETER === $subject_value_type ? '%1$s' : '<%1$s>' ) .
247
+            // Predicate.
248
+            ' <%2$s> ' .
249
+            // Object.
250
+            ( self::OBJECT_URI === $object_value_type ? '<%3$s>' :
251
+                ( self::OBJECT_PARAMETER === $object_value_type ? '%3$s' :
252
+                    // self::OBJECT_VALUE === $object_value_type
253
+                    '"%3$s"' . ( isset( $data_type ) ? '^^%4$s' : '' ) . ( isset( $language ) ? '@%5$s' : '' ) ) );
254
+
255
+        // Escape the subject, predicate and object.
256
+        $escaped_subject   = Wordlift_Sparql_Service::escape_uri( $subject );
257
+        $escaped_predicate = Wordlift_Sparql_Service::escape_uri( $predicate );
258
+        $escaped_object    = ( self::OBJECT_URI === $object_value_type ? Wordlift_Sparql_Service::escape_uri( $object ) : Wordlift_Sparql_Service::escape( $object ) );
259
+
260
+        // Prepare the statement and add it to the list of statements.
261
+        $this->statements[] = sprintf( $template, $escaped_subject, $escaped_predicate, $escaped_object, $data_type, $language );
262
+
263
+        return $this;
264
+    }
265
+
266
+    /**
267
+     * Build the query.
268
+     *
269
+     * @since 3.1.7
270
+     * @return string The query string.
271
+     */
272
+    public function build() {
273
+
274
+        // If there are no statements return an empty string.
275
+        if ( empty( $this->statements ) ) {
276
+            return '';
277
+        }
278
+
279
+        return sprintf( $this->template, implode( ' . ', $this->statements ) ) . "\n";
280
+    }
281
+
282
+    /**
283
+     * Guess the statement object type.
284
+     *
285
+     * @since 3.1.7
286
+     *
287
+     * @param string $predicate The predicate.
288
+     * @param string $object    The object.
289
+     *
290
+     * @return int {@link Wordlift_Query_Builder::OBJECT_URI} if the Query builder thinks the object must be an URI, {@link Wordlift_Query_Builder::OBJECT_VALUE} otherwise.
291
+     */
292
+    private function guess_object_type( $predicate, $object ) {
293
+
294
+        // If the object starts with a question mark, it's a parameter.
295
+        if ( 0 === strpos( $object, '?' ) ) {
296
+            return self::OBJECT_PARAMETER;
297
+        }
298
+
299
+        // Guess based on the predicate.
300
+        switch ( $predicate ) {
301
+
302
+            case self::DCTERMS_REFERENCES_URI:
303
+            case self::DCTERMS_SUBJECT_URI:
304
+            case self::RDFS_TYPE_URI:
305
+            case self::SCHEMA_AUTHOR_URI:
306
+            case self::SCHEMA_LOCATION_CREATED_URI:
307
+            case self::SCHEMA_URL_URI:
308
+            case self::SCHEMA_IMAGE_URI:
309
+                return self::OBJECT_URI;
310
+
311
+        }
312
+
313
+        return self::OBJECT_VALUE;
314
+    }
315
+
316
+    /**
317
+     * Guess the subject type.
318
+     *
319
+     * @since 3.12.3
320
+     *
321
+     * @param string $subject The subject string.
322
+     *
323
+     * @return int {@link Wordlift_Query_Builder::OBJECT_PARAMETER} if the Query builder thinks the subject is a parameter (starts with ?), otherwise {@link Wordlift_Query_Builder::OBJECT_URI}.
324
+     */
325
+    private function guess_subject_type( $subject ) {
326
+
327
+        // If the object starts with a question mark, it's a parameter.
328
+        if ( 0 === strpos( $subject, '?' ) ) {
329
+            return self::OBJECT_PARAMETER;
330
+        }
331
+
332
+        return self::OBJECT_URI;
333
+    }
334 334
 
335 335
 }
Please login to merge, or discard this patch.