Completed
Push — develop ( b9966d...2c0daf )
by David
01:47 queued 20s
created
src/wordlift/cache/class-ttl-cache.php 2 patches
Indentation   +168 added lines, -168 removed lines patch added patch discarded remove patch
@@ -17,190 +17,190 @@
 block discarded – undo
17 17
 // @@todo: add a hook to clear the cached files now and then.
18 18
 class Ttl_Cache {
19 19
 
20
-	/**
21
-	 * The cache name.
22
-	 *
23
-	 * @var string $name The cache name.
24
-	 * @access private
25
-	 * @since 3.21.2
26
-	 */
27
-	private $name;
28
-
29
-	/**
30
-	 * The TTL of cached responses in seconds.
31
-	 *
32
-	 * @var int $ttl The TTL in seconds.
33
-	 * @access private
34
-	 * @since 3.21.2
35
-	 */
36
-	private $ttl;
37
-
38
-	/**
39
-	 * The cache dir where the cached data is written.
40
-	 *
41
-	 * @since 3.21.2
42
-	 * @access private
43
-	 * @var string $cache_dir The cache dir where the cached responses are written.
44
-	 */
45
-	private $cache_dir;
46
-
47
-	/**
48
-	 * A {@link Wordlift_Log_Service} instance.
49
-	 *
50
-	 * @var Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
51
-	 * @access private
52
-	 * @since 3.21.2
53
-	 */
54
-	private $log;
55
-
56
-	/**
57
-	 * @var array
58
-	 */
59
-	private static $caches = array();
60
-
61
-	/**
62
-	 * Create a {@link Ttl_Cache} with the specified TTL, default 900 secs.
63
-	 *
64
-	 * @param string $name The cache name.
65
-	 * @param int $ttl The cache TTL, default 900 secs.
66
-	 *
67
-	 * @since 3.21.2
68
-	 */
69
-	public function __construct( $name, $ttl = 900 ) {
70
-
71
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
72
-
73
-		$this->name = $name;
74
-		$this->ttl  = $ttl;
75
-
76
-		$this->cache_dir = self::get_cache_folder() . DIRECTORY_SEPARATOR . md5( $name );
77
-
78
-		$this->log->trace( "Creating the cache folder {$this->cache_dir}..." );
79
-		wp_mkdir_p( $this->cache_dir );
80
-
81
-		self::$caches[ $name ] = $this;
82
-
83
-	}
84
-
85
-	/**
86
-	 * Get the root cache folder.
87
-	 *
88
-	 * This is useful to introduce a cache cleaning procedure which will scan and delete older stale cache files.
89
-	 *
90
-	 * @return string The root cache folder.
91
-	 * @since 3.22.5
92
-	 */
93
-	public static function get_cache_folder() {
94
-
95
-		// Get the temp dir and add the directory separator if missing.
96
-		$temp_dir = get_temp_dir();
97
-		if ( DIRECTORY_SEPARATOR !== substr( $temp_dir, - strlen( DIRECTORY_SEPARATOR ) ) ) {
98
-			$temp_dir .= DIRECTORY_SEPARATOR;
99
-		}
100
-
101
-		return $temp_dir . 'wl.cache' . DIRECTORY_SEPARATOR . md5( home_url() );
102
-	}
103
-
104
-	/**
105
-	 * Get the cached data for the specified key.
106
-	 *
107
-	 * @param mixed $key A serializable key.
108
-	 *
109
-	 * @return mixed|null
110
-	 * @since 3.21.2
111
-	 */
112
-	public function get( $key, $mintime = 0 ) {
113
-
114
-		$filename = $this->get_filename( $key );
115
-
116
-		// No cache.
117
-		if ( ! file_exists( $filename ) ) {
118
-			return null;
119
-		}
120
-
121
-		// The cache is not updated or the ttl expired. Delete.
122
-		$filemtime = filemtime( $filename );
123
-		if ( $filemtime < $mintime || $this->ttl < ( time() - $filemtime ) ) {
124
-			$this->delete( $key );
125
-
126
-			return null;
127
-		}
128
-
129
-
130
-		$this->log->trace( "Cache HIT.\n" );
131
-
132
-		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
133
-		return json_decode( file_get_contents( $filename ), true );
134
-	}
135
-
136
-	public function put( $key, $data ) {
137
-
138
-		$filename = $this->get_filename( $key );
139
-
140
-		// Cache.
141
-		if ( file_exists( $filename ) ) {
142
-			// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
143
-			@unlink( $filename );
144
-		}
20
+    /**
21
+     * The cache name.
22
+     *
23
+     * @var string $name The cache name.
24
+     * @access private
25
+     * @since 3.21.2
26
+     */
27
+    private $name;
28
+
29
+    /**
30
+     * The TTL of cached responses in seconds.
31
+     *
32
+     * @var int $ttl The TTL in seconds.
33
+     * @access private
34
+     * @since 3.21.2
35
+     */
36
+    private $ttl;
37
+
38
+    /**
39
+     * The cache dir where the cached data is written.
40
+     *
41
+     * @since 3.21.2
42
+     * @access private
43
+     * @var string $cache_dir The cache dir where the cached responses are written.
44
+     */
45
+    private $cache_dir;
46
+
47
+    /**
48
+     * A {@link Wordlift_Log_Service} instance.
49
+     *
50
+     * @var Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
51
+     * @access private
52
+     * @since 3.21.2
53
+     */
54
+    private $log;
55
+
56
+    /**
57
+     * @var array
58
+     */
59
+    private static $caches = array();
60
+
61
+    /**
62
+     * Create a {@link Ttl_Cache} with the specified TTL, default 900 secs.
63
+     *
64
+     * @param string $name The cache name.
65
+     * @param int $ttl The cache TTL, default 900 secs.
66
+     *
67
+     * @since 3.21.2
68
+     */
69
+    public function __construct( $name, $ttl = 900 ) {
70
+
71
+        $this->log = Wordlift_Log_Service::get_logger( get_class() );
72
+
73
+        $this->name = $name;
74
+        $this->ttl  = $ttl;
75
+
76
+        $this->cache_dir = self::get_cache_folder() . DIRECTORY_SEPARATOR . md5( $name );
77
+
78
+        $this->log->trace( "Creating the cache folder {$this->cache_dir}..." );
79
+        wp_mkdir_p( $this->cache_dir );
80
+
81
+        self::$caches[ $name ] = $this;
82
+
83
+    }
84
+
85
+    /**
86
+     * Get the root cache folder.
87
+     *
88
+     * This is useful to introduce a cache cleaning procedure which will scan and delete older stale cache files.
89
+     *
90
+     * @return string The root cache folder.
91
+     * @since 3.22.5
92
+     */
93
+    public static function get_cache_folder() {
94
+
95
+        // Get the temp dir and add the directory separator if missing.
96
+        $temp_dir = get_temp_dir();
97
+        if ( DIRECTORY_SEPARATOR !== substr( $temp_dir, - strlen( DIRECTORY_SEPARATOR ) ) ) {
98
+            $temp_dir .= DIRECTORY_SEPARATOR;
99
+        }
100
+
101
+        return $temp_dir . 'wl.cache' . DIRECTORY_SEPARATOR . md5( home_url() );
102
+    }
103
+
104
+    /**
105
+     * Get the cached data for the specified key.
106
+     *
107
+     * @param mixed $key A serializable key.
108
+     *
109
+     * @return mixed|null
110
+     * @since 3.21.2
111
+     */
112
+    public function get( $key, $mintime = 0 ) {
113
+
114
+        $filename = $this->get_filename( $key );
115
+
116
+        // No cache.
117
+        if ( ! file_exists( $filename ) ) {
118
+            return null;
119
+        }
120
+
121
+        // The cache is not updated or the ttl expired. Delete.
122
+        $filemtime = filemtime( $filename );
123
+        if ( $filemtime < $mintime || $this->ttl < ( time() - $filemtime ) ) {
124
+            $this->delete( $key );
125
+
126
+            return null;
127
+        }
128
+
129
+
130
+        $this->log->trace( "Cache HIT.\n" );
131
+
132
+        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
133
+        return json_decode( file_get_contents( $filename ), true );
134
+    }
135
+
136
+    public function put( $key, $data ) {
137
+
138
+        $filename = $this->get_filename( $key );
139
+
140
+        // Cache.
141
+        if ( file_exists( $filename ) ) {
142
+            // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
143
+            @unlink( $filename );
144
+        }
145 145
 
146
-		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged,WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents
147
-		@file_put_contents( $filename, wp_json_encode( $data ) );
146
+        // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged,WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents
147
+        @file_put_contents( $filename, wp_json_encode( $data ) );
148 148
 
149
-	}
149
+    }
150 150
 
151
-	public function delete( $key ) {
151
+    public function delete( $key ) {
152 152
 
153
-		$filename = $this->get_filename( $key );
153
+        $filename = $this->get_filename( $key );
154 154
 
155
-		// Delete.
156
-		if ( file_exists( $filename ) ) {
157
-			// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
158
-			@unlink( $filename );
159
-		}
155
+        // Delete.
156
+        if ( file_exists( $filename ) ) {
157
+            // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
158
+            @unlink( $filename );
159
+        }
160 160
 
161
-	}
161
+    }
162 162
 
163
-	public function flush() {
163
+    public function flush() {
164 164
 
165
-		$files = glob( $this->cache_dir . DIRECTORY_SEPARATOR . '*' );
166
-		foreach ( $files as $file ) { // iterate files
167
-			if ( is_file( $file ) ) {
168
-				// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
169
-				@unlink( $file );
170
-			}
171
-		}
165
+        $files = glob( $this->cache_dir . DIRECTORY_SEPARATOR . '*' );
166
+        foreach ( $files as $file ) { // iterate files
167
+            if ( is_file( $file ) ) {
168
+                // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
169
+                @unlink( $file );
170
+            }
171
+        }
172 172
 
173
-	}
173
+    }
174 174
 
175
-	public static function flush_all() {
175
+    public static function flush_all() {
176 176
 
177
-		/** @var Ttl_Cache $cache */
178
-		foreach ( self::$caches as $cache ) {
179
-			$cache->flush();
180
-		}
177
+        /** @var Ttl_Cache $cache */
178
+        foreach ( self::$caches as $cache ) {
179
+            $cache->flush();
180
+        }
181 181
 
182
-	}
182
+    }
183 183
 
184
-	/**
185
-	 * Get the full path for the given `$hash`. The file is not checked for its existence.
186
-	 *
187
-	 * @param string $hash A file hash.
188
-	 *
189
-	 * @return string The full path to the file.
190
-	 * @since 3.21.2
191
-	 */
192
-	private function get_path( $hash ) {
184
+    /**
185
+     * Get the full path for the given `$hash`. The file is not checked for its existence.
186
+     *
187
+     * @param string $hash A file hash.
188
+     *
189
+     * @return string The full path to the file.
190
+     * @since 3.21.2
191
+     */
192
+    private function get_path( $hash ) {
193 193
 
194
-		return $this->cache_dir . DIRECTORY_SEPARATOR . $hash;
195
-	}
194
+        return $this->cache_dir . DIRECTORY_SEPARATOR . $hash;
195
+    }
196 196
 
197
-	private function get_filename( $key ) {
197
+    private function get_filename( $key ) {
198 198
 
199
-		// Create a hash and a path to the cache file.
200
-		$hash     = md5( wp_json_encode( $key ) );
201
-		$filename = $this->get_path( $hash );
199
+        // Create a hash and a path to the cache file.
200
+        $hash     = md5( wp_json_encode( $key ) );
201
+        $filename = $this->get_path( $hash );
202 202
 
203
-		return $filename;
204
-	}
203
+        return $filename;
204
+    }
205 205
 
206 206
 }
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -66,19 +66,19 @@  discard block
 block discarded – undo
66 66
 	 *
67 67
 	 * @since 3.21.2
68 68
 	 */
69
-	public function __construct( $name, $ttl = 900 ) {
69
+	public function __construct($name, $ttl = 900) {
70 70
 
71
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
71
+		$this->log = Wordlift_Log_Service::get_logger(get_class());
72 72
 
73 73
 		$this->name = $name;
74 74
 		$this->ttl  = $ttl;
75 75
 
76
-		$this->cache_dir = self::get_cache_folder() . DIRECTORY_SEPARATOR . md5( $name );
76
+		$this->cache_dir = self::get_cache_folder().DIRECTORY_SEPARATOR.md5($name);
77 77
 
78
-		$this->log->trace( "Creating the cache folder {$this->cache_dir}..." );
79
-		wp_mkdir_p( $this->cache_dir );
78
+		$this->log->trace("Creating the cache folder {$this->cache_dir}...");
79
+		wp_mkdir_p($this->cache_dir);
80 80
 
81
-		self::$caches[ $name ] = $this;
81
+		self::$caches[$name] = $this;
82 82
 
83 83
 	}
84 84
 
@@ -94,11 +94,11 @@  discard block
 block discarded – undo
94 94
 
95 95
 		// Get the temp dir and add the directory separator if missing.
96 96
 		$temp_dir = get_temp_dir();
97
-		if ( DIRECTORY_SEPARATOR !== substr( $temp_dir, - strlen( DIRECTORY_SEPARATOR ) ) ) {
97
+		if (DIRECTORY_SEPARATOR !== substr($temp_dir, - strlen(DIRECTORY_SEPARATOR))) {
98 98
 			$temp_dir .= DIRECTORY_SEPARATOR;
99 99
 		}
100 100
 
101
-		return $temp_dir . 'wl.cache' . DIRECTORY_SEPARATOR . md5( home_url() );
101
+		return $temp_dir.'wl.cache'.DIRECTORY_SEPARATOR.md5(home_url());
102 102
 	}
103 103
 
104 104
 	/**
@@ -109,64 +109,64 @@  discard block
 block discarded – undo
109 109
 	 * @return mixed|null
110 110
 	 * @since 3.21.2
111 111
 	 */
112
-	public function get( $key, $mintime = 0 ) {
112
+	public function get($key, $mintime = 0) {
113 113
 
114
-		$filename = $this->get_filename( $key );
114
+		$filename = $this->get_filename($key);
115 115
 
116 116
 		// No cache.
117
-		if ( ! file_exists( $filename ) ) {
117
+		if ( ! file_exists($filename)) {
118 118
 			return null;
119 119
 		}
120 120
 
121 121
 		// The cache is not updated or the ttl expired. Delete.
122
-		$filemtime = filemtime( $filename );
123
-		if ( $filemtime < $mintime || $this->ttl < ( time() - $filemtime ) ) {
124
-			$this->delete( $key );
122
+		$filemtime = filemtime($filename);
123
+		if ($filemtime < $mintime || $this->ttl < (time() - $filemtime)) {
124
+			$this->delete($key);
125 125
 
126 126
 			return null;
127 127
 		}
128 128
 
129 129
 
130
-		$this->log->trace( "Cache HIT.\n" );
130
+		$this->log->trace("Cache HIT.\n");
131 131
 
132 132
 		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
133
-		return json_decode( file_get_contents( $filename ), true );
133
+		return json_decode(file_get_contents($filename), true);
134 134
 	}
135 135
 
136
-	public function put( $key, $data ) {
136
+	public function put($key, $data) {
137 137
 
138
-		$filename = $this->get_filename( $key );
138
+		$filename = $this->get_filename($key);
139 139
 
140 140
 		// Cache.
141
-		if ( file_exists( $filename ) ) {
141
+		if (file_exists($filename)) {
142 142
 			// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
143
-			@unlink( $filename );
143
+			@unlink($filename);
144 144
 		}
145 145
 
146 146
 		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged,WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents
147
-		@file_put_contents( $filename, wp_json_encode( $data ) );
147
+		@file_put_contents($filename, wp_json_encode($data));
148 148
 
149 149
 	}
150 150
 
151
-	public function delete( $key ) {
151
+	public function delete($key) {
152 152
 
153
-		$filename = $this->get_filename( $key );
153
+		$filename = $this->get_filename($key);
154 154
 
155 155
 		// Delete.
156
-		if ( file_exists( $filename ) ) {
156
+		if (file_exists($filename)) {
157 157
 			// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
158
-			@unlink( $filename );
158
+			@unlink($filename);
159 159
 		}
160 160
 
161 161
 	}
162 162
 
163 163
 	public function flush() {
164 164
 
165
-		$files = glob( $this->cache_dir . DIRECTORY_SEPARATOR . '*' );
166
-		foreach ( $files as $file ) { // iterate files
167
-			if ( is_file( $file ) ) {
165
+		$files = glob($this->cache_dir.DIRECTORY_SEPARATOR.'*');
166
+		foreach ($files as $file) { // iterate files
167
+			if (is_file($file)) {
168 168
 				// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
169
-				@unlink( $file );
169
+				@unlink($file);
170 170
 			}
171 171
 		}
172 172
 
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
 	public static function flush_all() {
176 176
 
177 177
 		/** @var Ttl_Cache $cache */
178
-		foreach ( self::$caches as $cache ) {
178
+		foreach (self::$caches as $cache) {
179 179
 			$cache->flush();
180 180
 		}
181 181
 
@@ -189,16 +189,16 @@  discard block
 block discarded – undo
189 189
 	 * @return string The full path to the file.
190 190
 	 * @since 3.21.2
191 191
 	 */
192
-	private function get_path( $hash ) {
192
+	private function get_path($hash) {
193 193
 
194
-		return $this->cache_dir . DIRECTORY_SEPARATOR . $hash;
194
+		return $this->cache_dir.DIRECTORY_SEPARATOR.$hash;
195 195
 	}
196 196
 
197
-	private function get_filename( $key ) {
197
+	private function get_filename($key) {
198 198
 
199 199
 		// Create a hash and a path to the cache file.
200
-		$hash     = md5( wp_json_encode( $key ) );
201
-		$filename = $this->get_path( $hash );
200
+		$hash     = md5(wp_json_encode($key));
201
+		$filename = $this->get_path($hash);
202 202
 
203 203
 		return $filename;
204 204
 	}
Please login to merge, or discard this patch.
src/includes/class-wordlift-abstract-post-to-jsonld-converter.php 2 patches
Indentation   +398 added lines, -398 removed lines patch added patch discarded remove patch
@@ -23,114 +23,114 @@  discard block
 block discarded – undo
23 23
  */
24 24
 abstract class Wordlift_Abstract_Post_To_Jsonld_Converter implements Wordlift_Post_Converter {
25 25
 
26
-	/**
27
-	 * The JSON-LD context.
28
-	 *
29
-	 * @since 3.10.0
30
-	 */
31
-	const CONTEXT = 'http://schema.org';
32
-
33
-	/**
34
-	 * A {@link Wordlift_Entity_Type_Service} instance.
35
-	 *
36
-	 * @since  3.10.0
37
-	 * @access protected
38
-	 * @var \Wordlift_Entity_Type_Service $entity_type_service A {@link Wordlift_Entity_Type_Service} instance.
39
-	 */
40
-	protected $entity_type_service;
41
-
42
-	/**
43
-	 * A {@link Wordlift_User_Service} instance.
44
-	 *
45
-	 * @since  3.10.0
46
-	 * @access private
47
-	 * @var \Wordlift_User_Service $user_service A {@link Wordlift_User_Service} instance.
48
-	 */
49
-	protected $user_service;
50
-
51
-	/**
52
-	 * A {@link Wordlift_Attachment_Service} instance.
53
-	 *
54
-	 * @since  3.10.0
55
-	 * @access private
56
-	 * @var \Wordlift_Attachment_Service $attachment_service A {@link Wordlift_Attachment_Service} instance.
57
-	 */
58
-	protected $attachment_service;
59
-
60
-	/**
61
-	 * @var Wordlift_Property_Getter
62
-	 */
63
-	private $property_getter;
64
-
65
-	/**
66
-	 * Wordlift_Post_To_Jsonld_Converter constructor.
67
-	 *
68
-	 * @param \Wordlift_Entity_Type_Service $entity_type_service A {@link Wordlift_Entity_Type_Service} instance.
69
-	 * @param \Wordlift_User_Service $user_service A {@link Wordlift_User_Service} instance.
70
-	 * @param \Wordlift_Attachment_Service $attachment_service A {@link Wordlift_Attachment_Service} instance.
71
-	 * @param \Wordlift_Property_Getter $property_getter
72
-	 *
73
-	 * @since 3.10.0
74
-	 */
75
-	public function __construct( $entity_type_service, $user_service, $attachment_service, $property_getter ) {
76
-		$this->entity_type_service = $entity_type_service;
77
-		$this->user_service        = $user_service;
78
-		$this->attachment_service  = $attachment_service;
79
-		$this->property_getter     = $property_getter;
80
-	}
81
-
82
-	/**
83
-	 * Convert the provided {@link WP_Post} to a JSON-LD array. Any entity reference
84
-	 * found while processing the post is set in the $references array.
85
-	 *
86
-	 * @param int $post_id The post id.
87
-	 * @param array $references An array of entity references.
88
-	 * @param array $references_infos
89
-	 *
90
-	 * @return array A JSON-LD array.
91
-	 * @since 3.10.0
92
-	 */
93
-	// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
94
-	public function convert( $post_id, &$references = array(), &$references_infos = array() ) {
95
-
96
-		// Get the post instance.
97
-		$post = get_post( $post_id );
98
-		if ( null === $post ) {
99
-			// Post not found.
100
-			return null;
101
-		}
102
-
103
-		// Get the post URI @id.
104
-		$id = Wordlift_Entity_Service::get_instance()->get_uri( $post->ID );
105
-		if ( $id === null ) {
106
-			$id = 'get_uri returned null, dataset is ' . wl_configuration_get_redlink_dataset_uri();
107
-		}
108
-
109
-		/*
26
+    /**
27
+     * The JSON-LD context.
28
+     *
29
+     * @since 3.10.0
30
+     */
31
+    const CONTEXT = 'http://schema.org';
32
+
33
+    /**
34
+     * A {@link Wordlift_Entity_Type_Service} instance.
35
+     *
36
+     * @since  3.10.0
37
+     * @access protected
38
+     * @var \Wordlift_Entity_Type_Service $entity_type_service A {@link Wordlift_Entity_Type_Service} instance.
39
+     */
40
+    protected $entity_type_service;
41
+
42
+    /**
43
+     * A {@link Wordlift_User_Service} instance.
44
+     *
45
+     * @since  3.10.0
46
+     * @access private
47
+     * @var \Wordlift_User_Service $user_service A {@link Wordlift_User_Service} instance.
48
+     */
49
+    protected $user_service;
50
+
51
+    /**
52
+     * A {@link Wordlift_Attachment_Service} instance.
53
+     *
54
+     * @since  3.10.0
55
+     * @access private
56
+     * @var \Wordlift_Attachment_Service $attachment_service A {@link Wordlift_Attachment_Service} instance.
57
+     */
58
+    protected $attachment_service;
59
+
60
+    /**
61
+     * @var Wordlift_Property_Getter
62
+     */
63
+    private $property_getter;
64
+
65
+    /**
66
+     * Wordlift_Post_To_Jsonld_Converter constructor.
67
+     *
68
+     * @param \Wordlift_Entity_Type_Service $entity_type_service A {@link Wordlift_Entity_Type_Service} instance.
69
+     * @param \Wordlift_User_Service $user_service A {@link Wordlift_User_Service} instance.
70
+     * @param \Wordlift_Attachment_Service $attachment_service A {@link Wordlift_Attachment_Service} instance.
71
+     * @param \Wordlift_Property_Getter $property_getter
72
+     *
73
+     * @since 3.10.0
74
+     */
75
+    public function __construct( $entity_type_service, $user_service, $attachment_service, $property_getter ) {
76
+        $this->entity_type_service = $entity_type_service;
77
+        $this->user_service        = $user_service;
78
+        $this->attachment_service  = $attachment_service;
79
+        $this->property_getter     = $property_getter;
80
+    }
81
+
82
+    /**
83
+     * Convert the provided {@link WP_Post} to a JSON-LD array. Any entity reference
84
+     * found while processing the post is set in the $references array.
85
+     *
86
+     * @param int $post_id The post id.
87
+     * @param array $references An array of entity references.
88
+     * @param array $references_infos
89
+     *
90
+     * @return array A JSON-LD array.
91
+     * @since 3.10.0
92
+     */
93
+    // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
94
+    public function convert( $post_id, &$references = array(), &$references_infos = array() ) {
95
+
96
+        // Get the post instance.
97
+        $post = get_post( $post_id );
98
+        if ( null === $post ) {
99
+            // Post not found.
100
+            return null;
101
+        }
102
+
103
+        // Get the post URI @id.
104
+        $id = Wordlift_Entity_Service::get_instance()->get_uri( $post->ID );
105
+        if ( $id === null ) {
106
+            $id = 'get_uri returned null, dataset is ' . wl_configuration_get_redlink_dataset_uri();
107
+        }
108
+
109
+        /*
110 110
 		 * The `types` variable holds one or more entity types. The `type` variable isn't used anymore.
111 111
 		 *
112 112
 		 * @since 3.20.0 We support more than one entity type.
113 113
 		 *
114 114
 		 * @see https://github.com/insideout10/wordlift-plugin/issues/835
115 115
 		 */
116
-		// Get the entity @type. We consider `post` BlogPostings.
117
-		// $type = $this->entity_type_service->get( $post_id );
118
-		$types = $this->entity_type_service->get_names( $post_id );
119
-		$type  = self::make_one( $types );
120
-
121
-		// Prepare the response.
122
-		$jsonld = array(
123
-			'@context' => self::CONTEXT,
124
-			'@id'      => $id,
125
-			'@type'    => $type,
126
-		);
127
-
128
-		if ( post_type_supports( $post->post_type, 'excerpt' ) ) {
129
-			$jsonld['description'] = Wordlift_Post_Excerpt_Helper::get_text_excerpt( $post );
130
-		}
131
-
132
-		// Set the `mainEntityOfPage` property if the post has some contents.
133
-		/*
116
+        // Get the entity @type. We consider `post` BlogPostings.
117
+        // $type = $this->entity_type_service->get( $post_id );
118
+        $types = $this->entity_type_service->get_names( $post_id );
119
+        $type  = self::make_one( $types );
120
+
121
+        // Prepare the response.
122
+        $jsonld = array(
123
+            '@context' => self::CONTEXT,
124
+            '@id'      => $id,
125
+            '@type'    => $type,
126
+        );
127
+
128
+        if ( post_type_supports( $post->post_type, 'excerpt' ) ) {
129
+            $jsonld['description'] = Wordlift_Post_Excerpt_Helper::get_text_excerpt( $post );
130
+        }
131
+
132
+        // Set the `mainEntityOfPage` property if the post has some contents.
133
+        /*
134 134
 		 * Apply the `wl_post_content` filter, in case 3rd parties want to change the post content, e.g.
135 135
 		 * because the content is written elsewhere.
136 136
 		 *
@@ -138,311 +138,311 @@  discard block
 block discarded – undo
138 138
 		 *
139 139
 		 * @since 3.20.0
140 140
 		 */
141
-		$post_content = apply_filters( 'wl_post_content', $post->post_content, $post );
142
-		if ( ! empty( $post_content ) || in_array( 'Product', (array) $type, true ) ) {
143
-			// We're setting the `mainEntityOfPage` to signal which one is the
144
-			// main entity for the specified URL. It might be however that the
145
-			// post/page is actually about another specific entity. How WL deals
146
-			// with that hasn't been defined yet (see https://github.com/insideout10/wordlift-plugin/issues/451).
147
-			//
148
-			// See http://schema.org/mainEntityOfPage
149
-			//
150
-			// No need to specify `'@type' => 'WebPage'.
151
-			//
152
-			// See https://github.com/insideout10/wordlift-plugin/issues/451.
153
-			$jsonld['mainEntityOfPage'] = get_the_permalink( $post->ID );
154
-
155
-			/**
156
-			 * @see https://github.com/insideout10/wordlift-plugin/issues/1207
157
-			 *
158
-			 * @since 3.27.7
159
-			 */
160
-			if ( in_array( $type, array(
161
-				'Occupation',
162
-				'OccupationAggregationByEmployer'
163
-			), true ) ) {
164
-				$jsonld['mainEntityOfPage'] = array(
165
-					'@type'        => 'WebPage',
166
-					'lastReviewed' => get_post_time( 'Y-m-d\TH:i:sP', true, $post, false ),
167
-				);
168
-			}
169
-		};
170
-
171
-		$this->set_images( $this->attachment_service, $post, $jsonld );
172
-
173
-		// Get the entities referenced by this post and set it to the `references`
174
-		// array so that the caller can do further processing, such as printing out
175
-		// more of those references.
176
-		$references_without_locations = Object_Relation_Service::get_instance()
177
-		                                                       ->get_references( $post_id, Object_Type_Enum::POST );
178
-
179
-		/*
141
+        $post_content = apply_filters( 'wl_post_content', $post->post_content, $post );
142
+        if ( ! empty( $post_content ) || in_array( 'Product', (array) $type, true ) ) {
143
+            // We're setting the `mainEntityOfPage` to signal which one is the
144
+            // main entity for the specified URL. It might be however that the
145
+            // post/page is actually about another specific entity. How WL deals
146
+            // with that hasn't been defined yet (see https://github.com/insideout10/wordlift-plugin/issues/451).
147
+            //
148
+            // See http://schema.org/mainEntityOfPage
149
+            //
150
+            // No need to specify `'@type' => 'WebPage'.
151
+            //
152
+            // See https://github.com/insideout10/wordlift-plugin/issues/451.
153
+            $jsonld['mainEntityOfPage'] = get_the_permalink( $post->ID );
154
+
155
+            /**
156
+             * @see https://github.com/insideout10/wordlift-plugin/issues/1207
157
+             *
158
+             * @since 3.27.7
159
+             */
160
+            if ( in_array( $type, array(
161
+                'Occupation',
162
+                'OccupationAggregationByEmployer'
163
+            ), true ) ) {
164
+                $jsonld['mainEntityOfPage'] = array(
165
+                    '@type'        => 'WebPage',
166
+                    'lastReviewed' => get_post_time( 'Y-m-d\TH:i:sP', true, $post, false ),
167
+                );
168
+            }
169
+        };
170
+
171
+        $this->set_images( $this->attachment_service, $post, $jsonld );
172
+
173
+        // Get the entities referenced by this post and set it to the `references`
174
+        // array so that the caller can do further processing, such as printing out
175
+        // more of those references.
176
+        $references_without_locations = Object_Relation_Service::get_instance()
177
+                                                                ->get_references( $post_id, Object_Type_Enum::POST );
178
+
179
+        /*
180 180
 		 * Add the locations to the references.
181 181
 		 *
182 182
 		 * @since 3.19.5
183 183
 		 *
184 184
 		 * @see https://github.com/insideout10/wordlift-plugin/issues/858.
185 185
 		 */
186
-		// A reference to use in closure.
187
-		$entity_type_service = $this->entity_type_service;
188
-		$locations           = array_reduce(
189
-			$references_without_locations,
190
-			function ( $carry, $reference ) use ( $entity_type_service ) {
191
-				/**
192
-				 * @var $reference Reference
193
-				 */
194
-				// @see https://schema.org/location for the schema.org types using the `location` property.
195
-				if ( ! $entity_type_service->has_entity_type( $reference->get_id(), 'http://schema.org/Action' )
196
-				     && ! $entity_type_service->has_entity_type( $reference->get_id(), 'http://schema.org/Event' )
197
-				     && ! $entity_type_service->has_entity_type( $reference->get_id(), 'http://schema.org/Organization' ) ) {
198
-
199
-					return $carry;
200
-				}
201
-				$post_location_ids        = get_post_meta( $reference->get_id(), Wordlift_Schema_Service::FIELD_LOCATION );
202
-				$post_location_references = array_map(
203
-					function ( $post_id ) {
204
-						return new Post_Reference( $post_id );
205
-					},
206
-					$post_location_ids
207
-				);
208
-
209
-				return array_merge( $carry, $post_location_references );
210
-			},
211
-			array()
212
-		);
213
-
214
-		// Merge the references with the referenced locations if any.
215
-		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
216
-		$references = array_merge( $references_without_locations, $locations );
217
-
218
-		return $jsonld;
219
-	}
220
-
221
-	/**
222
-	 * If the provided value starts with the schema.org context, we remove the schema.org
223
-	 * part since it is set with the '@context'.
224
-	 *
225
-	 * @param string $value The property value.
226
-	 *
227
-	 * @return string The property value without the context.
228
-	 * @since 3.10.0
229
-	 */
230
-	public function relative_to_context( $value ) {
231
-		return ! is_array( $value ) && 0 === strpos( $value, self::CONTEXT . '/' ) ? substr( $value, strlen( self::CONTEXT ) + 1 ) : $value;
232
-	}
233
-
234
-	/**
235
-	 * Set the images, by looking for embedded images, for images loaded via the
236
-	 * gallery and for the featured image.
237
-	 *
238
-	 * Uses the cache service to store the results of this function for a day.
239
-	 *
240
-	 * @param $attachment_service Wordlift_Attachment_Service
241
-	 * @param WP_Post $post The target {@link WP_Post}.
242
-	 * @param array $jsonld The JSON-LD array.
243
-	 *
244
-	 * @since 3.10.0
245
-	 */
246
-	public static function set_images( $attachment_service, $post, &$jsonld ) {
247
-
248
-		// Prepare the attachment ids array.
249
-		$ids = array();
250
-
251
-		// Set the thumbnail id as first attachment id, if any.
252
-		$thumbnail_id = get_post_thumbnail_id( $post->ID );
253
-		if ( '' !== $thumbnail_id && 0 !== $thumbnail_id ) {
254
-			$ids[] = $thumbnail_id;
255
-		}
256
-
257
-		// For the time being the following is being removed since the query
258
-		// initiated by `get_image_embeds` is consuming lots of CPU.
259
-		//
260
-		// See https://github.com/insideout10/wordlift-plugin/issues/689.
261
-		//
262
-		// Get the embeds, removing existing ids.
263
-		// phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
264
-		if ( apply_filters( 'wl_feature__enable__image-embeds', false ) ) {
265
-			$embeds = array_diff( $attachment_service->get_image_embeds( $post->post_content ), $ids );
266
-		} else {
267
-			$embeds = array();
268
-		}
269
-
270
-		// Get the gallery, removing existing ids.
271
-		$gallery = array_diff( $attachment_service->get_gallery( $post ), $ids, $embeds );
272
-
273
-		// Map the attachment ids to images' data structured for schema.org use.
274
-		$images_with_sizes = array_filter(
275
-			array_reduce(
276
-				array_merge( $ids, $embeds, $gallery ),
277
-				function ( $carry, $item ) {
278
-					/*
186
+        // A reference to use in closure.
187
+        $entity_type_service = $this->entity_type_service;
188
+        $locations           = array_reduce(
189
+            $references_without_locations,
190
+            function ( $carry, $reference ) use ( $entity_type_service ) {
191
+                /**
192
+                 * @var $reference Reference
193
+                 */
194
+                // @see https://schema.org/location for the schema.org types using the `location` property.
195
+                if ( ! $entity_type_service->has_entity_type( $reference->get_id(), 'http://schema.org/Action' )
196
+                     && ! $entity_type_service->has_entity_type( $reference->get_id(), 'http://schema.org/Event' )
197
+                     && ! $entity_type_service->has_entity_type( $reference->get_id(), 'http://schema.org/Organization' ) ) {
198
+
199
+                    return $carry;
200
+                }
201
+                $post_location_ids        = get_post_meta( $reference->get_id(), Wordlift_Schema_Service::FIELD_LOCATION );
202
+                $post_location_references = array_map(
203
+                    function ( $post_id ) {
204
+                        return new Post_Reference( $post_id );
205
+                    },
206
+                    $post_location_ids
207
+                );
208
+
209
+                return array_merge( $carry, $post_location_references );
210
+            },
211
+            array()
212
+        );
213
+
214
+        // Merge the references with the referenced locations if any.
215
+        // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
216
+        $references = array_merge( $references_without_locations, $locations );
217
+
218
+        return $jsonld;
219
+    }
220
+
221
+    /**
222
+     * If the provided value starts with the schema.org context, we remove the schema.org
223
+     * part since it is set with the '@context'.
224
+     *
225
+     * @param string $value The property value.
226
+     *
227
+     * @return string The property value without the context.
228
+     * @since 3.10.0
229
+     */
230
+    public function relative_to_context( $value ) {
231
+        return ! is_array( $value ) && 0 === strpos( $value, self::CONTEXT . '/' ) ? substr( $value, strlen( self::CONTEXT ) + 1 ) : $value;
232
+    }
233
+
234
+    /**
235
+     * Set the images, by looking for embedded images, for images loaded via the
236
+     * gallery and for the featured image.
237
+     *
238
+     * Uses the cache service to store the results of this function for a day.
239
+     *
240
+     * @param $attachment_service Wordlift_Attachment_Service
241
+     * @param WP_Post $post The target {@link WP_Post}.
242
+     * @param array $jsonld The JSON-LD array.
243
+     *
244
+     * @since 3.10.0
245
+     */
246
+    public static function set_images( $attachment_service, $post, &$jsonld ) {
247
+
248
+        // Prepare the attachment ids array.
249
+        $ids = array();
250
+
251
+        // Set the thumbnail id as first attachment id, if any.
252
+        $thumbnail_id = get_post_thumbnail_id( $post->ID );
253
+        if ( '' !== $thumbnail_id && 0 !== $thumbnail_id ) {
254
+            $ids[] = $thumbnail_id;
255
+        }
256
+
257
+        // For the time being the following is being removed since the query
258
+        // initiated by `get_image_embeds` is consuming lots of CPU.
259
+        //
260
+        // See https://github.com/insideout10/wordlift-plugin/issues/689.
261
+        //
262
+        // Get the embeds, removing existing ids.
263
+        // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
264
+        if ( apply_filters( 'wl_feature__enable__image-embeds', false ) ) {
265
+            $embeds = array_diff( $attachment_service->get_image_embeds( $post->post_content ), $ids );
266
+        } else {
267
+            $embeds = array();
268
+        }
269
+
270
+        // Get the gallery, removing existing ids.
271
+        $gallery = array_diff( $attachment_service->get_gallery( $post ), $ids, $embeds );
272
+
273
+        // Map the attachment ids to images' data structured for schema.org use.
274
+        $images_with_sizes = array_filter(
275
+            array_reduce(
276
+                array_merge( $ids, $embeds, $gallery ),
277
+                function ( $carry, $item ) {
278
+                    /*
279 279
 					* @todo: we're not sure that we're getting attachment data here, we
280 280
 					* should filter `false`s.
281 281
 					*/
282 282
 
283
-					$sources = array_merge(
284
-						Wordlift_Image_Service::get_sources( $item ),
285
-						array( wp_get_attachment_image_src( $item, 'full' ) )
286
-					);
287
-
288
-					$sources_with_image = array_filter(
289
-						$sources,
290
-						function ( $source ) {
291
-							return ! empty( $source[0] );
292
-						}
293
-					);
294
-
295
-					// Get the attachment data.
296
-					// $attachment = wp_get_attachment_image_src( $item, 'full' );
297
-
298
-					// var_dump( array( "sources-$item" => Wordlift_Image_Service::get_sources( $item ) ) );
299
-
300
-					// Bail if image is not found.
301
-					// In some cases, you can delete the image from the database
302
-					// or from uploads dir, but the image id still exists as featured image
303
-					// or in [gallery] shortcode.
304
-					// if ( empty( $attachment[0] ) ) {
305
-					if ( empty( $sources_with_image ) ) {
306
-						return $carry;
307
-					}
308
-
309
-					// Merge the arrays.
310
-					return array_merge(
311
-						$carry,
312
-						$sources_with_image
313
-					);
314
-				},
315
-				// Initial array.
316
-
317
-				array()
318
-			)
319
-		);
320
-
321
-		// Refactor data as per schema.org specifications.
322
-		$images = array_map(
323
-			function ( $attachment ) {
324
-				return Wordlift_Abstract_Post_To_Jsonld_Converter::set_image_size(
325
-					array(
326
-						'@type' => 'ImageObject',
327
-						'url'   => $attachment[0],
328
-					),
329
-					$attachment
330
-				);
331
-			},
332
-			$images_with_sizes
333
-		);
334
-
335
-		// Add images if present.
336
-		if ( 0 < count( $images ) ) {
337
-			$jsonld['image'] = $images;
338
-		}
339
-
340
-	}
341
-
342
-	/**
343
-	 * If the provided array of values contains only one value, then one single
344
-	 * value is returned, otherwise the original array is returned.
345
-	 *
346
-	 * @param array $value An array of values.
347
-	 *
348
-	 * @return mixed|array A single value or the original array.
349
-	 * @since 3.20.0 The function has been moved from {@link Wordlift_Entity_Post_To_Jsonld_Converter} to
350
-	 *  {@link Wordlift_Abstract_Post_To_Jsonld_Converter}.
351
-	 * @since  3.8.0
352
-	 * @access private
353
-	 */
354
-	protected static function make_one( $value ) {
355
-
356
-		return 1 === count( $value ) ? $value[0] : $value;
357
-	}
358
-
359
-	/**
360
-	 * Process the provided array by adding the width / height if the values
361
-	 * are available and are greater than 0.
362
-	 *
363
-	 * @param array $image The `ImageObject` array.
364
-	 * @param array $attachment The attachment array.
365
-	 *
366
-	 * @return array The enriched `ImageObject` array.
367
-	 * @since 3.14.0
368
-	 */
369
-	public static function set_image_size( $image, $attachment ) {
370
-
371
-		// If you specify a "width" or "height" value you should leave out
372
-		// 'px'. For example: "width":"4608px" should be "width":"4608".
373
-		//
374
-		// See https://github.com/insideout10/wordlift-plugin/issues/451.
375
-		if ( isset( $attachment[1] ) && is_numeric( $attachment[1] ) && 0 < $attachment[1] ) {
376
-			$image['width'] = $attachment[1];
377
-		}
378
-
379
-		if ( isset( $attachment[2] ) && is_numeric( $attachment[2] ) && 0 < $attachment[2] ) {
380
-			$image['height'] = $attachment[2];
381
-		}
382
-
383
-		return $image;
384
-	}
385
-
386
-	/**
387
-	 * Add data to the JSON-LD using the `custom_fields` array which contains the definitions of property
388
-	 * for the post entity type.
389
-	 *
390
-	 * @param array $jsonld The JSON-LD array.
391
-	 * @param array $fields The entity types field array.
392
-	 * @param WP_Post $post The target {@link WP_Post} instance.
393
-	 * @param array $references The references array.
394
-	 *
395
-	 * @since 3.20.0 This code moved from the above function `convert`, used for entity types defined in
396
-	 *  the {@link Wordlift_Schema_Service} class.
397
-	 */
398
-	protected function process_type_custom_fields( &$jsonld, $fields, $post, &$references, &$references_infos ) {
399
-
400
-		// Set a reference to use in closures.
401
-		$converter = $this;
402
-
403
-		// Try each field on the entity.
404
-		foreach ( $fields as $key => $value ) {
405
-
406
-			// Get the predicate.
407
-			$name = $this->relative_to_context( $value['predicate'] );
408
-
409
-			// Get the value, the property service will get the right extractor
410
-			// for that property.
411
-			$value = $this->property_getter->get( $post->ID, $key, Object_Type_Enum::POST );
412
-
413
-			if ( empty( $value ) ) {
414
-				continue;
415
-			}
416
-
417
-			// Map the value to the property name.
418
-			// If we got an array with just one value, we return that one value.
419
-			// If we got a Wordlift_Property_Entity_Reference we get the URL.
420
-			$jsonld[ $name ] = self::make_one(
421
-				array_map(
422
-					function ( $item ) use ( $converter, &$references, &$references_infos ) {
423
-
424
-						if ( $item instanceof Wordlift_Property_Entity_Reference ) {
425
-
426
-							$url = $item->get_url();
427
-
428
-							// The refactored converters require the entity id.
429
-							// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable
430
-							$references[] = $item->to_reference();
431
-
432
-							// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable
433
-							$references_infos[] = array( 'reference' => $item );
434
-
435
-							return array( '@id' => $url );
436
-						}
437
-
438
-						return $converter->relative_to_context( $item );
439
-					},
440
-					$value
441
-				)
442
-			);
443
-
444
-		}
445
-
446
-	}
283
+                    $sources = array_merge(
284
+                        Wordlift_Image_Service::get_sources( $item ),
285
+                        array( wp_get_attachment_image_src( $item, 'full' ) )
286
+                    );
287
+
288
+                    $sources_with_image = array_filter(
289
+                        $sources,
290
+                        function ( $source ) {
291
+                            return ! empty( $source[0] );
292
+                        }
293
+                    );
294
+
295
+                    // Get the attachment data.
296
+                    // $attachment = wp_get_attachment_image_src( $item, 'full' );
297
+
298
+                    // var_dump( array( "sources-$item" => Wordlift_Image_Service::get_sources( $item ) ) );
299
+
300
+                    // Bail if image is not found.
301
+                    // In some cases, you can delete the image from the database
302
+                    // or from uploads dir, but the image id still exists as featured image
303
+                    // or in [gallery] shortcode.
304
+                    // if ( empty( $attachment[0] ) ) {
305
+                    if ( empty( $sources_with_image ) ) {
306
+                        return $carry;
307
+                    }
308
+
309
+                    // Merge the arrays.
310
+                    return array_merge(
311
+                        $carry,
312
+                        $sources_with_image
313
+                    );
314
+                },
315
+                // Initial array.
316
+
317
+                array()
318
+            )
319
+        );
320
+
321
+        // Refactor data as per schema.org specifications.
322
+        $images = array_map(
323
+            function ( $attachment ) {
324
+                return Wordlift_Abstract_Post_To_Jsonld_Converter::set_image_size(
325
+                    array(
326
+                        '@type' => 'ImageObject',
327
+                        'url'   => $attachment[0],
328
+                    ),
329
+                    $attachment
330
+                );
331
+            },
332
+            $images_with_sizes
333
+        );
334
+
335
+        // Add images if present.
336
+        if ( 0 < count( $images ) ) {
337
+            $jsonld['image'] = $images;
338
+        }
339
+
340
+    }
341
+
342
+    /**
343
+     * If the provided array of values contains only one value, then one single
344
+     * value is returned, otherwise the original array is returned.
345
+     *
346
+     * @param array $value An array of values.
347
+     *
348
+     * @return mixed|array A single value or the original array.
349
+     * @since 3.20.0 The function has been moved from {@link Wordlift_Entity_Post_To_Jsonld_Converter} to
350
+     *  {@link Wordlift_Abstract_Post_To_Jsonld_Converter}.
351
+     * @since  3.8.0
352
+     * @access private
353
+     */
354
+    protected static function make_one( $value ) {
355
+
356
+        return 1 === count( $value ) ? $value[0] : $value;
357
+    }
358
+
359
+    /**
360
+     * Process the provided array by adding the width / height if the values
361
+     * are available and are greater than 0.
362
+     *
363
+     * @param array $image The `ImageObject` array.
364
+     * @param array $attachment The attachment array.
365
+     *
366
+     * @return array The enriched `ImageObject` array.
367
+     * @since 3.14.0
368
+     */
369
+    public static function set_image_size( $image, $attachment ) {
370
+
371
+        // If you specify a "width" or "height" value you should leave out
372
+        // 'px'. For example: "width":"4608px" should be "width":"4608".
373
+        //
374
+        // See https://github.com/insideout10/wordlift-plugin/issues/451.
375
+        if ( isset( $attachment[1] ) && is_numeric( $attachment[1] ) && 0 < $attachment[1] ) {
376
+            $image['width'] = $attachment[1];
377
+        }
378
+
379
+        if ( isset( $attachment[2] ) && is_numeric( $attachment[2] ) && 0 < $attachment[2] ) {
380
+            $image['height'] = $attachment[2];
381
+        }
382
+
383
+        return $image;
384
+    }
385
+
386
+    /**
387
+     * Add data to the JSON-LD using the `custom_fields` array which contains the definitions of property
388
+     * for the post entity type.
389
+     *
390
+     * @param array $jsonld The JSON-LD array.
391
+     * @param array $fields The entity types field array.
392
+     * @param WP_Post $post The target {@link WP_Post} instance.
393
+     * @param array $references The references array.
394
+     *
395
+     * @since 3.20.0 This code moved from the above function `convert`, used for entity types defined in
396
+     *  the {@link Wordlift_Schema_Service} class.
397
+     */
398
+    protected function process_type_custom_fields( &$jsonld, $fields, $post, &$references, &$references_infos ) {
399
+
400
+        // Set a reference to use in closures.
401
+        $converter = $this;
402
+
403
+        // Try each field on the entity.
404
+        foreach ( $fields as $key => $value ) {
405
+
406
+            // Get the predicate.
407
+            $name = $this->relative_to_context( $value['predicate'] );
408
+
409
+            // Get the value, the property service will get the right extractor
410
+            // for that property.
411
+            $value = $this->property_getter->get( $post->ID, $key, Object_Type_Enum::POST );
412
+
413
+            if ( empty( $value ) ) {
414
+                continue;
415
+            }
416
+
417
+            // Map the value to the property name.
418
+            // If we got an array with just one value, we return that one value.
419
+            // If we got a Wordlift_Property_Entity_Reference we get the URL.
420
+            $jsonld[ $name ] = self::make_one(
421
+                array_map(
422
+                    function ( $item ) use ( $converter, &$references, &$references_infos ) {
423
+
424
+                        if ( $item instanceof Wordlift_Property_Entity_Reference ) {
425
+
426
+                            $url = $item->get_url();
427
+
428
+                            // The refactored converters require the entity id.
429
+                            // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable
430
+                            $references[] = $item->to_reference();
431
+
432
+                            // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable
433
+                            $references_infos[] = array( 'reference' => $item );
434
+
435
+                            return array( '@id' => $url );
436
+                        }
437
+
438
+                        return $converter->relative_to_context( $item );
439
+                    },
440
+                    $value
441
+                )
442
+            );
443
+
444
+        }
445
+
446
+    }
447 447
 
448 448
 }
Please login to merge, or discard this patch.
Spacing   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
 	 *
73 73
 	 * @since 3.10.0
74 74
 	 */
75
-	public function __construct( $entity_type_service, $user_service, $attachment_service, $property_getter ) {
75
+	public function __construct($entity_type_service, $user_service, $attachment_service, $property_getter) {
76 76
 		$this->entity_type_service = $entity_type_service;
77 77
 		$this->user_service        = $user_service;
78 78
 		$this->attachment_service  = $attachment_service;
@@ -91,19 +91,19 @@  discard block
 block discarded – undo
91 91
 	 * @since 3.10.0
92 92
 	 */
93 93
 	// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
94
-	public function convert( $post_id, &$references = array(), &$references_infos = array() ) {
94
+	public function convert($post_id, &$references = array(), &$references_infos = array()) {
95 95
 
96 96
 		// Get the post instance.
97
-		$post = get_post( $post_id );
98
-		if ( null === $post ) {
97
+		$post = get_post($post_id);
98
+		if (null === $post) {
99 99
 			// Post not found.
100 100
 			return null;
101 101
 		}
102 102
 
103 103
 		// Get the post URI @id.
104
-		$id = Wordlift_Entity_Service::get_instance()->get_uri( $post->ID );
105
-		if ( $id === null ) {
106
-			$id = 'get_uri returned null, dataset is ' . wl_configuration_get_redlink_dataset_uri();
104
+		$id = Wordlift_Entity_Service::get_instance()->get_uri($post->ID);
105
+		if ($id === null) {
106
+			$id = 'get_uri returned null, dataset is '.wl_configuration_get_redlink_dataset_uri();
107 107
 		}
108 108
 
109 109
 		/*
@@ -115,8 +115,8 @@  discard block
 block discarded – undo
115 115
 		 */
116 116
 		// Get the entity @type. We consider `post` BlogPostings.
117 117
 		// $type = $this->entity_type_service->get( $post_id );
118
-		$types = $this->entity_type_service->get_names( $post_id );
119
-		$type  = self::make_one( $types );
118
+		$types = $this->entity_type_service->get_names($post_id);
119
+		$type  = self::make_one($types);
120 120
 
121 121
 		// Prepare the response.
122 122
 		$jsonld = array(
@@ -125,8 +125,8 @@  discard block
 block discarded – undo
125 125
 			'@type'    => $type,
126 126
 		);
127 127
 
128
-		if ( post_type_supports( $post->post_type, 'excerpt' ) ) {
129
-			$jsonld['description'] = Wordlift_Post_Excerpt_Helper::get_text_excerpt( $post );
128
+		if (post_type_supports($post->post_type, 'excerpt')) {
129
+			$jsonld['description'] = Wordlift_Post_Excerpt_Helper::get_text_excerpt($post);
130 130
 		}
131 131
 
132 132
 		// Set the `mainEntityOfPage` property if the post has some contents.
@@ -138,8 +138,8 @@  discard block
 block discarded – undo
138 138
 		 *
139 139
 		 * @since 3.20.0
140 140
 		 */
141
-		$post_content = apply_filters( 'wl_post_content', $post->post_content, $post );
142
-		if ( ! empty( $post_content ) || in_array( 'Product', (array) $type, true ) ) {
141
+		$post_content = apply_filters('wl_post_content', $post->post_content, $post);
142
+		if ( ! empty($post_content) || in_array('Product', (array) $type, true)) {
143 143
 			// We're setting the `mainEntityOfPage` to signal which one is the
144 144
 			// main entity for the specified URL. It might be however that the
145 145
 			// post/page is actually about another specific entity. How WL deals
@@ -150,31 +150,31 @@  discard block
 block discarded – undo
150 150
 			// No need to specify `'@type' => 'WebPage'.
151 151
 			//
152 152
 			// See https://github.com/insideout10/wordlift-plugin/issues/451.
153
-			$jsonld['mainEntityOfPage'] = get_the_permalink( $post->ID );
153
+			$jsonld['mainEntityOfPage'] = get_the_permalink($post->ID);
154 154
 
155 155
 			/**
156 156
 			 * @see https://github.com/insideout10/wordlift-plugin/issues/1207
157 157
 			 *
158 158
 			 * @since 3.27.7
159 159
 			 */
160
-			if ( in_array( $type, array(
160
+			if (in_array($type, array(
161 161
 				'Occupation',
162 162
 				'OccupationAggregationByEmployer'
163
-			), true ) ) {
163
+			), true)) {
164 164
 				$jsonld['mainEntityOfPage'] = array(
165 165
 					'@type'        => 'WebPage',
166
-					'lastReviewed' => get_post_time( 'Y-m-d\TH:i:sP', true, $post, false ),
166
+					'lastReviewed' => get_post_time('Y-m-d\TH:i:sP', true, $post, false),
167 167
 				);
168 168
 			}
169 169
 		};
170 170
 
171
-		$this->set_images( $this->attachment_service, $post, $jsonld );
171
+		$this->set_images($this->attachment_service, $post, $jsonld);
172 172
 
173 173
 		// Get the entities referenced by this post and set it to the `references`
174 174
 		// array so that the caller can do further processing, such as printing out
175 175
 		// more of those references.
176 176
 		$references_without_locations = Object_Relation_Service::get_instance()
177
-		                                                       ->get_references( $post_id, Object_Type_Enum::POST );
177
+		                                                       ->get_references($post_id, Object_Type_Enum::POST);
178 178
 
179 179
 		/*
180 180
 		 * Add the locations to the references.
@@ -187,33 +187,33 @@  discard block
 block discarded – undo
187 187
 		$entity_type_service = $this->entity_type_service;
188 188
 		$locations           = array_reduce(
189 189
 			$references_without_locations,
190
-			function ( $carry, $reference ) use ( $entity_type_service ) {
190
+			function($carry, $reference) use ($entity_type_service) {
191 191
 				/**
192 192
 				 * @var $reference Reference
193 193
 				 */
194 194
 				// @see https://schema.org/location for the schema.org types using the `location` property.
195
-				if ( ! $entity_type_service->has_entity_type( $reference->get_id(), 'http://schema.org/Action' )
196
-				     && ! $entity_type_service->has_entity_type( $reference->get_id(), 'http://schema.org/Event' )
197
-				     && ! $entity_type_service->has_entity_type( $reference->get_id(), 'http://schema.org/Organization' ) ) {
195
+				if ( ! $entity_type_service->has_entity_type($reference->get_id(), 'http://schema.org/Action')
196
+				     && ! $entity_type_service->has_entity_type($reference->get_id(), 'http://schema.org/Event')
197
+				     && ! $entity_type_service->has_entity_type($reference->get_id(), 'http://schema.org/Organization')) {
198 198
 
199 199
 					return $carry;
200 200
 				}
201
-				$post_location_ids        = get_post_meta( $reference->get_id(), Wordlift_Schema_Service::FIELD_LOCATION );
201
+				$post_location_ids        = get_post_meta($reference->get_id(), Wordlift_Schema_Service::FIELD_LOCATION);
202 202
 				$post_location_references = array_map(
203
-					function ( $post_id ) {
204
-						return new Post_Reference( $post_id );
203
+					function($post_id) {
204
+						return new Post_Reference($post_id);
205 205
 					},
206 206
 					$post_location_ids
207 207
 				);
208 208
 
209
-				return array_merge( $carry, $post_location_references );
209
+				return array_merge($carry, $post_location_references);
210 210
 			},
211 211
 			array()
212 212
 		);
213 213
 
214 214
 		// Merge the references with the referenced locations if any.
215 215
 		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
216
-		$references = array_merge( $references_without_locations, $locations );
216
+		$references = array_merge($references_without_locations, $locations);
217 217
 
218 218
 		return $jsonld;
219 219
 	}
@@ -227,8 +227,8 @@  discard block
 block discarded – undo
227 227
 	 * @return string The property value without the context.
228 228
 	 * @since 3.10.0
229 229
 	 */
230
-	public function relative_to_context( $value ) {
231
-		return ! is_array( $value ) && 0 === strpos( $value, self::CONTEXT . '/' ) ? substr( $value, strlen( self::CONTEXT ) + 1 ) : $value;
230
+	public function relative_to_context($value) {
231
+		return ! is_array($value) && 0 === strpos($value, self::CONTEXT.'/') ? substr($value, strlen(self::CONTEXT) + 1) : $value;
232 232
 	}
233 233
 
234 234
 	/**
@@ -243,14 +243,14 @@  discard block
 block discarded – undo
243 243
 	 *
244 244
 	 * @since 3.10.0
245 245
 	 */
246
-	public static function set_images( $attachment_service, $post, &$jsonld ) {
246
+	public static function set_images($attachment_service, $post, &$jsonld) {
247 247
 
248 248
 		// Prepare the attachment ids array.
249 249
 		$ids = array();
250 250
 
251 251
 		// Set the thumbnail id as first attachment id, if any.
252
-		$thumbnail_id = get_post_thumbnail_id( $post->ID );
253
-		if ( '' !== $thumbnail_id && 0 !== $thumbnail_id ) {
252
+		$thumbnail_id = get_post_thumbnail_id($post->ID);
253
+		if ('' !== $thumbnail_id && 0 !== $thumbnail_id) {
254 254
 			$ids[] = $thumbnail_id;
255 255
 		}
256 256
 
@@ -261,34 +261,34 @@  discard block
 block discarded – undo
261 261
 		//
262 262
 		// Get the embeds, removing existing ids.
263 263
 		// phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
264
-		if ( apply_filters( 'wl_feature__enable__image-embeds', false ) ) {
265
-			$embeds = array_diff( $attachment_service->get_image_embeds( $post->post_content ), $ids );
264
+		if (apply_filters('wl_feature__enable__image-embeds', false)) {
265
+			$embeds = array_diff($attachment_service->get_image_embeds($post->post_content), $ids);
266 266
 		} else {
267 267
 			$embeds = array();
268 268
 		}
269 269
 
270 270
 		// Get the gallery, removing existing ids.
271
-		$gallery = array_diff( $attachment_service->get_gallery( $post ), $ids, $embeds );
271
+		$gallery = array_diff($attachment_service->get_gallery($post), $ids, $embeds);
272 272
 
273 273
 		// Map the attachment ids to images' data structured for schema.org use.
274 274
 		$images_with_sizes = array_filter(
275 275
 			array_reduce(
276
-				array_merge( $ids, $embeds, $gallery ),
277
-				function ( $carry, $item ) {
276
+				array_merge($ids, $embeds, $gallery),
277
+				function($carry, $item) {
278 278
 					/*
279 279
 					* @todo: we're not sure that we're getting attachment data here, we
280 280
 					* should filter `false`s.
281 281
 					*/
282 282
 
283 283
 					$sources = array_merge(
284
-						Wordlift_Image_Service::get_sources( $item ),
285
-						array( wp_get_attachment_image_src( $item, 'full' ) )
284
+						Wordlift_Image_Service::get_sources($item),
285
+						array(wp_get_attachment_image_src($item, 'full'))
286 286
 					);
287 287
 
288 288
 					$sources_with_image = array_filter(
289 289
 						$sources,
290
-						function ( $source ) {
291
-							return ! empty( $source[0] );
290
+						function($source) {
291
+							return ! empty($source[0]);
292 292
 						}
293 293
 					);
294 294
 
@@ -302,7 +302,7 @@  discard block
 block discarded – undo
302 302
 					// or from uploads dir, but the image id still exists as featured image
303 303
 					// or in [gallery] shortcode.
304 304
 					// if ( empty( $attachment[0] ) ) {
305
-					if ( empty( $sources_with_image ) ) {
305
+					if (empty($sources_with_image)) {
306 306
 						return $carry;
307 307
 					}
308 308
 
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
 
321 321
 		// Refactor data as per schema.org specifications.
322 322
 		$images = array_map(
323
-			function ( $attachment ) {
323
+			function($attachment) {
324 324
 				return Wordlift_Abstract_Post_To_Jsonld_Converter::set_image_size(
325 325
 					array(
326 326
 						'@type' => 'ImageObject',
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 		);
334 334
 
335 335
 		// Add images if present.
336
-		if ( 0 < count( $images ) ) {
336
+		if (0 < count($images)) {
337 337
 			$jsonld['image'] = $images;
338 338
 		}
339 339
 
@@ -351,9 +351,9 @@  discard block
 block discarded – undo
351 351
 	 * @since  3.8.0
352 352
 	 * @access private
353 353
 	 */
354
-	protected static function make_one( $value ) {
354
+	protected static function make_one($value) {
355 355
 
356
-		return 1 === count( $value ) ? $value[0] : $value;
356
+		return 1 === count($value) ? $value[0] : $value;
357 357
 	}
358 358
 
359 359
 	/**
@@ -366,17 +366,17 @@  discard block
 block discarded – undo
366 366
 	 * @return array The enriched `ImageObject` array.
367 367
 	 * @since 3.14.0
368 368
 	 */
369
-	public static function set_image_size( $image, $attachment ) {
369
+	public static function set_image_size($image, $attachment) {
370 370
 
371 371
 		// If you specify a "width" or "height" value you should leave out
372 372
 		// 'px'. For example: "width":"4608px" should be "width":"4608".
373 373
 		//
374 374
 		// See https://github.com/insideout10/wordlift-plugin/issues/451.
375
-		if ( isset( $attachment[1] ) && is_numeric( $attachment[1] ) && 0 < $attachment[1] ) {
375
+		if (isset($attachment[1]) && is_numeric($attachment[1]) && 0 < $attachment[1]) {
376 376
 			$image['width'] = $attachment[1];
377 377
 		}
378 378
 
379
-		if ( isset( $attachment[2] ) && is_numeric( $attachment[2] ) && 0 < $attachment[2] ) {
379
+		if (isset($attachment[2]) && is_numeric($attachment[2]) && 0 < $attachment[2]) {
380 380
 			$image['height'] = $attachment[2];
381 381
 		}
382 382
 
@@ -395,33 +395,33 @@  discard block
 block discarded – undo
395 395
 	 * @since 3.20.0 This code moved from the above function `convert`, used for entity types defined in
396 396
 	 *  the {@link Wordlift_Schema_Service} class.
397 397
 	 */
398
-	protected function process_type_custom_fields( &$jsonld, $fields, $post, &$references, &$references_infos ) {
398
+	protected function process_type_custom_fields(&$jsonld, $fields, $post, &$references, &$references_infos) {
399 399
 
400 400
 		// Set a reference to use in closures.
401 401
 		$converter = $this;
402 402
 
403 403
 		// Try each field on the entity.
404
-		foreach ( $fields as $key => $value ) {
404
+		foreach ($fields as $key => $value) {
405 405
 
406 406
 			// Get the predicate.
407
-			$name = $this->relative_to_context( $value['predicate'] );
407
+			$name = $this->relative_to_context($value['predicate']);
408 408
 
409 409
 			// Get the value, the property service will get the right extractor
410 410
 			// for that property.
411
-			$value = $this->property_getter->get( $post->ID, $key, Object_Type_Enum::POST );
411
+			$value = $this->property_getter->get($post->ID, $key, Object_Type_Enum::POST);
412 412
 
413
-			if ( empty( $value ) ) {
413
+			if (empty($value)) {
414 414
 				continue;
415 415
 			}
416 416
 
417 417
 			// Map the value to the property name.
418 418
 			// If we got an array with just one value, we return that one value.
419 419
 			// If we got a Wordlift_Property_Entity_Reference we get the URL.
420
-			$jsonld[ $name ] = self::make_one(
420
+			$jsonld[$name] = self::make_one(
421 421
 				array_map(
422
-					function ( $item ) use ( $converter, &$references, &$references_infos ) {
422
+					function($item) use ($converter, &$references, &$references_infos) {
423 423
 
424
-						if ( $item instanceof Wordlift_Property_Entity_Reference ) {
424
+						if ($item instanceof Wordlift_Property_Entity_Reference) {
425 425
 
426 426
 							$url = $item->get_url();
427 427
 
@@ -430,12 +430,12 @@  discard block
 block discarded – undo
430 430
 							$references[] = $item->to_reference();
431 431
 
432 432
 							// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UndefinedVariable
433
-							$references_infos[] = array( 'reference' => $item );
433
+							$references_infos[] = array('reference' => $item);
434 434
 
435
-							return array( '@id' => $url );
435
+							return array('@id' => $url);
436 436
 						}
437 437
 
438
-						return $converter->relative_to_context( $item );
438
+						return $converter->relative_to_context($item);
439 439
 					},
440 440
 					$value
441 441
 				)
Please login to merge, or discard this patch.
src/includes/class-wordlift-key-validation-service.php 2 patches
Indentation   +182 added lines, -182 removed lines patch added patch discarded remove patch
@@ -21,190 +21,190 @@
 block discarded – undo
21 21
  */
22 22
 class Wordlift_Key_Validation_Service {
23 23
 
24
-	/**
25
-	 * A {@link Wordlift_Log_Service} instance.
26
-	 *
27
-	 * @since  3.14.0
28
-	 * @access private
29
-	 * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
30
-	 */
31
-	private $log;
32
-
33
-	/**
34
-	 * @var Ttl_Cache
35
-	 */
36
-	private $ttl_cache_service;
37
-
38
-	/**
39
-	 * Create a {@link Wordlift_Key_Validation_Service} instance.
40
-	 *
41
-	 * @since 3.14.0
42
-	 */
43
-	public function __construct() {
44
-
45
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Key_Validation_Service' );
46
-
47
-		add_action( 'admin_init', array( $this, 'wl_load_plugin' ) );
48
-		/**
49
-		 * Filter: wl_feature__enable__notices.
50
-		 *
51
-		 * @return bool
52
-		 * @since 3.27.6
53
-		 */
54
-		if ( apply_filters( 'wl_feature__enable__notices', true ) ) {
55
-			add_action( 'admin_notices', array( $this, 'wl_key_update_notice' ) );
56
-		}
57
-
58
-		$this->ttl_cache_service = new Ttl_Cache( 'key-validation-notification' );
59
-
60
-	}
61
-
62
-	/**
63
-	 * Validate the provided key.
64
-	 *
65
-	 * @param string $key WordLift's key to validate.
66
-	 *
67
-	 * @return WP_Error|array The response or WP_Error on failure.
68
-	 * @since 3.9.0
69
-	 */
70
-	public function get_account_info( $key ) {
71
-
72
-		$this->log->debug( 'Validating key...' );
73
-
74
-		$response = Default_Api_Service::get_instance()->get(
75
-			'/accounts/info',
76
-			array(
77
-				'Authorization' => "Key $key",
78
-			)
79
-		);
80
-
81
-		/**
82
-		 * @param $response \Wordlift\Api\Response
83
-		 *
84
-		 * @since 3.38.5
85
-		 * This action is fired when the key is validated.
86
-		 */
87
-		do_action( 'wl_key_validation_response', $response );
88
-
89
-		return $response->get_response();
90
-	}
91
-
92
-	private function key_validation_request( $key ) {
93
-		$response = $this->get_account_info( $key );
94
-
95
-		if ( is_wp_error( $response ) || 2 !== (int) $response['response']['code'] / 100 ) {
96
-			throw new \Exception( __( 'An error occurred, please contact us at [email protected]', 'wordlift' ) );
97
-		}
98
-
99
-		$res_body = json_decode( wp_remote_retrieve_body( $response ), true );
100
-
101
-		$url = $res_body['url'];
102
-
103
-		$enabled_features = array_keys( array_filter( (array) $res_body['features'] ) );
104
-		$plugin_features  = array(
105
-			Entity_Type_Setter::STARTER_PLAN,
106
-			Entity_Type_Setter::PROFESSIONAL_PLAN,
107
-			Entity_Type_Setter::BUSINESS_PLAN,
108
-		);
109
-
110
-		if ( count( array_intersect( $enabled_features, $plugin_features ) ) === 0 ) {
111
-			throw new \Exception( __( 'This key is not valid. Start building your Knowledge Graph by purchasing a WordLift subscription <a href=\'https://wordlift.io/pricing/\'>here</a>.', 'wordlift' ) );
112
-		}
113
-
114
-		// Considering that production URL may be filtered.
115
-		$home_url = get_option( 'home' );
116
-		$site_url = apply_filters( 'wl_production_site_url', untrailingslashit( $home_url ) );
117
-
118
-		if ( ! empty( $url ) && $url !== $site_url ) {
119
-			throw new \Exception( __( 'The key is already used on another site, please contact us at [email protected] to move the key to another site.', 'wordlift' ) );
120
-		}
121
-
122
-		return true;
123
-	}
124
-
125
-	/**
126
-	 * Check if key is valid
127
-	 *
128
-	 * @param $key string
129
-	 *
130
-	 * @return bool
131
-	 */
132
-	public function is_key_valid( $key ) {
133
-		try {
134
-			$this->key_validation_request( $key );
135
-
136
-			return true;
137
-		} catch ( \Exception $e ) {
138
-			return false;
139
-		}
140
-	}
141
-
142
-	/**
143
-	 * This function is hooked to the `wl_validate_key` AJAX call.
144
-	 *
145
-	 * @since 3.9.0
146
-	 */
147
-	public function validate_key() {
148
-
149
-		// Ensure we don't have garbage before us.
150
-		ob_clean();
151
-
152
-		// Check if we have a key.
153
-		if ( ! isset( $_POST['key'] ) ) {  //phpcs:ignore WordPress.Security.NonceVerification.Missing
154
-			wp_send_json_error( 'The key parameter is required.' );
155
-		}
156
-
157
-		$this->ttl_cache_service->delete( 'is_key_valid' );
158
-
159
-		try {
160
-			$this->key_validation_request( sanitize_text_field( wp_unslash( (string) $_POST['key'] ) ) ); //phpcs:ignore WordPress.Security.NonceVerification.Missing
161
-			wp_send_json_success(
162
-				array(
163
-					'valid'   => true,
164
-					'message' => '',
165
-				)
166
-			);
167
-
168
-		} catch ( \Exception $e ) {
169
-			Wordlift_Configuration_Service::get_instance()->set_key( '' );
170
-			wp_send_json_success(
171
-				array(
172
-					'valid'   => false,
173
-					'message' => $e->getMessage(),
174
-					'api_url' => Default_Api_Service::get_instance()->get_base_url(),
175
-				)
176
-			);
177
-		}
178
-	}
179
-
180
-	/**
181
-	 * This function is hooked `admin_init` to check _wl_blog_url.
182
-	 */
183
-	public function wl_load_plugin() {
184
-
185
-		$wl_blog_url = get_option( '_wl_blog_url' );
186
-		$home_url    = get_option( 'home' );
187
-
188
-		if ( ! $wl_blog_url ) {
189
-			update_option( '_wl_blog_url', $home_url, true );
190
-		} elseif ( $wl_blog_url !== $home_url ) {
191
-			update_option( '_wl_blog_url', $home_url, true );
192
-			Wordlift_Configuration_Service::get_instance()->set_key( '' );
193
-			set_transient( 'wl-key-error-msg', __( "Your web site URL has changed. To avoid data corruption, WordLift's key has been removed. Please provide a new key in WordLift Settings. If you believe this to be an error, please contact us at [email protected]", 'wordlift' ), 10 );
194
-		}
195
-
196
-	}
197
-
198
-	/**
199
-	 * This function is hooked to the `admin_notices` to show admin notification.
200
-	 */
201
-	public function wl_key_update_notice() {
202
-		if ( get_transient( 'wl-key-error-msg' ) ) {
203
-			?>
24
+    /**
25
+     * A {@link Wordlift_Log_Service} instance.
26
+     *
27
+     * @since  3.14.0
28
+     * @access private
29
+     * @var \Wordlift_Log_Service $log A {@link Wordlift_Log_Service} instance.
30
+     */
31
+    private $log;
32
+
33
+    /**
34
+     * @var Ttl_Cache
35
+     */
36
+    private $ttl_cache_service;
37
+
38
+    /**
39
+     * Create a {@link Wordlift_Key_Validation_Service} instance.
40
+     *
41
+     * @since 3.14.0
42
+     */
43
+    public function __construct() {
44
+
45
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Key_Validation_Service' );
46
+
47
+        add_action( 'admin_init', array( $this, 'wl_load_plugin' ) );
48
+        /**
49
+         * Filter: wl_feature__enable__notices.
50
+         *
51
+         * @return bool
52
+         * @since 3.27.6
53
+         */
54
+        if ( apply_filters( 'wl_feature__enable__notices', true ) ) {
55
+            add_action( 'admin_notices', array( $this, 'wl_key_update_notice' ) );
56
+        }
57
+
58
+        $this->ttl_cache_service = new Ttl_Cache( 'key-validation-notification' );
59
+
60
+    }
61
+
62
+    /**
63
+     * Validate the provided key.
64
+     *
65
+     * @param string $key WordLift's key to validate.
66
+     *
67
+     * @return WP_Error|array The response or WP_Error on failure.
68
+     * @since 3.9.0
69
+     */
70
+    public function get_account_info( $key ) {
71
+
72
+        $this->log->debug( 'Validating key...' );
73
+
74
+        $response = Default_Api_Service::get_instance()->get(
75
+            '/accounts/info',
76
+            array(
77
+                'Authorization' => "Key $key",
78
+            )
79
+        );
80
+
81
+        /**
82
+         * @param $response \Wordlift\Api\Response
83
+         *
84
+         * @since 3.38.5
85
+         * This action is fired when the key is validated.
86
+         */
87
+        do_action( 'wl_key_validation_response', $response );
88
+
89
+        return $response->get_response();
90
+    }
91
+
92
+    private function key_validation_request( $key ) {
93
+        $response = $this->get_account_info( $key );
94
+
95
+        if ( is_wp_error( $response ) || 2 !== (int) $response['response']['code'] / 100 ) {
96
+            throw new \Exception( __( 'An error occurred, please contact us at [email protected]', 'wordlift' ) );
97
+        }
98
+
99
+        $res_body = json_decode( wp_remote_retrieve_body( $response ), true );
100
+
101
+        $url = $res_body['url'];
102
+
103
+        $enabled_features = array_keys( array_filter( (array) $res_body['features'] ) );
104
+        $plugin_features  = array(
105
+            Entity_Type_Setter::STARTER_PLAN,
106
+            Entity_Type_Setter::PROFESSIONAL_PLAN,
107
+            Entity_Type_Setter::BUSINESS_PLAN,
108
+        );
109
+
110
+        if ( count( array_intersect( $enabled_features, $plugin_features ) ) === 0 ) {
111
+            throw new \Exception( __( 'This key is not valid. Start building your Knowledge Graph by purchasing a WordLift subscription <a href=\'https://wordlift.io/pricing/\'>here</a>.', 'wordlift' ) );
112
+        }
113
+
114
+        // Considering that production URL may be filtered.
115
+        $home_url = get_option( 'home' );
116
+        $site_url = apply_filters( 'wl_production_site_url', untrailingslashit( $home_url ) );
117
+
118
+        if ( ! empty( $url ) && $url !== $site_url ) {
119
+            throw new \Exception( __( 'The key is already used on another site, please contact us at [email protected] to move the key to another site.', 'wordlift' ) );
120
+        }
121
+
122
+        return true;
123
+    }
124
+
125
+    /**
126
+     * Check if key is valid
127
+     *
128
+     * @param $key string
129
+     *
130
+     * @return bool
131
+     */
132
+    public function is_key_valid( $key ) {
133
+        try {
134
+            $this->key_validation_request( $key );
135
+
136
+            return true;
137
+        } catch ( \Exception $e ) {
138
+            return false;
139
+        }
140
+    }
141
+
142
+    /**
143
+     * This function is hooked to the `wl_validate_key` AJAX call.
144
+     *
145
+     * @since 3.9.0
146
+     */
147
+    public function validate_key() {
148
+
149
+        // Ensure we don't have garbage before us.
150
+        ob_clean();
151
+
152
+        // Check if we have a key.
153
+        if ( ! isset( $_POST['key'] ) ) {  //phpcs:ignore WordPress.Security.NonceVerification.Missing
154
+            wp_send_json_error( 'The key parameter is required.' );
155
+        }
156
+
157
+        $this->ttl_cache_service->delete( 'is_key_valid' );
158
+
159
+        try {
160
+            $this->key_validation_request( sanitize_text_field( wp_unslash( (string) $_POST['key'] ) ) ); //phpcs:ignore WordPress.Security.NonceVerification.Missing
161
+            wp_send_json_success(
162
+                array(
163
+                    'valid'   => true,
164
+                    'message' => '',
165
+                )
166
+            );
167
+
168
+        } catch ( \Exception $e ) {
169
+            Wordlift_Configuration_Service::get_instance()->set_key( '' );
170
+            wp_send_json_success(
171
+                array(
172
+                    'valid'   => false,
173
+                    'message' => $e->getMessage(),
174
+                    'api_url' => Default_Api_Service::get_instance()->get_base_url(),
175
+                )
176
+            );
177
+        }
178
+    }
179
+
180
+    /**
181
+     * This function is hooked `admin_init` to check _wl_blog_url.
182
+     */
183
+    public function wl_load_plugin() {
184
+
185
+        $wl_blog_url = get_option( '_wl_blog_url' );
186
+        $home_url    = get_option( 'home' );
187
+
188
+        if ( ! $wl_blog_url ) {
189
+            update_option( '_wl_blog_url', $home_url, true );
190
+        } elseif ( $wl_blog_url !== $home_url ) {
191
+            update_option( '_wl_blog_url', $home_url, true );
192
+            Wordlift_Configuration_Service::get_instance()->set_key( '' );
193
+            set_transient( 'wl-key-error-msg', __( "Your web site URL has changed. To avoid data corruption, WordLift's key has been removed. Please provide a new key in WordLift Settings. If you believe this to be an error, please contact us at [email protected]", 'wordlift' ), 10 );
194
+        }
195
+
196
+    }
197
+
198
+    /**
199
+     * This function is hooked to the `admin_notices` to show admin notification.
200
+     */
201
+    public function wl_key_update_notice() {
202
+        if ( get_transient( 'wl-key-error-msg' ) ) {
203
+            ?>
204 204
           <div class="updated notice is-dismissible error">
205 205
             <p><?php esc_html( get_transient( 'wl-key-error-msg' ) ); ?></p>
206 206
           </div>
207 207
 			<?php
208
-		}
209
-	}
208
+        }
209
+    }
210 210
 }
Please login to merge, or discard this patch.
Spacing   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -42,20 +42,20 @@  discard block
 block discarded – undo
42 42
 	 */
43 43
 	public function __construct() {
44 44
 
45
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Key_Validation_Service' );
45
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Key_Validation_Service');
46 46
 
47
-		add_action( 'admin_init', array( $this, 'wl_load_plugin' ) );
47
+		add_action('admin_init', array($this, 'wl_load_plugin'));
48 48
 		/**
49 49
 		 * Filter: wl_feature__enable__notices.
50 50
 		 *
51 51
 		 * @return bool
52 52
 		 * @since 3.27.6
53 53
 		 */
54
-		if ( apply_filters( 'wl_feature__enable__notices', true ) ) {
55
-			add_action( 'admin_notices', array( $this, 'wl_key_update_notice' ) );
54
+		if (apply_filters('wl_feature__enable__notices', true)) {
55
+			add_action('admin_notices', array($this, 'wl_key_update_notice'));
56 56
 		}
57 57
 
58
-		$this->ttl_cache_service = new Ttl_Cache( 'key-validation-notification' );
58
+		$this->ttl_cache_service = new Ttl_Cache('key-validation-notification');
59 59
 
60 60
 	}
61 61
 
@@ -67,9 +67,9 @@  discard block
 block discarded – undo
67 67
 	 * @return WP_Error|array The response or WP_Error on failure.
68 68
 	 * @since 3.9.0
69 69
 	 */
70
-	public function get_account_info( $key ) {
70
+	public function get_account_info($key) {
71 71
 
72
-		$this->log->debug( 'Validating key...' );
72
+		$this->log->debug('Validating key...');
73 73
 
74 74
 		$response = Default_Api_Service::get_instance()->get(
75 75
 			'/accounts/info',
@@ -84,39 +84,39 @@  discard block
 block discarded – undo
84 84
 		 * @since 3.38.5
85 85
 		 * This action is fired when the key is validated.
86 86
 		 */
87
-		do_action( 'wl_key_validation_response', $response );
87
+		do_action('wl_key_validation_response', $response);
88 88
 
89 89
 		return $response->get_response();
90 90
 	}
91 91
 
92
-	private function key_validation_request( $key ) {
93
-		$response = $this->get_account_info( $key );
92
+	private function key_validation_request($key) {
93
+		$response = $this->get_account_info($key);
94 94
 
95
-		if ( is_wp_error( $response ) || 2 !== (int) $response['response']['code'] / 100 ) {
96
-			throw new \Exception( __( 'An error occurred, please contact us at [email protected]', 'wordlift' ) );
95
+		if (is_wp_error($response) || 2 !== (int) $response['response']['code'] / 100) {
96
+			throw new \Exception(__('An error occurred, please contact us at [email protected]', 'wordlift'));
97 97
 		}
98 98
 
99
-		$res_body = json_decode( wp_remote_retrieve_body( $response ), true );
99
+		$res_body = json_decode(wp_remote_retrieve_body($response), true);
100 100
 
101 101
 		$url = $res_body['url'];
102 102
 
103
-		$enabled_features = array_keys( array_filter( (array) $res_body['features'] ) );
103
+		$enabled_features = array_keys(array_filter((array) $res_body['features']));
104 104
 		$plugin_features  = array(
105 105
 			Entity_Type_Setter::STARTER_PLAN,
106 106
 			Entity_Type_Setter::PROFESSIONAL_PLAN,
107 107
 			Entity_Type_Setter::BUSINESS_PLAN,
108 108
 		);
109 109
 
110
-		if ( count( array_intersect( $enabled_features, $plugin_features ) ) === 0 ) {
111
-			throw new \Exception( __( 'This key is not valid. Start building your Knowledge Graph by purchasing a WordLift subscription <a href=\'https://wordlift.io/pricing/\'>here</a>.', 'wordlift' ) );
110
+		if (count(array_intersect($enabled_features, $plugin_features)) === 0) {
111
+			throw new \Exception(__('This key is not valid. Start building your Knowledge Graph by purchasing a WordLift subscription <a href=\'https://wordlift.io/pricing/\'>here</a>.', 'wordlift'));
112 112
 		}
113 113
 
114 114
 		// Considering that production URL may be filtered.
115
-		$home_url = get_option( 'home' );
116
-		$site_url = apply_filters( 'wl_production_site_url', untrailingslashit( $home_url ) );
115
+		$home_url = get_option('home');
116
+		$site_url = apply_filters('wl_production_site_url', untrailingslashit($home_url));
117 117
 
118
-		if ( ! empty( $url ) && $url !== $site_url ) {
119
-			throw new \Exception( __( 'The key is already used on another site, please contact us at [email protected] to move the key to another site.', 'wordlift' ) );
118
+		if ( ! empty($url) && $url !== $site_url) {
119
+			throw new \Exception(__('The key is already used on another site, please contact us at [email protected] to move the key to another site.', 'wordlift'));
120 120
 		}
121 121
 
122 122
 		return true;
@@ -129,12 +129,12 @@  discard block
 block discarded – undo
129 129
 	 *
130 130
 	 * @return bool
131 131
 	 */
132
-	public function is_key_valid( $key ) {
132
+	public function is_key_valid($key) {
133 133
 		try {
134
-			$this->key_validation_request( $key );
134
+			$this->key_validation_request($key);
135 135
 
136 136
 			return true;
137
-		} catch ( \Exception $e ) {
137
+		} catch (\Exception $e) {
138 138
 			return false;
139 139
 		}
140 140
 	}
@@ -150,14 +150,14 @@  discard block
 block discarded – undo
150 150
 		ob_clean();
151 151
 
152 152
 		// Check if we have a key.
153
-		if ( ! isset( $_POST['key'] ) ) {  //phpcs:ignore WordPress.Security.NonceVerification.Missing
154
-			wp_send_json_error( 'The key parameter is required.' );
153
+		if ( ! isset($_POST['key'])) {  //phpcs:ignore WordPress.Security.NonceVerification.Missing
154
+			wp_send_json_error('The key parameter is required.');
155 155
 		}
156 156
 
157
-		$this->ttl_cache_service->delete( 'is_key_valid' );
157
+		$this->ttl_cache_service->delete('is_key_valid');
158 158
 
159 159
 		try {
160
-			$this->key_validation_request( sanitize_text_field( wp_unslash( (string) $_POST['key'] ) ) ); //phpcs:ignore WordPress.Security.NonceVerification.Missing
160
+			$this->key_validation_request(sanitize_text_field(wp_unslash((string) $_POST['key']))); //phpcs:ignore WordPress.Security.NonceVerification.Missing
161 161
 			wp_send_json_success(
162 162
 				array(
163 163
 					'valid'   => true,
@@ -165,8 +165,8 @@  discard block
 block discarded – undo
165 165
 				)
166 166
 			);
167 167
 
168
-		} catch ( \Exception $e ) {
169
-			Wordlift_Configuration_Service::get_instance()->set_key( '' );
168
+		} catch (\Exception $e) {
169
+			Wordlift_Configuration_Service::get_instance()->set_key('');
170 170
 			wp_send_json_success(
171 171
 				array(
172 172
 					'valid'   => false,
@@ -182,15 +182,15 @@  discard block
 block discarded – undo
182 182
 	 */
183 183
 	public function wl_load_plugin() {
184 184
 
185
-		$wl_blog_url = get_option( '_wl_blog_url' );
186
-		$home_url    = get_option( 'home' );
185
+		$wl_blog_url = get_option('_wl_blog_url');
186
+		$home_url    = get_option('home');
187 187
 
188
-		if ( ! $wl_blog_url ) {
189
-			update_option( '_wl_blog_url', $home_url, true );
190
-		} elseif ( $wl_blog_url !== $home_url ) {
191
-			update_option( '_wl_blog_url', $home_url, true );
192
-			Wordlift_Configuration_Service::get_instance()->set_key( '' );
193
-			set_transient( 'wl-key-error-msg', __( "Your web site URL has changed. To avoid data corruption, WordLift's key has been removed. Please provide a new key in WordLift Settings. If you believe this to be an error, please contact us at [email protected]", 'wordlift' ), 10 );
188
+		if ( ! $wl_blog_url) {
189
+			update_option('_wl_blog_url', $home_url, true);
190
+		} elseif ($wl_blog_url !== $home_url) {
191
+			update_option('_wl_blog_url', $home_url, true);
192
+			Wordlift_Configuration_Service::get_instance()->set_key('');
193
+			set_transient('wl-key-error-msg', __("Your web site URL has changed. To avoid data corruption, WordLift's key has been removed. Please provide a new key in WordLift Settings. If you believe this to be an error, please contact us at [email protected]", 'wordlift'), 10);
194 194
 		}
195 195
 
196 196
 	}
@@ -199,10 +199,10 @@  discard block
 block discarded – undo
199 199
 	 * This function is hooked to the `admin_notices` to show admin notification.
200 200
 	 */
201 201
 	public function wl_key_update_notice() {
202
-		if ( get_transient( 'wl-key-error-msg' ) ) {
202
+		if (get_transient('wl-key-error-msg')) {
203 203
 			?>
204 204
           <div class="updated notice is-dismissible error">
205
-            <p><?php esc_html( get_transient( 'wl-key-error-msg' ) ); ?></p>
205
+            <p><?php esc_html(get_transient('wl-key-error-msg')); ?></p>
206 206
           </div>
207 207
 			<?php
208 208
 		}
Please login to merge, or discard this patch.
src/includes/cache/class-wordlift-cached-post-converter.php 2 patches
Indentation   +350 added lines, -350 removed lines patch added patch discarded remove patch
@@ -21,355 +21,355 @@
 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
-		$modified_date_time = get_post_datetime( $post_id, 'modified', 'gmt' );
214
-		$contents           = $this->cache->get( $post_id, $modified_date_time ? $modified_date_time->getTimestamp() : 0 );
215
-
216
-		// Bail out if we don't have cached contents or the cached contents are
217
-		// invalid.
218
-		if ( null === $contents || ! isset( $contents['jsonld'] ) || ! isset( $contents['references'] ) ) {
219
-			$this->log->debug( "Cached contents for post $post_id not found." );
220
-
221
-			return false;
222
-		}
223
-
224
-		// Remap the cache.
225
-		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
226
-		$references = $this->reference_processor->deserialize_references( $contents['references'] );
227
-
228
-		return $contents['jsonld'];
229
-	}
230
-
231
-	/**
232
-	 * Set the cache with the provided results.
233
-	 *
234
-	 * The function will prepare the provided results and will ask the {@link Ttl_Cache} to cache them.
235
-	 *
236
-	 * @param int $post_id The {@link WP_Post} id.
237
-	 * @param array $references An array of references.
238
-	 * @param array $jsonld A JSON-LD structure.
239
-	 *
240
-	 * @since 3.16.0
241
-	 */
242
-	private function set_cache( $post_id, $references, $jsonld ) {
243
-
244
-		$this->log->trace( "Caching result for post $post_id..." );
245
-
246
-		$this->cache->put(
247
-			$post_id,
248
-			array(
249
-				'references' => $this->reference_processor->serialize_references( $references ),
250
-				'jsonld'     => $jsonld,
251
-			)
252
-		);
253
-
254
-	}
255
-
256
-	/**
257
-	 * Hook to 'save_post', will invalidate the cache for that post.
258
-	 *
259
-	 * @param int $post_id The {@link WP_Post} id.
260
-	 *
261
-	 * @since 3.16.0
262
-	 */
263
-	public function save_post( $post_id ) {
264
-
265
-		$this->log->trace( "Post $post_id saved, invalidating cache..." );
266
-
267
-		$this->cache->delete( $post_id );
268
-
269
-		$this->flush_cache_if_publisher( $post_id );
270
-
271
-	}
272
-
273
-	/**
274
-	 * Hook to meta changed for a {@link WP_Post}, will cause the cause to
275
-	 * invalidate.
276
-	 *
277
-	 * @param int $id The {@link WP_Post} meta id.
278
-	 * @param int $post_id The {@link WP_Post} id.
279
-	 * @param string $meta_key The meta key.
280
-	 *
281
-	 * @since 3.16.0
282
-	 */
283
-	public function changed_post_meta( $id, $post_id, $meta_key ) {
284
-
285
-		if ( in_array( $meta_key, self::$ignored_meta_keys, true ) ) {
286
-			$this->log->trace( "Post $post_id meta $meta_key ignored." );
287
-
288
-			return;
289
-		}
290
-
291
-		$this->log->trace( "Post $post_id meta $meta_key changed, invalidating cache..." );
292
-
293
-		// Delete the single cache file.
294
-		$this->cache->delete( $post_id );
295
-
296
-		// Flush the cache if it's the publisher.
297
-		$this->flush_cache_if_publisher( $post_id );
298
-
299
-	}
300
-
301
-	/**
302
-	 * Hook to WordLift's options changes, will flush the cache.
303
-	 *
304
-	 * @since 3.16.0
305
-	 */
306
-	public function update_option_wl_general_settings() {
307
-		$this->log->trace( 'WordLift options changed, flushing cache...' );
308
-
309
-		$this->cache->flush();
310
-	}
311
-
312
-	/**
313
-	 * Hook when permalinks are changed, will flush the cache.
314
-	 *
315
-	 * @since 3.17.0
316
-	 */
317
-	public function permalinks_structure_changed() {
318
-		$this->log->trace( 'Permalinks structure changed, flushing cache...' );
319
-
320
-		$this->cache->flush();
321
-	}
322
-
323
-	/**
324
-	 * Hook to WordLift's post/entity relation changes, will invalidate the cache.
325
-	 *
326
-	 * @param int $post_id The {@link WP_Post} id.
327
-	 *
328
-	 * @since 3.16.0
329
-	 */
330
-	public function relation_changed( $post_id ) {
331
-		$this->log->trace( "Post $post_id relations changed, invalidating cache..." );
332
-
333
-		$this->cache->delete( $post_id );
334
-	}
335
-
336
-	/**
337
-	 * When in Ajax, prints an http header with the information whether the
338
-	 * response is cached or not.
339
-	 *
340
-	 * @param int $post_id The {@link WP_Post} id.
341
-	 * @param bool $cache Whether the response fragment is cached.
342
-	 *
343
-	 * @since 3.16.0
344
-	 */
345
-	private function add_http_header( $post_id, $cache ) {
346
-
347
-		if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX || headers_sent() ) {
348
-			return;
349
-		}
350
-
351
-		header( "X-WordLift-JsonLd-Cache-$post_id: " . ( $cache ? 'HIT' : 'MISS' ) );
352
-
353
-	}
354
-
355
-	/**
356
-	 * Call the `flush` operation on the {@link Ttl_Cache} if
357
-	 * the publisher has changed.
358
-	 *
359
-	 * @param int $post_id The changed {@link WP_Post}'s id.
360
-	 *
361
-	 * @since 3.16.0
362
-	 */
363
-	private function flush_cache_if_publisher( $post_id ) {
364
-
365
-		// Bail out if it's not the publisher.
366
-		if ( Wordlift_Configuration_Service::get_instance()->get_publisher_id() !== $post_id ) {
367
-			return;
368
-		}
369
-
370
-		// Flush the cache, since the publisher has changed.
371
-		$this->cache->flush();
372
-
373
-	}
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
+        $modified_date_time = get_post_datetime( $post_id, 'modified', 'gmt' );
214
+        $contents           = $this->cache->get( $post_id, $modified_date_time ? $modified_date_time->getTimestamp() : 0 );
215
+
216
+        // Bail out if we don't have cached contents or the cached contents are
217
+        // invalid.
218
+        if ( null === $contents || ! isset( $contents['jsonld'] ) || ! isset( $contents['references'] ) ) {
219
+            $this->log->debug( "Cached contents for post $post_id not found." );
220
+
221
+            return false;
222
+        }
223
+
224
+        // Remap the cache.
225
+        // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
226
+        $references = $this->reference_processor->deserialize_references( $contents['references'] );
227
+
228
+        return $contents['jsonld'];
229
+    }
230
+
231
+    /**
232
+     * Set the cache with the provided results.
233
+     *
234
+     * The function will prepare the provided results and will ask the {@link Ttl_Cache} to cache them.
235
+     *
236
+     * @param int $post_id The {@link WP_Post} id.
237
+     * @param array $references An array of references.
238
+     * @param array $jsonld A JSON-LD structure.
239
+     *
240
+     * @since 3.16.0
241
+     */
242
+    private function set_cache( $post_id, $references, $jsonld ) {
243
+
244
+        $this->log->trace( "Caching result for post $post_id..." );
245
+
246
+        $this->cache->put(
247
+            $post_id,
248
+            array(
249
+                'references' => $this->reference_processor->serialize_references( $references ),
250
+                'jsonld'     => $jsonld,
251
+            )
252
+        );
253
+
254
+    }
255
+
256
+    /**
257
+     * Hook to 'save_post', will invalidate the cache for that post.
258
+     *
259
+     * @param int $post_id The {@link WP_Post} id.
260
+     *
261
+     * @since 3.16.0
262
+     */
263
+    public function save_post( $post_id ) {
264
+
265
+        $this->log->trace( "Post $post_id saved, invalidating cache..." );
266
+
267
+        $this->cache->delete( $post_id );
268
+
269
+        $this->flush_cache_if_publisher( $post_id );
270
+
271
+    }
272
+
273
+    /**
274
+     * Hook to meta changed for a {@link WP_Post}, will cause the cause to
275
+     * invalidate.
276
+     *
277
+     * @param int $id The {@link WP_Post} meta id.
278
+     * @param int $post_id The {@link WP_Post} id.
279
+     * @param string $meta_key The meta key.
280
+     *
281
+     * @since 3.16.0
282
+     */
283
+    public function changed_post_meta( $id, $post_id, $meta_key ) {
284
+
285
+        if ( in_array( $meta_key, self::$ignored_meta_keys, true ) ) {
286
+            $this->log->trace( "Post $post_id meta $meta_key ignored." );
287
+
288
+            return;
289
+        }
290
+
291
+        $this->log->trace( "Post $post_id meta $meta_key changed, invalidating cache..." );
292
+
293
+        // Delete the single cache file.
294
+        $this->cache->delete( $post_id );
295
+
296
+        // Flush the cache if it's the publisher.
297
+        $this->flush_cache_if_publisher( $post_id );
298
+
299
+    }
300
+
301
+    /**
302
+     * Hook to WordLift's options changes, will flush the cache.
303
+     *
304
+     * @since 3.16.0
305
+     */
306
+    public function update_option_wl_general_settings() {
307
+        $this->log->trace( 'WordLift options changed, flushing cache...' );
308
+
309
+        $this->cache->flush();
310
+    }
311
+
312
+    /**
313
+     * Hook when permalinks are changed, will flush the cache.
314
+     *
315
+     * @since 3.17.0
316
+     */
317
+    public function permalinks_structure_changed() {
318
+        $this->log->trace( 'Permalinks structure changed, flushing cache...' );
319
+
320
+        $this->cache->flush();
321
+    }
322
+
323
+    /**
324
+     * Hook to WordLift's post/entity relation changes, will invalidate the cache.
325
+     *
326
+     * @param int $post_id The {@link WP_Post} id.
327
+     *
328
+     * @since 3.16.0
329
+     */
330
+    public function relation_changed( $post_id ) {
331
+        $this->log->trace( "Post $post_id relations changed, invalidating cache..." );
332
+
333
+        $this->cache->delete( $post_id );
334
+    }
335
+
336
+    /**
337
+     * When in Ajax, prints an http header with the information whether the
338
+     * response is cached or not.
339
+     *
340
+     * @param int $post_id The {@link WP_Post} id.
341
+     * @param bool $cache Whether the response fragment is cached.
342
+     *
343
+     * @since 3.16.0
344
+     */
345
+    private function add_http_header( $post_id, $cache ) {
346
+
347
+        if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX || headers_sent() ) {
348
+            return;
349
+        }
350
+
351
+        header( "X-WordLift-JsonLd-Cache-$post_id: " . ( $cache ? 'HIT' : 'MISS' ) );
352
+
353
+    }
354
+
355
+    /**
356
+     * Call the `flush` operation on the {@link Ttl_Cache} if
357
+     * the publisher has changed.
358
+     *
359
+     * @param int $post_id The changed {@link WP_Post}'s id.
360
+     *
361
+     * @since 3.16.0
362
+     */
363
+    private function flush_cache_if_publisher( $post_id ) {
364
+
365
+        // Bail out if it's not the publisher.
366
+        if ( Wordlift_Configuration_Service::get_instance()->get_publisher_id() !== $post_id ) {
367
+            return;
368
+        }
369
+
370
+        // Flush the cache, since the publisher has changed.
371
+        $this->cache->flush();
372
+
373
+    }
374 374
 
375 375
 }
Please login to merge, or discard this patch.
Spacing   +44 added lines, -44 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,28 +202,28 @@  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
-		$modified_date_time = get_post_datetime( $post_id, 'modified', 'gmt' );
214
-		$contents           = $this->cache->get( $post_id, $modified_date_time ? $modified_date_time->getTimestamp() : 0 );
213
+		$modified_date_time = get_post_datetime($post_id, 'modified', 'gmt');
214
+		$contents           = $this->cache->get($post_id, $modified_date_time ? $modified_date_time->getTimestamp() : 0);
215 215
 
216 216
 		// Bail out if we don't have cached contents or the cached contents are
217 217
 		// invalid.
218
-		if ( null === $contents || ! isset( $contents['jsonld'] ) || ! isset( $contents['references'] ) ) {
219
-			$this->log->debug( "Cached contents for post $post_id not found." );
218
+		if (null === $contents || ! isset($contents['jsonld']) || ! isset($contents['references'])) {
219
+			$this->log->debug("Cached contents for post $post_id not found.");
220 220
 
221 221
 			return false;
222 222
 		}
223 223
 
224 224
 		// Remap the cache.
225 225
 		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
226
-		$references = $this->reference_processor->deserialize_references( $contents['references'] );
226
+		$references = $this->reference_processor->deserialize_references($contents['references']);
227 227
 
228 228
 		return $contents['jsonld'];
229 229
 	}
@@ -239,14 +239,14 @@  discard block
 block discarded – undo
239 239
 	 *
240 240
 	 * @since 3.16.0
241 241
 	 */
242
-	private function set_cache( $post_id, $references, $jsonld ) {
242
+	private function set_cache($post_id, $references, $jsonld) {
243 243
 
244
-		$this->log->trace( "Caching result for post $post_id..." );
244
+		$this->log->trace("Caching result for post $post_id...");
245 245
 
246 246
 		$this->cache->put(
247 247
 			$post_id,
248 248
 			array(
249
-				'references' => $this->reference_processor->serialize_references( $references ),
249
+				'references' => $this->reference_processor->serialize_references($references),
250 250
 				'jsonld'     => $jsonld,
251 251
 			)
252 252
 		);
@@ -260,13 +260,13 @@  discard block
 block discarded – undo
260 260
 	 *
261 261
 	 * @since 3.16.0
262 262
 	 */
263
-	public function save_post( $post_id ) {
263
+	public function save_post($post_id) {
264 264
 
265
-		$this->log->trace( "Post $post_id saved, invalidating cache..." );
265
+		$this->log->trace("Post $post_id saved, invalidating cache...");
266 266
 
267
-		$this->cache->delete( $post_id );
267
+		$this->cache->delete($post_id);
268 268
 
269
-		$this->flush_cache_if_publisher( $post_id );
269
+		$this->flush_cache_if_publisher($post_id);
270 270
 
271 271
 	}
272 272
 
@@ -280,21 +280,21 @@  discard block
 block discarded – undo
280 280
 	 *
281 281
 	 * @since 3.16.0
282 282
 	 */
283
-	public function changed_post_meta( $id, $post_id, $meta_key ) {
283
+	public function changed_post_meta($id, $post_id, $meta_key) {
284 284
 
285
-		if ( in_array( $meta_key, self::$ignored_meta_keys, true ) ) {
286
-			$this->log->trace( "Post $post_id meta $meta_key ignored." );
285
+		if (in_array($meta_key, self::$ignored_meta_keys, true)) {
286
+			$this->log->trace("Post $post_id meta $meta_key ignored.");
287 287
 
288 288
 			return;
289 289
 		}
290 290
 
291
-		$this->log->trace( "Post $post_id meta $meta_key changed, invalidating cache..." );
291
+		$this->log->trace("Post $post_id meta $meta_key changed, invalidating cache...");
292 292
 
293 293
 		// Delete the single cache file.
294
-		$this->cache->delete( $post_id );
294
+		$this->cache->delete($post_id);
295 295
 
296 296
 		// Flush the cache if it's the publisher.
297
-		$this->flush_cache_if_publisher( $post_id );
297
+		$this->flush_cache_if_publisher($post_id);
298 298
 
299 299
 	}
300 300
 
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
 	 * @since 3.16.0
305 305
 	 */
306 306
 	public function update_option_wl_general_settings() {
307
-		$this->log->trace( 'WordLift options changed, flushing cache...' );
307
+		$this->log->trace('WordLift options changed, flushing cache...');
308 308
 
309 309
 		$this->cache->flush();
310 310
 	}
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
 	 * @since 3.17.0
316 316
 	 */
317 317
 	public function permalinks_structure_changed() {
318
-		$this->log->trace( 'Permalinks structure changed, flushing cache...' );
318
+		$this->log->trace('Permalinks structure changed, flushing cache...');
319 319
 
320 320
 		$this->cache->flush();
321 321
 	}
@@ -327,10 +327,10 @@  discard block
 block discarded – undo
327 327
 	 *
328 328
 	 * @since 3.16.0
329 329
 	 */
330
-	public function relation_changed( $post_id ) {
331
-		$this->log->trace( "Post $post_id relations changed, invalidating cache..." );
330
+	public function relation_changed($post_id) {
331
+		$this->log->trace("Post $post_id relations changed, invalidating cache...");
332 332
 
333
-		$this->cache->delete( $post_id );
333
+		$this->cache->delete($post_id);
334 334
 	}
335 335
 
336 336
 	/**
@@ -342,13 +342,13 @@  discard block
 block discarded – undo
342 342
 	 *
343 343
 	 * @since 3.16.0
344 344
 	 */
345
-	private function add_http_header( $post_id, $cache ) {
345
+	private function add_http_header($post_id, $cache) {
346 346
 
347
-		if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX || headers_sent() ) {
347
+		if ( ! defined('DOING_AJAX') || ! DOING_AJAX || headers_sent()) {
348 348
 			return;
349 349
 		}
350 350
 
351
-		header( "X-WordLift-JsonLd-Cache-$post_id: " . ( $cache ? 'HIT' : 'MISS' ) );
351
+		header("X-WordLift-JsonLd-Cache-$post_id: ".($cache ? 'HIT' : 'MISS'));
352 352
 
353 353
 	}
354 354
 
@@ -360,10 +360,10 @@  discard block
 block discarded – undo
360 360
 	 *
361 361
 	 * @since 3.16.0
362 362
 	 */
363
-	private function flush_cache_if_publisher( $post_id ) {
363
+	private function flush_cache_if_publisher($post_id) {
364 364
 
365 365
 		// Bail out if it's not the publisher.
366
-		if ( Wordlift_Configuration_Service::get_instance()->get_publisher_id() !== $post_id ) {
366
+		if (Wordlift_Configuration_Service::get_instance()->get_publisher_id() !== $post_id) {
367 367
 			return;
368 368
 		}
369 369
 
Please login to merge, or discard this patch.
src/wordlift/configuration/class-config.php 2 patches
Indentation   +191 added lines, -191 removed lines patch added patch discarded remove patch
@@ -3,197 +3,197 @@
 block discarded – undo
3 3
 namespace Wordlift\Configuration;
4 4
 
5 5
 class Config {
6
-	/**
7
-	 * @var \Wordlift_Admin_Setup
8
-	 */
9
-	private $admin_setup;
10
-	/**
11
-	 * @var \Wordlift_Key_Validation_Service
12
-	 */
13
-	private $key_validation_service;
14
-
15
-	/**
16
-	 * Config constructor.
17
-	 *
18
-	 * @param $admin_setup \Wordlift_Admin_Setup
19
-	 * @param $key_validation_service \Wordlift_Key_Validation_Service
20
-	 */
21
-	public function __construct( $admin_setup, $key_validation_service ) {
22
-
23
-		$this->admin_setup            = $admin_setup;
24
-		$this->key_validation_service = $key_validation_service;
25
-		add_action( 'wp_ajax_nopriv_wl_config_plugin', array( $this, 'config' ) );
26
-		add_action( 'wp_ajax_wl_config_plugin', array( $this, 'config' ) );
27
-
28
-	}
29
-
30
-	/**
31
-	 * Check if the key is valid and also not bound to any domain.
32
-	 *
33
-	 * @param $key string
34
-	 *
35
-	 * @return bool
36
-	 */
37
-	private function is_key_valid_and_not_bound_to_any_domain( $key ) {
38
-		$account_info = $this->key_validation_service->get_account_info( $key );
39
-
40
-		/**
41
-		 * we need to check if the key is not associated with any account
42
-		 * before setting it, we should check if the url is null.
43
-		 */
44
-		if ( is_wp_error( $account_info )
45
-		     || wp_remote_retrieve_response_code( $account_info ) !== 200 ) {
46
-			return false;
47
-		}
48
-
49
-		$account_info_json = $account_info['body'];
50
-
51
-		$account_info_data = json_decode( $account_info_json, true );
52
-
53
-		if ( ! $account_info_data ) {
54
-			// Invalid json returned by api.
55
-			return false;
56
-		}
57
-
58
-		$site_url = apply_filters( 'wl_production_site_url', untrailingslashit( get_option( 'home' ) ) );
59
-
60
-		if ( null === $account_info_data['url'] ) {
61
-			return true;
62
-		}
63
-
64
-		// Check if the key belongs to same site.
65
-		if ( untrailingslashit( $account_info_data['url'] ) !== $site_url ) {
66
-			// key already associated with another account.
67
-			return false;
68
-		}
69
-
70
-		// Return true if the key domain and site domain are the same.
71
-		return true;
72
-	}
73
-
74
-	public function config() {
75
-
76
-		// Perform validation check for all the parameters.
77
-		$required_fields = array(
78
-			'diagnostic',
79
-			'vocabulary',
80
-			// Don't ask for language from webapp.
81
-			// 'language',
82
-			'country',
83
-			'publisherName',
84
-			'publisher',
85
-			'license',
86
-		);
87
-
88
-		header( 'Access-Control-Allow-Origin: *' );
89
-
90
-		// validate all the fields before processing
91
-		foreach ( $required_fields as $field ) {
92
-			if ( ! array_key_exists( $field, $_POST ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Missing
93
-				/* translators: %s: field name */
94
-				wp_send_json_error( sprintf( __( 'Field %s is required', 'wordlift' ), $field ), 422 );
95
-
96
-				return;
97
-			}
98
-		}
99
-
100
-		$key = isset( $_POST['license'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['license'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
101
-
102
-		if ( ! $this->is_key_valid_and_not_bound_to_any_domain( $key ) ) {
103
-			wp_send_json_error( __( 'Key is not valid or associated with other domain', 'wordlift' ), 403 );
104
-
105
-			// exit if not valid.
106
-			return;
107
-		}
108
-
109
-		// check if key is already configured, if yes then dont save settings.
110
-		if ( \Wordlift_Configuration_Service::get_instance()->get_key() ) {
111
-			wp_send_json_error( __( 'Key already configured.', 'wordlift' ), 403 );
112
-
113
-			// key already configured
114
-			return;
115
-		}
116
-
117
-		$this->admin_setup->save_configuration( $this->get_params() );
118
-
119
-		// This prevents invalid key issue with automatic installation in sites which have redis cache enabled.
120
-		wp_cache_flush();
121
-
122
-		wp_send_json_success( __( 'Configuration Saved', 'wordlift' ) );
123
-	}
124
-
125
-	/**
126
-	 *
127
-	 * @return array
128
-	 */
129
-	private function get_params() {
130
-
131
-		$attachment_id = $this->may_be_get_attachment_id();
132
-
133
-		$params = array(
134
-			'key'             => isset( $_POST['license'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['license'] ) ) : '',
135
-			// phpcs:ignore WordPress.Security.NonceVerification.Missing
136
-			'vocabulary'      => isset( $_POST['vocabulary'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['vocabulary'] ) ) : '',
137
-			// phpcs:ignore WordPress.Security.NonceVerification.Missing
138
-			'wl-country-code' => isset( $_POST['country'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['country'] ) ) : '',
139
-			// phpcs:ignore WordPress.Security.NonceVerification.Missing
140
-			'name'            => isset( $_POST['publisherName'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['publisherName'] ) ) : '',
141
-			// phpcs:ignore WordPress.Security.NonceVerification.Missing
142
-			'user_type'       => isset( $_POST['publisher'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['publisher'] ) ) : '',
143
-			// phpcs:ignore WordPress.Security.NonceVerification.Missing
144
-			'logo'            => $attachment_id,
145
-		);
146
-
147
-		$diagnostic = isset( $_POST['diagnostic'] ) ? (bool) $_POST['diagnostic'] : false; // phpcs:ignore WordPress.Security.NonceVerification.Missing
148
-		if ( $diagnostic ) {
149
-			$params['share-diagnostic'] = 'on';
150
-		}
151
-
152
-		return $params;
153
-	}
154
-
155
-	/**
156
-	 * @return int | bool
157
-	 */
158
-	private function may_be_get_attachment_id() {
159
-
160
-		// if image or image extension not posted then return false.
161
-		if ( ! isset( $_POST['image'] ) || ! isset( $_POST['imageExtension'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
162
-			return false;
163
-		}
164
-
165
-		$allowed_extensions = array( 'png', 'jpeg', 'jpg' );
166
-		$image_string       = sanitize_text_field( wp_unslash( (string) $_POST['image'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
167
-		$image_ext          = sanitize_text_field( wp_unslash( (string) $_POST['imageExtension'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
168
-
169
-		if ( ! in_array( $image_ext, $allowed_extensions, true ) ) {
170
-			return false;
171
-		}
172
-
173
-		// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
174
-		$image_decoded_string = base64_decode( $image_string );
175
-
176
-		$upload_dir = wp_upload_dir();
177
-
178
-		$file_path = $upload_dir['path'] . DIRECTORY_SEPARATOR . md5( $image_string ) . '.' . $image_ext;
179
-
180
-		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents
181
-		file_put_contents( $file_path, $image_decoded_string );
182
-
183
-		$attachment_id = wp_insert_attachment(
184
-			array(
185
-				'post_status'    => 'inherit',
186
-				'post_mime_type' => "image/$image_ext",
187
-			),
188
-			$file_path
189
-		);
190
-
191
-		// Generate the metadata for the attachment, and update the database record.
192
-		$attachment_data = wp_generate_attachment_metadata( $attachment_id, $file_path );
193
-		// Update the attachment metadata.
194
-		wp_update_attachment_metadata( $attachment_id, $attachment_data );
6
+    /**
7
+     * @var \Wordlift_Admin_Setup
8
+     */
9
+    private $admin_setup;
10
+    /**
11
+     * @var \Wordlift_Key_Validation_Service
12
+     */
13
+    private $key_validation_service;
14
+
15
+    /**
16
+     * Config constructor.
17
+     *
18
+     * @param $admin_setup \Wordlift_Admin_Setup
19
+     * @param $key_validation_service \Wordlift_Key_Validation_Service
20
+     */
21
+    public function __construct( $admin_setup, $key_validation_service ) {
22
+
23
+        $this->admin_setup            = $admin_setup;
24
+        $this->key_validation_service = $key_validation_service;
25
+        add_action( 'wp_ajax_nopriv_wl_config_plugin', array( $this, 'config' ) );
26
+        add_action( 'wp_ajax_wl_config_plugin', array( $this, 'config' ) );
27
+
28
+    }
29
+
30
+    /**
31
+     * Check if the key is valid and also not bound to any domain.
32
+     *
33
+     * @param $key string
34
+     *
35
+     * @return bool
36
+     */
37
+    private function is_key_valid_and_not_bound_to_any_domain( $key ) {
38
+        $account_info = $this->key_validation_service->get_account_info( $key );
39
+
40
+        /**
41
+         * we need to check if the key is not associated with any account
42
+         * before setting it, we should check if the url is null.
43
+         */
44
+        if ( is_wp_error( $account_info )
45
+             || wp_remote_retrieve_response_code( $account_info ) !== 200 ) {
46
+            return false;
47
+        }
48
+
49
+        $account_info_json = $account_info['body'];
50
+
51
+        $account_info_data = json_decode( $account_info_json, true );
52
+
53
+        if ( ! $account_info_data ) {
54
+            // Invalid json returned by api.
55
+            return false;
56
+        }
57
+
58
+        $site_url = apply_filters( 'wl_production_site_url', untrailingslashit( get_option( 'home' ) ) );
59
+
60
+        if ( null === $account_info_data['url'] ) {
61
+            return true;
62
+        }
63
+
64
+        // Check if the key belongs to same site.
65
+        if ( untrailingslashit( $account_info_data['url'] ) !== $site_url ) {
66
+            // key already associated with another account.
67
+            return false;
68
+        }
69
+
70
+        // Return true if the key domain and site domain are the same.
71
+        return true;
72
+    }
73
+
74
+    public function config() {
75
+
76
+        // Perform validation check for all the parameters.
77
+        $required_fields = array(
78
+            'diagnostic',
79
+            'vocabulary',
80
+            // Don't ask for language from webapp.
81
+            // 'language',
82
+            'country',
83
+            'publisherName',
84
+            'publisher',
85
+            'license',
86
+        );
87
+
88
+        header( 'Access-Control-Allow-Origin: *' );
89
+
90
+        // validate all the fields before processing
91
+        foreach ( $required_fields as $field ) {
92
+            if ( ! array_key_exists( $field, $_POST ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Missing
93
+                /* translators: %s: field name */
94
+                wp_send_json_error( sprintf( __( 'Field %s is required', 'wordlift' ), $field ), 422 );
95
+
96
+                return;
97
+            }
98
+        }
99
+
100
+        $key = isset( $_POST['license'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['license'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
101
+
102
+        if ( ! $this->is_key_valid_and_not_bound_to_any_domain( $key ) ) {
103
+            wp_send_json_error( __( 'Key is not valid or associated with other domain', 'wordlift' ), 403 );
104
+
105
+            // exit if not valid.
106
+            return;
107
+        }
108
+
109
+        // check if key is already configured, if yes then dont save settings.
110
+        if ( \Wordlift_Configuration_Service::get_instance()->get_key() ) {
111
+            wp_send_json_error( __( 'Key already configured.', 'wordlift' ), 403 );
112
+
113
+            // key already configured
114
+            return;
115
+        }
116
+
117
+        $this->admin_setup->save_configuration( $this->get_params() );
118
+
119
+        // This prevents invalid key issue with automatic installation in sites which have redis cache enabled.
120
+        wp_cache_flush();
121
+
122
+        wp_send_json_success( __( 'Configuration Saved', 'wordlift' ) );
123
+    }
124
+
125
+    /**
126
+     *
127
+     * @return array
128
+     */
129
+    private function get_params() {
130
+
131
+        $attachment_id = $this->may_be_get_attachment_id();
132
+
133
+        $params = array(
134
+            'key'             => isset( $_POST['license'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['license'] ) ) : '',
135
+            // phpcs:ignore WordPress.Security.NonceVerification.Missing
136
+            'vocabulary'      => isset( $_POST['vocabulary'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['vocabulary'] ) ) : '',
137
+            // phpcs:ignore WordPress.Security.NonceVerification.Missing
138
+            'wl-country-code' => isset( $_POST['country'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['country'] ) ) : '',
139
+            // phpcs:ignore WordPress.Security.NonceVerification.Missing
140
+            'name'            => isset( $_POST['publisherName'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['publisherName'] ) ) : '',
141
+            // phpcs:ignore WordPress.Security.NonceVerification.Missing
142
+            'user_type'       => isset( $_POST['publisher'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['publisher'] ) ) : '',
143
+            // phpcs:ignore WordPress.Security.NonceVerification.Missing
144
+            'logo'            => $attachment_id,
145
+        );
146
+
147
+        $diagnostic = isset( $_POST['diagnostic'] ) ? (bool) $_POST['diagnostic'] : false; // phpcs:ignore WordPress.Security.NonceVerification.Missing
148
+        if ( $diagnostic ) {
149
+            $params['share-diagnostic'] = 'on';
150
+        }
151
+
152
+        return $params;
153
+    }
154
+
155
+    /**
156
+     * @return int | bool
157
+     */
158
+    private function may_be_get_attachment_id() {
159
+
160
+        // if image or image extension not posted then return false.
161
+        if ( ! isset( $_POST['image'] ) || ! isset( $_POST['imageExtension'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
162
+            return false;
163
+        }
164
+
165
+        $allowed_extensions = array( 'png', 'jpeg', 'jpg' );
166
+        $image_string       = sanitize_text_field( wp_unslash( (string) $_POST['image'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
167
+        $image_ext          = sanitize_text_field( wp_unslash( (string) $_POST['imageExtension'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
168
+
169
+        if ( ! in_array( $image_ext, $allowed_extensions, true ) ) {
170
+            return false;
171
+        }
172
+
173
+        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
174
+        $image_decoded_string = base64_decode( $image_string );
175
+
176
+        $upload_dir = wp_upload_dir();
177
+
178
+        $file_path = $upload_dir['path'] . DIRECTORY_SEPARATOR . md5( $image_string ) . '.' . $image_ext;
179
+
180
+        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents
181
+        file_put_contents( $file_path, $image_decoded_string );
182
+
183
+        $attachment_id = wp_insert_attachment(
184
+            array(
185
+                'post_status'    => 'inherit',
186
+                'post_mime_type' => "image/$image_ext",
187
+            ),
188
+            $file_path
189
+        );
190
+
191
+        // Generate the metadata for the attachment, and update the database record.
192
+        $attachment_data = wp_generate_attachment_metadata( $attachment_id, $file_path );
193
+        // Update the attachment metadata.
194
+        wp_update_attachment_metadata( $attachment_id, $attachment_data );
195 195
 
196
-		return $attachment_id;
197
-	}
196
+        return $attachment_id;
197
+    }
198 198
 
199 199
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -18,12 +18,12 @@  discard block
 block discarded – undo
18 18
 	 * @param $admin_setup \Wordlift_Admin_Setup
19 19
 	 * @param $key_validation_service \Wordlift_Key_Validation_Service
20 20
 	 */
21
-	public function __construct( $admin_setup, $key_validation_service ) {
21
+	public function __construct($admin_setup, $key_validation_service) {
22 22
 
23 23
 		$this->admin_setup            = $admin_setup;
24 24
 		$this->key_validation_service = $key_validation_service;
25
-		add_action( 'wp_ajax_nopriv_wl_config_plugin', array( $this, 'config' ) );
26
-		add_action( 'wp_ajax_wl_config_plugin', array( $this, 'config' ) );
25
+		add_action('wp_ajax_nopriv_wl_config_plugin', array($this, 'config'));
26
+		add_action('wp_ajax_wl_config_plugin', array($this, 'config'));
27 27
 
28 28
 	}
29 29
 
@@ -34,35 +34,35 @@  discard block
 block discarded – undo
34 34
 	 *
35 35
 	 * @return bool
36 36
 	 */
37
-	private function is_key_valid_and_not_bound_to_any_domain( $key ) {
38
-		$account_info = $this->key_validation_service->get_account_info( $key );
37
+	private function is_key_valid_and_not_bound_to_any_domain($key) {
38
+		$account_info = $this->key_validation_service->get_account_info($key);
39 39
 
40 40
 		/**
41 41
 		 * we need to check if the key is not associated with any account
42 42
 		 * before setting it, we should check if the url is null.
43 43
 		 */
44
-		if ( is_wp_error( $account_info )
45
-		     || wp_remote_retrieve_response_code( $account_info ) !== 200 ) {
44
+		if (is_wp_error($account_info)
45
+		     || wp_remote_retrieve_response_code($account_info) !== 200) {
46 46
 			return false;
47 47
 		}
48 48
 
49 49
 		$account_info_json = $account_info['body'];
50 50
 
51
-		$account_info_data = json_decode( $account_info_json, true );
51
+		$account_info_data = json_decode($account_info_json, true);
52 52
 
53
-		if ( ! $account_info_data ) {
53
+		if ( ! $account_info_data) {
54 54
 			// Invalid json returned by api.
55 55
 			return false;
56 56
 		}
57 57
 
58
-		$site_url = apply_filters( 'wl_production_site_url', untrailingslashit( get_option( 'home' ) ) );
58
+		$site_url = apply_filters('wl_production_site_url', untrailingslashit(get_option('home')));
59 59
 
60
-		if ( null === $account_info_data['url'] ) {
60
+		if (null === $account_info_data['url']) {
61 61
 			return true;
62 62
 		}
63 63
 
64 64
 		// Check if the key belongs to same site.
65
-		if ( untrailingslashit( $account_info_data['url'] ) !== $site_url ) {
65
+		if (untrailingslashit($account_info_data['url']) !== $site_url) {
66 66
 			// key already associated with another account.
67 67
 			return false;
68 68
 		}
@@ -85,41 +85,41 @@  discard block
 block discarded – undo
85 85
 			'license',
86 86
 		);
87 87
 
88
-		header( 'Access-Control-Allow-Origin: *' );
88
+		header('Access-Control-Allow-Origin: *');
89 89
 
90 90
 		// validate all the fields before processing
91
-		foreach ( $required_fields as $field ) {
92
-			if ( ! array_key_exists( $field, $_POST ) ) { //phpcs:ignore WordPress.Security.NonceVerification.Missing
91
+		foreach ($required_fields as $field) {
92
+			if ( ! array_key_exists($field, $_POST)) { //phpcs:ignore WordPress.Security.NonceVerification.Missing
93 93
 				/* translators: %s: field name */
94
-				wp_send_json_error( sprintf( __( 'Field %s is required', 'wordlift' ), $field ), 422 );
94
+				wp_send_json_error(sprintf(__('Field %s is required', 'wordlift'), $field), 422);
95 95
 
96 96
 				return;
97 97
 			}
98 98
 		}
99 99
 
100
-		$key = isset( $_POST['license'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['license'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
100
+		$key = isset($_POST['license']) ? sanitize_text_field(wp_unslash((string) $_POST['license'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
101 101
 
102
-		if ( ! $this->is_key_valid_and_not_bound_to_any_domain( $key ) ) {
103
-			wp_send_json_error( __( 'Key is not valid or associated with other domain', 'wordlift' ), 403 );
102
+		if ( ! $this->is_key_valid_and_not_bound_to_any_domain($key)) {
103
+			wp_send_json_error(__('Key is not valid or associated with other domain', 'wordlift'), 403);
104 104
 
105 105
 			// exit if not valid.
106 106
 			return;
107 107
 		}
108 108
 
109 109
 		// check if key is already configured, if yes then dont save settings.
110
-		if ( \Wordlift_Configuration_Service::get_instance()->get_key() ) {
111
-			wp_send_json_error( __( 'Key already configured.', 'wordlift' ), 403 );
110
+		if (\Wordlift_Configuration_Service::get_instance()->get_key()) {
111
+			wp_send_json_error(__('Key already configured.', 'wordlift'), 403);
112 112
 
113 113
 			// key already configured
114 114
 			return;
115 115
 		}
116 116
 
117
-		$this->admin_setup->save_configuration( $this->get_params() );
117
+		$this->admin_setup->save_configuration($this->get_params());
118 118
 
119 119
 		// This prevents invalid key issue with automatic installation in sites which have redis cache enabled.
120 120
 		wp_cache_flush();
121 121
 
122
-		wp_send_json_success( __( 'Configuration Saved', 'wordlift' ) );
122
+		wp_send_json_success(__('Configuration Saved', 'wordlift'));
123 123
 	}
124 124
 
125 125
 	/**
@@ -131,21 +131,21 @@  discard block
 block discarded – undo
131 131
 		$attachment_id = $this->may_be_get_attachment_id();
132 132
 
133 133
 		$params = array(
134
-			'key'             => isset( $_POST['license'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['license'] ) ) : '',
134
+			'key'             => isset($_POST['license']) ? sanitize_text_field(wp_unslash((string) $_POST['license'])) : '',
135 135
 			// phpcs:ignore WordPress.Security.NonceVerification.Missing
136
-			'vocabulary'      => isset( $_POST['vocabulary'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['vocabulary'] ) ) : '',
136
+			'vocabulary'      => isset($_POST['vocabulary']) ? sanitize_text_field(wp_unslash((string) $_POST['vocabulary'])) : '',
137 137
 			// phpcs:ignore WordPress.Security.NonceVerification.Missing
138
-			'wl-country-code' => isset( $_POST['country'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['country'] ) ) : '',
138
+			'wl-country-code' => isset($_POST['country']) ? sanitize_text_field(wp_unslash((string) $_POST['country'])) : '',
139 139
 			// phpcs:ignore WordPress.Security.NonceVerification.Missing
140
-			'name'            => isset( $_POST['publisherName'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['publisherName'] ) ) : '',
140
+			'name'            => isset($_POST['publisherName']) ? sanitize_text_field(wp_unslash((string) $_POST['publisherName'])) : '',
141 141
 			// phpcs:ignore WordPress.Security.NonceVerification.Missing
142
-			'user_type'       => isset( $_POST['publisher'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['publisher'] ) ) : '',
142
+			'user_type'       => isset($_POST['publisher']) ? sanitize_text_field(wp_unslash((string) $_POST['publisher'])) : '',
143 143
 			// phpcs:ignore WordPress.Security.NonceVerification.Missing
144 144
 			'logo'            => $attachment_id,
145 145
 		);
146 146
 
147
-		$diagnostic = isset( $_POST['diagnostic'] ) ? (bool) $_POST['diagnostic'] : false; // phpcs:ignore WordPress.Security.NonceVerification.Missing
148
-		if ( $diagnostic ) {
147
+		$diagnostic = isset($_POST['diagnostic']) ? (bool) $_POST['diagnostic'] : false; // phpcs:ignore WordPress.Security.NonceVerification.Missing
148
+		if ($diagnostic) {
149 149
 			$params['share-diagnostic'] = 'on';
150 150
 		}
151 151
 
@@ -158,27 +158,27 @@  discard block
 block discarded – undo
158 158
 	private function may_be_get_attachment_id() {
159 159
 
160 160
 		// if image or image extension not posted then return false.
161
-		if ( ! isset( $_POST['image'] ) || ! isset( $_POST['imageExtension'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
161
+		if ( ! isset($_POST['image']) || ! isset($_POST['imageExtension'])) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
162 162
 			return false;
163 163
 		}
164 164
 
165
-		$allowed_extensions = array( 'png', 'jpeg', 'jpg' );
166
-		$image_string       = sanitize_text_field( wp_unslash( (string) $_POST['image'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
167
-		$image_ext          = sanitize_text_field( wp_unslash( (string) $_POST['imageExtension'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Missing
165
+		$allowed_extensions = array('png', 'jpeg', 'jpg');
166
+		$image_string       = sanitize_text_field(wp_unslash((string) $_POST['image'])); // phpcs:ignore WordPress.Security.NonceVerification.Missing
167
+		$image_ext          = sanitize_text_field(wp_unslash((string) $_POST['imageExtension'])); // phpcs:ignore WordPress.Security.NonceVerification.Missing
168 168
 
169
-		if ( ! in_array( $image_ext, $allowed_extensions, true ) ) {
169
+		if ( ! in_array($image_ext, $allowed_extensions, true)) {
170 170
 			return false;
171 171
 		}
172 172
 
173 173
 		// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode
174
-		$image_decoded_string = base64_decode( $image_string );
174
+		$image_decoded_string = base64_decode($image_string);
175 175
 
176 176
 		$upload_dir = wp_upload_dir();
177 177
 
178
-		$file_path = $upload_dir['path'] . DIRECTORY_SEPARATOR . md5( $image_string ) . '.' . $image_ext;
178
+		$file_path = $upload_dir['path'].DIRECTORY_SEPARATOR.md5($image_string).'.'.$image_ext;
179 179
 
180 180
 		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents
181
-		file_put_contents( $file_path, $image_decoded_string );
181
+		file_put_contents($file_path, $image_decoded_string);
182 182
 
183 183
 		$attachment_id = wp_insert_attachment(
184 184
 			array(
@@ -189,9 +189,9 @@  discard block
 block discarded – undo
189 189
 		);
190 190
 
191 191
 		// Generate the metadata for the attachment, and update the database record.
192
-		$attachment_data = wp_generate_attachment_metadata( $attachment_id, $file_path );
192
+		$attachment_data = wp_generate_attachment_metadata($attachment_id, $file_path);
193 193
 		// Update the attachment metadata.
194
-		wp_update_attachment_metadata( $attachment_id, $attachment_data );
194
+		wp_update_attachment_metadata($attachment_id, $attachment_data);
195 195
 
196 196
 		return $attachment_id;
197 197
 	}
Please login to merge, or discard this patch.
src/wordlift/jsonld/class-mentions.php 2 patches
Indentation   +225 added lines, -225 removed lines patch added patch discarded remove patch
@@ -16,245 +16,245 @@
 block discarded – undo
16 16
 
17 17
 class Mentions {
18 18
 
19
-	private static $schema_descendants = array(
20
-		'AmpStory',
21
-		'ArchiveComponent',
22
-		'Article',
23
-		'Atlas',
24
-		'Blog',
25
-		'Book',
26
-		'Chapter',
27
-		'Claim',
28
-		'Clip',
29
-		'Code',
30
-		'Collection',
31
-		'ComicStory',
32
-		'Comment',
33
-		'Conversation',
34
-		'Course',
35
-		'CreativeWorkSeason',
36
-		'CreativeWorkSeries',
37
-		'DataCatalog',
38
-		'Dataset',
39
-		'DefinedTermSet',
40
-		'Diet',
41
-		'DigitalDocument',
42
-		'Drawing',
43
-		'EducationalOccupationalCredential',
44
-		'Episode',
45
-		'ExercisePlan',
46
-		'Game',
47
-		'Guide',
48
-		'HowTo',
49
-		'HowToDirection',
50
-		'HowToSection',
51
-		'HowToStep',
52
-		'HowToTip',
53
-		'HyperToc',
54
-		'HyperTocEntry',
55
-		'LearningResource',
56
-		'Legislation',
57
-		'Manuscript',
58
-		'Map',
59
-		'MathSolver',
60
-		'MediaObject',
61
-		'Menu',
62
-		'MenuSection',
63
-		'Message',
64
-		'Movie',
65
-		'MusicComposition',
66
-		'MusicPlaylist',
67
-		'MusicRecording',
68
-		'Painting',
69
-		'Photograph',
70
-		'Play',
71
-		'Poster',
72
-		'PublicationIssue',
73
-		'PublicationVolume',
74
-		'Quotation',
75
-		'Review',
76
-		'Sculpture',
77
-		'Season',
78
-		'SheetMusic',
79
-		'ShortStory',
80
-		'SoftwareApplication',
81
-		'SoftwareSourceCode',
82
-		'SpecialAnnouncement',
83
-		'Thesis',
84
-		'TvSeason',
85
-		'TvSeries',
86
-		'VisualArtwork',
87
-		'WebContent',
88
-		'WebPage',
89
-		'WebPageElement',
90
-		'WebSite',
91
-		'AdvertiserContentArticle',
92
-		'NewsArticle',
93
-		'Report',
94
-		'SatiricalArticle',
95
-		'ScholarlyArticle',
96
-		'SocialMediaPosting',
97
-		'TechArticle',
98
-		'AnalysisNewsArticle',
99
-		'AskPublicNewsArticle',
100
-		'BackgroundNewsArticle',
101
-		'OpinionNewsArticle',
102
-		'ReportageNewsArticle',
103
-		'ReviewNewsArticle',
104
-		'MedicalScholarlyArticle',
105
-		'BlogPosting',
106
-		'DiscussionForumPosting',
107
-		'LiveBlogPosting',
108
-		'ApiReference',
109
-		'Audiobook',
110
-		'MovieClip',
111
-		'RadioClip',
112
-		'TvClip',
113
-		'VideoGameClip',
114
-		'ProductCollection',
115
-		'ComicCoverArt',
116
-		'Answer',
117
-		'CorrectionComment',
118
-		'Question',
119
-		'PodcastSeason',
120
-		'RadioSeason',
121
-		'TvSeason',
122
-		'BookSeries',
123
-		'MovieSeries',
124
-		'Periodical',
125
-		'PodcastSeries',
126
-		'RadioSeries',
127
-		'TvSeries',
128
-		'VideoGameSeries',
129
-		'ComicSeries',
130
-		'Newspaper',
131
-		'DataFeed',
132
-		'CompleteDataFeed',
133
-		'CategoryCodeSet',
134
-		'NoteDigitalDocument',
135
-		'PresentationDigitalDocument',
136
-		'SpreadsheetDigitalDocument',
137
-		'TextDigitalDocument',
138
-		'PodcastEpisode',
139
-		'RadioEpisode',
140
-		'TvEpisode',
141
-		'VideoGame',
142
-		'Recipe',
143
-		'Course',
144
-		'Quiz',
145
-		'LegislationObject',
146
-		'AudioObject',
147
-		'DModel',
148
-		'DataDownload',
149
-		'ImageObject',
150
-		'LegislationObject',
151
-		'MusicVideoObject',
152
-		'VideoObject',
153
-		'Audiobook',
154
-		'Barcode',
155
-		'EmailMessage',
156
-		'MusicAlbum',
157
-		'MusicRelease',
158
-		'ComicIssue',
159
-		'ClaimReview',
160
-		'CriticReview',
161
-		'EmployerReview',
162
-		'MediaReview',
163
-		'Recommendation',
164
-		'UserReview',
165
-		'ReviewNewsArticle',
166
-		'MobileApplication',
167
-		'VideoGame',
168
-		'WebApplication',
169
-		'CoverArt',
170
-		'ComicCoverArt',
171
-		'HealthTopicContent',
172
-		'AboutPage',
173
-		'CheckoutPage',
174
-		'CollectionPage',
175
-		'ContactPage',
176
-		'FaqPage',
177
-		'ItemPage',
178
-		'MedicalWebPage',
179
-		'ProfilePage',
180
-		'QaPage',
181
-		'RealEstateListing',
182
-		'SearchResultsPage',
183
-		'MediaGallery',
184
-		'ImageGallery',
185
-		'VideoGallery',
186
-		'SiteNavigationElement',
187
-		'Table',
188
-		'WpAdBlock',
189
-		'WpFooter',
190
-		'WpHeader',
191
-		'WpSideBar',
192
-	);
19
+    private static $schema_descendants = array(
20
+        'AmpStory',
21
+        'ArchiveComponent',
22
+        'Article',
23
+        'Atlas',
24
+        'Blog',
25
+        'Book',
26
+        'Chapter',
27
+        'Claim',
28
+        'Clip',
29
+        'Code',
30
+        'Collection',
31
+        'ComicStory',
32
+        'Comment',
33
+        'Conversation',
34
+        'Course',
35
+        'CreativeWorkSeason',
36
+        'CreativeWorkSeries',
37
+        'DataCatalog',
38
+        'Dataset',
39
+        'DefinedTermSet',
40
+        'Diet',
41
+        'DigitalDocument',
42
+        'Drawing',
43
+        'EducationalOccupationalCredential',
44
+        'Episode',
45
+        'ExercisePlan',
46
+        'Game',
47
+        'Guide',
48
+        'HowTo',
49
+        'HowToDirection',
50
+        'HowToSection',
51
+        'HowToStep',
52
+        'HowToTip',
53
+        'HyperToc',
54
+        'HyperTocEntry',
55
+        'LearningResource',
56
+        'Legislation',
57
+        'Manuscript',
58
+        'Map',
59
+        'MathSolver',
60
+        'MediaObject',
61
+        'Menu',
62
+        'MenuSection',
63
+        'Message',
64
+        'Movie',
65
+        'MusicComposition',
66
+        'MusicPlaylist',
67
+        'MusicRecording',
68
+        'Painting',
69
+        'Photograph',
70
+        'Play',
71
+        'Poster',
72
+        'PublicationIssue',
73
+        'PublicationVolume',
74
+        'Quotation',
75
+        'Review',
76
+        'Sculpture',
77
+        'Season',
78
+        'SheetMusic',
79
+        'ShortStory',
80
+        'SoftwareApplication',
81
+        'SoftwareSourceCode',
82
+        'SpecialAnnouncement',
83
+        'Thesis',
84
+        'TvSeason',
85
+        'TvSeries',
86
+        'VisualArtwork',
87
+        'WebContent',
88
+        'WebPage',
89
+        'WebPageElement',
90
+        'WebSite',
91
+        'AdvertiserContentArticle',
92
+        'NewsArticle',
93
+        'Report',
94
+        'SatiricalArticle',
95
+        'ScholarlyArticle',
96
+        'SocialMediaPosting',
97
+        'TechArticle',
98
+        'AnalysisNewsArticle',
99
+        'AskPublicNewsArticle',
100
+        'BackgroundNewsArticle',
101
+        'OpinionNewsArticle',
102
+        'ReportageNewsArticle',
103
+        'ReviewNewsArticle',
104
+        'MedicalScholarlyArticle',
105
+        'BlogPosting',
106
+        'DiscussionForumPosting',
107
+        'LiveBlogPosting',
108
+        'ApiReference',
109
+        'Audiobook',
110
+        'MovieClip',
111
+        'RadioClip',
112
+        'TvClip',
113
+        'VideoGameClip',
114
+        'ProductCollection',
115
+        'ComicCoverArt',
116
+        'Answer',
117
+        'CorrectionComment',
118
+        'Question',
119
+        'PodcastSeason',
120
+        'RadioSeason',
121
+        'TvSeason',
122
+        'BookSeries',
123
+        'MovieSeries',
124
+        'Periodical',
125
+        'PodcastSeries',
126
+        'RadioSeries',
127
+        'TvSeries',
128
+        'VideoGameSeries',
129
+        'ComicSeries',
130
+        'Newspaper',
131
+        'DataFeed',
132
+        'CompleteDataFeed',
133
+        'CategoryCodeSet',
134
+        'NoteDigitalDocument',
135
+        'PresentationDigitalDocument',
136
+        'SpreadsheetDigitalDocument',
137
+        'TextDigitalDocument',
138
+        'PodcastEpisode',
139
+        'RadioEpisode',
140
+        'TvEpisode',
141
+        'VideoGame',
142
+        'Recipe',
143
+        'Course',
144
+        'Quiz',
145
+        'LegislationObject',
146
+        'AudioObject',
147
+        'DModel',
148
+        'DataDownload',
149
+        'ImageObject',
150
+        'LegislationObject',
151
+        'MusicVideoObject',
152
+        'VideoObject',
153
+        'Audiobook',
154
+        'Barcode',
155
+        'EmailMessage',
156
+        'MusicAlbum',
157
+        'MusicRelease',
158
+        'ComicIssue',
159
+        'ClaimReview',
160
+        'CriticReview',
161
+        'EmployerReview',
162
+        'MediaReview',
163
+        'Recommendation',
164
+        'UserReview',
165
+        'ReviewNewsArticle',
166
+        'MobileApplication',
167
+        'VideoGame',
168
+        'WebApplication',
169
+        'CoverArt',
170
+        'ComicCoverArt',
171
+        'HealthTopicContent',
172
+        'AboutPage',
173
+        'CheckoutPage',
174
+        'CollectionPage',
175
+        'ContactPage',
176
+        'FaqPage',
177
+        'ItemPage',
178
+        'MedicalWebPage',
179
+        'ProfilePage',
180
+        'QaPage',
181
+        'RealEstateListing',
182
+        'SearchResultsPage',
183
+        'MediaGallery',
184
+        'ImageGallery',
185
+        'VideoGallery',
186
+        'SiteNavigationElement',
187
+        'Table',
188
+        'WpAdBlock',
189
+        'WpFooter',
190
+        'WpHeader',
191
+        'WpSideBar',
192
+    );
193 193
 
194
-	public function __construct() {
195
-		add_filter( 'wl_after_get_jsonld', array( $this, 'wl_after_get_jsonld' ), 10, 2 );
196
-	}
194
+    public function __construct() {
195
+        add_filter( 'wl_after_get_jsonld', array( $this, 'wl_after_get_jsonld' ), 10, 2 );
196
+    }
197 197
 
198
-	public function wl_after_get_jsonld( $jsonld, $post_id ) {
198
+    public function wl_after_get_jsonld( $jsonld, $post_id ) {
199 199
 
200
-		if ( count( $jsonld ) === 0 || ! is_array( $jsonld[0] ) || ! array_key_exists( '@type', $jsonld[0] ) || array_key_exists( 'mentions', $jsonld[0] ) ) {
201
-			return $jsonld;
202
-		}
200
+        if ( count( $jsonld ) === 0 || ! is_array( $jsonld[0] ) || ! array_key_exists( '@type', $jsonld[0] ) || array_key_exists( 'mentions', $jsonld[0] ) ) {
201
+            return $jsonld;
202
+        }
203 203
 
204
-		$type = $jsonld[0]['@type'];
204
+        $type = $jsonld[0]['@type'];
205 205
 
206
-		if ( ! $this->entity_is_descendant_of_creative_work( $type ) && ! $this->entity_is_creative_work( $type ) ) {
207
-			return $jsonld;
208
-		}
206
+        if ( ! $this->entity_is_descendant_of_creative_work( $type ) && ! $this->entity_is_creative_work( $type ) ) {
207
+            return $jsonld;
208
+        }
209 209
 
210
-		$entity_references = Object_Relation_Service::get_instance()
211
-		                                            ->get_references( $post_id, Object_Type_Enum::POST );
210
+        $entity_references = Object_Relation_Service::get_instance()
211
+                                                    ->get_references( $post_id, Object_Type_Enum::POST );
212 212
 
213
-		$about_id = array();
214
-		if ( array_key_exists( 'about', $jsonld[0] ) && is_array( $jsonld[0]['about'] ) ) {
215
-			foreach ( $jsonld[0]['about'] as $about ) {
216
-				// see https://trello.com/c/PbZMJmMs/1269-matt-artz-error-in-wlp
217
-				if ( isset( $about['@id'] ) ) {
218
-					$about_id[] = $about['@id'];
219
-				}
220
-			}
221
-		}
213
+        $about_id = array();
214
+        if ( array_key_exists( 'about', $jsonld[0] ) && is_array( $jsonld[0]['about'] ) ) {
215
+            foreach ( $jsonld[0]['about'] as $about ) {
216
+                // see https://trello.com/c/PbZMJmMs/1269-matt-artz-error-in-wlp
217
+                if ( isset( $about['@id'] ) ) {
218
+                    $about_id[] = $about['@id'];
219
+                }
220
+            }
221
+        }
222 222
 
223
-		$jsonld[0]['mentions'] = array_values(
224
-			array_filter(
225
-				array_map(
226
-					function ( $item ) use ( $about_id ) {
227
-						$id = \Wordlift_Entity_Service::get_instance()->get_uri( $item->get_id() );
228
-						if ( ! $id || in_array( $id, $about_id, true ) ) {
229
-							return false;
230
-						}
223
+        $jsonld[0]['mentions'] = array_values(
224
+            array_filter(
225
+                array_map(
226
+                    function ( $item ) use ( $about_id ) {
227
+                        $id = \Wordlift_Entity_Service::get_instance()->get_uri( $item->get_id() );
228
+                        if ( ! $id || in_array( $id, $about_id, true ) ) {
229
+                            return false;
230
+                        }
231 231
 
232
-						return array( '@id' => $id );
232
+                        return array( '@id' => $id );
233 233
 
234
-					},
235
-					$entity_references
236
-				)
237
-			)
238
-		);
234
+                    },
235
+                    $entity_references
236
+                )
237
+            )
238
+        );
239 239
 
240
-		// Remove mentions if the count is zero.
241
-		if ( count( $jsonld[0]['mentions'] ) === 0 ) {
242
-			unset( $jsonld[0]['mentions'] );
243
-		}
240
+        // Remove mentions if the count is zero.
241
+        if ( count( $jsonld[0]['mentions'] ) === 0 ) {
242
+            unset( $jsonld[0]['mentions'] );
243
+        }
244 244
 
245
-		return $jsonld;
246
-	}
245
+        return $jsonld;
246
+    }
247 247
 
248
-	private function entity_is_descendant_of_creative_work( $type ) {
249
-		if ( is_string( $type ) ) {
250
-			$type = array( $type );
251
-		}
248
+    private function entity_is_descendant_of_creative_work( $type ) {
249
+        if ( is_string( $type ) ) {
250
+            $type = array( $type );
251
+        }
252 252
 
253
-		return count( array_intersect( $type, $this::$schema_descendants ) ) > 0;
254
-	}
253
+        return count( array_intersect( $type, $this::$schema_descendants ) ) > 0;
254
+    }
255 255
 
256
-	private function entity_is_creative_work( $type ) {
257
-		return ( 'CreativeWork' === $type ) || ( is_array( $type ) && in_array( 'CreativeWork', $type, true ) );
258
-	}
256
+    private function entity_is_creative_work( $type ) {
257
+        return ( 'CreativeWork' === $type ) || ( is_array( $type ) && in_array( 'CreativeWork', $type, true ) );
258
+    }
259 259
 
260 260
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -192,29 +192,29 @@  discard block
 block discarded – undo
192 192
 	);
193 193
 
194 194
 	public function __construct() {
195
-		add_filter( 'wl_after_get_jsonld', array( $this, 'wl_after_get_jsonld' ), 10, 2 );
195
+		add_filter('wl_after_get_jsonld', array($this, 'wl_after_get_jsonld'), 10, 2);
196 196
 	}
197 197
 
198
-	public function wl_after_get_jsonld( $jsonld, $post_id ) {
198
+	public function wl_after_get_jsonld($jsonld, $post_id) {
199 199
 
200
-		if ( count( $jsonld ) === 0 || ! is_array( $jsonld[0] ) || ! array_key_exists( '@type', $jsonld[0] ) || array_key_exists( 'mentions', $jsonld[0] ) ) {
200
+		if (count($jsonld) === 0 || ! is_array($jsonld[0]) || ! array_key_exists('@type', $jsonld[0]) || array_key_exists('mentions', $jsonld[0])) {
201 201
 			return $jsonld;
202 202
 		}
203 203
 
204 204
 		$type = $jsonld[0]['@type'];
205 205
 
206
-		if ( ! $this->entity_is_descendant_of_creative_work( $type ) && ! $this->entity_is_creative_work( $type ) ) {
206
+		if ( ! $this->entity_is_descendant_of_creative_work($type) && ! $this->entity_is_creative_work($type)) {
207 207
 			return $jsonld;
208 208
 		}
209 209
 
210 210
 		$entity_references = Object_Relation_Service::get_instance()
211
-		                                            ->get_references( $post_id, Object_Type_Enum::POST );
211
+		                                            ->get_references($post_id, Object_Type_Enum::POST);
212 212
 
213 213
 		$about_id = array();
214
-		if ( array_key_exists( 'about', $jsonld[0] ) && is_array( $jsonld[0]['about'] ) ) {
215
-			foreach ( $jsonld[0]['about'] as $about ) {
214
+		if (array_key_exists('about', $jsonld[0]) && is_array($jsonld[0]['about'])) {
215
+			foreach ($jsonld[0]['about'] as $about) {
216 216
 				// see https://trello.com/c/PbZMJmMs/1269-matt-artz-error-in-wlp
217
-				if ( isset( $about['@id'] ) ) {
217
+				if (isset($about['@id'])) {
218 218
 					$about_id[] = $about['@id'];
219 219
 				}
220 220
 			}
@@ -223,13 +223,13 @@  discard block
 block discarded – undo
223 223
 		$jsonld[0]['mentions'] = array_values(
224 224
 			array_filter(
225 225
 				array_map(
226
-					function ( $item ) use ( $about_id ) {
227
-						$id = \Wordlift_Entity_Service::get_instance()->get_uri( $item->get_id() );
228
-						if ( ! $id || in_array( $id, $about_id, true ) ) {
226
+					function($item) use ($about_id) {
227
+						$id = \Wordlift_Entity_Service::get_instance()->get_uri($item->get_id());
228
+						if ( ! $id || in_array($id, $about_id, true)) {
229 229
 							return false;
230 230
 						}
231 231
 
232
-						return array( '@id' => $id );
232
+						return array('@id' => $id);
233 233
 
234 234
 					},
235 235
 					$entity_references
@@ -238,23 +238,23 @@  discard block
 block discarded – undo
238 238
 		);
239 239
 
240 240
 		// Remove mentions if the count is zero.
241
-		if ( count( $jsonld[0]['mentions'] ) === 0 ) {
242
-			unset( $jsonld[0]['mentions'] );
241
+		if (count($jsonld[0]['mentions']) === 0) {
242
+			unset($jsonld[0]['mentions']);
243 243
 		}
244 244
 
245 245
 		return $jsonld;
246 246
 	}
247 247
 
248
-	private function entity_is_descendant_of_creative_work( $type ) {
249
-		if ( is_string( $type ) ) {
250
-			$type = array( $type );
248
+	private function entity_is_descendant_of_creative_work($type) {
249
+		if (is_string($type)) {
250
+			$type = array($type);
251 251
 		}
252 252
 
253
-		return count( array_intersect( $type, $this::$schema_descendants ) ) > 0;
253
+		return count(array_intersect($type, $this::$schema_descendants)) > 0;
254 254
 	}
255 255
 
256
-	private function entity_is_creative_work( $type ) {
257
-		return ( 'CreativeWork' === $type ) || ( is_array( $type ) && in_array( 'CreativeWork', $type, true ) );
256
+	private function entity_is_creative_work($type) {
257
+		return ('CreativeWork' === $type) || (is_array($type) && in_array('CreativeWork', $type, true));
258 258
 	}
259 259
 
260 260
 }
Please login to merge, or discard this patch.
src/wordlift.php 2 patches
Indentation   +168 added lines, -168 removed lines patch added patch discarded remove patch
@@ -33,11 +33,11 @@  discard block
 block discarded – undo
33 33
 
34 34
 // If this file is called directly, abort.
35 35
 if ( ! defined( 'WPINC' ) ) {
36
-	die;
36
+    die;
37 37
 }
38 38
 define(
39
-	'WORDLIFT_PLUGIN_FILE',
40
-	__FILE__
39
+    'WORDLIFT_PLUGIN_FILE',
40
+    __FILE__
41 41
 );
42 42
 
43 43
 define( 'WORDLIFT_VERSION', '3.41.0-dev.1' );
@@ -52,7 +52,7 @@  discard block
 block discarded – undo
52 52
  * @since 3.33.6
53 53
  */
54 54
 if ( ! apply_filters( 'wl_is_enabled', true ) ) {
55
-	return;
55
+    return;
56 56
 }
57 57
 
58 58
 require_once plugin_dir_path( __FILE__ ) . 'vendor/autoload.php';
@@ -81,33 +81,33 @@  discard block
 block discarded – undo
81 81
  */
82 82
 function activate_wordlift() {
83 83
 
84
-	$log = Wordlift_Log_Service::get_logger( 'activate_wordlift' );
84
+    $log = Wordlift_Log_Service::get_logger( 'activate_wordlift' );
85 85
 
86
-	$log->info( 'Activating WordLift...' );
86
+    $log->info( 'Activating WordLift...' );
87 87
 
88
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-activator.php';
89
-	Wordlift_Activator::activate();
88
+    require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-activator.php';
89
+    Wordlift_Activator::activate();
90 90
 
91
-	/**
92
-	 * Tell the {@link Wordlift_Http_Api} class that we're activating, to let it run activation tasks.
93
-	 *
94
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/820 related issue.
95
-	 * @since 3.19.2
96
-	 */
97
-	Wordlift_Http_Api::activate();
98
-
99
-	// Ensure the post type is registered before flushing the rewrite rules.
100
-	Wordlift_Entity_Post_Type_Service::get_instance()->register();
101
-	flush_rewrite_rules();
102
-	/**
103
-	 * @since 3.27.7
104
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/1214
105
-	 */
106
-	Top_Entities::activate();
91
+    /**
92
+     * Tell the {@link Wordlift_Http_Api} class that we're activating, to let it run activation tasks.
93
+     *
94
+     * @see https://github.com/insideout10/wordlift-plugin/issues/820 related issue.
95
+     * @since 3.19.2
96
+     */
97
+    Wordlift_Http_Api::activate();
98
+
99
+    // Ensure the post type is registered before flushing the rewrite rules.
100
+    Wordlift_Entity_Post_Type_Service::get_instance()->register();
101
+    flush_rewrite_rules();
102
+    /**
103
+     * @since 3.27.7
104
+     * @see https://github.com/insideout10/wordlift-plugin/issues/1214
105
+     */
106
+    Top_Entities::activate();
107 107
 
108
-	if ( ! wp_next_scheduled( 'wl_daily_cron' ) ) {
109
-		wp_schedule_event( time(), 'daily', 'wl_daily_cron' );
110
-	}
108
+    if ( ! wp_next_scheduled( 'wl_daily_cron' ) ) {
109
+        wp_schedule_event( time(), 'daily', 'wl_daily_cron' );
110
+    }
111 111
 
112 112
 }
113 113
 
@@ -117,23 +117,23 @@  discard block
 block discarded – undo
117 117
  */
118 118
 function deactivate_wordlift() {
119 119
 
120
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
121
-	Wordlift_Deactivator::deactivate();
122
-	Wordlift_Http_Api::deactivate();
123
-	Ttl_Cache_Cleaner::deactivate();
124
-	/**
125
-	 * @since 3.27.7
126
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/1214
127
-	 */
128
-	Top_Entities::deactivate();
129
-	/**
130
-	 * @since 3.27.8
131
-	 * Remove notification flag on deactivation.
132
-	 */
133
-	Key_Validation_Notice::remove_notification_flag();
134
-	flush_rewrite_rules();
135
-
136
-	wp_clear_scheduled_hook( 'wl_daily_cron' );
120
+    require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
121
+    Wordlift_Deactivator::deactivate();
122
+    Wordlift_Http_Api::deactivate();
123
+    Ttl_Cache_Cleaner::deactivate();
124
+    /**
125
+     * @since 3.27.7
126
+     * @see https://github.com/insideout10/wordlift-plugin/issues/1214
127
+     */
128
+    Top_Entities::deactivate();
129
+    /**
130
+     * @since 3.27.8
131
+     * Remove notification flag on deactivation.
132
+     */
133
+    Key_Validation_Notice::remove_notification_flag();
134
+    flush_rewrite_rules();
135
+
136
+    wp_clear_scheduled_hook( 'wl_daily_cron' );
137 137
 
138 138
 }
139 139
 
@@ -156,84 +156,84 @@  discard block
 block discarded – undo
156 156
  * @since    1.0.0
157 157
  */
158 158
 function run_wordlift() {
159
-	/**
160
-	 * Filter: wl_feature__enable__widgets.
161
-	 *
162
-	 * @param bool whether the widgets needed to be registered, defaults to true.
163
-	 *
164
-	 * @return bool
165
-	 * @since 3.27.6
166
-	 */
167
-	if ( apply_filters( 'wl_feature__enable__widgets', true ) ) {
168
-		add_action( 'widgets_init', 'wl_register_chord_widget' );
169
-		add_action( 'widgets_init', 'wl_register_geo_widget' );
170
-		add_action( 'widgets_init', 'wl_register_timeline_widget' );
171
-	}
172
-	add_filter( 'widget_text', 'do_shortcode' );
173
-
174
-	/**
175
-	 * Filter: wl_feature__enable__analysis
176
-	 *
177
-	 * @param bool Whether to send api request to analysis or not
178
-	 *
179
-	 * @return bool
180
-	 * @since 3.27.6
181
-	 */
182
-	if ( apply_filters( 'wl_feature__enable__analysis', true ) ) {
183
-		add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_action' );
184
-	} else {
185
-		add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_disabled_action' );
186
-	}
187
-
188
-	$plugin = new Wordlift();
189
-	$plugin->run();
190
-
191
-	// Initialize the TTL Cache Cleaner.
192
-	new Ttl_Cache_Cleaner();
193
-
194
-	// Load the new Post Adapter.
195
-	new Post_Adapter();
196
-
197
-	// Load the API Data Hooks.
198
-	new Api_Data_Hooks();
199
-
200
-	add_action(
201
-		'plugins_loaded',
202
-		function () {
203
-			// All features from registry should be initialized here.
204
-			$features_registry = Features_Registry::get_instance();
205
-			$features_registry->initialize_all_features();
206
-		},
207
-		5
208
-	);
209
-
210
-	add_action(
211
-		'plugins_loaded',
212
-		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
213
-		function () use ( $plugin ) {
214
-
215
-			new Wordlift_Products_Navigator_Shortcode_REST();
216
-
217
-			// Register the Dataset module, requires `$api_service`.
218
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/dataset/index.php';
219
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/shipping-data/index.php';
220
-
221
-			/*
159
+    /**
160
+     * Filter: wl_feature__enable__widgets.
161
+     *
162
+     * @param bool whether the widgets needed to be registered, defaults to true.
163
+     *
164
+     * @return bool
165
+     * @since 3.27.6
166
+     */
167
+    if ( apply_filters( 'wl_feature__enable__widgets', true ) ) {
168
+        add_action( 'widgets_init', 'wl_register_chord_widget' );
169
+        add_action( 'widgets_init', 'wl_register_geo_widget' );
170
+        add_action( 'widgets_init', 'wl_register_timeline_widget' );
171
+    }
172
+    add_filter( 'widget_text', 'do_shortcode' );
173
+
174
+    /**
175
+     * Filter: wl_feature__enable__analysis
176
+     *
177
+     * @param bool Whether to send api request to analysis or not
178
+     *
179
+     * @return bool
180
+     * @since 3.27.6
181
+     */
182
+    if ( apply_filters( 'wl_feature__enable__analysis', true ) ) {
183
+        add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_action' );
184
+    } else {
185
+        add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_disabled_action' );
186
+    }
187
+
188
+    $plugin = new Wordlift();
189
+    $plugin->run();
190
+
191
+    // Initialize the TTL Cache Cleaner.
192
+    new Ttl_Cache_Cleaner();
193
+
194
+    // Load the new Post Adapter.
195
+    new Post_Adapter();
196
+
197
+    // Load the API Data Hooks.
198
+    new Api_Data_Hooks();
199
+
200
+    add_action(
201
+        'plugins_loaded',
202
+        function () {
203
+            // All features from registry should be initialized here.
204
+            $features_registry = Features_Registry::get_instance();
205
+            $features_registry->initialize_all_features();
206
+        },
207
+        5
208
+    );
209
+
210
+    add_action(
211
+        'plugins_loaded',
212
+        // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
213
+        function () use ( $plugin ) {
214
+
215
+            new Wordlift_Products_Navigator_Shortcode_REST();
216
+
217
+            // Register the Dataset module, requires `$api_service`.
218
+            require_once plugin_dir_path( __FILE__ ) . 'wordlift/dataset/index.php';
219
+            require_once plugin_dir_path( __FILE__ ) . 'wordlift/shipping-data/index.php';
220
+
221
+            /*
222 222
 			* Require the Entity annotation cleanup module.
223 223
 			*
224 224
 			* @since 3.34.6
225 225
 			*/
226
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/cleanup/index.php';
226
+            require_once plugin_dir_path( __FILE__ ) . 'wordlift/cleanup/index.php';
227 227
 
228
-			/*
228
+            /*
229 229
 			* Import LOD entities.
230 230
 			*
231 231
 			* @since 3.35.0
232 232
 			*/
233
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/lod-import/index.php';
233
+            require_once plugin_dir_path( __FILE__ ) . 'wordlift/lod-import/index.php';
234 234
 
235
-		}
236
-	);
235
+        }
236
+    );
237 237
 
238 238
 }
239 239
 
@@ -247,45 +247,45 @@  discard block
 block discarded – undo
247 247
  */
248 248
 function wordlift_plugin_autoload_register() {
249 249
 
250
-	spl_autoload_register(
251
-		function ( $class_name ) {
250
+    spl_autoload_register(
251
+        function ( $class_name ) {
252 252
 
253
-			// Bail out if these are not our classes.
254
-			if ( 0 !== strpos( $class_name, 'Wordlift\\' ) ) {
255
-				return false;
256
-			}
253
+            // Bail out if these are not our classes.
254
+            if ( 0 !== strpos( $class_name, 'Wordlift\\' ) ) {
255
+                return false;
256
+            }
257 257
 
258
-			$class_name_lc = strtolower( str_replace( '_', '-', $class_name ) );
258
+            $class_name_lc = strtolower( str_replace( '_', '-', $class_name ) );
259 259
 
260
-			preg_match( '|^(?:(.*)\\\\)?(.+?)$|', $class_name_lc, $matches );
260
+            preg_match( '|^(?:(.*)\\\\)?(.+?)$|', $class_name_lc, $matches );
261 261
 
262
-			$path = str_replace( '\\', DIRECTORY_SEPARATOR, $matches[1] );
263
-			$file = 'class-' . $matches[2] . '.php';
262
+            $path = str_replace( '\\', DIRECTORY_SEPARATOR, $matches[1] );
263
+            $file = 'class-' . $matches[2] . '.php';
264 264
 
265
-			$full_path = plugin_dir_path( __FILE__ ) . $path . DIRECTORY_SEPARATOR . $file;
265
+            $full_path = plugin_dir_path( __FILE__ ) . $path . DIRECTORY_SEPARATOR . $file;
266 266
 
267
-			if ( ! file_exists( $full_path ) ) {
268
-				return false;
269
-			}
267
+            if ( ! file_exists( $full_path ) ) {
268
+                return false;
269
+            }
270 270
 
271
-			require_once $full_path;
271
+            require_once $full_path;
272 272
 
273
-			return true;
274
-		}
275
-	);
273
+            return true;
274
+        }
275
+    );
276 276
 
277 277
 }
278 278
 
279 279
 function wl_block_categories( $categories ) {
280
-	return array_merge(
281
-		$categories,
282
-		array(
283
-			array(
284
-				'slug'  => 'wordlift',
285
-				'title' => __( 'WordLift', 'wordlift' ),
286
-			),
287
-		)
288
-	);
280
+    return array_merge(
281
+        $categories,
282
+        array(
283
+            array(
284
+                'slug'  => 'wordlift',
285
+                'title' => __( 'WordLift', 'wordlift' ),
286
+            ),
287
+        )
288
+    );
289 289
 }
290 290
 
291 291
 /**
@@ -293,19 +293,19 @@  discard block
 block discarded – undo
293 293
  * this has to be removed when removing the legacy fields from the ui.
294 294
  */
295 295
 function wl_enqueue_leaflet( $in_footer = false ) {
296
-	// Leaflet.
297
-	wp_enqueue_style( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.css', array(), '1.6.0' );
298
-	wp_enqueue_script( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.js', array(), '1.6.0', $in_footer );
296
+    // Leaflet.
297
+    wp_enqueue_style( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.css', array(), '1.6.0' );
298
+    wp_enqueue_script( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.js', array(), '1.6.0', $in_footer );
299 299
 }
300 300
 
301 301
 add_filter( 'block_categories', 'wl_block_categories', 10 );
302 302
 
303 303
 // Temporary fix for a typo in WooCommerce Extension.
304 304
 add_filter(
305
-	'wl_feature__enable__dataset',
306
-	function ( $value ) {
307
-		return apply_filters( 'wl_features__enable__dataset', $value );
308
-	}
305
+    'wl_feature__enable__dataset',
306
+    function ( $value ) {
307
+        return apply_filters( 'wl_features__enable__dataset', $value );
308
+    }
309 309
 );
310 310
 
311 311
 require_once __DIR__ . '/modules/food-kg/load.php';
@@ -314,26 +314,26 @@  discard block
 block discarded – undo
314 314
 require_once __DIR__ . '/modules/include-exclude-push-config/load.php';
315 315
 
316 316
 add_action(
317
-	'update_plugins_adthrive.wordlift.io',
318
-	function ( $update, $plugin_data, $plugin_file ) {
319
-		// Bail out if it's not our plugin.
320
-		$update_uri = $plugin_data['UpdateURI'];
321
-		if ( 'wordlift/wordlift.php' !== $plugin_file || ! isset( $update_uri ) ) {
322
-			return $update;
323
-		}
324
-
325
-		$response = wp_remote_get( "$update_uri?nocache=" . time() );
326
-
327
-		if ( is_wp_error( $response ) ) {
328
-			return $update;
329
-		}
330
-
331
-		try {
332
-			return json_decode( wp_remote_retrieve_body( $response ) );
333
-		} catch ( Exception $e ) {
334
-			return $update;
335
-		}
336
-	},
337
-	10,
338
-	3
317
+    'update_plugins_adthrive.wordlift.io',
318
+    function ( $update, $plugin_data, $plugin_file ) {
319
+        // Bail out if it's not our plugin.
320
+        $update_uri = $plugin_data['UpdateURI'];
321
+        if ( 'wordlift/wordlift.php' !== $plugin_file || ! isset( $update_uri ) ) {
322
+            return $update;
323
+        }
324
+
325
+        $response = wp_remote_get( "$update_uri?nocache=" . time() );
326
+
327
+        if ( is_wp_error( $response ) ) {
328
+            return $update;
329
+        }
330
+
331
+        try {
332
+            return json_decode( wp_remote_retrieve_body( $response ) );
333
+        } catch ( Exception $e ) {
334
+            return $update;
335
+        }
336
+    },
337
+    10,
338
+    3
339 339
 );
Please login to merge, or discard this patch.
Spacing   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
 use Wordlift\Post\Post_Adapter;
33 33
 
34 34
 // If this file is called directly, abort.
35
-if ( ! defined( 'WPINC' ) ) {
35
+if ( ! defined('WPINC')) {
36 36
 	die;
37 37
 }
38 38
 define(
@@ -40,22 +40,22 @@  discard block
 block discarded – undo
40 40
 	__FILE__
41 41
 );
42 42
 
43
-define( 'WORDLIFT_VERSION', '3.41.0-dev.1' );
43
+define('WORDLIFT_VERSION', '3.41.0-dev.1');
44 44
 
45
-require_once plugin_dir_path( __FILE__ ) . '/libraries/action-scheduler/action-scheduler.php';
46
-require_once __DIR__ . '/modules/common/load.php';
47
-require_once __DIR__ . '/modules/include-exclude/load.php';
45
+require_once plugin_dir_path(__FILE__).'/libraries/action-scheduler/action-scheduler.php';
46
+require_once __DIR__.'/modules/common/load.php';
47
+require_once __DIR__.'/modules/include-exclude/load.php';
48 48
 
49 49
 /**
50 50
  * Filter to disable WLP on any request, defaults to true.
51 51
  *
52 52
  * @since 3.33.6
53 53
  */
54
-if ( ! apply_filters( 'wl_is_enabled', true ) ) {
54
+if ( ! apply_filters('wl_is_enabled', true)) {
55 55
 	return;
56 56
 }
57 57
 
58
-require_once plugin_dir_path( __FILE__ ) . 'vendor/autoload.php';
58
+require_once plugin_dir_path(__FILE__).'vendor/autoload.php';
59 59
 
60 60
 /*
61 61
 	 * We introduce the WordLift autoloader, since we start using classes in namespaces, i.e. Wordlift\Http.
@@ -65,15 +65,15 @@  discard block
 block discarded – undo
65 65
 wordlift_plugin_autoload_register();
66 66
 
67 67
 // Include WordLift constants.
68
-require_once plugin_dir_path( __FILE__ ) . 'wordlift-constants.php';
68
+require_once plugin_dir_path(__FILE__).'wordlift-constants.php';
69 69
 
70 70
 // Load modules.
71
-require_once plugin_dir_path( __FILE__ ) . 'modules/core/wordlift-core.php';
71
+require_once plugin_dir_path(__FILE__).'modules/core/wordlift-core.php';
72 72
 
73
-require_once plugin_dir_path( __FILE__ ) . 'deprecations.php';
73
+require_once plugin_dir_path(__FILE__).'deprecations.php';
74 74
 
75 75
 // Load early to enable/disable features.
76
-require_once plugin_dir_path( __FILE__ ) . 'wordlift/features/index.php';
76
+require_once plugin_dir_path(__FILE__).'wordlift/features/index.php';
77 77
 
78 78
 /**
79 79
  * The code that runs during plugin activation.
@@ -81,11 +81,11 @@  discard block
 block discarded – undo
81 81
  */
82 82
 function activate_wordlift() {
83 83
 
84
-	$log = Wordlift_Log_Service::get_logger( 'activate_wordlift' );
84
+	$log = Wordlift_Log_Service::get_logger('activate_wordlift');
85 85
 
86
-	$log->info( 'Activating WordLift...' );
86
+	$log->info('Activating WordLift...');
87 87
 
88
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-activator.php';
88
+	require_once plugin_dir_path(__FILE__).'includes/class-wordlift-activator.php';
89 89
 	Wordlift_Activator::activate();
90 90
 
91 91
 	/**
@@ -105,8 +105,8 @@  discard block
 block discarded – undo
105 105
 	 */
106 106
 	Top_Entities::activate();
107 107
 
108
-	if ( ! wp_next_scheduled( 'wl_daily_cron' ) ) {
109
-		wp_schedule_event( time(), 'daily', 'wl_daily_cron' );
108
+	if ( ! wp_next_scheduled('wl_daily_cron')) {
109
+		wp_schedule_event(time(), 'daily', 'wl_daily_cron');
110 110
 	}
111 111
 
112 112
 }
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
  */
118 118
 function deactivate_wordlift() {
119 119
 
120
-	require_once plugin_dir_path( __FILE__ ) . 'includes/class-wordlift-deactivator.php';
120
+	require_once plugin_dir_path(__FILE__).'includes/class-wordlift-deactivator.php';
121 121
 	Wordlift_Deactivator::deactivate();
122 122
 	Wordlift_Http_Api::deactivate();
123 123
 	Ttl_Cache_Cleaner::deactivate();
@@ -133,18 +133,18 @@  discard block
 block discarded – undo
133 133
 	Key_Validation_Notice::remove_notification_flag();
134 134
 	flush_rewrite_rules();
135 135
 
136
-	wp_clear_scheduled_hook( 'wl_daily_cron' );
136
+	wp_clear_scheduled_hook('wl_daily_cron');
137 137
 
138 138
 }
139 139
 
140
-register_activation_hook( __FILE__, 'activate_wordlift' );
141
-register_deactivation_hook( __FILE__, 'deactivate_wordlift' );
140
+register_activation_hook(__FILE__, 'activate_wordlift');
141
+register_deactivation_hook(__FILE__, 'deactivate_wordlift');
142 142
 
143 143
 /**
144 144
  * The core plugin class that is used to define internationalization,
145 145
  * admin-specific hooks, and public-facing site hooks.
146 146
  */
147
-require plugin_dir_path( __FILE__ ) . 'includes/class-wordlift.php';
147
+require plugin_dir_path(__FILE__).'includes/class-wordlift.php';
148 148
 
149 149
 /**
150 150
  * Begins execution of the plugin.
@@ -164,12 +164,12 @@  discard block
 block discarded – undo
164 164
 	 * @return bool
165 165
 	 * @since 3.27.6
166 166
 	 */
167
-	if ( apply_filters( 'wl_feature__enable__widgets', true ) ) {
168
-		add_action( 'widgets_init', 'wl_register_chord_widget' );
169
-		add_action( 'widgets_init', 'wl_register_geo_widget' );
170
-		add_action( 'widgets_init', 'wl_register_timeline_widget' );
167
+	if (apply_filters('wl_feature__enable__widgets', true)) {
168
+		add_action('widgets_init', 'wl_register_chord_widget');
169
+		add_action('widgets_init', 'wl_register_geo_widget');
170
+		add_action('widgets_init', 'wl_register_timeline_widget');
171 171
 	}
172
-	add_filter( 'widget_text', 'do_shortcode' );
172
+	add_filter('widget_text', 'do_shortcode');
173 173
 
174 174
 	/**
175 175
 	 * Filter: wl_feature__enable__analysis
@@ -179,10 +179,10 @@  discard block
 block discarded – undo
179 179
 	 * @return bool
180 180
 	 * @since 3.27.6
181 181
 	 */
182
-	if ( apply_filters( 'wl_feature__enable__analysis', true ) ) {
183
-		add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_action' );
182
+	if (apply_filters('wl_feature__enable__analysis', true)) {
183
+		add_action('wp_ajax_wl_analyze', 'wl_ajax_analyze_action');
184 184
 	} else {
185
-		add_action( 'wp_ajax_wl_analyze', 'wl_ajax_analyze_disabled_action' );
185
+		add_action('wp_ajax_wl_analyze', 'wl_ajax_analyze_disabled_action');
186 186
 	}
187 187
 
188 188
 	$plugin = new Wordlift();
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
 
200 200
 	add_action(
201 201
 		'plugins_loaded',
202
-		function () {
202
+		function() {
203 203
 			// All features from registry should be initialized here.
204 204
 			$features_registry = Features_Registry::get_instance();
205 205
 			$features_registry->initialize_all_features();
@@ -210,27 +210,27 @@  discard block
 block discarded – undo
210 210
 	add_action(
211 211
 		'plugins_loaded',
212 212
 		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
213
-		function () use ( $plugin ) {
213
+		function() use ($plugin) {
214 214
 
215 215
 			new Wordlift_Products_Navigator_Shortcode_REST();
216 216
 
217 217
 			// Register the Dataset module, requires `$api_service`.
218
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/dataset/index.php';
219
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/shipping-data/index.php';
218
+			require_once plugin_dir_path(__FILE__).'wordlift/dataset/index.php';
219
+			require_once plugin_dir_path(__FILE__).'wordlift/shipping-data/index.php';
220 220
 
221 221
 			/*
222 222
 			* Require the Entity annotation cleanup module.
223 223
 			*
224 224
 			* @since 3.34.6
225 225
 			*/
226
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/cleanup/index.php';
226
+			require_once plugin_dir_path(__FILE__).'wordlift/cleanup/index.php';
227 227
 
228 228
 			/*
229 229
 			* Import LOD entities.
230 230
 			*
231 231
 			* @since 3.35.0
232 232
 			*/
233
-			require_once plugin_dir_path( __FILE__ ) . 'wordlift/lod-import/index.php';
233
+			require_once plugin_dir_path(__FILE__).'wordlift/lod-import/index.php';
234 234
 
235 235
 		}
236 236
 	);
@@ -248,23 +248,23 @@  discard block
 block discarded – undo
248 248
 function wordlift_plugin_autoload_register() {
249 249
 
250 250
 	spl_autoload_register(
251
-		function ( $class_name ) {
251
+		function($class_name) {
252 252
 
253 253
 			// Bail out if these are not our classes.
254
-			if ( 0 !== strpos( $class_name, 'Wordlift\\' ) ) {
254
+			if (0 !== strpos($class_name, 'Wordlift\\')) {
255 255
 				return false;
256 256
 			}
257 257
 
258
-			$class_name_lc = strtolower( str_replace( '_', '-', $class_name ) );
258
+			$class_name_lc = strtolower(str_replace('_', '-', $class_name));
259 259
 
260
-			preg_match( '|^(?:(.*)\\\\)?(.+?)$|', $class_name_lc, $matches );
260
+			preg_match('|^(?:(.*)\\\\)?(.+?)$|', $class_name_lc, $matches);
261 261
 
262
-			$path = str_replace( '\\', DIRECTORY_SEPARATOR, $matches[1] );
263
-			$file = 'class-' . $matches[2] . '.php';
262
+			$path = str_replace('\\', DIRECTORY_SEPARATOR, $matches[1]);
263
+			$file = 'class-'.$matches[2].'.php';
264 264
 
265
-			$full_path = plugin_dir_path( __FILE__ ) . $path . DIRECTORY_SEPARATOR . $file;
265
+			$full_path = plugin_dir_path(__FILE__).$path.DIRECTORY_SEPARATOR.$file;
266 266
 
267
-			if ( ! file_exists( $full_path ) ) {
267
+			if ( ! file_exists($full_path)) {
268 268
 				return false;
269 269
 			}
270 270
 
@@ -276,13 +276,13 @@  discard block
 block discarded – undo
276 276
 
277 277
 }
278 278
 
279
-function wl_block_categories( $categories ) {
279
+function wl_block_categories($categories) {
280 280
 	return array_merge(
281 281
 		$categories,
282 282
 		array(
283 283
 			array(
284 284
 				'slug'  => 'wordlift',
285
-				'title' => __( 'WordLift', 'wordlift' ),
285
+				'title' => __('WordLift', 'wordlift'),
286 286
 			),
287 287
 		)
288 288
 	);
@@ -292,45 +292,45 @@  discard block
 block discarded – undo
292 292
  * This function is created temporarily to handle the legacy library,
293 293
  * this has to be removed when removing the legacy fields from the ui.
294 294
  */
295
-function wl_enqueue_leaflet( $in_footer = false ) {
295
+function wl_enqueue_leaflet($in_footer = false) {
296 296
 	// Leaflet.
297
-	wp_enqueue_style( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.css', array(), '1.6.0' );
298
-	wp_enqueue_script( 'wl-leaflet', plugin_dir_url( __FILE__ ) . 'js/leaflet/leaflet.js', array(), '1.6.0', $in_footer );
297
+	wp_enqueue_style('wl-leaflet', plugin_dir_url(__FILE__).'js/leaflet/leaflet.css', array(), '1.6.0');
298
+	wp_enqueue_script('wl-leaflet', plugin_dir_url(__FILE__).'js/leaflet/leaflet.js', array(), '1.6.0', $in_footer);
299 299
 }
300 300
 
301
-add_filter( 'block_categories', 'wl_block_categories', 10 );
301
+add_filter('block_categories', 'wl_block_categories', 10);
302 302
 
303 303
 // Temporary fix for a typo in WooCommerce Extension.
304 304
 add_filter(
305 305
 	'wl_feature__enable__dataset',
306
-	function ( $value ) {
307
-		return apply_filters( 'wl_features__enable__dataset', $value );
306
+	function($value) {
307
+		return apply_filters('wl_features__enable__dataset', $value);
308 308
 	}
309 309
 );
310 310
 
311
-require_once __DIR__ . '/modules/food-kg/load.php';
312
-require_once __DIR__ . '/modules/acf4so/load.php';
313
-require_once __DIR__ . '/modules/pods/load.php';
314
-require_once __DIR__ . '/modules/include-exclude-push-config/load.php';
311
+require_once __DIR__.'/modules/food-kg/load.php';
312
+require_once __DIR__.'/modules/acf4so/load.php';
313
+require_once __DIR__.'/modules/pods/load.php';
314
+require_once __DIR__.'/modules/include-exclude-push-config/load.php';
315 315
 
316 316
 add_action(
317 317
 	'update_plugins_adthrive.wordlift.io',
318
-	function ( $update, $plugin_data, $plugin_file ) {
318
+	function($update, $plugin_data, $plugin_file) {
319 319
 		// Bail out if it's not our plugin.
320 320
 		$update_uri = $plugin_data['UpdateURI'];
321
-		if ( 'wordlift/wordlift.php' !== $plugin_file || ! isset( $update_uri ) ) {
321
+		if ('wordlift/wordlift.php' !== $plugin_file || ! isset($update_uri)) {
322 322
 			return $update;
323 323
 		}
324 324
 
325
-		$response = wp_remote_get( "$update_uri?nocache=" . time() );
325
+		$response = wp_remote_get("$update_uri?nocache=".time());
326 326
 
327
-		if ( is_wp_error( $response ) ) {
327
+		if (is_wp_error($response)) {
328 328
 			return $update;
329 329
 		}
330 330
 
331 331
 		try {
332
-			return json_decode( wp_remote_retrieve_body( $response ) );
333
-		} catch ( Exception $e ) {
332
+			return json_decode(wp_remote_retrieve_body($response));
333
+		} catch (Exception $e) {
334 334
 			return $update;
335 335
 		}
336 336
 	},
Please login to merge, or discard this patch.