Completed
Pull Request — master (#1641)
by Naveen
01:35
created
src/includes/cache/intf-wordlift-cache-service.php 2 patches
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -17,52 +17,52 @@
 block discarded – undo
17 17
  */
18 18
 interface Wordlift_Cache_Service {
19 19
 
20
-	/**
21
-	 * Get the cached response for the specified `id`.
22
-	 *
23
-	 * @since 3.16.0
24
-	 *
25
-	 * @param string $id The cache `id`.
26
-	 *
27
-	 * @return mixed|false The cached contents or false if the cache isn't found.
28
-	 */
29
-	public function get_cache( $id );
20
+    /**
21
+     * Get the cached response for the specified `id`.
22
+     *
23
+     * @since 3.16.0
24
+     *
25
+     * @param string $id The cache `id`.
26
+     *
27
+     * @return mixed|false The cached contents or false if the cache isn't found.
28
+     */
29
+    public function get_cache( $id );
30 30
 
31
-	/**
32
-	 * Check whether we have cached results for the provided id.
33
-	 *
34
-	 * @since 3.16.3
35
-	 *
36
-	 * @param string $id The cache `id`.
37
-	 *
38
-	 * @return bool True if we have cached results otherwise false.
39
-	 */
40
-	public function has_cache( $id );
31
+    /**
32
+     * Check whether we have cached results for the provided id.
33
+     *
34
+     * @since 3.16.3
35
+     *
36
+     * @param string $id The cache `id`.
37
+     *
38
+     * @return bool True if we have cached results otherwise false.
39
+     */
40
+    public function has_cache( $id );
41 41
 
42
-	/**
43
-	 * Set the cache contents for the specified `id`.
44
-	 *
45
-	 * @since 3.16.0
46
-	 *
47
-	 * @param string $id       The cache id.
48
-	 * @param mixed  $contents The cache contents.
49
-	 */
50
-	public function set_cache( $id, $contents );
42
+    /**
43
+     * Set the cache contents for the specified `id`.
44
+     *
45
+     * @since 3.16.0
46
+     *
47
+     * @param string $id       The cache id.
48
+     * @param mixed  $contents The cache contents.
49
+     */
50
+    public function set_cache( $id, $contents );
51 51
 
52
-	/**
53
-	 * Delete the cache for the specified `id`.
54
-	 *
55
-	 * @since 3.16.0
56
-	 *
57
-	 * @param string $id The cache `id`.
58
-	 */
59
-	public function delete_cache( $id );
52
+    /**
53
+     * Delete the cache for the specified `id`.
54
+     *
55
+     * @since 3.16.0
56
+     *
57
+     * @param string $id The cache `id`.
58
+     */
59
+    public function delete_cache( $id );
60 60
 
61
-	/**
62
-	 * Flush the whole cache.
63
-	 *
64
-	 * @since 3.16.0
65
-	 */
66
-	public function flush();
61
+    /**
62
+     * Flush the whole cache.
63
+     *
64
+     * @since 3.16.0
65
+     */
66
+    public function flush();
67 67
 
68 68
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -26,7 +26,7 @@  discard block
 block discarded – undo
26 26
 	 *
27 27
 	 * @return mixed|false The cached contents or false if the cache isn't found.
28 28
 	 */
29
-	public function get_cache( $id );
29
+	public function get_cache($id);
30 30
 
31 31
 	/**
32 32
 	 * Check whether we have cached results for the provided id.
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
 	 *
38 38
 	 * @return bool True if we have cached results otherwise false.
39 39
 	 */
40
-	public function has_cache( $id );
40
+	public function has_cache($id);
41 41
 
42 42
 	/**
43 43
 	 * Set the cache contents for the specified `id`.
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
 	 * @param string $id       The cache id.
48 48
 	 * @param mixed  $contents The cache contents.
49 49
 	 */
50
-	public function set_cache( $id, $contents );
50
+	public function set_cache($id, $contents);
51 51
 
52 52
 	/**
53 53
 	 * Delete the cache for the specified `id`.
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 	 *
57 57
 	 * @param string $id The cache `id`.
58 58
 	 */
59
-	public function delete_cache( $id );
59
+	public function delete_cache($id);
60 60
 
61 61
 	/**
62 62
 	 * Flush the whole cache.
Please login to merge, or discard this patch.
src/includes/cache/require.php 1 patch
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@
 block discarded – undo
8 8
  * @package    Wordlift
9 9
  * @subpackage Wordlift/includes/cache
10 10
  */
11
-require_once plugin_dir_path( dirname( __DIR__ ) ) . 'includes/cache/intf-wordlift-cache-service.php';
12
-require_once plugin_dir_path( dirname( __DIR__ ) ) . 'includes/cache/class-wordlift-file-cache-service.php';
13
-require_once plugin_dir_path( dirname( __DIR__ ) ) . 'includes/cache/class-wordlift-cached-post-converter.php';
14
-require_once plugin_dir_path( dirname( __DIR__ ) ) . 'includes/cache/class-wordlift-cached-entity-uri-service.php';
11
+require_once plugin_dir_path(dirname(__DIR__)).'includes/cache/intf-wordlift-cache-service.php';
12
+require_once plugin_dir_path(dirname(__DIR__)).'includes/cache/class-wordlift-file-cache-service.php';
13
+require_once plugin_dir_path(dirname(__DIR__)).'includes/cache/class-wordlift-cached-post-converter.php';
14
+require_once plugin_dir_path(dirname(__DIR__)).'includes/cache/class-wordlift-cached-entity-uri-service.php';
Please login to merge, or discard this patch.
src/includes/cache/class-wordlift-cached-entity-uri-service.php 2 patches
Indentation   +198 added lines, -198 removed lines patch added patch discarded remove patch
@@ -14,203 +14,203 @@
 block discarded – undo
14 14
  */
15 15
 class Wordlift_Cached_Entity_Uri_Service extends Wordlift_Entity_Uri_Service {
16 16
 
17
-	/**
18
-	 * The {@link Wordlift_Cache_Service} instance.
19
-	 *
20
-	 * @since  3.16.3
21
-	 * @access private
22
-	 * @var \Wordlift_Cache_Service $cache_service The {@link Wordlift_Cache_Service} instance.
23
-	 */
24
-	private $cache_service;
25
-
26
-	/**
27
-	 * A {@link Wordlift_Log_Service} instance.
28
-	 *
29
-	 * @since  3.16.3
30
-	 * @access private
31
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
32
-	 */
33
-	private $log;
34
-
35
-	/**
36
-	 * Create a {@link Wordlift_Cached_Entity_Uri_Service} instance.
37
-	 *
38
-	 * @param \Wordlift_Cache_Service $cache_service
39
-	 *
40
-	 * @since 3.16.3
41
-	 */
42
-	public function __construct( $cache_service ) {
43
-		parent::__construct();
44
-
45
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
46
-
47
-		// Add hooks for meta being added/modified/deleted.
48
-		$this->cache_service = $cache_service;
49
-
50
-		add_action( 'add_post_meta', array( $this, 'on_before_post_meta_add' ), 10, 3 );
51
-		add_action( 'update_post_meta', array( $this, 'on_before_post_meta_change' ), 10, 4 );
52
-		add_action( 'delete_post_meta', array( $this, 'on_before_post_meta_change' ), 10, 4 );
53
-
54
-	}
55
-
56
-	/**
57
-	 * Preload the URIs.
58
-	 *
59
-	 * @param array $uris Preload an array of URIs.
60
-	 *
61
-	 * @since 3.16.3
62
-	 */
63
-	public function preload_uris( $uris ) {
64
-
65
-		// Filter the URIs which aren't yet cached.
66
-		$cache_service = $this->cache_service;
67
-		$uris_to_cache = array_filter(
68
-			(array) $uris,
69
-			function ( $item ) use ( $cache_service ) {
70
-				return ! $cache_service->has_cache( $item );
71
-			}
72
-		);
73
-
74
-		// Preload the URIs.
75
-		parent::preload_uris( $uris_to_cache );
76
-
77
-		// Store them in cache.
78
-		if ( is_array( $this->uri_to_post ) && ! empty( $this->uri_to_post ) ) {
79
-			foreach ( $this->uri_to_post as $uri => $post_id ) {
80
-				$this->set_cache( $uri, $post_id );
81
-			}
82
-		}
83
-
84
-	}
85
-
86
-	/**
87
-	 * Get the entity post for the specified URI.
88
-	 *
89
-	 * @param string $uri The URI.
90
-	 *
91
-	 * @return null|WP_Post The {@link WP_Post} or null if not found.
92
-	 * @since 3.16.3
93
-	 */
94
-	public function get_entity( $uri ) {
95
-
96
-		$this->log->trace( "Getting entity for uri $uri..." );
97
-
98
-		// Get the cached post for the specified URI.
99
-		$cache = $this->cache_service->get_cache( $uri );
100
-
101
-		// Return the cached data if valid.
102
-		if ( false !== $cache && is_numeric( $cache ) ) {
103
-			$this->log->debug( "Cached entity $cache for uri $uri found." );
104
-
105
-			return get_post( $cache );
106
-		}
107
-
108
-		// Get the actual result.
109
-		$post = parent::get_entity( $uri );
110
-
111
-		// Cache the result.
112
-		if ( null !== $post ) {
113
-			$this->set_cache( $uri, $post->ID );
114
-		}
115
-
116
-		// Return the result.
117
-		return $post;
118
-	}
119
-
120
-	/**
121
-	 * Set the cached URI for the specified {@link WP_Post}.
122
-	 *
123
-	 * @param string $uri The URI.
124
-	 * @param int    $post_id The post ID.
125
-	 *
126
-	 * @since 3.16.3
127
-	 * @since 3.29.0 takes a post ID as input.
128
-	 */
129
-	private function set_cache( $uri, $post_id ) {
130
-
131
-		// Cache the result.
132
-		$this->cache_service->set_cache( $uri, $post_id );
133
-
134
-	}
135
-
136
-	/**
137
-	 * Delete the cache for the specified URIs.
138
-	 *
139
-	 * @param array $uris An array of URIs.
140
-	 *
141
-	 * @since 3.16.3
142
-	 */
143
-	private function delete_cache( $uris ) {
144
-
145
-		// Delete the cache for each URI.
146
-		foreach ( $uris as $uri ) {
147
-			// Delete the single cache file.
148
-			$this->cache_service->delete_cache( $uri );
149
-		}
150
-
151
-	}
152
-
153
-	/**
154
-	 * Before post meta change.
155
-	 *
156
-	 * When a post meta is going to be changed, we check if the `meta_key` is
157
-	 * either the `entity_url` or the `same_as` in which case we delete the cache
158
-	 * for all the associated URIs.
159
-	 *
160
-	 * @param int|array $meta_ids The {@link WP_Post} meta id(s).
161
-	 * @param int       $post_id The {@link WP_Post} id.
162
-	 * @param string    $meta_key The meta key.
163
-	 * @param mixed     $meta_value The meta value(s).
164
-	 *
165
-	 * @since 3.16.3
166
-	 */
167
-	public function on_before_post_meta_change( $meta_ids, $post_id, $meta_key, $meta_value ) {
168
-
169
-		// Bail out if we're not interested in the meta key.
170
-		if ( WL_ENTITY_URL_META_NAME !== $meta_key && Wordlift_Schema_Service::FIELD_SAME_AS !== $meta_key ) {
171
-			return;
172
-		}
173
-
174
-		$this->log->trace( "Updating/deleting $meta_key for post $post_id ($meta_key), invalidating cache..." );
175
-
176
-		// The list of existing URIs, plus the list of URIs being deleted/updated.
177
-		$old_value = get_post_meta( $post_id, $meta_key );
178
-
179
-		// We expect an array here from the `get_post_meta` signature. However `get_post_meta` is prone to side effects
180
-		// because of filters. So if it's not we return an empty array.
181
-		if ( ! is_array( $old_value ) ) {
182
-			$old_value = array();
183
-		}
184
-		$new_value = isset( $meta_value ) ? (array) $meta_value : array();
185
-		$uris      = array_merge( $old_value, $new_value );
186
-
187
-		// Delete the cache for those URIs.
188
-		$this->delete_cache( $uris );
189
-
190
-	}
191
-
192
-	/**
193
-	 * Hook to meta add for a {@link WP_Post}, will cause the cache to
194
-	 * invalidate.
195
-	 *
196
-	 * @param int    $post_id The {@link WP_Post} id.
197
-	 * @param string $meta_key The meta key.
198
-	 * @param mixed  $meta_value The meta value(s).
199
-	 *
200
-	 * @since 3.16.3
201
-	 */
202
-	public function on_before_post_meta_add( $post_id, $meta_key, $meta_value ) {
203
-
204
-		// Bail out if we're not interested in the meta key.
205
-		if ( WL_ENTITY_URL_META_NAME !== $meta_key && Wordlift_Schema_Service::FIELD_SAME_AS !== $meta_key ) {
206
-			return;
207
-		}
208
-
209
-		$this->log->trace( "Adding $meta_key for post $post_id ($meta_key), invalidating cache..." );
210
-
211
-		// Delete the cache for the URIs being added.
212
-		$this->delete_cache( (array) $meta_value );
213
-
214
-	}
17
+    /**
18
+     * The {@link Wordlift_Cache_Service} instance.
19
+     *
20
+     * @since  3.16.3
21
+     * @access private
22
+     * @var \Wordlift_Cache_Service $cache_service The {@link Wordlift_Cache_Service} instance.
23
+     */
24
+    private $cache_service;
25
+
26
+    /**
27
+     * A {@link Wordlift_Log_Service} instance.
28
+     *
29
+     * @since  3.16.3
30
+     * @access private
31
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
32
+     */
33
+    private $log;
34
+
35
+    /**
36
+     * Create a {@link Wordlift_Cached_Entity_Uri_Service} instance.
37
+     *
38
+     * @param \Wordlift_Cache_Service $cache_service
39
+     *
40
+     * @since 3.16.3
41
+     */
42
+    public function __construct( $cache_service ) {
43
+        parent::__construct();
44
+
45
+        $this->log = Wordlift_Log_Service::get_logger( get_class() );
46
+
47
+        // Add hooks for meta being added/modified/deleted.
48
+        $this->cache_service = $cache_service;
49
+
50
+        add_action( 'add_post_meta', array( $this, 'on_before_post_meta_add' ), 10, 3 );
51
+        add_action( 'update_post_meta', array( $this, 'on_before_post_meta_change' ), 10, 4 );
52
+        add_action( 'delete_post_meta', array( $this, 'on_before_post_meta_change' ), 10, 4 );
53
+
54
+    }
55
+
56
+    /**
57
+     * Preload the URIs.
58
+     *
59
+     * @param array $uris Preload an array of URIs.
60
+     *
61
+     * @since 3.16.3
62
+     */
63
+    public function preload_uris( $uris ) {
64
+
65
+        // Filter the URIs which aren't yet cached.
66
+        $cache_service = $this->cache_service;
67
+        $uris_to_cache = array_filter(
68
+            (array) $uris,
69
+            function ( $item ) use ( $cache_service ) {
70
+                return ! $cache_service->has_cache( $item );
71
+            }
72
+        );
73
+
74
+        // Preload the URIs.
75
+        parent::preload_uris( $uris_to_cache );
76
+
77
+        // Store them in cache.
78
+        if ( is_array( $this->uri_to_post ) && ! empty( $this->uri_to_post ) ) {
79
+            foreach ( $this->uri_to_post as $uri => $post_id ) {
80
+                $this->set_cache( $uri, $post_id );
81
+            }
82
+        }
83
+
84
+    }
85
+
86
+    /**
87
+     * Get the entity post for the specified URI.
88
+     *
89
+     * @param string $uri The URI.
90
+     *
91
+     * @return null|WP_Post The {@link WP_Post} or null if not found.
92
+     * @since 3.16.3
93
+     */
94
+    public function get_entity( $uri ) {
95
+
96
+        $this->log->trace( "Getting entity for uri $uri..." );
97
+
98
+        // Get the cached post for the specified URI.
99
+        $cache = $this->cache_service->get_cache( $uri );
100
+
101
+        // Return the cached data if valid.
102
+        if ( false !== $cache && is_numeric( $cache ) ) {
103
+            $this->log->debug( "Cached entity $cache for uri $uri found." );
104
+
105
+            return get_post( $cache );
106
+        }
107
+
108
+        // Get the actual result.
109
+        $post = parent::get_entity( $uri );
110
+
111
+        // Cache the result.
112
+        if ( null !== $post ) {
113
+            $this->set_cache( $uri, $post->ID );
114
+        }
115
+
116
+        // Return the result.
117
+        return $post;
118
+    }
119
+
120
+    /**
121
+     * Set the cached URI for the specified {@link WP_Post}.
122
+     *
123
+     * @param string $uri The URI.
124
+     * @param int    $post_id The post ID.
125
+     *
126
+     * @since 3.16.3
127
+     * @since 3.29.0 takes a post ID as input.
128
+     */
129
+    private function set_cache( $uri, $post_id ) {
130
+
131
+        // Cache the result.
132
+        $this->cache_service->set_cache( $uri, $post_id );
133
+
134
+    }
135
+
136
+    /**
137
+     * Delete the cache for the specified URIs.
138
+     *
139
+     * @param array $uris An array of URIs.
140
+     *
141
+     * @since 3.16.3
142
+     */
143
+    private function delete_cache( $uris ) {
144
+
145
+        // Delete the cache for each URI.
146
+        foreach ( $uris as $uri ) {
147
+            // Delete the single cache file.
148
+            $this->cache_service->delete_cache( $uri );
149
+        }
150
+
151
+    }
152
+
153
+    /**
154
+     * Before post meta change.
155
+     *
156
+     * When a post meta is going to be changed, we check if the `meta_key` is
157
+     * either the `entity_url` or the `same_as` in which case we delete the cache
158
+     * for all the associated URIs.
159
+     *
160
+     * @param int|array $meta_ids The {@link WP_Post} meta id(s).
161
+     * @param int       $post_id The {@link WP_Post} id.
162
+     * @param string    $meta_key The meta key.
163
+     * @param mixed     $meta_value The meta value(s).
164
+     *
165
+     * @since 3.16.3
166
+     */
167
+    public function on_before_post_meta_change( $meta_ids, $post_id, $meta_key, $meta_value ) {
168
+
169
+        // Bail out if we're not interested in the meta key.
170
+        if ( WL_ENTITY_URL_META_NAME !== $meta_key && Wordlift_Schema_Service::FIELD_SAME_AS !== $meta_key ) {
171
+            return;
172
+        }
173
+
174
+        $this->log->trace( "Updating/deleting $meta_key for post $post_id ($meta_key), invalidating cache..." );
175
+
176
+        // The list of existing URIs, plus the list of URIs being deleted/updated.
177
+        $old_value = get_post_meta( $post_id, $meta_key );
178
+
179
+        // We expect an array here from the `get_post_meta` signature. However `get_post_meta` is prone to side effects
180
+        // because of filters. So if it's not we return an empty array.
181
+        if ( ! is_array( $old_value ) ) {
182
+            $old_value = array();
183
+        }
184
+        $new_value = isset( $meta_value ) ? (array) $meta_value : array();
185
+        $uris      = array_merge( $old_value, $new_value );
186
+
187
+        // Delete the cache for those URIs.
188
+        $this->delete_cache( $uris );
189
+
190
+    }
191
+
192
+    /**
193
+     * Hook to meta add for a {@link WP_Post}, will cause the cache to
194
+     * invalidate.
195
+     *
196
+     * @param int    $post_id The {@link WP_Post} id.
197
+     * @param string $meta_key The meta key.
198
+     * @param mixed  $meta_value The meta value(s).
199
+     *
200
+     * @since 3.16.3
201
+     */
202
+    public function on_before_post_meta_add( $post_id, $meta_key, $meta_value ) {
203
+
204
+        // Bail out if we're not interested in the meta key.
205
+        if ( WL_ENTITY_URL_META_NAME !== $meta_key && Wordlift_Schema_Service::FIELD_SAME_AS !== $meta_key ) {
206
+            return;
207
+        }
208
+
209
+        $this->log->trace( "Adding $meta_key for post $post_id ($meta_key), invalidating cache..." );
210
+
211
+        // Delete the cache for the URIs being added.
212
+        $this->delete_cache( (array) $meta_value );
213
+
214
+    }
215 215
 
216 216
 }
Please login to merge, or discard this patch.
Spacing   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -39,17 +39,17 @@  discard block
 block discarded – undo
39 39
 	 *
40 40
 	 * @since 3.16.3
41 41
 	 */
42
-	public function __construct( $cache_service ) {
42
+	public function __construct($cache_service) {
43 43
 		parent::__construct();
44 44
 
45
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
45
+		$this->log = Wordlift_Log_Service::get_logger(get_class());
46 46
 
47 47
 		// Add hooks for meta being added/modified/deleted.
48 48
 		$this->cache_service = $cache_service;
49 49
 
50
-		add_action( 'add_post_meta', array( $this, 'on_before_post_meta_add' ), 10, 3 );
51
-		add_action( 'update_post_meta', array( $this, 'on_before_post_meta_change' ), 10, 4 );
52
-		add_action( 'delete_post_meta', array( $this, 'on_before_post_meta_change' ), 10, 4 );
50
+		add_action('add_post_meta', array($this, 'on_before_post_meta_add'), 10, 3);
51
+		add_action('update_post_meta', array($this, 'on_before_post_meta_change'), 10, 4);
52
+		add_action('delete_post_meta', array($this, 'on_before_post_meta_change'), 10, 4);
53 53
 
54 54
 	}
55 55
 
@@ -60,24 +60,24 @@  discard block
 block discarded – undo
60 60
 	 *
61 61
 	 * @since 3.16.3
62 62
 	 */
63
-	public function preload_uris( $uris ) {
63
+	public function preload_uris($uris) {
64 64
 
65 65
 		// Filter the URIs which aren't yet cached.
66 66
 		$cache_service = $this->cache_service;
67 67
 		$uris_to_cache = array_filter(
68 68
 			(array) $uris,
69
-			function ( $item ) use ( $cache_service ) {
70
-				return ! $cache_service->has_cache( $item );
69
+			function($item) use ($cache_service) {
70
+				return ! $cache_service->has_cache($item);
71 71
 			}
72 72
 		);
73 73
 
74 74
 		// Preload the URIs.
75
-		parent::preload_uris( $uris_to_cache );
75
+		parent::preload_uris($uris_to_cache);
76 76
 
77 77
 		// Store them in cache.
78
-		if ( is_array( $this->uri_to_post ) && ! empty( $this->uri_to_post ) ) {
79
-			foreach ( $this->uri_to_post as $uri => $post_id ) {
80
-				$this->set_cache( $uri, $post_id );
78
+		if (is_array($this->uri_to_post) && ! empty($this->uri_to_post)) {
79
+			foreach ($this->uri_to_post as $uri => $post_id) {
80
+				$this->set_cache($uri, $post_id);
81 81
 			}
82 82
 		}
83 83
 
@@ -91,26 +91,26 @@  discard block
 block discarded – undo
91 91
 	 * @return null|WP_Post The {@link WP_Post} or null if not found.
92 92
 	 * @since 3.16.3
93 93
 	 */
94
-	public function get_entity( $uri ) {
94
+	public function get_entity($uri) {
95 95
 
96
-		$this->log->trace( "Getting entity for uri $uri..." );
96
+		$this->log->trace("Getting entity for uri $uri...");
97 97
 
98 98
 		// Get the cached post for the specified URI.
99
-		$cache = $this->cache_service->get_cache( $uri );
99
+		$cache = $this->cache_service->get_cache($uri);
100 100
 
101 101
 		// Return the cached data if valid.
102
-		if ( false !== $cache && is_numeric( $cache ) ) {
103
-			$this->log->debug( "Cached entity $cache for uri $uri found." );
102
+		if (false !== $cache && is_numeric($cache)) {
103
+			$this->log->debug("Cached entity $cache for uri $uri found.");
104 104
 
105
-			return get_post( $cache );
105
+			return get_post($cache);
106 106
 		}
107 107
 
108 108
 		// Get the actual result.
109
-		$post = parent::get_entity( $uri );
109
+		$post = parent::get_entity($uri);
110 110
 
111 111
 		// Cache the result.
112
-		if ( null !== $post ) {
113
-			$this->set_cache( $uri, $post->ID );
112
+		if (null !== $post) {
113
+			$this->set_cache($uri, $post->ID);
114 114
 		}
115 115
 
116 116
 		// Return the result.
@@ -126,10 +126,10 @@  discard block
 block discarded – undo
126 126
 	 * @since 3.16.3
127 127
 	 * @since 3.29.0 takes a post ID as input.
128 128
 	 */
129
-	private function set_cache( $uri, $post_id ) {
129
+	private function set_cache($uri, $post_id) {
130 130
 
131 131
 		// Cache the result.
132
-		$this->cache_service->set_cache( $uri, $post_id );
132
+		$this->cache_service->set_cache($uri, $post_id);
133 133
 
134 134
 	}
135 135
 
@@ -140,12 +140,12 @@  discard block
 block discarded – undo
140 140
 	 *
141 141
 	 * @since 3.16.3
142 142
 	 */
143
-	private function delete_cache( $uris ) {
143
+	private function delete_cache($uris) {
144 144
 
145 145
 		// Delete the cache for each URI.
146
-		foreach ( $uris as $uri ) {
146
+		foreach ($uris as $uri) {
147 147
 			// Delete the single cache file.
148
-			$this->cache_service->delete_cache( $uri );
148
+			$this->cache_service->delete_cache($uri);
149 149
 		}
150 150
 
151 151
 	}
@@ -164,28 +164,28 @@  discard block
 block discarded – undo
164 164
 	 *
165 165
 	 * @since 3.16.3
166 166
 	 */
167
-	public function on_before_post_meta_change( $meta_ids, $post_id, $meta_key, $meta_value ) {
167
+	public function on_before_post_meta_change($meta_ids, $post_id, $meta_key, $meta_value) {
168 168
 
169 169
 		// Bail out if we're not interested in the meta key.
170
-		if ( WL_ENTITY_URL_META_NAME !== $meta_key && Wordlift_Schema_Service::FIELD_SAME_AS !== $meta_key ) {
170
+		if (WL_ENTITY_URL_META_NAME !== $meta_key && Wordlift_Schema_Service::FIELD_SAME_AS !== $meta_key) {
171 171
 			return;
172 172
 		}
173 173
 
174
-		$this->log->trace( "Updating/deleting $meta_key for post $post_id ($meta_key), invalidating cache..." );
174
+		$this->log->trace("Updating/deleting $meta_key for post $post_id ($meta_key), invalidating cache...");
175 175
 
176 176
 		// The list of existing URIs, plus the list of URIs being deleted/updated.
177
-		$old_value = get_post_meta( $post_id, $meta_key );
177
+		$old_value = get_post_meta($post_id, $meta_key);
178 178
 
179 179
 		// We expect an array here from the `get_post_meta` signature. However `get_post_meta` is prone to side effects
180 180
 		// because of filters. So if it's not we return an empty array.
181
-		if ( ! is_array( $old_value ) ) {
181
+		if ( ! is_array($old_value)) {
182 182
 			$old_value = array();
183 183
 		}
184
-		$new_value = isset( $meta_value ) ? (array) $meta_value : array();
185
-		$uris      = array_merge( $old_value, $new_value );
184
+		$new_value = isset($meta_value) ? (array) $meta_value : array();
185
+		$uris      = array_merge($old_value, $new_value);
186 186
 
187 187
 		// Delete the cache for those URIs.
188
-		$this->delete_cache( $uris );
188
+		$this->delete_cache($uris);
189 189
 
190 190
 	}
191 191
 
@@ -199,17 +199,17 @@  discard block
 block discarded – undo
199 199
 	 *
200 200
 	 * @since 3.16.3
201 201
 	 */
202
-	public function on_before_post_meta_add( $post_id, $meta_key, $meta_value ) {
202
+	public function on_before_post_meta_add($post_id, $meta_key, $meta_value) {
203 203
 
204 204
 		// Bail out if we're not interested in the meta key.
205
-		if ( WL_ENTITY_URL_META_NAME !== $meta_key && Wordlift_Schema_Service::FIELD_SAME_AS !== $meta_key ) {
205
+		if (WL_ENTITY_URL_META_NAME !== $meta_key && Wordlift_Schema_Service::FIELD_SAME_AS !== $meta_key) {
206 206
 			return;
207 207
 		}
208 208
 
209
-		$this->log->trace( "Adding $meta_key for post $post_id ($meta_key), invalidating cache..." );
209
+		$this->log->trace("Adding $meta_key for post $post_id ($meta_key), invalidating cache...");
210 210
 
211 211
 		// Delete the cache for the URIs being added.
212
-		$this->delete_cache( (array) $meta_value );
212
+		$this->delete_cache((array) $meta_value);
213 213
 
214 214
 	}
215 215
 
Please login to merge, or discard this patch.
src/includes/cache/class-wordlift-cached-post-converter.php 2 patches
Indentation   +349 added lines, -349 removed lines patch added patch discarded remove patch
@@ -21,354 +21,354 @@
 block discarded – undo
21 21
  */
22 22
 class Wordlift_Cached_Post_Converter implements Wordlift_Post_Converter {
23 23
 
24
-	/**
25
-	 * A {@link Wordlift_Post_Converter} instance.
26
-	 *
27
-	 * @since 3.16.0
28
-	 *
29
-	 * @var \Wordlift_Post_Converter $converter A {@link Wordlift_Post_Converter} instance.
30
-	 */
31
-	private $converter;
32
-
33
-	/**
34
-	 * A {@link Wordlift_Log_Service} instance.
35
-	 *
36
-	 * @since 3.16.0
37
-	 *
38
-	 * @var Wordlift_Log_Service \$log A {@link Wordlift_Log_Service} instance.
39
-	 */
40
-	private $log;
41
-
42
-	/**
43
-	 * A list of meta keys that do not cause the cache to update.
44
-	 *
45
-	 * @since 3.17.3
46
-	 * @var array An array of ignored meta keys.
47
-	 */
48
-	private static $ignored_meta_keys = array(
49
-		'_edit_lock',
50
-		'_edit_last',
51
-		'_wp_page_template',
52
-		'_wp_attachment_is_custom_background',
53
-		'_wp_attachment_backup_sizes',
54
-		'_wp_attachment_is_custom_header',
55
-	);
56
-	/**
57
-	 * @var Ttl_Cache
58
-	 */
59
-	private $cache;
60
-	/**
61
-	 * @var Reference_Processor
62
-	 */
63
-	private $reference_processor;
64
-
65
-	/**
66
-	 * Wordlift_Cached_Post_Converter constructor.
67
-	 *
68
-	 * @param \Wordlift_Post_Converter $converter The {@link Wordlift_Post_Converter} implementation.
69
-	 * @param Ttl_Cache                $cache The {@link Ttl_Cache} cache instance.
70
-	 */
71
-	public function __construct( $converter, $cache ) {
72
-
73
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
74
-
75
-		$this->cache               = $cache;
76
-		$this->converter           = $converter;
77
-		$this->reference_processor = Reference_Processor::get_instance();
78
-		$this->init_hooks();
79
-
80
-	}
81
-
82
-	/**
83
-	 * Hooks to catch post/post meta changes in order to invalidate the cache.
84
-	 *
85
-	 * @since 3.16.0
86
-	 */
87
-	private function init_hooks() {
88
-
89
-		// Hook on post save to flush relevant cache.
90
-		add_action( 'save_post', array( $this, 'save_post' ) );
91
-
92
-		add_action(
93
-			'added_post_meta',
94
-			array(
95
-				$this,
96
-				'changed_post_meta',
97
-			),
98
-			10,
99
-			3
100
-		);
101
-		add_action(
102
-			'updated_post_meta',
103
-			array(
104
-				$this,
105
-				'changed_post_meta',
106
-			),
107
-			10,
108
-			3
109
-		);
110
-		add_action(
111
-			'deleted_post_meta',
112
-			array(
113
-				$this,
114
-				'changed_post_meta',
115
-			),
116
-			10,
117
-			3
118
-		);
119
-
120
-		// Flush cache when wordlift settings were updated.
121
-		add_action(
122
-			'update_option_wl_general_settings',
123
-			array(
124
-				$this,
125
-				'update_option_wl_general_settings',
126
-			)
127
-		);
128
-
129
-		// Flushes the cache when permalink structure is changed.
130
-		add_action(
131
-			'update_option_permalink_structure',
132
-			array(
133
-				$this,
134
-				'permalinks_structure_changed',
135
-			)
136
-		);
137
-
138
-		// Invalid cache on relationship change.
139
-		add_action( 'wl_relation_added', array( $this, 'relation_changed' ) );
140
-		add_action( 'wl_relation_deleted', array( $this, 'relation_changed' ) );
141
-
142
-	}
143
-
144
-	/**
145
-	 * Note that the `&$cache` parameter here is used only to report whether the response comes from the cache. It
146
-	 * used by `test-issue-626.php` and nowhere else in code.
147
-	 *
148
-	 * @inheritdoc
149
-	 */
150
-	// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
151
-	public function convert( $post_id, &$references = array(), &$references_infos = array(), &$cache = false ) {
152
-
153
-		// Ensure post ID is `int`. Otherwise we may have issues with caching, since caching is strict about
154
-		// key var types.
155
-		$post_id = (int) $post_id;
156
-
157
-		$this->log->trace( "Converting post $post_id..." );
158
-
159
-		// Try to get a cached result.
160
-		$contents = $this->get_cache( $post_id, $references );
161
-
162
-		// Return the cached contents if any.
163
-		if ( false !== $contents ) {
164
-			$this->log->debug( "Cached contents found for post $post_id." );
165
-
166
-			// Inform the caller that this is cached result.
167
-			// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
168
-			$cache = true;
169
-			$this->add_http_header( $post_id, true );
170
-
171
-			// Return the contents.
172
-			return $contents;
173
-		}
174
-
175
-		// Set cached to false.
176
-		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
177
-		$cache = false;
178
-		$this->add_http_header( $post_id, false );
179
-
180
-		// Convert the post.
181
-		$jsonld = $this->converter->convert( $post_id, $references, $references_infos );
182
-
183
-		/**
184
-		 * @since 3.32.0
185
-		 * We cant apply json_encode on the objects {@link \Wordlift\Jsonld\Reference}, so we decode
186
-		 * it here before saving it on cache.
187
-		 */
188
-		// Cache the results.
189
-		$this->set_cache( $post_id, $references, $jsonld );
190
-
191
-		// Finally return the JSON-LD.
192
-		return $jsonld;
193
-	}
194
-
195
-	/**
196
-	 * Try to get the cached contents.
197
-	 *
198
-	 * @param int   $post_id The {@link WP_Post} id.
199
-	 * @param array $references The referenced posts.
200
-	 *
201
-	 * @return mixed|bool The cached contents or false if the cached isn't found.
202
-	 * @since 3.16.0
203
-	 */
204
-	// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
205
-	private function get_cache( $post_id, &$references = array() ) {
206
-
207
-		// Ensure post ID is int, because cache is strict about var types.
208
-		$post_id = (int) $post_id;
209
-
210
-		$this->log->trace( "Getting cached contents for post $post_id..." );
211
-
212
-		// Get the cache.
213
-		$contents = $this->cache->get( $post_id );
214
-
215
-		// Bail out if we don't have cached contents or the cached contents are
216
-		// invalid.
217
-		if ( null === $contents || ! isset( $contents['jsonld'] ) || ! isset( $contents['references'] ) ) {
218
-			$this->log->debug( "Cached contents for post $post_id not found." );
219
-
220
-			return false;
221
-		}
222
-
223
-		// Remap the cache.
224
-		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
225
-		$references = $this->reference_processor->deserialize_references( $contents['references'] );
226
-
227
-		return $contents['jsonld'];
228
-	}
229
-
230
-	/**
231
-	 * Set the cache with the provided results.
232
-	 *
233
-	 * The function will prepare the provided results and will ask the {@link Ttl_Cache} to cache them.
234
-	 *
235
-	 * @param int   $post_id The {@link WP_Post} id.
236
-	 * @param array $references An array of references.
237
-	 * @param array $jsonld A JSON-LD structure.
238
-	 *
239
-	 * @since 3.16.0
240
-	 */
241
-	private function set_cache( $post_id, $references, $jsonld ) {
242
-
243
-		$this->log->trace( "Caching result for post $post_id..." );
244
-
245
-		$this->cache->put(
246
-			$post_id,
247
-			array(
248
-				'references' => $this->reference_processor->serialize_references( $references ),
249
-				'jsonld'     => $jsonld,
250
-			)
251
-		);
252
-
253
-	}
254
-
255
-	/**
256
-	 * Hook to 'save_post', will invalidate the cache for that post.
257
-	 *
258
-	 * @param int $post_id The {@link WP_Post} id.
259
-	 *
260
-	 * @since 3.16.0
261
-	 */
262
-	public function save_post( $post_id ) {
263
-
264
-		$this->log->trace( "Post $post_id saved, invalidating cache..." );
265
-
266
-		$this->cache->delete( $post_id );
267
-
268
-		$this->flush_cache_if_publisher( $post_id );
269
-
270
-	}
271
-
272
-	/**
273
-	 * Hook to meta changed for a {@link WP_Post}, will cause the cause to
274
-	 * invalidate.
275
-	 *
276
-	 * @param int    $id The {@link WP_Post} meta id.
277
-	 * @param int    $post_id The {@link WP_Post} id.
278
-	 * @param string $meta_key The meta key.
279
-	 *
280
-	 * @since 3.16.0
281
-	 */
282
-	public function changed_post_meta( $id, $post_id, $meta_key ) {
283
-
284
-		if ( in_array( $meta_key, self::$ignored_meta_keys, true ) ) {
285
-			$this->log->trace( "Post $post_id meta $meta_key ignored." );
286
-
287
-			return;
288
-		}
289
-
290
-		$this->log->trace( "Post $post_id meta $meta_key changed, invalidating cache..." );
291
-
292
-		// Delete the single cache file.
293
-		$this->cache->delete( $post_id );
294
-
295
-		// Flush the cache if it's the publisher.
296
-		$this->flush_cache_if_publisher( $post_id );
297
-
298
-	}
299
-
300
-	/**
301
-	 * Hook to WordLift's options changes, will flush the cache.
302
-	 *
303
-	 * @since 3.16.0
304
-	 */
305
-	public function update_option_wl_general_settings() {
306
-		$this->log->trace( 'WordLift options changed, flushing cache...' );
307
-
308
-		$this->cache->flush();
309
-	}
310
-
311
-	/**
312
-	 * Hook when permalinks are changed, will flush the cache.
313
-	 *
314
-	 * @since 3.17.0
315
-	 */
316
-	public function permalinks_structure_changed() {
317
-		$this->log->trace( 'Permalinks structure changed, flushing cache...' );
318
-
319
-		$this->cache->flush();
320
-	}
321
-
322
-	/**
323
-	 * Hook to WordLift's post/entity relation changes, will invalidate the cache.
324
-	 *
325
-	 * @param int $post_id The {@link WP_Post} id.
326
-	 *
327
-	 * @since 3.16.0
328
-	 */
329
-	public function relation_changed( $post_id ) {
330
-		$this->log->trace( "Post $post_id relations changed, invalidating cache..." );
331
-
332
-		$this->cache->delete( $post_id );
333
-	}
334
-
335
-	/**
336
-	 * When in Ajax, prints an http header with the information whether the
337
-	 * response is cached or not.
338
-	 *
339
-	 * @param int  $post_id The {@link WP_Post} id.
340
-	 * @param bool $cache Whether the response fragment is cached.
341
-	 *
342
-	 * @since 3.16.0
343
-	 */
344
-	private function add_http_header( $post_id, $cache ) {
345
-
346
-		if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX || headers_sent() ) {
347
-			return;
348
-		}
349
-
350
-		header( "X-WordLift-JsonLd-Cache-$post_id: " . ( $cache ? 'HIT' : 'MISS' ) );
351
-
352
-	}
353
-
354
-	/**
355
-	 * Call the `flush` operation on the {@link Ttl_Cache} if
356
-	 * the publisher has changed.
357
-	 *
358
-	 * @param int $post_id The changed {@link WP_Post}'s id.
359
-	 *
360
-	 * @since 3.16.0
361
-	 */
362
-	private function flush_cache_if_publisher( $post_id ) {
363
-
364
-		// Bail out if it's not the publisher.
365
-		if ( Wordlift_Configuration_Service::get_instance()->get_publisher_id() !== $post_id ) {
366
-			return;
367
-		}
368
-
369
-		// Flush the cache, since the publisher has changed.
370
-		$this->cache->flush();
371
-
372
-	}
24
+    /**
25
+     * A {@link Wordlift_Post_Converter} instance.
26
+     *
27
+     * @since 3.16.0
28
+     *
29
+     * @var \Wordlift_Post_Converter $converter A {@link Wordlift_Post_Converter} instance.
30
+     */
31
+    private $converter;
32
+
33
+    /**
34
+     * A {@link Wordlift_Log_Service} instance.
35
+     *
36
+     * @since 3.16.0
37
+     *
38
+     * @var Wordlift_Log_Service \$log A {@link Wordlift_Log_Service} instance.
39
+     */
40
+    private $log;
41
+
42
+    /**
43
+     * A list of meta keys that do not cause the cache to update.
44
+     *
45
+     * @since 3.17.3
46
+     * @var array An array of ignored meta keys.
47
+     */
48
+    private static $ignored_meta_keys = array(
49
+        '_edit_lock',
50
+        '_edit_last',
51
+        '_wp_page_template',
52
+        '_wp_attachment_is_custom_background',
53
+        '_wp_attachment_backup_sizes',
54
+        '_wp_attachment_is_custom_header',
55
+    );
56
+    /**
57
+     * @var Ttl_Cache
58
+     */
59
+    private $cache;
60
+    /**
61
+     * @var Reference_Processor
62
+     */
63
+    private $reference_processor;
64
+
65
+    /**
66
+     * Wordlift_Cached_Post_Converter constructor.
67
+     *
68
+     * @param \Wordlift_Post_Converter $converter The {@link Wordlift_Post_Converter} implementation.
69
+     * @param Ttl_Cache                $cache The {@link Ttl_Cache} cache instance.
70
+     */
71
+    public function __construct( $converter, $cache ) {
72
+
73
+        $this->log = Wordlift_Log_Service::get_logger( get_class() );
74
+
75
+        $this->cache               = $cache;
76
+        $this->converter           = $converter;
77
+        $this->reference_processor = Reference_Processor::get_instance();
78
+        $this->init_hooks();
79
+
80
+    }
81
+
82
+    /**
83
+     * Hooks to catch post/post meta changes in order to invalidate the cache.
84
+     *
85
+     * @since 3.16.0
86
+     */
87
+    private function init_hooks() {
88
+
89
+        // Hook on post save to flush relevant cache.
90
+        add_action( 'save_post', array( $this, 'save_post' ) );
91
+
92
+        add_action(
93
+            'added_post_meta',
94
+            array(
95
+                $this,
96
+                'changed_post_meta',
97
+            ),
98
+            10,
99
+            3
100
+        );
101
+        add_action(
102
+            'updated_post_meta',
103
+            array(
104
+                $this,
105
+                'changed_post_meta',
106
+            ),
107
+            10,
108
+            3
109
+        );
110
+        add_action(
111
+            'deleted_post_meta',
112
+            array(
113
+                $this,
114
+                'changed_post_meta',
115
+            ),
116
+            10,
117
+            3
118
+        );
119
+
120
+        // Flush cache when wordlift settings were updated.
121
+        add_action(
122
+            'update_option_wl_general_settings',
123
+            array(
124
+                $this,
125
+                'update_option_wl_general_settings',
126
+            )
127
+        );
128
+
129
+        // Flushes the cache when permalink structure is changed.
130
+        add_action(
131
+            'update_option_permalink_structure',
132
+            array(
133
+                $this,
134
+                'permalinks_structure_changed',
135
+            )
136
+        );
137
+
138
+        // Invalid cache on relationship change.
139
+        add_action( 'wl_relation_added', array( $this, 'relation_changed' ) );
140
+        add_action( 'wl_relation_deleted', array( $this, 'relation_changed' ) );
141
+
142
+    }
143
+
144
+    /**
145
+     * Note that the `&$cache` parameter here is used only to report whether the response comes from the cache. It
146
+     * used by `test-issue-626.php` and nowhere else in code.
147
+     *
148
+     * @inheritdoc
149
+     */
150
+    // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
151
+    public function convert( $post_id, &$references = array(), &$references_infos = array(), &$cache = false ) {
152
+
153
+        // Ensure post ID is `int`. Otherwise we may have issues with caching, since caching is strict about
154
+        // key var types.
155
+        $post_id = (int) $post_id;
156
+
157
+        $this->log->trace( "Converting post $post_id..." );
158
+
159
+        // Try to get a cached result.
160
+        $contents = $this->get_cache( $post_id, $references );
161
+
162
+        // Return the cached contents if any.
163
+        if ( false !== $contents ) {
164
+            $this->log->debug( "Cached contents found for post $post_id." );
165
+
166
+            // Inform the caller that this is cached result.
167
+            // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
168
+            $cache = true;
169
+            $this->add_http_header( $post_id, true );
170
+
171
+            // Return the contents.
172
+            return $contents;
173
+        }
174
+
175
+        // Set cached to false.
176
+        // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
177
+        $cache = false;
178
+        $this->add_http_header( $post_id, false );
179
+
180
+        // Convert the post.
181
+        $jsonld = $this->converter->convert( $post_id, $references, $references_infos );
182
+
183
+        /**
184
+         * @since 3.32.0
185
+         * We cant apply json_encode on the objects {@link \Wordlift\Jsonld\Reference}, so we decode
186
+         * it here before saving it on cache.
187
+         */
188
+        // Cache the results.
189
+        $this->set_cache( $post_id, $references, $jsonld );
190
+
191
+        // Finally return the JSON-LD.
192
+        return $jsonld;
193
+    }
194
+
195
+    /**
196
+     * Try to get the cached contents.
197
+     *
198
+     * @param int   $post_id The {@link WP_Post} id.
199
+     * @param array $references The referenced posts.
200
+     *
201
+     * @return mixed|bool The cached contents or false if the cached isn't found.
202
+     * @since 3.16.0
203
+     */
204
+    // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
205
+    private function get_cache( $post_id, &$references = array() ) {
206
+
207
+        // Ensure post ID is int, because cache is strict about var types.
208
+        $post_id = (int) $post_id;
209
+
210
+        $this->log->trace( "Getting cached contents for post $post_id..." );
211
+
212
+        // Get the cache.
213
+        $contents = $this->cache->get( $post_id );
214
+
215
+        // Bail out if we don't have cached contents or the cached contents are
216
+        // invalid.
217
+        if ( null === $contents || ! isset( $contents['jsonld'] ) || ! isset( $contents['references'] ) ) {
218
+            $this->log->debug( "Cached contents for post $post_id not found." );
219
+
220
+            return false;
221
+        }
222
+
223
+        // Remap the cache.
224
+        // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
225
+        $references = $this->reference_processor->deserialize_references( $contents['references'] );
226
+
227
+        return $contents['jsonld'];
228
+    }
229
+
230
+    /**
231
+     * Set the cache with the provided results.
232
+     *
233
+     * The function will prepare the provided results and will ask the {@link Ttl_Cache} to cache them.
234
+     *
235
+     * @param int   $post_id The {@link WP_Post} id.
236
+     * @param array $references An array of references.
237
+     * @param array $jsonld A JSON-LD structure.
238
+     *
239
+     * @since 3.16.0
240
+     */
241
+    private function set_cache( $post_id, $references, $jsonld ) {
242
+
243
+        $this->log->trace( "Caching result for post $post_id..." );
244
+
245
+        $this->cache->put(
246
+            $post_id,
247
+            array(
248
+                'references' => $this->reference_processor->serialize_references( $references ),
249
+                'jsonld'     => $jsonld,
250
+            )
251
+        );
252
+
253
+    }
254
+
255
+    /**
256
+     * Hook to 'save_post', will invalidate the cache for that post.
257
+     *
258
+     * @param int $post_id The {@link WP_Post} id.
259
+     *
260
+     * @since 3.16.0
261
+     */
262
+    public function save_post( $post_id ) {
263
+
264
+        $this->log->trace( "Post $post_id saved, invalidating cache..." );
265
+
266
+        $this->cache->delete( $post_id );
267
+
268
+        $this->flush_cache_if_publisher( $post_id );
269
+
270
+    }
271
+
272
+    /**
273
+     * Hook to meta changed for a {@link WP_Post}, will cause the cause to
274
+     * invalidate.
275
+     *
276
+     * @param int    $id The {@link WP_Post} meta id.
277
+     * @param int    $post_id The {@link WP_Post} id.
278
+     * @param string $meta_key The meta key.
279
+     *
280
+     * @since 3.16.0
281
+     */
282
+    public function changed_post_meta( $id, $post_id, $meta_key ) {
283
+
284
+        if ( in_array( $meta_key, self::$ignored_meta_keys, true ) ) {
285
+            $this->log->trace( "Post $post_id meta $meta_key ignored." );
286
+
287
+            return;
288
+        }
289
+
290
+        $this->log->trace( "Post $post_id meta $meta_key changed, invalidating cache..." );
291
+
292
+        // Delete the single cache file.
293
+        $this->cache->delete( $post_id );
294
+
295
+        // Flush the cache if it's the publisher.
296
+        $this->flush_cache_if_publisher( $post_id );
297
+
298
+    }
299
+
300
+    /**
301
+     * Hook to WordLift's options changes, will flush the cache.
302
+     *
303
+     * @since 3.16.0
304
+     */
305
+    public function update_option_wl_general_settings() {
306
+        $this->log->trace( 'WordLift options changed, flushing cache...' );
307
+
308
+        $this->cache->flush();
309
+    }
310
+
311
+    /**
312
+     * Hook when permalinks are changed, will flush the cache.
313
+     *
314
+     * @since 3.17.0
315
+     */
316
+    public function permalinks_structure_changed() {
317
+        $this->log->trace( 'Permalinks structure changed, flushing cache...' );
318
+
319
+        $this->cache->flush();
320
+    }
321
+
322
+    /**
323
+     * Hook to WordLift's post/entity relation changes, will invalidate the cache.
324
+     *
325
+     * @param int $post_id The {@link WP_Post} id.
326
+     *
327
+     * @since 3.16.0
328
+     */
329
+    public function relation_changed( $post_id ) {
330
+        $this->log->trace( "Post $post_id relations changed, invalidating cache..." );
331
+
332
+        $this->cache->delete( $post_id );
333
+    }
334
+
335
+    /**
336
+     * When in Ajax, prints an http header with the information whether the
337
+     * response is cached or not.
338
+     *
339
+     * @param int  $post_id The {@link WP_Post} id.
340
+     * @param bool $cache Whether the response fragment is cached.
341
+     *
342
+     * @since 3.16.0
343
+     */
344
+    private function add_http_header( $post_id, $cache ) {
345
+
346
+        if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX || headers_sent() ) {
347
+            return;
348
+        }
349
+
350
+        header( "X-WordLift-JsonLd-Cache-$post_id: " . ( $cache ? 'HIT' : 'MISS' ) );
351
+
352
+    }
353
+
354
+    /**
355
+     * Call the `flush` operation on the {@link Ttl_Cache} if
356
+     * the publisher has changed.
357
+     *
358
+     * @param int $post_id The changed {@link WP_Post}'s id.
359
+     *
360
+     * @since 3.16.0
361
+     */
362
+    private function flush_cache_if_publisher( $post_id ) {
363
+
364
+        // Bail out if it's not the publisher.
365
+        if ( Wordlift_Configuration_Service::get_instance()->get_publisher_id() !== $post_id ) {
366
+            return;
367
+        }
368
+
369
+        // Flush the cache, since the publisher has changed.
370
+        $this->cache->flush();
371
+
372
+    }
373 373
 
374 374
 }
Please login to merge, or discard this patch.
Spacing   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -68,9 +68,9 @@  discard block
 block discarded – undo
68 68
 	 * @param \Wordlift_Post_Converter $converter The {@link Wordlift_Post_Converter} implementation.
69 69
 	 * @param Ttl_Cache                $cache The {@link Ttl_Cache} cache instance.
70 70
 	 */
71
-	public function __construct( $converter, $cache ) {
71
+	public function __construct($converter, $cache) {
72 72
 
73
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
73
+		$this->log = Wordlift_Log_Service::get_logger(get_class());
74 74
 
75 75
 		$this->cache               = $cache;
76 76
 		$this->converter           = $converter;
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 	private function init_hooks() {
88 88
 
89 89
 		// Hook on post save to flush relevant cache.
90
-		add_action( 'save_post', array( $this, 'save_post' ) );
90
+		add_action('save_post', array($this, 'save_post'));
91 91
 
92 92
 		add_action(
93 93
 			'added_post_meta',
@@ -136,8 +136,8 @@  discard block
 block discarded – undo
136 136
 		);
137 137
 
138 138
 		// Invalid cache on relationship change.
139
-		add_action( 'wl_relation_added', array( $this, 'relation_changed' ) );
140
-		add_action( 'wl_relation_deleted', array( $this, 'relation_changed' ) );
139
+		add_action('wl_relation_added', array($this, 'relation_changed'));
140
+		add_action('wl_relation_deleted', array($this, 'relation_changed'));
141 141
 
142 142
 	}
143 143
 
@@ -148,25 +148,25 @@  discard block
 block discarded – undo
148 148
 	 * @inheritdoc
149 149
 	 */
150 150
 	// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
151
-	public function convert( $post_id, &$references = array(), &$references_infos = array(), &$cache = false ) {
151
+	public function convert($post_id, &$references = array(), &$references_infos = array(), &$cache = false) {
152 152
 
153 153
 		// Ensure post ID is `int`. Otherwise we may have issues with caching, since caching is strict about
154 154
 		// key var types.
155 155
 		$post_id = (int) $post_id;
156 156
 
157
-		$this->log->trace( "Converting post $post_id..." );
157
+		$this->log->trace("Converting post $post_id...");
158 158
 
159 159
 		// Try to get a cached result.
160
-		$contents = $this->get_cache( $post_id, $references );
160
+		$contents = $this->get_cache($post_id, $references);
161 161
 
162 162
 		// Return the cached contents if any.
163
-		if ( false !== $contents ) {
164
-			$this->log->debug( "Cached contents found for post $post_id." );
163
+		if (false !== $contents) {
164
+			$this->log->debug("Cached contents found for post $post_id.");
165 165
 
166 166
 			// Inform the caller that this is cached result.
167 167
 			// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
168 168
 			$cache = true;
169
-			$this->add_http_header( $post_id, true );
169
+			$this->add_http_header($post_id, true);
170 170
 
171 171
 			// Return the contents.
172 172
 			return $contents;
@@ -175,10 +175,10 @@  discard block
 block discarded – undo
175 175
 		// Set cached to false.
176 176
 		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
177 177
 		$cache = false;
178
-		$this->add_http_header( $post_id, false );
178
+		$this->add_http_header($post_id, false);
179 179
 
180 180
 		// Convert the post.
181
-		$jsonld = $this->converter->convert( $post_id, $references, $references_infos );
181
+		$jsonld = $this->converter->convert($post_id, $references, $references_infos);
182 182
 
183 183
 		/**
184 184
 		 * @since 3.32.0
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
 		 * it here before saving it on cache.
187 187
 		 */
188 188
 		// Cache the results.
189
-		$this->set_cache( $post_id, $references, $jsonld );
189
+		$this->set_cache($post_id, $references, $jsonld);
190 190
 
191 191
 		// Finally return the JSON-LD.
192 192
 		return $jsonld;
@@ -202,27 +202,27 @@  discard block
 block discarded – undo
202 202
 	 * @since 3.16.0
203 203
 	 */
204 204
 	// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
205
-	private function get_cache( $post_id, &$references = array() ) {
205
+	private function get_cache($post_id, &$references = array()) {
206 206
 
207 207
 		// Ensure post ID is int, because cache is strict about var types.
208 208
 		$post_id = (int) $post_id;
209 209
 
210
-		$this->log->trace( "Getting cached contents for post $post_id..." );
210
+		$this->log->trace("Getting cached contents for post $post_id...");
211 211
 
212 212
 		// Get the cache.
213
-		$contents = $this->cache->get( $post_id );
213
+		$contents = $this->cache->get($post_id);
214 214
 
215 215
 		// Bail out if we don't have cached contents or the cached contents are
216 216
 		// invalid.
217
-		if ( null === $contents || ! isset( $contents['jsonld'] ) || ! isset( $contents['references'] ) ) {
218
-			$this->log->debug( "Cached contents for post $post_id not found." );
217
+		if (null === $contents || ! isset($contents['jsonld']) || ! isset($contents['references'])) {
218
+			$this->log->debug("Cached contents for post $post_id not found.");
219 219
 
220 220
 			return false;
221 221
 		}
222 222
 
223 223
 		// Remap the cache.
224 224
 		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
225
-		$references = $this->reference_processor->deserialize_references( $contents['references'] );
225
+		$references = $this->reference_processor->deserialize_references($contents['references']);
226 226
 
227 227
 		return $contents['jsonld'];
228 228
 	}
@@ -238,14 +238,14 @@  discard block
 block discarded – undo
238 238
 	 *
239 239
 	 * @since 3.16.0
240 240
 	 */
241
-	private function set_cache( $post_id, $references, $jsonld ) {
241
+	private function set_cache($post_id, $references, $jsonld) {
242 242
 
243
-		$this->log->trace( "Caching result for post $post_id..." );
243
+		$this->log->trace("Caching result for post $post_id...");
244 244
 
245 245
 		$this->cache->put(
246 246
 			$post_id,
247 247
 			array(
248
-				'references' => $this->reference_processor->serialize_references( $references ),
248
+				'references' => $this->reference_processor->serialize_references($references),
249 249
 				'jsonld'     => $jsonld,
250 250
 			)
251 251
 		);
@@ -259,13 +259,13 @@  discard block
 block discarded – undo
259 259
 	 *
260 260
 	 * @since 3.16.0
261 261
 	 */
262
-	public function save_post( $post_id ) {
262
+	public function save_post($post_id) {
263 263
 
264
-		$this->log->trace( "Post $post_id saved, invalidating cache..." );
264
+		$this->log->trace("Post $post_id saved, invalidating cache...");
265 265
 
266
-		$this->cache->delete( $post_id );
266
+		$this->cache->delete($post_id);
267 267
 
268
-		$this->flush_cache_if_publisher( $post_id );
268
+		$this->flush_cache_if_publisher($post_id);
269 269
 
270 270
 	}
271 271
 
@@ -279,21 +279,21 @@  discard block
 block discarded – undo
279 279
 	 *
280 280
 	 * @since 3.16.0
281 281
 	 */
282
-	public function changed_post_meta( $id, $post_id, $meta_key ) {
282
+	public function changed_post_meta($id, $post_id, $meta_key) {
283 283
 
284
-		if ( in_array( $meta_key, self::$ignored_meta_keys, true ) ) {
285
-			$this->log->trace( "Post $post_id meta $meta_key ignored." );
284
+		if (in_array($meta_key, self::$ignored_meta_keys, true)) {
285
+			$this->log->trace("Post $post_id meta $meta_key ignored.");
286 286
 
287 287
 			return;
288 288
 		}
289 289
 
290
-		$this->log->trace( "Post $post_id meta $meta_key changed, invalidating cache..." );
290
+		$this->log->trace("Post $post_id meta $meta_key changed, invalidating cache...");
291 291
 
292 292
 		// Delete the single cache file.
293
-		$this->cache->delete( $post_id );
293
+		$this->cache->delete($post_id);
294 294
 
295 295
 		// Flush the cache if it's the publisher.
296
-		$this->flush_cache_if_publisher( $post_id );
296
+		$this->flush_cache_if_publisher($post_id);
297 297
 
298 298
 	}
299 299
 
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
 	 * @since 3.16.0
304 304
 	 */
305 305
 	public function update_option_wl_general_settings() {
306
-		$this->log->trace( 'WordLift options changed, flushing cache...' );
306
+		$this->log->trace('WordLift options changed, flushing cache...');
307 307
 
308 308
 		$this->cache->flush();
309 309
 	}
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
 	 * @since 3.17.0
315 315
 	 */
316 316
 	public function permalinks_structure_changed() {
317
-		$this->log->trace( 'Permalinks structure changed, flushing cache...' );
317
+		$this->log->trace('Permalinks structure changed, flushing cache...');
318 318
 
319 319
 		$this->cache->flush();
320 320
 	}
@@ -326,10 +326,10 @@  discard block
 block discarded – undo
326 326
 	 *
327 327
 	 * @since 3.16.0
328 328
 	 */
329
-	public function relation_changed( $post_id ) {
330
-		$this->log->trace( "Post $post_id relations changed, invalidating cache..." );
329
+	public function relation_changed($post_id) {
330
+		$this->log->trace("Post $post_id relations changed, invalidating cache...");
331 331
 
332
-		$this->cache->delete( $post_id );
332
+		$this->cache->delete($post_id);
333 333
 	}
334 334
 
335 335
 	/**
@@ -341,13 +341,13 @@  discard block
 block discarded – undo
341 341
 	 *
342 342
 	 * @since 3.16.0
343 343
 	 */
344
-	private function add_http_header( $post_id, $cache ) {
344
+	private function add_http_header($post_id, $cache) {
345 345
 
346
-		if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX || headers_sent() ) {
346
+		if ( ! defined('DOING_AJAX') || ! DOING_AJAX || headers_sent()) {
347 347
 			return;
348 348
 		}
349 349
 
350
-		header( "X-WordLift-JsonLd-Cache-$post_id: " . ( $cache ? 'HIT' : 'MISS' ) );
350
+		header("X-WordLift-JsonLd-Cache-$post_id: ".($cache ? 'HIT' : 'MISS'));
351 351
 
352 352
 	}
353 353
 
@@ -359,10 +359,10 @@  discard block
 block discarded – undo
359 359
 	 *
360 360
 	 * @since 3.16.0
361 361
 	 */
362
-	private function flush_cache_if_publisher( $post_id ) {
362
+	private function flush_cache_if_publisher($post_id) {
363 363
 
364 364
 		// Bail out if it's not the publisher.
365
-		if ( Wordlift_Configuration_Service::get_instance()->get_publisher_id() !== $post_id ) {
365
+		if (Wordlift_Configuration_Service::get_instance()->get_publisher_id() !== $post_id) {
366 366
 			return;
367 367
 		}
368 368
 
Please login to merge, or discard this patch.
src/includes/class-wordlift-http-api.php 2 patches
Indentation   +180 added lines, -180 removed lines patch added patch discarded remove patch
@@ -16,185 +16,185 @@
 block discarded – undo
16 16
  */
17 17
 class Wordlift_Http_Api {
18 18
 
19
-	/**
20
-	 * A {@link Wordlift_Log_Service} instance.
21
-	 *
22
-	 * @since 3.15.3
23
-	 *
24
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
25
-	 */
26
-	private $log;
27
-
28
-	/**
29
-	 * Create a {@link Wordlift_End_Point} instance.
30
-	 *
31
-	 * @since 3.15.3
32
-	 */
33
-	public function __construct() {
34
-
35
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
36
-
37
-		add_action( 'init', array( $this, 'add_rewrite_endpoint' ) );
38
-		add_action( 'template_redirect', array( $this, 'template_redirect' ) );
39
-
40
-		// region SAMPLE ACTIONS.
41
-		add_action(
42
-			'admin_post_wl_hello_world',
43
-			array(
44
-				$this,
45
-				'hello_world',
46
-			)
47
-		);
48
-		add_action(
49
-			'admin_post_nopriv_wl_hello_world',
50
-			array(
51
-				$this,
52
-				'nopriv_hello_world',
53
-			)
54
-		);
55
-		// endregion
56
-	}
57
-
58
-	/**
59
-	 * Add the `wl-api` rewrite end-point.
60
-	 *
61
-	 * @since 3.15.3
62
-	 */
63
-	public function add_rewrite_endpoint() {
64
-
65
-		add_rewrite_endpoint( 'wl-api', EP_ROOT );
66
-		$this->ensure_rewrite_rules_are_flushed();
67
-
68
-	}
69
-
70
-	/**
71
-	 * Handle `template_redirect` hooks.
72
-	 *
73
-	 * @since 3.15.3
74
-	 */
75
-	public function template_redirect() {
76
-
77
-		global $wp_query;
78
-
79
-		if ( ! isset( $wp_query->query_vars['wl-api'] ) ) {
80
-			$this->log->trace( 'Skipping, not a `wl-api` call.' );
81
-
82
-			return;
83
-		}
84
-
85
-		$action = isset( $_REQUEST['action'] ) ? sanitize_text_field( wp_unslash( (string) $_REQUEST['action'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended
86
-		$this->do_action( $action );
87
-
88
-		exit;
89
-
90
-	}
91
-
92
-	/**
93
-	 * Do the requested action.
94
-	 *
95
-	 * @param string $action The action to execute.
96
-	 *
97
-	 * @since 3.15.3
98
-	 */
99
-	private function do_action( $action ) {
100
-
101
-		if ( empty( $action ) ) {
102
-			return;
103
-		}
104
-
105
-		if ( ! wp_validate_auth_cookie( '', 'logged_in' ) ) {
106
-			/**
107
-			 * Fires on a non-authenticated admin post request for the given action.
108
-			 *
109
-			 * The dynamic portion of the hook name, `$action`, refers to the given
110
-			 * request action.
111
-			 *
112
-			 * @since 2.6.0
113
-			 */
114
-			do_action( "admin_post_nopriv_{$action}" );
115
-		} else {
116
-			/**
117
-			 * Fires on an authenticated admin post request for the given action.
118
-			 *
119
-			 * The dynamic portion of the hook name, `$action`, refers to the given
120
-			 * request action.
121
-			 *
122
-			 * @since 2.6.0
123
-			 */
124
-			do_action( "admin_post_{$action}" );
125
-		}
126
-
127
-	}
128
-
129
-	/**
130
-	 * Test function, anonymous.
131
-	 *
132
-	 * @since 3.15.3
133
-	 */
134
-	public function nopriv_hello_world() {
135
-
136
-		wp_die( 'Hello World! (from anonymous)' );
137
-
138
-	}
139
-
140
-	/**
141
-	 * Test function, authenticated.
142
-	 *
143
-	 * @since 3.15.3
144
-	 */
145
-	public function hello_world() {
146
-
147
-		wp_die( 'Hello World! (from authenticated)' );
148
-
149
-	}
150
-
151
-	/**
152
-	 * Ensure that the rewrite rules are flushed the first time.
153
-	 *
154
-	 * @since 3.16.0 changed the value from 1 to `yes` to avoid type juggling issues.
155
-	 * @since 3.15.3
156
-	 */
157
-	public static function ensure_rewrite_rules_are_flushed() {
158
-
159
-		// See https://github.com/insideout10/wordlift-plugin/issues/698.
160
-		if ( 'yes' !== get_option( 'wl_http_api' ) ) {
161
-			update_option( 'wl_http_api', 'yes' );
162
-			add_action(
163
-				'wp_loaded',
164
-				function () {
165
-					flush_rewrite_rules();
166
-				}
167
-			);
168
-		}
169
-
170
-	}
171
-
172
-	/**
173
-	 * Called by {@see activate_wordlift}, resets the `wl_http_api` option flag in order to force WordLift to
174
-	 * reinitialize the `wl-api` route.
175
-	 *
176
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/820 related issue.
177
-	 *
178
-	 * @since 3.19.2
179
-	 */
180
-	public static function activate() {
181
-
182
-		// Force the plugin to reinitialize the rewrite rules.
183
-		update_option( 'wl_http_api', 'no' );
184
-
185
-	}
186
-
187
-	/**
188
-	 * Delete the option when the plugin is deactivated.
189
-	 *
190
-	 * @since 3.19.4
191
-	 *
192
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/846
193
-	 */
194
-	public static function deactivate() {
195
-
196
-		delete_option( 'wl_http_api' );
197
-
198
-	}
19
+    /**
20
+     * A {@link Wordlift_Log_Service} instance.
21
+     *
22
+     * @since 3.15.3
23
+     *
24
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
25
+     */
26
+    private $log;
27
+
28
+    /**
29
+     * Create a {@link Wordlift_End_Point} instance.
30
+     *
31
+     * @since 3.15.3
32
+     */
33
+    public function __construct() {
34
+
35
+        $this->log = Wordlift_Log_Service::get_logger( get_class() );
36
+
37
+        add_action( 'init', array( $this, 'add_rewrite_endpoint' ) );
38
+        add_action( 'template_redirect', array( $this, 'template_redirect' ) );
39
+
40
+        // region SAMPLE ACTIONS.
41
+        add_action(
42
+            'admin_post_wl_hello_world',
43
+            array(
44
+                $this,
45
+                'hello_world',
46
+            )
47
+        );
48
+        add_action(
49
+            'admin_post_nopriv_wl_hello_world',
50
+            array(
51
+                $this,
52
+                'nopriv_hello_world',
53
+            )
54
+        );
55
+        // endregion
56
+    }
57
+
58
+    /**
59
+     * Add the `wl-api` rewrite end-point.
60
+     *
61
+     * @since 3.15.3
62
+     */
63
+    public function add_rewrite_endpoint() {
64
+
65
+        add_rewrite_endpoint( 'wl-api', EP_ROOT );
66
+        $this->ensure_rewrite_rules_are_flushed();
67
+
68
+    }
69
+
70
+    /**
71
+     * Handle `template_redirect` hooks.
72
+     *
73
+     * @since 3.15.3
74
+     */
75
+    public function template_redirect() {
76
+
77
+        global $wp_query;
78
+
79
+        if ( ! isset( $wp_query->query_vars['wl-api'] ) ) {
80
+            $this->log->trace( 'Skipping, not a `wl-api` call.' );
81
+
82
+            return;
83
+        }
84
+
85
+        $action = isset( $_REQUEST['action'] ) ? sanitize_text_field( wp_unslash( (string) $_REQUEST['action'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended
86
+        $this->do_action( $action );
87
+
88
+        exit;
89
+
90
+    }
91
+
92
+    /**
93
+     * Do the requested action.
94
+     *
95
+     * @param string $action The action to execute.
96
+     *
97
+     * @since 3.15.3
98
+     */
99
+    private function do_action( $action ) {
100
+
101
+        if ( empty( $action ) ) {
102
+            return;
103
+        }
104
+
105
+        if ( ! wp_validate_auth_cookie( '', 'logged_in' ) ) {
106
+            /**
107
+             * Fires on a non-authenticated admin post request for the given action.
108
+             *
109
+             * The dynamic portion of the hook name, `$action`, refers to the given
110
+             * request action.
111
+             *
112
+             * @since 2.6.0
113
+             */
114
+            do_action( "admin_post_nopriv_{$action}" );
115
+        } else {
116
+            /**
117
+             * Fires on an authenticated admin post request for the given action.
118
+             *
119
+             * The dynamic portion of the hook name, `$action`, refers to the given
120
+             * request action.
121
+             *
122
+             * @since 2.6.0
123
+             */
124
+            do_action( "admin_post_{$action}" );
125
+        }
126
+
127
+    }
128
+
129
+    /**
130
+     * Test function, anonymous.
131
+     *
132
+     * @since 3.15.3
133
+     */
134
+    public function nopriv_hello_world() {
135
+
136
+        wp_die( 'Hello World! (from anonymous)' );
137
+
138
+    }
139
+
140
+    /**
141
+     * Test function, authenticated.
142
+     *
143
+     * @since 3.15.3
144
+     */
145
+    public function hello_world() {
146
+
147
+        wp_die( 'Hello World! (from authenticated)' );
148
+
149
+    }
150
+
151
+    /**
152
+     * Ensure that the rewrite rules are flushed the first time.
153
+     *
154
+     * @since 3.16.0 changed the value from 1 to `yes` to avoid type juggling issues.
155
+     * @since 3.15.3
156
+     */
157
+    public static function ensure_rewrite_rules_are_flushed() {
158
+
159
+        // See https://github.com/insideout10/wordlift-plugin/issues/698.
160
+        if ( 'yes' !== get_option( 'wl_http_api' ) ) {
161
+            update_option( 'wl_http_api', 'yes' );
162
+            add_action(
163
+                'wp_loaded',
164
+                function () {
165
+                    flush_rewrite_rules();
166
+                }
167
+            );
168
+        }
169
+
170
+    }
171
+
172
+    /**
173
+     * Called by {@see activate_wordlift}, resets the `wl_http_api` option flag in order to force WordLift to
174
+     * reinitialize the `wl-api` route.
175
+     *
176
+     * @see https://github.com/insideout10/wordlift-plugin/issues/820 related issue.
177
+     *
178
+     * @since 3.19.2
179
+     */
180
+    public static function activate() {
181
+
182
+        // Force the plugin to reinitialize the rewrite rules.
183
+        update_option( 'wl_http_api', 'no' );
184
+
185
+    }
186
+
187
+    /**
188
+     * Delete the option when the plugin is deactivated.
189
+     *
190
+     * @since 3.19.4
191
+     *
192
+     * @see https://github.com/insideout10/wordlift-plugin/issues/846
193
+     */
194
+    public static function deactivate() {
195
+
196
+        delete_option( 'wl_http_api' );
197
+
198
+    }
199 199
 
200 200
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -32,10 +32,10 @@  discard block
 block discarded – undo
32 32
 	 */
33 33
 	public function __construct() {
34 34
 
35
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
35
+		$this->log = Wordlift_Log_Service::get_logger(get_class());
36 36
 
37
-		add_action( 'init', array( $this, 'add_rewrite_endpoint' ) );
38
-		add_action( 'template_redirect', array( $this, 'template_redirect' ) );
37
+		add_action('init', array($this, 'add_rewrite_endpoint'));
38
+		add_action('template_redirect', array($this, 'template_redirect'));
39 39
 
40 40
 		// region SAMPLE ACTIONS.
41 41
 		add_action(
@@ -62,7 +62,7 @@  discard block
 block discarded – undo
62 62
 	 */
63 63
 	public function add_rewrite_endpoint() {
64 64
 
65
-		add_rewrite_endpoint( 'wl-api', EP_ROOT );
65
+		add_rewrite_endpoint('wl-api', EP_ROOT);
66 66
 		$this->ensure_rewrite_rules_are_flushed();
67 67
 
68 68
 	}
@@ -76,14 +76,14 @@  discard block
 block discarded – undo
76 76
 
77 77
 		global $wp_query;
78 78
 
79
-		if ( ! isset( $wp_query->query_vars['wl-api'] ) ) {
80
-			$this->log->trace( 'Skipping, not a `wl-api` call.' );
79
+		if ( ! isset($wp_query->query_vars['wl-api'])) {
80
+			$this->log->trace('Skipping, not a `wl-api` call.');
81 81
 
82 82
 			return;
83 83
 		}
84 84
 
85
-		$action = isset( $_REQUEST['action'] ) ? sanitize_text_field( wp_unslash( (string) $_REQUEST['action'] ) ) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended
86
-		$this->do_action( $action );
85
+		$action = isset($_REQUEST['action']) ? sanitize_text_field(wp_unslash((string) $_REQUEST['action'])) : ''; //phpcs:ignore WordPress.Security.NonceVerification.Recommended
86
+		$this->do_action($action);
87 87
 
88 88
 		exit;
89 89
 
@@ -96,13 +96,13 @@  discard block
 block discarded – undo
96 96
 	 *
97 97
 	 * @since 3.15.3
98 98
 	 */
99
-	private function do_action( $action ) {
99
+	private function do_action($action) {
100 100
 
101
-		if ( empty( $action ) ) {
101
+		if (empty($action)) {
102 102
 			return;
103 103
 		}
104 104
 
105
-		if ( ! wp_validate_auth_cookie( '', 'logged_in' ) ) {
105
+		if ( ! wp_validate_auth_cookie('', 'logged_in')) {
106 106
 			/**
107 107
 			 * Fires on a non-authenticated admin post request for the given action.
108 108
 			 *
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 			 *
112 112
 			 * @since 2.6.0
113 113
 			 */
114
-			do_action( "admin_post_nopriv_{$action}" );
114
+			do_action("admin_post_nopriv_{$action}");
115 115
 		} else {
116 116
 			/**
117 117
 			 * Fires on an authenticated admin post request for the given action.
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
 			 *
122 122
 			 * @since 2.6.0
123 123
 			 */
124
-			do_action( "admin_post_{$action}" );
124
+			do_action("admin_post_{$action}");
125 125
 		}
126 126
 
127 127
 	}
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 	 */
134 134
 	public function nopriv_hello_world() {
135 135
 
136
-		wp_die( 'Hello World! (from anonymous)' );
136
+		wp_die('Hello World! (from anonymous)');
137 137
 
138 138
 	}
139 139
 
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 	 */
145 145
 	public function hello_world() {
146 146
 
147
-		wp_die( 'Hello World! (from authenticated)' );
147
+		wp_die('Hello World! (from authenticated)');
148 148
 
149 149
 	}
150 150
 
@@ -157,11 +157,11 @@  discard block
 block discarded – undo
157 157
 	public static function ensure_rewrite_rules_are_flushed() {
158 158
 
159 159
 		// See https://github.com/insideout10/wordlift-plugin/issues/698.
160
-		if ( 'yes' !== get_option( 'wl_http_api' ) ) {
161
-			update_option( 'wl_http_api', 'yes' );
160
+		if ('yes' !== get_option('wl_http_api')) {
161
+			update_option('wl_http_api', 'yes');
162 162
 			add_action(
163 163
 				'wp_loaded',
164
-				function () {
164
+				function() {
165 165
 					flush_rewrite_rules();
166 166
 				}
167 167
 			);
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
 	public static function activate() {
181 181
 
182 182
 		// Force the plugin to reinitialize the rewrite rules.
183
-		update_option( 'wl_http_api', 'no' );
183
+		update_option('wl_http_api', 'no');
184 184
 
185 185
 	}
186 186
 
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
 	 */
194 194
 	public static function deactivate() {
195 195
 
196
-		delete_option( 'wl_http_api' );
196
+		delete_option('wl_http_api');
197 197
 
198 198
 	}
199 199
 
Please login to merge, or discard this patch.
src/includes/mapping/class-wordlift-mapping-ajax-adapter.php 2 patches
Indentation   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -8,80 +8,80 @@
 block discarded – undo
8 8
 
9 9
 class Wordlift_Mapping_Ajax_Adapter {
10 10
 
11
-	/**
12
-	 * The {@link Wordlift_Mapping_Service} instance.
13
-	 *
14
-	 * @since 3.20.0
15
-	 * @access private
16
-	 * @var \Wordlift_Mapping_Service $mapping_service The {@link Wordlift_Mapping_Service} instance.
17
-	 */
18
-	private $mapping_service;
11
+    /**
12
+     * The {@link Wordlift_Mapping_Service} instance.
13
+     *
14
+     * @since 3.20.0
15
+     * @access private
16
+     * @var \Wordlift_Mapping_Service $mapping_service The {@link Wordlift_Mapping_Service} instance.
17
+     */
18
+    private $mapping_service;
19 19
 
20
-	/**
21
-	 * Create a {@link Wordlift_Mapping_Ajax_Adapter} instance.
22
-	 *
23
-	 * @param Wordlift_Mapping_Service $mapping_service The {@link Wordlift_Mapping_Service} instance.
24
-	 *
25
-	 * @since 3.20.0
26
-	 */
27
-	public function __construct( $mapping_service ) {
20
+    /**
21
+     * Create a {@link Wordlift_Mapping_Ajax_Adapter} instance.
22
+     *
23
+     * @param Wordlift_Mapping_Service $mapping_service The {@link Wordlift_Mapping_Service} instance.
24
+     *
25
+     * @since 3.20.0
26
+     */
27
+    public function __construct( $mapping_service ) {
28 28
 
29
-		$this->mapping_service = $mapping_service;
29
+        $this->mapping_service = $mapping_service;
30 30
 
31
-		add_action( 'wp_ajax_wl_set_entity_types_for_post_type', array( $this, 'set_entity_types_for_post_type' ) );
32
-		add_action( 'wp_ajax_wl_update_post_type_entity_types', array( $this, 'update_post_type_entity_types' ) );
31
+        add_action( 'wp_ajax_wl_set_entity_types_for_post_type', array( $this, 'set_entity_types_for_post_type' ) );
32
+        add_action( 'wp_ajax_wl_update_post_type_entity_types', array( $this, 'update_post_type_entity_types' ) );
33 33
 
34
-	}
34
+    }
35 35
 
36
-	public function set_entity_types_for_post_type() {
36
+    public function set_entity_types_for_post_type() {
37 37
 
38
-		if ( ! isset( $_REQUEST['post_type'] ) || ! isset( $_REQUEST['entity_types'] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
39
-			return;
40
-		}
38
+        if ( ! isset( $_REQUEST['post_type'] ) || ! isset( $_REQUEST['entity_types'] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
39
+            return;
40
+        }
41 41
 
42
-		$post_type    = sanitize_text_field( wp_unslash( $_REQUEST['post_type'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended
43
-		$entity_types = array_map( 'sanitize_text_field', wp_unslash( (array) $_REQUEST['entity_types'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended
42
+        $post_type    = sanitize_text_field( wp_unslash( $_REQUEST['post_type'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended
43
+        $entity_types = array_map( 'sanitize_text_field', wp_unslash( (array) $_REQUEST['entity_types'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended
44 44
 
45
-		$this->mapping_service->set_entity_types_for_post_type( $post_type, $entity_types );
45
+        $this->mapping_service->set_entity_types_for_post_type( $post_type, $entity_types );
46 46
 
47
-		wp_send_json_success();
47
+        wp_send_json_success();
48 48
 
49
-	}
49
+    }
50 50
 
51
-	public function update_post_type_entity_types() {
51
+    public function update_post_type_entity_types() {
52 52
 
53
-		// If the nonce is invalid, return an error.
54
-		$nonce = isset( $_REQUEST['_nonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['_nonce'] ) ) : '';
55
-		if ( ! wp_verify_nonce( $nonce, 'update_post_type_entity_types' ) ) {
56
-			wp_send_json_error( __( 'Nonce Security Check Failed!', 'wordlift' ) );
57
-		}
53
+        // If the nonce is invalid, return an error.
54
+        $nonce = isset( $_REQUEST['_nonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['_nonce'] ) ) : '';
55
+        if ( ! wp_verify_nonce( $nonce, 'update_post_type_entity_types' ) ) {
56
+            wp_send_json_error( __( 'Nonce Security Check Failed!', 'wordlift' ) );
57
+        }
58 58
 
59
-		if ( empty( $_REQUEST['post_type'] ) ) {
60
-			wp_send_json_error( __( '`post_type` is required', 'wordlift' ) );
61
-		}
59
+        if ( empty( $_REQUEST['post_type'] ) ) {
60
+            wp_send_json_error( __( '`post_type` is required', 'wordlift' ) );
61
+        }
62 62
 
63
-		if ( empty( $_REQUEST['entity_types'] ) ) {
64
-			wp_send_json_error( __( '`entity_types` is required', 'wordlift' ) );
65
-		}
63
+        if ( empty( $_REQUEST['entity_types'] ) ) {
64
+            wp_send_json_error( __( '`entity_types` is required', 'wordlift' ) );
65
+        }
66 66
 
67
-		// Get the post type.
68
-		$post_type = isset( $_REQUEST['post_type'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['post_type'] ) ) : '';
67
+        // Get the post type.
68
+        $post_type = isset( $_REQUEST['post_type'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['post_type'] ) ) : '';
69 69
 
70
-		// Get the entity types URIs.
71
-		$entity_types = isset( $_REQUEST['entity_types'] ) ? filter_var( wp_unslash( $_REQUEST['entity_types'] ), FILTER_REQUIRE_ARRAY ) : array();
70
+        // Get the entity types URIs.
71
+        $entity_types = isset( $_REQUEST['entity_types'] ) ? filter_var( wp_unslash( $_REQUEST['entity_types'] ), FILTER_REQUIRE_ARRAY ) : array();
72 72
 
73
-		// Get the offset.
74
-		$offset = isset( $_REQUEST['offset'] ) ? intval( $_REQUEST['offset'] ) : 0;
73
+        // Get the offset.
74
+        $offset = isset( $_REQUEST['offset'] ) ? intval( $_REQUEST['offset'] ) : 0;
75 75
 
76
-		// Update and get the results.
77
-		$result = $this->mapping_service->update( $post_type, $entity_types, $offset );
76
+        // Update and get the results.
77
+        $result = $this->mapping_service->update( $post_type, $entity_types, $offset );
78 78
 
79
-		// Add our nonce to the result.
80
-		$result['_nonce'] = wp_create_nonce( 'update_post_type_entity_types' );
79
+        // Add our nonce to the result.
80
+        $result['_nonce'] = wp_create_nonce( 'update_post_type_entity_types' );
81 81
 
82
-		// Finally send the results.
83
-		wp_send_json_success( $result );
82
+        // Finally send the results.
83
+        wp_send_json_success( $result );
84 84
 
85
-	}
85
+    }
86 86
 
87 87
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -24,25 +24,25 @@  discard block
 block discarded – undo
24 24
 	 *
25 25
 	 * @since 3.20.0
26 26
 	 */
27
-	public function __construct( $mapping_service ) {
27
+	public function __construct($mapping_service) {
28 28
 
29 29
 		$this->mapping_service = $mapping_service;
30 30
 
31
-		add_action( 'wp_ajax_wl_set_entity_types_for_post_type', array( $this, 'set_entity_types_for_post_type' ) );
32
-		add_action( 'wp_ajax_wl_update_post_type_entity_types', array( $this, 'update_post_type_entity_types' ) );
31
+		add_action('wp_ajax_wl_set_entity_types_for_post_type', array($this, 'set_entity_types_for_post_type'));
32
+		add_action('wp_ajax_wl_update_post_type_entity_types', array($this, 'update_post_type_entity_types'));
33 33
 
34 34
 	}
35 35
 
36 36
 	public function set_entity_types_for_post_type() {
37 37
 
38
-		if ( ! isset( $_REQUEST['post_type'] ) || ! isset( $_REQUEST['entity_types'] ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
38
+		if ( ! isset($_REQUEST['post_type']) || ! isset($_REQUEST['entity_types'])) { //phpcs:ignore WordPress.Security.NonceVerification.Recommended
39 39
 			return;
40 40
 		}
41 41
 
42
-		$post_type    = sanitize_text_field( wp_unslash( $_REQUEST['post_type'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended
43
-		$entity_types = array_map( 'sanitize_text_field', wp_unslash( (array) $_REQUEST['entity_types'] ) ); //phpcs:ignore WordPress.Security.NonceVerification.Recommended
42
+		$post_type    = sanitize_text_field(wp_unslash($_REQUEST['post_type'])); //phpcs:ignore WordPress.Security.NonceVerification.Recommended
43
+		$entity_types = array_map('sanitize_text_field', wp_unslash((array) $_REQUEST['entity_types'])); //phpcs:ignore WordPress.Security.NonceVerification.Recommended
44 44
 
45
-		$this->mapping_service->set_entity_types_for_post_type( $post_type, $entity_types );
45
+		$this->mapping_service->set_entity_types_for_post_type($post_type, $entity_types);
46 46
 
47 47
 		wp_send_json_success();
48 48
 
@@ -51,36 +51,36 @@  discard block
 block discarded – undo
51 51
 	public function update_post_type_entity_types() {
52 52
 
53 53
 		// If the nonce is invalid, return an error.
54
-		$nonce = isset( $_REQUEST['_nonce'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['_nonce'] ) ) : '';
55
-		if ( ! wp_verify_nonce( $nonce, 'update_post_type_entity_types' ) ) {
56
-			wp_send_json_error( __( 'Nonce Security Check Failed!', 'wordlift' ) );
54
+		$nonce = isset($_REQUEST['_nonce']) ? sanitize_text_field(wp_unslash($_REQUEST['_nonce'])) : '';
55
+		if ( ! wp_verify_nonce($nonce, 'update_post_type_entity_types')) {
56
+			wp_send_json_error(__('Nonce Security Check Failed!', 'wordlift'));
57 57
 		}
58 58
 
59
-		if ( empty( $_REQUEST['post_type'] ) ) {
60
-			wp_send_json_error( __( '`post_type` is required', 'wordlift' ) );
59
+		if (empty($_REQUEST['post_type'])) {
60
+			wp_send_json_error(__('`post_type` is required', 'wordlift'));
61 61
 		}
62 62
 
63
-		if ( empty( $_REQUEST['entity_types'] ) ) {
64
-			wp_send_json_error( __( '`entity_types` is required', 'wordlift' ) );
63
+		if (empty($_REQUEST['entity_types'])) {
64
+			wp_send_json_error(__('`entity_types` is required', 'wordlift'));
65 65
 		}
66 66
 
67 67
 		// Get the post type.
68
-		$post_type = isset( $_REQUEST['post_type'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['post_type'] ) ) : '';
68
+		$post_type = isset($_REQUEST['post_type']) ? sanitize_text_field(wp_unslash($_REQUEST['post_type'])) : '';
69 69
 
70 70
 		// Get the entity types URIs.
71
-		$entity_types = isset( $_REQUEST['entity_types'] ) ? filter_var( wp_unslash( $_REQUEST['entity_types'] ), FILTER_REQUIRE_ARRAY ) : array();
71
+		$entity_types = isset($_REQUEST['entity_types']) ? filter_var(wp_unslash($_REQUEST['entity_types']), FILTER_REQUIRE_ARRAY) : array();
72 72
 
73 73
 		// Get the offset.
74
-		$offset = isset( $_REQUEST['offset'] ) ? intval( $_REQUEST['offset'] ) : 0;
74
+		$offset = isset($_REQUEST['offset']) ? intval($_REQUEST['offset']) : 0;
75 75
 
76 76
 		// Update and get the results.
77
-		$result = $this->mapping_service->update( $post_type, $entity_types, $offset );
77
+		$result = $this->mapping_service->update($post_type, $entity_types, $offset);
78 78
 
79 79
 		// Add our nonce to the result.
80
-		$result['_nonce'] = wp_create_nonce( 'update_post_type_entity_types' );
80
+		$result['_nonce'] = wp_create_nonce('update_post_type_entity_types');
81 81
 
82 82
 		// Finally send the results.
83
-		wp_send_json_success( $result );
83
+		wp_send_json_success($result);
84 84
 
85 85
 	}
86 86
 
Please login to merge, or discard this patch.
src/includes/mapping/class-wordlift-mapping-service.php 2 patches
Indentation   +218 added lines, -218 removed lines patch added patch discarded remove patch
@@ -14,223 +14,223 @@
 block discarded – undo
14 14
  */
15 15
 class Wordlift_Mapping_Service {
16 16
 
17
-	/**
18
-	 * The mapping's options.
19
-	 *
20
-	 * @since 3.20.0
21
-	 * @access private
22
-	 * @var array $options The mapping's options.
23
-	 */
24
-	private $options;
25
-
26
-	/**
27
-	 * The {@link Wordlift_Entity_Type_Service} instance.
28
-	 *
29
-	 * @since 3.20.0
30
-	 * @access private
31
-	 * @var \Wordlift_Entity_Type_Service $entity_type_service The {@link Wordlift_Entity_Type_Service} instance.
32
-	 */
33
-	private $entity_type_service;
34
-
35
-	/**
36
-	 * The singleton instance.
37
-	 *
38
-	 * @since 3.20.0
39
-	 * @access private
40
-	 * @var \Wordlift_Mapping_Service $instance The singleton instance.
41
-	 */
42
-	private static $instance;
43
-
44
-	/**
45
-	 * Create a {@link Wordlift_Mapping_Service} instance.
46
-	 *
47
-	 * @since 3.20.0
48
-	 *
49
-	 * @param \Wordlift_Entity_Type_Service $entity_type_service The {@link Wordlift_Entity_Type_Service} instance.
50
-	 */
51
-	public function __construct( $entity_type_service ) {
52
-
53
-		// Set the entity type service instance.
54
-		$this->entity_type_service = $entity_type_service;
55
-
56
-		// Load the options.
57
-		$this->options = get_option( 'wl_mappings', array() );
58
-
59
-		// Hook to `wl_valid_entity_post_types` and to `wl_default_entity_types_for_post_type`.
60
-		add_filter( 'wl_valid_entity_post_types', array( $this, 'valid_entity_post_types' ), 9 );
61
-		add_filter(
62
-			'wl_default_entity_types_for_post_type',
63
-			array(
64
-				$this,
65
-				'default_entity_types_for_post_type',
66
-			),
67
-			9,
68
-			2
69
-		);
70
-
71
-		// Set the singleton instance.
72
-		self::$instance = $this;
73
-
74
-	}
75
-
76
-	/**
77
-	 * Get the singleton instance.
78
-	 *
79
-	 * @since 3.20.0
80
-	 *
81
-	 * @return \Wordlift_Mapping_Service The singleton instance.
82
-	 */
83
-	public static function get_instance() {
84
-
85
-		return self::$instance;
86
-	}
87
-
88
-	/**
89
-	 * Save the options.
90
-	 *
91
-	 * @since 3.20.0
92
-	 */
93
-	private function save_options() {
94
-
95
-		update_option( 'wl_mappings', $this->options, true );
96
-
97
-	}
98
-
99
-	/**
100
-	 * Set the default entity types for a post type.
101
-	 *
102
-	 * @since 3.20.0
103
-	 *
104
-	 * @param string $post_type Post type.
105
-	 * @param array  $entity_types An array of entity types slugs.
106
-	 */
107
-	public function set_entity_types_for_post_type( $post_type, $entity_types ) {
108
-
109
-		$this->options[ $post_type ] = $entity_types;
110
-		$this->save_options();
111
-
112
-	}
113
-
114
-	/**
115
-	 * Hook to `wl_valid_entity_post_types` to declare schema.org support for the configured post types.
116
-	 *
117
-	 * @since 3.20.0
118
-	 *
119
-	 * @param array $post_types The default post types.
120
-	 *
121
-	 * @return array The supported post types.
122
-	 */
123
-	public function valid_entity_post_types( $post_types ) {
124
-
125
-		return array_merge( $post_types, array_keys( $this->options ) );
126
-	}
127
-
128
-	/**
129
-	 * Hook to `wl_default_entity_types_for_post_type` to declare the entity types for a post type.
130
-	 *
131
-	 * @since 3.20.0
132
-	 *
133
-	 * @param array  $default The default entity types.
134
-	 * @param string $post_type The post type.
135
-	 *
136
-	 * @return array The default entity types.
137
-	 */
138
-	public function default_entity_types_for_post_type( $default, $post_type ) {
139
-
140
-		return isset( $this->options[ $post_type ] ) ? $this->options[ $post_type ] : $default;
141
-	}
142
-
143
-	/**
144
-	 * Update the post type with the entity types, starting at the specified offset.
145
-	 *
146
-	 * @since 3.20.0
147
-	 *
148
-	 * @param string $post_type The post type.
149
-	 * @param array  $entity_types The entity types.
150
-	 * @param int    $offset The offset (0 by default).
151
-	 *
152
-	 * @return array {
153
-	 * The result array.
154
-	 *
155
-	 * @type int     $current The current offset.
156
-	 * @type int     $next The next offset.
157
-	 * @type int     $count The total element count.
158
-	 * }
159
-	 */
160
-	public function update( $post_type, $entity_types, $offset = 0 ) {
161
-
162
-		$entity_type_service = $this->entity_type_service;
163
-		$tax_query           = $this->get_tax_query( $entity_types );
164
-
165
-		return Wordlift_Batch_Action::process(
166
-			$post_type,
167
-			$offset,
168
-			$tax_query,
169
-			function ( $post_id ) use ( $entity_type_service, $entity_types ) {
170
-				foreach ( $entity_types as $entity_type ) {
171
-					$entity_type_service->set( $post_id, $entity_type, false );
172
-				}
173
-			}
174
-		);
175
-	}
176
-
177
-	/**
178
-	 * Count the number of posts that need to be assigned with the entity types.
179
-	 *
180
-	 * @since 3.20.0
181
-	 *
182
-	 * @param string $post_type The post type.
183
-	 * @param array  $entity_types An array of entity types.
184
-	 *
185
-	 * @return int The number of posts to be assigned with entity types.
186
-	 */
187
-	public function count( $post_type, $entity_types ) {
188
-
189
-		$tax_query = $this->get_tax_query( $entity_types );
190
-
191
-		return Wordlift_Batch_Action::count( $post_type, $tax_query );
192
-	}
193
-
194
-	/**
195
-	 * Get the taxonomy query for the specified entity types.
196
-	 *
197
-	 * @since 3.20.0
198
-	 *
199
-	 * @param array $entity_types The entity types.
200
-	 *
201
-	 * @return array The tax query.
202
-	 */
203
-	private function get_tax_query( $entity_types ) {
204
-
205
-		$entity_type_service = $this->entity_type_service;
206
-		$entity_types_terms  = array_filter(
207
-			array_map(
208
-				function ( $item ) use ( $entity_type_service ) {
209
-					return $entity_type_service->get_term_by_uri( $item );
210
-				},
211
-				$entity_types
212
-			)
213
-		);
214
-
215
-		$entity_types_terms_ids = array_map(
216
-			function ( $term ) {
217
-				return $term->term_id;
218
-			},
219
-			$entity_types_terms
220
-		);
221
-
222
-		$tax_query = array(
223
-			'tax_query' => array(
224
-				array(
225
-					'taxonomy' => Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
226
-					'field'    => 'term_id',
227
-					'terms'    => $entity_types_terms_ids,
228
-					'operator' => 'NOT IN',
229
-				),
230
-			),
231
-		);
232
-
233
-		return $tax_query;
234
-	}
17
+    /**
18
+     * The mapping's options.
19
+     *
20
+     * @since 3.20.0
21
+     * @access private
22
+     * @var array $options The mapping's options.
23
+     */
24
+    private $options;
25
+
26
+    /**
27
+     * The {@link Wordlift_Entity_Type_Service} instance.
28
+     *
29
+     * @since 3.20.0
30
+     * @access private
31
+     * @var \Wordlift_Entity_Type_Service $entity_type_service The {@link Wordlift_Entity_Type_Service} instance.
32
+     */
33
+    private $entity_type_service;
34
+
35
+    /**
36
+     * The singleton instance.
37
+     *
38
+     * @since 3.20.0
39
+     * @access private
40
+     * @var \Wordlift_Mapping_Service $instance The singleton instance.
41
+     */
42
+    private static $instance;
43
+
44
+    /**
45
+     * Create a {@link Wordlift_Mapping_Service} instance.
46
+     *
47
+     * @since 3.20.0
48
+     *
49
+     * @param \Wordlift_Entity_Type_Service $entity_type_service The {@link Wordlift_Entity_Type_Service} instance.
50
+     */
51
+    public function __construct( $entity_type_service ) {
52
+
53
+        // Set the entity type service instance.
54
+        $this->entity_type_service = $entity_type_service;
55
+
56
+        // Load the options.
57
+        $this->options = get_option( 'wl_mappings', array() );
58
+
59
+        // Hook to `wl_valid_entity_post_types` and to `wl_default_entity_types_for_post_type`.
60
+        add_filter( 'wl_valid_entity_post_types', array( $this, 'valid_entity_post_types' ), 9 );
61
+        add_filter(
62
+            'wl_default_entity_types_for_post_type',
63
+            array(
64
+                $this,
65
+                'default_entity_types_for_post_type',
66
+            ),
67
+            9,
68
+            2
69
+        );
70
+
71
+        // Set the singleton instance.
72
+        self::$instance = $this;
73
+
74
+    }
75
+
76
+    /**
77
+     * Get the singleton instance.
78
+     *
79
+     * @since 3.20.0
80
+     *
81
+     * @return \Wordlift_Mapping_Service The singleton instance.
82
+     */
83
+    public static function get_instance() {
84
+
85
+        return self::$instance;
86
+    }
87
+
88
+    /**
89
+     * Save the options.
90
+     *
91
+     * @since 3.20.0
92
+     */
93
+    private function save_options() {
94
+
95
+        update_option( 'wl_mappings', $this->options, true );
96
+
97
+    }
98
+
99
+    /**
100
+     * Set the default entity types for a post type.
101
+     *
102
+     * @since 3.20.0
103
+     *
104
+     * @param string $post_type Post type.
105
+     * @param array  $entity_types An array of entity types slugs.
106
+     */
107
+    public function set_entity_types_for_post_type( $post_type, $entity_types ) {
108
+
109
+        $this->options[ $post_type ] = $entity_types;
110
+        $this->save_options();
111
+
112
+    }
113
+
114
+    /**
115
+     * Hook to `wl_valid_entity_post_types` to declare schema.org support for the configured post types.
116
+     *
117
+     * @since 3.20.0
118
+     *
119
+     * @param array $post_types The default post types.
120
+     *
121
+     * @return array The supported post types.
122
+     */
123
+    public function valid_entity_post_types( $post_types ) {
124
+
125
+        return array_merge( $post_types, array_keys( $this->options ) );
126
+    }
127
+
128
+    /**
129
+     * Hook to `wl_default_entity_types_for_post_type` to declare the entity types for a post type.
130
+     *
131
+     * @since 3.20.0
132
+     *
133
+     * @param array  $default The default entity types.
134
+     * @param string $post_type The post type.
135
+     *
136
+     * @return array The default entity types.
137
+     */
138
+    public function default_entity_types_for_post_type( $default, $post_type ) {
139
+
140
+        return isset( $this->options[ $post_type ] ) ? $this->options[ $post_type ] : $default;
141
+    }
142
+
143
+    /**
144
+     * Update the post type with the entity types, starting at the specified offset.
145
+     *
146
+     * @since 3.20.0
147
+     *
148
+     * @param string $post_type The post type.
149
+     * @param array  $entity_types The entity types.
150
+     * @param int    $offset The offset (0 by default).
151
+     *
152
+     * @return array {
153
+     * The result array.
154
+     *
155
+     * @type int     $current The current offset.
156
+     * @type int     $next The next offset.
157
+     * @type int     $count The total element count.
158
+     * }
159
+     */
160
+    public function update( $post_type, $entity_types, $offset = 0 ) {
161
+
162
+        $entity_type_service = $this->entity_type_service;
163
+        $tax_query           = $this->get_tax_query( $entity_types );
164
+
165
+        return Wordlift_Batch_Action::process(
166
+            $post_type,
167
+            $offset,
168
+            $tax_query,
169
+            function ( $post_id ) use ( $entity_type_service, $entity_types ) {
170
+                foreach ( $entity_types as $entity_type ) {
171
+                    $entity_type_service->set( $post_id, $entity_type, false );
172
+                }
173
+            }
174
+        );
175
+    }
176
+
177
+    /**
178
+     * Count the number of posts that need to be assigned with the entity types.
179
+     *
180
+     * @since 3.20.0
181
+     *
182
+     * @param string $post_type The post type.
183
+     * @param array  $entity_types An array of entity types.
184
+     *
185
+     * @return int The number of posts to be assigned with entity types.
186
+     */
187
+    public function count( $post_type, $entity_types ) {
188
+
189
+        $tax_query = $this->get_tax_query( $entity_types );
190
+
191
+        return Wordlift_Batch_Action::count( $post_type, $tax_query );
192
+    }
193
+
194
+    /**
195
+     * Get the taxonomy query for the specified entity types.
196
+     *
197
+     * @since 3.20.0
198
+     *
199
+     * @param array $entity_types The entity types.
200
+     *
201
+     * @return array The tax query.
202
+     */
203
+    private function get_tax_query( $entity_types ) {
204
+
205
+        $entity_type_service = $this->entity_type_service;
206
+        $entity_types_terms  = array_filter(
207
+            array_map(
208
+                function ( $item ) use ( $entity_type_service ) {
209
+                    return $entity_type_service->get_term_by_uri( $item );
210
+                },
211
+                $entity_types
212
+            )
213
+        );
214
+
215
+        $entity_types_terms_ids = array_map(
216
+            function ( $term ) {
217
+                return $term->term_id;
218
+            },
219
+            $entity_types_terms
220
+        );
221
+
222
+        $tax_query = array(
223
+            'tax_query' => array(
224
+                array(
225
+                    'taxonomy' => Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
226
+                    'field'    => 'term_id',
227
+                    'terms'    => $entity_types_terms_ids,
228
+                    'operator' => 'NOT IN',
229
+                ),
230
+            ),
231
+        );
232
+
233
+        return $tax_query;
234
+    }
235 235
 
236 236
 }
Please login to merge, or discard this patch.
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -48,16 +48,16 @@  discard block
 block discarded – undo
48 48
 	 *
49 49
 	 * @param \Wordlift_Entity_Type_Service $entity_type_service The {@link Wordlift_Entity_Type_Service} instance.
50 50
 	 */
51
-	public function __construct( $entity_type_service ) {
51
+	public function __construct($entity_type_service) {
52 52
 
53 53
 		// Set the entity type service instance.
54 54
 		$this->entity_type_service = $entity_type_service;
55 55
 
56 56
 		// Load the options.
57
-		$this->options = get_option( 'wl_mappings', array() );
57
+		$this->options = get_option('wl_mappings', array());
58 58
 
59 59
 		// Hook to `wl_valid_entity_post_types` and to `wl_default_entity_types_for_post_type`.
60
-		add_filter( 'wl_valid_entity_post_types', array( $this, 'valid_entity_post_types' ), 9 );
60
+		add_filter('wl_valid_entity_post_types', array($this, 'valid_entity_post_types'), 9);
61 61
 		add_filter(
62 62
 			'wl_default_entity_types_for_post_type',
63 63
 			array(
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
 	 */
93 93
 	private function save_options() {
94 94
 
95
-		update_option( 'wl_mappings', $this->options, true );
95
+		update_option('wl_mappings', $this->options, true);
96 96
 
97 97
 	}
98 98
 
@@ -104,9 +104,9 @@  discard block
 block discarded – undo
104 104
 	 * @param string $post_type Post type.
105 105
 	 * @param array  $entity_types An array of entity types slugs.
106 106
 	 */
107
-	public function set_entity_types_for_post_type( $post_type, $entity_types ) {
107
+	public function set_entity_types_for_post_type($post_type, $entity_types) {
108 108
 
109
-		$this->options[ $post_type ] = $entity_types;
109
+		$this->options[$post_type] = $entity_types;
110 110
 		$this->save_options();
111 111
 
112 112
 	}
@@ -120,9 +120,9 @@  discard block
 block discarded – undo
120 120
 	 *
121 121
 	 * @return array The supported post types.
122 122
 	 */
123
-	public function valid_entity_post_types( $post_types ) {
123
+	public function valid_entity_post_types($post_types) {
124 124
 
125
-		return array_merge( $post_types, array_keys( $this->options ) );
125
+		return array_merge($post_types, array_keys($this->options));
126 126
 	}
127 127
 
128 128
 	/**
@@ -135,9 +135,9 @@  discard block
 block discarded – undo
135 135
 	 *
136 136
 	 * @return array The default entity types.
137 137
 	 */
138
-	public function default_entity_types_for_post_type( $default, $post_type ) {
138
+	public function default_entity_types_for_post_type($default, $post_type) {
139 139
 
140
-		return isset( $this->options[ $post_type ] ) ? $this->options[ $post_type ] : $default;
140
+		return isset($this->options[$post_type]) ? $this->options[$post_type] : $default;
141 141
 	}
142 142
 
143 143
 	/**
@@ -157,18 +157,18 @@  discard block
 block discarded – undo
157 157
 	 * @type int     $count The total element count.
158 158
 	 * }
159 159
 	 */
160
-	public function update( $post_type, $entity_types, $offset = 0 ) {
160
+	public function update($post_type, $entity_types, $offset = 0) {
161 161
 
162 162
 		$entity_type_service = $this->entity_type_service;
163
-		$tax_query           = $this->get_tax_query( $entity_types );
163
+		$tax_query           = $this->get_tax_query($entity_types);
164 164
 
165 165
 		return Wordlift_Batch_Action::process(
166 166
 			$post_type,
167 167
 			$offset,
168 168
 			$tax_query,
169
-			function ( $post_id ) use ( $entity_type_service, $entity_types ) {
170
-				foreach ( $entity_types as $entity_type ) {
171
-					$entity_type_service->set( $post_id, $entity_type, false );
169
+			function($post_id) use ($entity_type_service, $entity_types) {
170
+				foreach ($entity_types as $entity_type) {
171
+					$entity_type_service->set($post_id, $entity_type, false);
172 172
 				}
173 173
 			}
174 174
 		);
@@ -184,11 +184,11 @@  discard block
 block discarded – undo
184 184
 	 *
185 185
 	 * @return int The number of posts to be assigned with entity types.
186 186
 	 */
187
-	public function count( $post_type, $entity_types ) {
187
+	public function count($post_type, $entity_types) {
188 188
 
189
-		$tax_query = $this->get_tax_query( $entity_types );
189
+		$tax_query = $this->get_tax_query($entity_types);
190 190
 
191
-		return Wordlift_Batch_Action::count( $post_type, $tax_query );
191
+		return Wordlift_Batch_Action::count($post_type, $tax_query);
192 192
 	}
193 193
 
194 194
 	/**
@@ -200,20 +200,20 @@  discard block
 block discarded – undo
200 200
 	 *
201 201
 	 * @return array The tax query.
202 202
 	 */
203
-	private function get_tax_query( $entity_types ) {
203
+	private function get_tax_query($entity_types) {
204 204
 
205 205
 		$entity_type_service = $this->entity_type_service;
206 206
 		$entity_types_terms  = array_filter(
207 207
 			array_map(
208
-				function ( $item ) use ( $entity_type_service ) {
209
-					return $entity_type_service->get_term_by_uri( $item );
208
+				function($item) use ($entity_type_service) {
209
+					return $entity_type_service->get_term_by_uri($item);
210 210
 				},
211 211
 				$entity_types
212 212
 			)
213 213
 		);
214 214
 
215 215
 		$entity_types_terms_ids = array_map(
216
-			function ( $term ) {
216
+			function($term) {
217 217
 				return $term->term_id;
218 218
 			},
219 219
 			$entity_types_terms
Please login to merge, or discard this patch.
src/includes/class-wordlift-post-adapter.php 2 patches
Indentation   +248 added lines, -248 removed lines patch added patch discarded remove patch
@@ -19,258 +19,258 @@
 block discarded – undo
19 19
  */
20 20
 class Wordlift_Post_Adapter {
21 21
 
22
-	/**
23
-	 * The post id to which the adopter relates.
24
-	 *
25
-	 * @since 3.14.0
26
-	 *
27
-	 * @var integer $post_id .
28
-	 */
29
-	private $post_id;
30
-
31
-	const TYPE_ENTITY_LINK = 0;
32
-	const TYPE_TERM_LINK   = 1;
33
-
34
-	/**
35
-	 * Create the {@link Wordlift_Post_Adatpter} instance.
36
-	 *
37
-	 * @param integer $post_id the post ID of the post the adopter relates to.
38
-	 *
39
-	 * @since 3.14.0
40
-	 */
41
-	public function __construct( $post_id ) {
42
-
43
-		$this->post_id = $post_id;
44
-
45
-	}
46
-
47
-	/**
48
-	 * Get the word count of the post content.
49
-	 *
50
-	 * The count is calculated over the post content after stripping shortcodes and html tags.
51
-	 *
52
-	 * @return integer the number of words in the content after stripping shortcodes and html tags..
53
-	 * @since 3.14.0
54
-	 */
55
-	public function word_count() {
56
-
57
-		$post = get_post( $this->post_id );
58
-
59
-		/*
22
+    /**
23
+     * The post id to which the adopter relates.
24
+     *
25
+     * @since 3.14.0
26
+     *
27
+     * @var integer $post_id .
28
+     */
29
+    private $post_id;
30
+
31
+    const TYPE_ENTITY_LINK = 0;
32
+    const TYPE_TERM_LINK   = 1;
33
+
34
+    /**
35
+     * Create the {@link Wordlift_Post_Adatpter} instance.
36
+     *
37
+     * @param integer $post_id the post ID of the post the adopter relates to.
38
+     *
39
+     * @since 3.14.0
40
+     */
41
+    public function __construct( $post_id ) {
42
+
43
+        $this->post_id = $post_id;
44
+
45
+    }
46
+
47
+    /**
48
+     * Get the word count of the post content.
49
+     *
50
+     * The count is calculated over the post content after stripping shortcodes and html tags.
51
+     *
52
+     * @return integer the number of words in the content after stripping shortcodes and html tags..
53
+     * @since 3.14.0
54
+     */
55
+    public function word_count() {
56
+
57
+        $post = get_post( $this->post_id );
58
+
59
+        /*
60 60
 		 * Apply the `wl_post_content` filter, in case 3rd parties want to change the post content, e.g.
61 61
 		 * because the content is written elsewhere.
62 62
 		 *
63 63
 		 * @since 3.20.0
64 64
 		 */
65
-		$post_content = apply_filters( 'wl_post_content', $post->post_content, $post );
66
-
67
-		return self::str_word_count_utf8( wp_strip_all_tags( strip_shortcodes( $post_content ) ) );
68
-	}
69
-
70
-	/**
71
-	 * Count words in the string, taking into account UTF-8 characters.
72
-	 *
73
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/884
74
-	 *
75
-	 * @since 3.20.0
76
-	 *
77
-	 * @param string $str The target string.
78
-	 *
79
-	 * @return int The number of words.
80
-	 */
81
-	private static function str_word_count_utf8( $str ) {
82
-
83
-		$words = preg_split( '~[^\p{L}\p{N}\']+~u', $str );
84
-
85
-		return $words ? count( $words ) : 0;
86
-	}
87
-
88
-	/**
89
-	 * Get the {@link WP_Post} permalink allowing 3rd parties to alter the URL.
90
-	 *
91
-	 * @param int $post_id Post ID.
92
-	 *
93
-	 * @return string The post permalink.
94
-	 * @since 3.20.0
95
-	 */
96
-	public static function get_production_permalink( $post_id, $object_type = Object_Type_Enum::POST ) {
97
-
98
-		$object_link_service = Object_Link_Provider::get_instance();
99
-		$permalink           = $object_link_service->get_permalink( $post_id, $object_type );
100
-
101
-		/**
102
-		 * WordPress 4.4 doesn't support meta queries for terms, therefore we only support post permalinks here.
103
-		 *
104
-		 * Later on for WordPress 4.5+ we look for terms bound to the entity and we use the term link instead of the
105
-		 * post permalink if we find them.
106
-		 */
107
-		global $wp_version;
108
-		if ( version_compare( $wp_version, '4.5', '<' ) ) {
109
-			return apply_filters( 'wl_production_permalink', $permalink, $post_id, self::TYPE_ENTITY_LINK, null );
110
-		}
111
-
112
-		/**
113
-		 * The `wl_production_permalink` filter allows to change the permalink, this is useful in contexts
114
-		 * when the production environment is copied over from a staging environment with staging
115
-		 * URLs.
116
-		 *
117
-		 * @param string $permalink_url The default permalink.
118
-		 * @param int $post_id The post id.
119
-		 *
120
-		 * @since 3.23.0 we check whether the entity is bound to a term and, in that case, we link to the term.
121
-		 * @since 3.20.0
122
-		 *
123
-		 * @see https://github.com/insideout10/wordlift-plugin/issues/850
124
-		 */
125
-
126
-		$uris = $object_link_service->get_same_as_uris(
127
-			$post_id,
128
-			$object_type
129
-		);
130
-
131
-		// Only try to link a term if `WL_ENABLE_TERM_LINKING` is enabled.
132
-		$terms = array();
133
-		if ( defined( 'WL_ENABLE_TERM_LINKING' ) && WL_ENABLE_TERM_LINKING ) {
134
-			// Try to find one term matching the entity.
135
-			$terms = get_terms(
136
-				array(
137
-					'number'                 => 1,
138
-					'hide_empty'             => false,
139
-					'update_term_meta_cache' => false,
140
-					'meta_key'               => '_wl_entity_id',
141
-					'meta_value'             => $uris,
142
-					'meta_compare'           => 'IN',
143
-				)
144
-			);
145
-		}
146
-
147
-		$type = self::TYPE_ENTITY_LINK;
148
-		$term = null;
149
-		// If found use the term link, otherwise the permalink.
150
-		if ( 1 === count( $terms ) ) {
151
-			$term      = current( $terms );
152
-			$permalink = get_term_link( $term );
153
-			$type      = self::TYPE_TERM_LINK;
154
-		}
155
-
156
-		/**
157
-		 * Apply the `wl_production_permalink` filter.
158
-		 *
159
-		 * @param string $permalink The permalink.
160
-		 * @param int $post_id The post id.
161
-		 * @param int $type The permalink type: 0 = entity permalink, 1 = term link.
162
-		 * @param WP_Term $term The term if type is term link, otherwise null.
163
-		 *
164
-		 * @since 3.23.0 add the permalink type and term parameters.
165
-		 */
166
-		return apply_filters( 'wl_production_permalink', $permalink, $post_id, $type, $term );
167
-	}
168
-
169
-	/**
170
-	 * Get comma separated tags to be used as keywords
171
-	 *
172
-	 * @return string|void Comma separated tags
173
-	 *
174
-	 * @since 3.27.2
175
-	 */
176
-	public function keywords() {
177
-		$tags = get_the_tags( $this->post_id );
178
-
179
-		if ( empty( $tags ) ) {
180
-			return;
181
-		}
182
-
183
-		return implode(
184
-			',',
185
-			array_map(
186
-				function ( $tag ) {
187
-					return $tag->name;
188
-				},
189
-				$tags
190
-			)
191
-		);
192
-	}
193
-
194
-	/**
195
-	 * Get comma separated categories to be used as article section
196
-	 *
197
-	 * @return string[] Comma separated categories
198
-	 *
199
-	 * @since 3.27.2
200
-	 */
201
-	public function article_section() {
202
-		$categories = get_the_category( $this->post_id );
203
-
204
-		return wp_list_pluck( $categories, 'cat_name' );
205
-	}
206
-
207
-	/**
208
-	 * Get comment count
209
-	 *
210
-	 * @return string|void Comment count
211
-	 *
212
-	 * @since 3.27.2
213
-	 */
214
-	public function comment_count() {
215
-		return get_comments_number( $this->post_id );
216
-	}
217
-
218
-	/**
219
-	 * Get Language
220
-	 * Try WPML, Polylang for post specific languages, else fallback on get_locale()
221
-	 *
222
-	 * @return string|void Language code (locale)
223
-	 *
224
-	 * @since 3.27.2
225
-	 */
226
-	public function locale() {
227
-		$language = 'en-US';
228
-
229
-		if ( function_exists( 'wpml_get_language_information' ) ) {
230
-			// WPML handling
231
-			// WPML: Updated function signature.
232
-			// function wpml_get_language_information( $empty_value = null, $post_id = null )
233
-			$post_language = wpml_get_language_information( null, $this->post_id );
234
-			if ( ! $post_language instanceof WP_Error ) {
235
-				$language = $post_language['locale'];
236
-			}
237
-		} elseif ( function_exists( 'pll_get_post_language' ) ) {
238
-			// Polylang handling
239
-			$language = pll_get_post_language( $this->post_id, 'locale' );
240
-		} else {
241
-			$language = get_locale();
242
-		}
243
-
244
-		return str_replace( '_', '-', $language );
245
-	}
246
-
247
-	/**
248
-	 * Add mentions to an article.
249
-	 * To add mentions we just push the referenced entities to mentions.
250
-	 *
251
-	 * @param $post_id int
252
-	 * @param $references int[]
253
-	 */
254
-	public function add_references( $post_id, &$references ) {
255
-		$tags = get_the_tags( $post_id );
256
-
257
-		if ( $tags && ! is_wp_error( $tags ) ) {
258
-			// Loop through the tags and push it to references.
259
-			foreach ( $tags as $tag ) {
260
-				/**
261
-				 * @var $tag WP_Term
262
-				 */
263
-				$entity_uris = get_term_meta( $tag->term_id, '_wl_entity_id' );
264
-				foreach ( $entity_uris as $uri ) {
265
-					$referenced_entity = Wordlift_Entity_Uri_Service::get_instance()->get_entity( $uri );
266
-					if ( $referenced_entity instanceof WP_Post ) {
267
-						// push the referenced entities to references.
268
-						$references[] = $referenced_entity->ID;
269
-					}
270
-				}
271
-			}
272
-		}
273
-
274
-	}
65
+        $post_content = apply_filters( 'wl_post_content', $post->post_content, $post );
66
+
67
+        return self::str_word_count_utf8( wp_strip_all_tags( strip_shortcodes( $post_content ) ) );
68
+    }
69
+
70
+    /**
71
+     * Count words in the string, taking into account UTF-8 characters.
72
+     *
73
+     * @see https://github.com/insideout10/wordlift-plugin/issues/884
74
+     *
75
+     * @since 3.20.0
76
+     *
77
+     * @param string $str The target string.
78
+     *
79
+     * @return int The number of words.
80
+     */
81
+    private static function str_word_count_utf8( $str ) {
82
+
83
+        $words = preg_split( '~[^\p{L}\p{N}\']+~u', $str );
84
+
85
+        return $words ? count( $words ) : 0;
86
+    }
87
+
88
+    /**
89
+     * Get the {@link WP_Post} permalink allowing 3rd parties to alter the URL.
90
+     *
91
+     * @param int $post_id Post ID.
92
+     *
93
+     * @return string The post permalink.
94
+     * @since 3.20.0
95
+     */
96
+    public static function get_production_permalink( $post_id, $object_type = Object_Type_Enum::POST ) {
97
+
98
+        $object_link_service = Object_Link_Provider::get_instance();
99
+        $permalink           = $object_link_service->get_permalink( $post_id, $object_type );
100
+
101
+        /**
102
+         * WordPress 4.4 doesn't support meta queries for terms, therefore we only support post permalinks here.
103
+         *
104
+         * Later on for WordPress 4.5+ we look for terms bound to the entity and we use the term link instead of the
105
+         * post permalink if we find them.
106
+         */
107
+        global $wp_version;
108
+        if ( version_compare( $wp_version, '4.5', '<' ) ) {
109
+            return apply_filters( 'wl_production_permalink', $permalink, $post_id, self::TYPE_ENTITY_LINK, null );
110
+        }
111
+
112
+        /**
113
+         * The `wl_production_permalink` filter allows to change the permalink, this is useful in contexts
114
+         * when the production environment is copied over from a staging environment with staging
115
+         * URLs.
116
+         *
117
+         * @param string $permalink_url The default permalink.
118
+         * @param int $post_id The post id.
119
+         *
120
+         * @since 3.23.0 we check whether the entity is bound to a term and, in that case, we link to the term.
121
+         * @since 3.20.0
122
+         *
123
+         * @see https://github.com/insideout10/wordlift-plugin/issues/850
124
+         */
125
+
126
+        $uris = $object_link_service->get_same_as_uris(
127
+            $post_id,
128
+            $object_type
129
+        );
130
+
131
+        // Only try to link a term if `WL_ENABLE_TERM_LINKING` is enabled.
132
+        $terms = array();
133
+        if ( defined( 'WL_ENABLE_TERM_LINKING' ) && WL_ENABLE_TERM_LINKING ) {
134
+            // Try to find one term matching the entity.
135
+            $terms = get_terms(
136
+                array(
137
+                    'number'                 => 1,
138
+                    'hide_empty'             => false,
139
+                    'update_term_meta_cache' => false,
140
+                    'meta_key'               => '_wl_entity_id',
141
+                    'meta_value'             => $uris,
142
+                    'meta_compare'           => 'IN',
143
+                )
144
+            );
145
+        }
146
+
147
+        $type = self::TYPE_ENTITY_LINK;
148
+        $term = null;
149
+        // If found use the term link, otherwise the permalink.
150
+        if ( 1 === count( $terms ) ) {
151
+            $term      = current( $terms );
152
+            $permalink = get_term_link( $term );
153
+            $type      = self::TYPE_TERM_LINK;
154
+        }
155
+
156
+        /**
157
+         * Apply the `wl_production_permalink` filter.
158
+         *
159
+         * @param string $permalink The permalink.
160
+         * @param int $post_id The post id.
161
+         * @param int $type The permalink type: 0 = entity permalink, 1 = term link.
162
+         * @param WP_Term $term The term if type is term link, otherwise null.
163
+         *
164
+         * @since 3.23.0 add the permalink type and term parameters.
165
+         */
166
+        return apply_filters( 'wl_production_permalink', $permalink, $post_id, $type, $term );
167
+    }
168
+
169
+    /**
170
+     * Get comma separated tags to be used as keywords
171
+     *
172
+     * @return string|void Comma separated tags
173
+     *
174
+     * @since 3.27.2
175
+     */
176
+    public function keywords() {
177
+        $tags = get_the_tags( $this->post_id );
178
+
179
+        if ( empty( $tags ) ) {
180
+            return;
181
+        }
182
+
183
+        return implode(
184
+            ',',
185
+            array_map(
186
+                function ( $tag ) {
187
+                    return $tag->name;
188
+                },
189
+                $tags
190
+            )
191
+        );
192
+    }
193
+
194
+    /**
195
+     * Get comma separated categories to be used as article section
196
+     *
197
+     * @return string[] Comma separated categories
198
+     *
199
+     * @since 3.27.2
200
+     */
201
+    public function article_section() {
202
+        $categories = get_the_category( $this->post_id );
203
+
204
+        return wp_list_pluck( $categories, 'cat_name' );
205
+    }
206
+
207
+    /**
208
+     * Get comment count
209
+     *
210
+     * @return string|void Comment count
211
+     *
212
+     * @since 3.27.2
213
+     */
214
+    public function comment_count() {
215
+        return get_comments_number( $this->post_id );
216
+    }
217
+
218
+    /**
219
+     * Get Language
220
+     * Try WPML, Polylang for post specific languages, else fallback on get_locale()
221
+     *
222
+     * @return string|void Language code (locale)
223
+     *
224
+     * @since 3.27.2
225
+     */
226
+    public function locale() {
227
+        $language = 'en-US';
228
+
229
+        if ( function_exists( 'wpml_get_language_information' ) ) {
230
+            // WPML handling
231
+            // WPML: Updated function signature.
232
+            // function wpml_get_language_information( $empty_value = null, $post_id = null )
233
+            $post_language = wpml_get_language_information( null, $this->post_id );
234
+            if ( ! $post_language instanceof WP_Error ) {
235
+                $language = $post_language['locale'];
236
+            }
237
+        } elseif ( function_exists( 'pll_get_post_language' ) ) {
238
+            // Polylang handling
239
+            $language = pll_get_post_language( $this->post_id, 'locale' );
240
+        } else {
241
+            $language = get_locale();
242
+        }
243
+
244
+        return str_replace( '_', '-', $language );
245
+    }
246
+
247
+    /**
248
+     * Add mentions to an article.
249
+     * To add mentions we just push the referenced entities to mentions.
250
+     *
251
+     * @param $post_id int
252
+     * @param $references int[]
253
+     */
254
+    public function add_references( $post_id, &$references ) {
255
+        $tags = get_the_tags( $post_id );
256
+
257
+        if ( $tags && ! is_wp_error( $tags ) ) {
258
+            // Loop through the tags and push it to references.
259
+            foreach ( $tags as $tag ) {
260
+                /**
261
+                 * @var $tag WP_Term
262
+                 */
263
+                $entity_uris = get_term_meta( $tag->term_id, '_wl_entity_id' );
264
+                foreach ( $entity_uris as $uri ) {
265
+                    $referenced_entity = Wordlift_Entity_Uri_Service::get_instance()->get_entity( $uri );
266
+                    if ( $referenced_entity instanceof WP_Post ) {
267
+                        // push the referenced entities to references.
268
+                        $references[] = $referenced_entity->ID;
269
+                    }
270
+                }
271
+            }
272
+        }
273
+
274
+    }
275 275
 
276 276
 }
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
 	 *
39 39
 	 * @since 3.14.0
40 40
 	 */
41
-	public function __construct( $post_id ) {
41
+	public function __construct($post_id) {
42 42
 
43 43
 		$this->post_id = $post_id;
44 44
 
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
 	 */
55 55
 	public function word_count() {
56 56
 
57
-		$post = get_post( $this->post_id );
57
+		$post = get_post($this->post_id);
58 58
 
59 59
 		/*
60 60
 		 * Apply the `wl_post_content` filter, in case 3rd parties want to change the post content, e.g.
@@ -62,9 +62,9 @@  discard block
 block discarded – undo
62 62
 		 *
63 63
 		 * @since 3.20.0
64 64
 		 */
65
-		$post_content = apply_filters( 'wl_post_content', $post->post_content, $post );
65
+		$post_content = apply_filters('wl_post_content', $post->post_content, $post);
66 66
 
67
-		return self::str_word_count_utf8( wp_strip_all_tags( strip_shortcodes( $post_content ) ) );
67
+		return self::str_word_count_utf8(wp_strip_all_tags(strip_shortcodes($post_content)));
68 68
 	}
69 69
 
70 70
 	/**
@@ -78,11 +78,11 @@  discard block
 block discarded – undo
78 78
 	 *
79 79
 	 * @return int The number of words.
80 80
 	 */
81
-	private static function str_word_count_utf8( $str ) {
81
+	private static function str_word_count_utf8($str) {
82 82
 
83
-		$words = preg_split( '~[^\p{L}\p{N}\']+~u', $str );
83
+		$words = preg_split('~[^\p{L}\p{N}\']+~u', $str);
84 84
 
85
-		return $words ? count( $words ) : 0;
85
+		return $words ? count($words) : 0;
86 86
 	}
87 87
 
88 88
 	/**
@@ -93,10 +93,10 @@  discard block
 block discarded – undo
93 93
 	 * @return string The post permalink.
94 94
 	 * @since 3.20.0
95 95
 	 */
96
-	public static function get_production_permalink( $post_id, $object_type = Object_Type_Enum::POST ) {
96
+	public static function get_production_permalink($post_id, $object_type = Object_Type_Enum::POST) {
97 97
 
98 98
 		$object_link_service = Object_Link_Provider::get_instance();
99
-		$permalink           = $object_link_service->get_permalink( $post_id, $object_type );
99
+		$permalink           = $object_link_service->get_permalink($post_id, $object_type);
100 100
 
101 101
 		/**
102 102
 		 * WordPress 4.4 doesn't support meta queries for terms, therefore we only support post permalinks here.
@@ -105,8 +105,8 @@  discard block
 block discarded – undo
105 105
 		 * post permalink if we find them.
106 106
 		 */
107 107
 		global $wp_version;
108
-		if ( version_compare( $wp_version, '4.5', '<' ) ) {
109
-			return apply_filters( 'wl_production_permalink', $permalink, $post_id, self::TYPE_ENTITY_LINK, null );
108
+		if (version_compare($wp_version, '4.5', '<')) {
109
+			return apply_filters('wl_production_permalink', $permalink, $post_id, self::TYPE_ENTITY_LINK, null);
110 110
 		}
111 111
 
112 112
 		/**
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 
131 131
 		// Only try to link a term if `WL_ENABLE_TERM_LINKING` is enabled.
132 132
 		$terms = array();
133
-		if ( defined( 'WL_ENABLE_TERM_LINKING' ) && WL_ENABLE_TERM_LINKING ) {
133
+		if (defined('WL_ENABLE_TERM_LINKING') && WL_ENABLE_TERM_LINKING) {
134 134
 			// Try to find one term matching the entity.
135 135
 			$terms = get_terms(
136 136
 				array(
@@ -147,9 +147,9 @@  discard block
 block discarded – undo
147 147
 		$type = self::TYPE_ENTITY_LINK;
148 148
 		$term = null;
149 149
 		// If found use the term link, otherwise the permalink.
150
-		if ( 1 === count( $terms ) ) {
151
-			$term      = current( $terms );
152
-			$permalink = get_term_link( $term );
150
+		if (1 === count($terms)) {
151
+			$term      = current($terms);
152
+			$permalink = get_term_link($term);
153 153
 			$type      = self::TYPE_TERM_LINK;
154 154
 		}
155 155
 
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 		 *
164 164
 		 * @since 3.23.0 add the permalink type and term parameters.
165 165
 		 */
166
-		return apply_filters( 'wl_production_permalink', $permalink, $post_id, $type, $term );
166
+		return apply_filters('wl_production_permalink', $permalink, $post_id, $type, $term);
167 167
 	}
168 168
 
169 169
 	/**
@@ -174,16 +174,16 @@  discard block
 block discarded – undo
174 174
 	 * @since 3.27.2
175 175
 	 */
176 176
 	public function keywords() {
177
-		$tags = get_the_tags( $this->post_id );
177
+		$tags = get_the_tags($this->post_id);
178 178
 
179
-		if ( empty( $tags ) ) {
179
+		if (empty($tags)) {
180 180
 			return;
181 181
 		}
182 182
 
183 183
 		return implode(
184 184
 			',',
185 185
 			array_map(
186
-				function ( $tag ) {
186
+				function($tag) {
187 187
 					return $tag->name;
188 188
 				},
189 189
 				$tags
@@ -199,9 +199,9 @@  discard block
 block discarded – undo
199 199
 	 * @since 3.27.2
200 200
 	 */
201 201
 	public function article_section() {
202
-		$categories = get_the_category( $this->post_id );
202
+		$categories = get_the_category($this->post_id);
203 203
 
204
-		return wp_list_pluck( $categories, 'cat_name' );
204
+		return wp_list_pluck($categories, 'cat_name');
205 205
 	}
206 206
 
207 207
 	/**
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
 	 * @since 3.27.2
213 213
 	 */
214 214
 	public function comment_count() {
215
-		return get_comments_number( $this->post_id );
215
+		return get_comments_number($this->post_id);
216 216
 	}
217 217
 
218 218
 	/**
@@ -226,22 +226,22 @@  discard block
 block discarded – undo
226 226
 	public function locale() {
227 227
 		$language = 'en-US';
228 228
 
229
-		if ( function_exists( 'wpml_get_language_information' ) ) {
229
+		if (function_exists('wpml_get_language_information')) {
230 230
 			// WPML handling
231 231
 			// WPML: Updated function signature.
232 232
 			// function wpml_get_language_information( $empty_value = null, $post_id = null )
233
-			$post_language = wpml_get_language_information( null, $this->post_id );
234
-			if ( ! $post_language instanceof WP_Error ) {
233
+			$post_language = wpml_get_language_information(null, $this->post_id);
234
+			if ( ! $post_language instanceof WP_Error) {
235 235
 				$language = $post_language['locale'];
236 236
 			}
237
-		} elseif ( function_exists( 'pll_get_post_language' ) ) {
237
+		} elseif (function_exists('pll_get_post_language')) {
238 238
 			// Polylang handling
239
-			$language = pll_get_post_language( $this->post_id, 'locale' );
239
+			$language = pll_get_post_language($this->post_id, 'locale');
240 240
 		} else {
241 241
 			$language = get_locale();
242 242
 		}
243 243
 
244
-		return str_replace( '_', '-', $language );
244
+		return str_replace('_', '-', $language);
245 245
 	}
246 246
 
247 247
 	/**
@@ -251,19 +251,19 @@  discard block
 block discarded – undo
251 251
 	 * @param $post_id int
252 252
 	 * @param $references int[]
253 253
 	 */
254
-	public function add_references( $post_id, &$references ) {
255
-		$tags = get_the_tags( $post_id );
254
+	public function add_references($post_id, &$references) {
255
+		$tags = get_the_tags($post_id);
256 256
 
257
-		if ( $tags && ! is_wp_error( $tags ) ) {
257
+		if ($tags && ! is_wp_error($tags)) {
258 258
 			// Loop through the tags and push it to references.
259
-			foreach ( $tags as $tag ) {
259
+			foreach ($tags as $tag) {
260 260
 				/**
261 261
 				 * @var $tag WP_Term
262 262
 				 */
263
-				$entity_uris = get_term_meta( $tag->term_id, '_wl_entity_id' );
264
-				foreach ( $entity_uris as $uri ) {
265
-					$referenced_entity = Wordlift_Entity_Uri_Service::get_instance()->get_entity( $uri );
266
-					if ( $referenced_entity instanceof WP_Post ) {
263
+				$entity_uris = get_term_meta($tag->term_id, '_wl_entity_id');
264
+				foreach ($entity_uris as $uri) {
265
+					$referenced_entity = Wordlift_Entity_Uri_Service::get_instance()->get_entity($uri);
266
+					if ($referenced_entity instanceof WP_Post) {
267 267
 						// push the referenced entities to references.
268 268
 						$references[] = $referenced_entity->ID;
269 269
 					}
Please login to merge, or discard this patch.
src/includes/class-wordlift-entity-uri-service.php 2 patches
Indentation   +239 added lines, -239 removed lines patch added patch discarded remove patch
@@ -20,100 +20,100 @@  discard block
 block discarded – undo
20 20
  */
21 21
 class Wordlift_Entity_Uri_Service {
22 22
 
23
-	/**
24
-	 * A {@link Wordlift_Log_Service} instance.
25
-	 *
26
-	 * @since  3.16.3
27
-	 * @access private
28
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
29
-	 */
30
-	private $log;
31
-
32
-	/**
33
-	 * An array of URIs to post ID valid for the current request.
34
-	 *
35
-	 * @since  3.16.3
36
-	 * @access private
37
-	 * @var array $uri_to_post An array of URIs to post ID valid for the current request.
38
-	 */
39
-	protected $uri_to_post;
40
-
41
-	/**
42
-	 * Create a {@link Wordlift_Entity_Uri_Service} instance.
43
-	 *
44
-	 * @since 3.16.3
45
-	 */
46
-	protected function __construct() {
47
-
48
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
49
-
50
-		// Add a filter to the `rest_post_dispatch` filter to add the wl_entity_url meta as `wl:entity_url`.
51
-		add_filter( 'rest_post_dispatch', array( $this, 'rest_post_dispatch' ) );
52
-		add_filter( 'wl_content_service__post__not_found', array( $this, 'content_service__post__not_found' ), 10, 2 );
53
-
54
-	}
55
-
56
-	/**
57
-	 * Holds the {@link Wordlift_Entity_Uri_Service} instance.
58
-	 *
59
-	 * @since 3.21.5
60
-	 * @access private
61
-	 * @var Wordlift_Entity_Uri_Service $instance The {@link Wordlift_Entity_Uri_Service} singleton.
62
-	 */
63
-	private static $instance = null;
64
-
65
-	/**
66
-	 * Get the singleton.
67
-	 *
68
-	 * @return Wordlift_Entity_Uri_Service The singleton instance.
69
-	 * @since 3.21.5
70
-	 */
71
-	public static function get_instance() {
72
-
73
-		if ( ! isset( self::$instance ) ) {
74
-			$entity_uri_cache_service = new Wordlift_File_Cache_Service( WL_TEMP_DIR . 'entity_uri/' );
75
-			self::$instance           = new Wordlift_Cached_Entity_Uri_Service( $entity_uri_cache_service );
76
-
77
-		}
78
-
79
-		return self::$instance;
80
-	}
81
-
82
-	/**
83
-	 * Try to find a post when the content service doesn't find it.
84
-	 *
85
-	 * @param WP_Post|null $post
86
-	 * @param string       $uri
87
-	 *
88
-	 * @return false|int
89
-	 */
90
-	public function content_service__post__not_found( $post, $uri ) {
91
-		return $this->get_post_id_from_url( $uri );
92
-	}
93
-
94
-	/**
95
-	 * Preload the provided URIs in the local cache.
96
-	 *
97
-	 * This function will populate the local `$uri_to_post` array by running a
98
-	 * single query with all the URIs and returning the mappings in the array.
99
-	 *
100
-	 * @param array $uris An array of URIs.
101
-	 *
102
-	 * @since 3.16.3
103
-	 */
104
-	public function preload_uris( $uris ) {
105
-
106
-		// Bail out if there are no URIs.
107
-		if ( 0 === count( $uris ) ) {
108
-			return;
109
-		}
110
-
111
-		$this->log->trace( 'Preloading ' . count( $uris ) . ' URI(s)...' );
112
-
113
-		global $wpdb;
114
-		$in_post_types  = implode( "','", array_map( 'esc_sql', Wordlift_Entity_Service::valid_entity_post_types() ) );
115
-		$in_entity_uris = implode( "','", array_map( 'esc_sql', $uris ) );
116
-		$sql            = "
23
+    /**
24
+     * A {@link Wordlift_Log_Service} instance.
25
+     *
26
+     * @since  3.16.3
27
+     * @access private
28
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
29
+     */
30
+    private $log;
31
+
32
+    /**
33
+     * An array of URIs to post ID valid for the current request.
34
+     *
35
+     * @since  3.16.3
36
+     * @access private
37
+     * @var array $uri_to_post An array of URIs to post ID valid for the current request.
38
+     */
39
+    protected $uri_to_post;
40
+
41
+    /**
42
+     * Create a {@link Wordlift_Entity_Uri_Service} instance.
43
+     *
44
+     * @since 3.16.3
45
+     */
46
+    protected function __construct() {
47
+
48
+        $this->log = Wordlift_Log_Service::get_logger( get_class() );
49
+
50
+        // Add a filter to the `rest_post_dispatch` filter to add the wl_entity_url meta as `wl:entity_url`.
51
+        add_filter( 'rest_post_dispatch', array( $this, 'rest_post_dispatch' ) );
52
+        add_filter( 'wl_content_service__post__not_found', array( $this, 'content_service__post__not_found' ), 10, 2 );
53
+
54
+    }
55
+
56
+    /**
57
+     * Holds the {@link Wordlift_Entity_Uri_Service} instance.
58
+     *
59
+     * @since 3.21.5
60
+     * @access private
61
+     * @var Wordlift_Entity_Uri_Service $instance The {@link Wordlift_Entity_Uri_Service} singleton.
62
+     */
63
+    private static $instance = null;
64
+
65
+    /**
66
+     * Get the singleton.
67
+     *
68
+     * @return Wordlift_Entity_Uri_Service The singleton instance.
69
+     * @since 3.21.5
70
+     */
71
+    public static function get_instance() {
72
+
73
+        if ( ! isset( self::$instance ) ) {
74
+            $entity_uri_cache_service = new Wordlift_File_Cache_Service( WL_TEMP_DIR . 'entity_uri/' );
75
+            self::$instance           = new Wordlift_Cached_Entity_Uri_Service( $entity_uri_cache_service );
76
+
77
+        }
78
+
79
+        return self::$instance;
80
+    }
81
+
82
+    /**
83
+     * Try to find a post when the content service doesn't find it.
84
+     *
85
+     * @param WP_Post|null $post
86
+     * @param string       $uri
87
+     *
88
+     * @return false|int
89
+     */
90
+    public function content_service__post__not_found( $post, $uri ) {
91
+        return $this->get_post_id_from_url( $uri );
92
+    }
93
+
94
+    /**
95
+     * Preload the provided URIs in the local cache.
96
+     *
97
+     * This function will populate the local `$uri_to_post` array by running a
98
+     * single query with all the URIs and returning the mappings in the array.
99
+     *
100
+     * @param array $uris An array of URIs.
101
+     *
102
+     * @since 3.16.3
103
+     */
104
+    public function preload_uris( $uris ) {
105
+
106
+        // Bail out if there are no URIs.
107
+        if ( 0 === count( $uris ) ) {
108
+            return;
109
+        }
110
+
111
+        $this->log->trace( 'Preloading ' . count( $uris ) . ' URI(s)...' );
112
+
113
+        global $wpdb;
114
+        $in_post_types  = implode( "','", array_map( 'esc_sql', Wordlift_Entity_Service::valid_entity_post_types() ) );
115
+        $in_entity_uris = implode( "','", array_map( 'esc_sql', $uris ) );
116
+        $sql            = "
117 117
 			SELECT ID FROM $wpdb->posts p
118 118
 			INNER JOIN $wpdb->postmeta pm
119 119
 			 ON pm.post_id = p.ID
@@ -123,150 +123,150 @@  discard block
 block discarded – undo
123 123
 			  AND p.post_status IN ( 'publish', 'draft', 'private', 'future' )
124 124
   		";
125 125
 
126
-		// Get the posts.
127
-		$posts = $wpdb->get_col( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
128
-
129
-		// Populate the array. We reinitialize the array on purpose because
130
-		// we don't want these data to long live.
131
-		$this->uri_to_post = array_reduce(
132
-			$posts,
133
-			function ( $carry, $item ) {
134
-				$uris = get_post_meta( $item, Wordlift_Schema_Service::FIELD_SAME_AS );
135
-
136
-				$uri = Wordpress_Content_Service::get_instance()
137
-											->get_entity_id( Wordpress_Content_Id::create_post( $item ) );
138
-
139
-				if ( isset( $uri ) ) {
140
-					$uris[] = $uri;
141
-				}
142
-
143
-				return $carry
144
-				   // Get the URI related to the post and fill them with the item id.
145
-				   + array_fill_keys( $uris, $item );
146
-			},
147
-			array()
148
-		);
149
-
150
-		// Add the not found URIs.
151
-		$this->uri_to_post += array_fill_keys( $uris, null );
152
-
153
-		$this->log->debug( count( $this->uri_to_post ) . ' URI(s) preloaded.' );
154
-
155
-	}
156
-
157
-	/**
158
-	 * Reset the URI to post local cache.
159
-	 *
160
-	 * @since 3.16.3
161
-	 */
162
-	public function reset_uris() {
163
-
164
-		$this->uri_to_post = array();
165
-
166
-	}
167
-
168
-	/**
169
-	 * Find entity posts by the entity URI. Entity as searched by their entity URI or same as.
170
-	 *
171
-	 * @param string $uri The entity URI.
172
-	 *
173
-	 * @return WP_Post|null A WP_Post instance or null if not found.
174
-	 * @since 3.2.0
175
-	 */
176
-	public function get_entity( $uri ) {
177
-
178
-		$this->log->trace( "Getting an entity post for URI $uri..." );
179
-
180
-		$content = Wordpress_Content_Service::get_instance()->get_by_entity_id_or_same_as( $uri );
181
-
182
-		// Return null if the content isn't found or isn't a post.
183
-		if ( ! isset( $content ) || ! is_a( $content->get_bag(), '\WP_Post' ) ) {
184
-			return null;
185
-		}
186
-
187
-		return $content->get_bag();
188
-	}
189
-
190
-	/**
191
-	 * Determines whether a given uri is an internal uri or not.
192
-	 *
193
-	 * @param string $uri An uri.
194
-	 *
195
-	 * @return true if the uri internal to the current dataset otherwise false.
196
-	 * @since 3.16.3
197
-	 */
198
-	public function is_internal( $uri ) {
199
-
200
-		return ( 0 === strrpos( $uri, (string) Wordlift_Configuration_Service::get_instance()->get_dataset_uri() ) );
201
-	}
202
-
203
-	/**
204
-	 * Hook to `rest_post_dispatch` to alter the response and add the `wl_entity_url` post meta as `wl:entity_url`.
205
-	 *
206
-	 * We're using this filter instead of the well known `register_meta` / `register_rest_field` because we still need
207
-	 * to provide full compatibility with WordPress 4.4+.
208
-	 *
209
-	 * @param WP_HTTP_Response $result Result to send to the client. Usually a WP_REST_Response.
210
-	 *
211
-	 * @return WP_HTTP_Response The result to send to the client.
212
-	 *
213
-	 * @since 3.23.0
214
-	 */
215
-	public function rest_post_dispatch( $result ) {
216
-
217
-		// Get a reference to the actual data.
218
-		$data = &$result->data;
219
-
220
-		// Bail out if we don't have the required parameters, or if the type is not a valid entity.
221
-		if ( ! is_array( $data ) || ! isset( $data['id'] ) || ! isset( $data['type'] )
222
-			 || ! Wordlift_Entity_Type_Service::is_valid_entity_post_type( $data['type'] ) ) {
223
-			return $result;
224
-		}
225
-
226
-		// Add the `wl:entity_url`.
227
-		$data['wl:entity_url'] = Wordlift_Entity_Service::get_instance()->get_uri( $data['id'] );
228
-
229
-		return $result;
230
-	}
231
-
232
-	/**
233
-	 * Helper function to fetch post_id from a WordPress URL
234
-	 * Primarily used when dataset is not enabled
235
-	 *
236
-	 * @param $url
237
-	 *
238
-	 * @return int Post ID | bool false
239
-	 */
240
-	public function get_post_id_from_url( $url ) {
241
-
242
-		// Try url_to_postid
243
-		$post_id = url_to_postid( htmlspecialchars_decode( $url ) );
244
-		if ( 0 !== $post_id ) {
245
-			return $post_id;
246
-		}
247
-
248
-		$parsed_url = wp_parse_url( $url );
249
-
250
-		if ( ! isset( $parsed_url['query'] ) ) {
251
-			return false;
252
-		}
253
-
254
-		parse_str( $parsed_url['query'], $parsed_query );
255
-
256
-		// Try to parse WooCommerce non-pretty product URL
257
-		if ( $parsed_query['product'] ) {
258
-			$posts = get_posts(
259
-				array(
260
-					'name'      => $parsed_query['product'],
261
-					'post_type' => 'product',
262
-				)
263
-			);
264
-			if ( count( $posts ) > 0 ) {
265
-				return $posts[0]->ID;
266
-			}
267
-		}
268
-
269
-		return false;
270
-	}
126
+        // Get the posts.
127
+        $posts = $wpdb->get_col( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
128
+
129
+        // Populate the array. We reinitialize the array on purpose because
130
+        // we don't want these data to long live.
131
+        $this->uri_to_post = array_reduce(
132
+            $posts,
133
+            function ( $carry, $item ) {
134
+                $uris = get_post_meta( $item, Wordlift_Schema_Service::FIELD_SAME_AS );
135
+
136
+                $uri = Wordpress_Content_Service::get_instance()
137
+                                            ->get_entity_id( Wordpress_Content_Id::create_post( $item ) );
138
+
139
+                if ( isset( $uri ) ) {
140
+                    $uris[] = $uri;
141
+                }
142
+
143
+                return $carry
144
+                    // Get the URI related to the post and fill them with the item id.
145
+                   + array_fill_keys( $uris, $item );
146
+            },
147
+            array()
148
+        );
149
+
150
+        // Add the not found URIs.
151
+        $this->uri_to_post += array_fill_keys( $uris, null );
152
+
153
+        $this->log->debug( count( $this->uri_to_post ) . ' URI(s) preloaded.' );
154
+
155
+    }
156
+
157
+    /**
158
+     * Reset the URI to post local cache.
159
+     *
160
+     * @since 3.16.3
161
+     */
162
+    public function reset_uris() {
163
+
164
+        $this->uri_to_post = array();
165
+
166
+    }
167
+
168
+    /**
169
+     * Find entity posts by the entity URI. Entity as searched by their entity URI or same as.
170
+     *
171
+     * @param string $uri The entity URI.
172
+     *
173
+     * @return WP_Post|null A WP_Post instance or null if not found.
174
+     * @since 3.2.0
175
+     */
176
+    public function get_entity( $uri ) {
177
+
178
+        $this->log->trace( "Getting an entity post for URI $uri..." );
179
+
180
+        $content = Wordpress_Content_Service::get_instance()->get_by_entity_id_or_same_as( $uri );
181
+
182
+        // Return null if the content isn't found or isn't a post.
183
+        if ( ! isset( $content ) || ! is_a( $content->get_bag(), '\WP_Post' ) ) {
184
+            return null;
185
+        }
186
+
187
+        return $content->get_bag();
188
+    }
189
+
190
+    /**
191
+     * Determines whether a given uri is an internal uri or not.
192
+     *
193
+     * @param string $uri An uri.
194
+     *
195
+     * @return true if the uri internal to the current dataset otherwise false.
196
+     * @since 3.16.3
197
+     */
198
+    public function is_internal( $uri ) {
199
+
200
+        return ( 0 === strrpos( $uri, (string) Wordlift_Configuration_Service::get_instance()->get_dataset_uri() ) );
201
+    }
202
+
203
+    /**
204
+     * Hook to `rest_post_dispatch` to alter the response and add the `wl_entity_url` post meta as `wl:entity_url`.
205
+     *
206
+     * We're using this filter instead of the well known `register_meta` / `register_rest_field` because we still need
207
+     * to provide full compatibility with WordPress 4.4+.
208
+     *
209
+     * @param WP_HTTP_Response $result Result to send to the client. Usually a WP_REST_Response.
210
+     *
211
+     * @return WP_HTTP_Response The result to send to the client.
212
+     *
213
+     * @since 3.23.0
214
+     */
215
+    public function rest_post_dispatch( $result ) {
216
+
217
+        // Get a reference to the actual data.
218
+        $data = &$result->data;
219
+
220
+        // Bail out if we don't have the required parameters, or if the type is not a valid entity.
221
+        if ( ! is_array( $data ) || ! isset( $data['id'] ) || ! isset( $data['type'] )
222
+             || ! Wordlift_Entity_Type_Service::is_valid_entity_post_type( $data['type'] ) ) {
223
+            return $result;
224
+        }
225
+
226
+        // Add the `wl:entity_url`.
227
+        $data['wl:entity_url'] = Wordlift_Entity_Service::get_instance()->get_uri( $data['id'] );
228
+
229
+        return $result;
230
+    }
231
+
232
+    /**
233
+     * Helper function to fetch post_id from a WordPress URL
234
+     * Primarily used when dataset is not enabled
235
+     *
236
+     * @param $url
237
+     *
238
+     * @return int Post ID | bool false
239
+     */
240
+    public function get_post_id_from_url( $url ) {
241
+
242
+        // Try url_to_postid
243
+        $post_id = url_to_postid( htmlspecialchars_decode( $url ) );
244
+        if ( 0 !== $post_id ) {
245
+            return $post_id;
246
+        }
247
+
248
+        $parsed_url = wp_parse_url( $url );
249
+
250
+        if ( ! isset( $parsed_url['query'] ) ) {
251
+            return false;
252
+        }
253
+
254
+        parse_str( $parsed_url['query'], $parsed_query );
255
+
256
+        // Try to parse WooCommerce non-pretty product URL
257
+        if ( $parsed_query['product'] ) {
258
+            $posts = get_posts(
259
+                array(
260
+                    'name'      => $parsed_query['product'],
261
+                    'post_type' => 'product',
262
+                )
263
+            );
264
+            if ( count( $posts ) > 0 ) {
265
+                return $posts[0]->ID;
266
+            }
267
+        }
268
+
269
+        return false;
270
+    }
271 271
 
272 272
 }
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -45,11 +45,11 @@  discard block
 block discarded – undo
45 45
 	 */
46 46
 	protected function __construct() {
47 47
 
48
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
48
+		$this->log = Wordlift_Log_Service::get_logger(get_class());
49 49
 
50 50
 		// Add a filter to the `rest_post_dispatch` filter to add the wl_entity_url meta as `wl:entity_url`.
51
-		add_filter( 'rest_post_dispatch', array( $this, 'rest_post_dispatch' ) );
52
-		add_filter( 'wl_content_service__post__not_found', array( $this, 'content_service__post__not_found' ), 10, 2 );
51
+		add_filter('rest_post_dispatch', array($this, 'rest_post_dispatch'));
52
+		add_filter('wl_content_service__post__not_found', array($this, 'content_service__post__not_found'), 10, 2);
53 53
 
54 54
 	}
55 55
 
@@ -70,9 +70,9 @@  discard block
 block discarded – undo
70 70
 	 */
71 71
 	public static function get_instance() {
72 72
 
73
-		if ( ! isset( self::$instance ) ) {
74
-			$entity_uri_cache_service = new Wordlift_File_Cache_Service( WL_TEMP_DIR . 'entity_uri/' );
75
-			self::$instance           = new Wordlift_Cached_Entity_Uri_Service( $entity_uri_cache_service );
73
+		if ( ! isset(self::$instance)) {
74
+			$entity_uri_cache_service = new Wordlift_File_Cache_Service(WL_TEMP_DIR.'entity_uri/');
75
+			self::$instance           = new Wordlift_Cached_Entity_Uri_Service($entity_uri_cache_service);
76 76
 
77 77
 		}
78 78
 
@@ -87,8 +87,8 @@  discard block
 block discarded – undo
87 87
 	 *
88 88
 	 * @return false|int
89 89
 	 */
90
-	public function content_service__post__not_found( $post, $uri ) {
91
-		return $this->get_post_id_from_url( $uri );
90
+	public function content_service__post__not_found($post, $uri) {
91
+		return $this->get_post_id_from_url($uri);
92 92
 	}
93 93
 
94 94
 	/**
@@ -101,18 +101,18 @@  discard block
 block discarded – undo
101 101
 	 *
102 102
 	 * @since 3.16.3
103 103
 	 */
104
-	public function preload_uris( $uris ) {
104
+	public function preload_uris($uris) {
105 105
 
106 106
 		// Bail out if there are no URIs.
107
-		if ( 0 === count( $uris ) ) {
107
+		if (0 === count($uris)) {
108 108
 			return;
109 109
 		}
110 110
 
111
-		$this->log->trace( 'Preloading ' . count( $uris ) . ' URI(s)...' );
111
+		$this->log->trace('Preloading '.count($uris).' URI(s)...');
112 112
 
113 113
 		global $wpdb;
114
-		$in_post_types  = implode( "','", array_map( 'esc_sql', Wordlift_Entity_Service::valid_entity_post_types() ) );
115
-		$in_entity_uris = implode( "','", array_map( 'esc_sql', $uris ) );
114
+		$in_post_types  = implode("','", array_map('esc_sql', Wordlift_Entity_Service::valid_entity_post_types()));
115
+		$in_entity_uris = implode("','", array_map('esc_sql', $uris));
116 116
 		$sql            = "
117 117
 			SELECT ID FROM $wpdb->posts p
118 118
 			INNER JOIN $wpdb->postmeta pm
@@ -124,33 +124,33 @@  discard block
 block discarded – undo
124 124
   		";
125 125
 
126 126
 		// Get the posts.
127
-		$posts = $wpdb->get_col( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
127
+		$posts = $wpdb->get_col($sql); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
128 128
 
129 129
 		// Populate the array. We reinitialize the array on purpose because
130 130
 		// we don't want these data to long live.
131 131
 		$this->uri_to_post = array_reduce(
132 132
 			$posts,
133
-			function ( $carry, $item ) {
134
-				$uris = get_post_meta( $item, Wordlift_Schema_Service::FIELD_SAME_AS );
133
+			function($carry, $item) {
134
+				$uris = get_post_meta($item, Wordlift_Schema_Service::FIELD_SAME_AS);
135 135
 
136 136
 				$uri = Wordpress_Content_Service::get_instance()
137
-											->get_entity_id( Wordpress_Content_Id::create_post( $item ) );
137
+											->get_entity_id(Wordpress_Content_Id::create_post($item));
138 138
 
139
-				if ( isset( $uri ) ) {
139
+				if (isset($uri)) {
140 140
 					$uris[] = $uri;
141 141
 				}
142 142
 
143 143
 				return $carry
144 144
 				   // Get the URI related to the post and fill them with the item id.
145
-				   + array_fill_keys( $uris, $item );
145
+				   + array_fill_keys($uris, $item);
146 146
 			},
147 147
 			array()
148 148
 		);
149 149
 
150 150
 		// Add the not found URIs.
151
-		$this->uri_to_post += array_fill_keys( $uris, null );
151
+		$this->uri_to_post += array_fill_keys($uris, null);
152 152
 
153
-		$this->log->debug( count( $this->uri_to_post ) . ' URI(s) preloaded.' );
153
+		$this->log->debug(count($this->uri_to_post).' URI(s) preloaded.');
154 154
 
155 155
 	}
156 156
 
@@ -173,14 +173,14 @@  discard block
 block discarded – undo
173 173
 	 * @return WP_Post|null A WP_Post instance or null if not found.
174 174
 	 * @since 3.2.0
175 175
 	 */
176
-	public function get_entity( $uri ) {
176
+	public function get_entity($uri) {
177 177
 
178
-		$this->log->trace( "Getting an entity post for URI $uri..." );
178
+		$this->log->trace("Getting an entity post for URI $uri...");
179 179
 
180
-		$content = Wordpress_Content_Service::get_instance()->get_by_entity_id_or_same_as( $uri );
180
+		$content = Wordpress_Content_Service::get_instance()->get_by_entity_id_or_same_as($uri);
181 181
 
182 182
 		// Return null if the content isn't found or isn't a post.
183
-		if ( ! isset( $content ) || ! is_a( $content->get_bag(), '\WP_Post' ) ) {
183
+		if ( ! isset($content) || ! is_a($content->get_bag(), '\WP_Post')) {
184 184
 			return null;
185 185
 		}
186 186
 
@@ -195,9 +195,9 @@  discard block
 block discarded – undo
195 195
 	 * @return true if the uri internal to the current dataset otherwise false.
196 196
 	 * @since 3.16.3
197 197
 	 */
198
-	public function is_internal( $uri ) {
198
+	public function is_internal($uri) {
199 199
 
200
-		return ( 0 === strrpos( $uri, (string) Wordlift_Configuration_Service::get_instance()->get_dataset_uri() ) );
200
+		return (0 === strrpos($uri, (string) Wordlift_Configuration_Service::get_instance()->get_dataset_uri()));
201 201
 	}
202 202
 
203 203
 	/**
@@ -212,19 +212,19 @@  discard block
 block discarded – undo
212 212
 	 *
213 213
 	 * @since 3.23.0
214 214
 	 */
215
-	public function rest_post_dispatch( $result ) {
215
+	public function rest_post_dispatch($result) {
216 216
 
217 217
 		// Get a reference to the actual data.
218 218
 		$data = &$result->data;
219 219
 
220 220
 		// Bail out if we don't have the required parameters, or if the type is not a valid entity.
221
-		if ( ! is_array( $data ) || ! isset( $data['id'] ) || ! isset( $data['type'] )
222
-			 || ! Wordlift_Entity_Type_Service::is_valid_entity_post_type( $data['type'] ) ) {
221
+		if ( ! is_array($data) || ! isset($data['id']) || ! isset($data['type'])
222
+			 || ! Wordlift_Entity_Type_Service::is_valid_entity_post_type($data['type'])) {
223 223
 			return $result;
224 224
 		}
225 225
 
226 226
 		// Add the `wl:entity_url`.
227
-		$data['wl:entity_url'] = Wordlift_Entity_Service::get_instance()->get_uri( $data['id'] );
227
+		$data['wl:entity_url'] = Wordlift_Entity_Service::get_instance()->get_uri($data['id']);
228 228
 
229 229
 		return $result;
230 230
 	}
@@ -237,31 +237,31 @@  discard block
 block discarded – undo
237 237
 	 *
238 238
 	 * @return int Post ID | bool false
239 239
 	 */
240
-	public function get_post_id_from_url( $url ) {
240
+	public function get_post_id_from_url($url) {
241 241
 
242 242
 		// Try url_to_postid
243
-		$post_id = url_to_postid( htmlspecialchars_decode( $url ) );
244
-		if ( 0 !== $post_id ) {
243
+		$post_id = url_to_postid(htmlspecialchars_decode($url));
244
+		if (0 !== $post_id) {
245 245
 			return $post_id;
246 246
 		}
247 247
 
248
-		$parsed_url = wp_parse_url( $url );
248
+		$parsed_url = wp_parse_url($url);
249 249
 
250
-		if ( ! isset( $parsed_url['query'] ) ) {
250
+		if ( ! isset($parsed_url['query'])) {
251 251
 			return false;
252 252
 		}
253 253
 
254
-		parse_str( $parsed_url['query'], $parsed_query );
254
+		parse_str($parsed_url['query'], $parsed_query);
255 255
 
256 256
 		// Try to parse WooCommerce non-pretty product URL
257
-		if ( $parsed_query['product'] ) {
257
+		if ($parsed_query['product']) {
258 258
 			$posts = get_posts(
259 259
 				array(
260 260
 					'name'      => $parsed_query['product'],
261 261
 					'post_type' => 'product',
262 262
 				)
263 263
 			);
264
-			if ( count( $posts ) > 0 ) {
264
+			if (count($posts) > 0) {
265 265
 				return $posts[0]->ID;
266 266
 			}
267 267
 		}
Please login to merge, or discard this patch.