PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 27.7
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v27.7
28.6 28.5 28.4 28.3 28.2 28.1 28.0 27.9 27.8 27.7 27.6 27.5 trunk 18.0 18.1 18.2 18.3 18.4 18.4.1 18.5 18.5.1 18.6 18.7 18.8 18.9 All 130 releases
wordpress-seo / src / actions / wincher / wincher-keyphrases-action.php

wincher-keyphrases-action.php in Yoast SEO – Advanced SEO with real-time guidance and built-in AI 27.7, at src/actions/wincher/wincher-keyphrases-action.php

362 lines 9.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Yoast\WP\SEO\Actions\Wincher;
4
5 use Exception;
6 use WP_Post;
7 use WPSEO_Utils;
8 use Yoast\WP\SEO\Config\Wincher_Client;
9 use Yoast\WP\SEO\Helpers\Options_Helper;
10 use Yoast\WP\SEO\Repositories\Indexable_Repository;
11
12 /**
13 * Class Wincher_Keyphrases_Action
14 */
15 class Wincher_Keyphrases_Action {
16
17 /**
18 * The Wincher keyphrase URL for bulk addition.
19 *
20 * @var string
21 */
22 public const KEYPHRASES_ADD_URL = 'https://api.wincher.com/beta/websites/%s/keywords/bulk';
23
24 /**
25 * The Wincher tracked keyphrase retrieval URL.
26 *
27 * @var string
28 */
29 public const KEYPHRASES_URL = 'https://api.wincher.com/beta/yoast/%s';
30
31 /**
32 * The Wincher delete tracked keyphrase URL.
33 *
34 * @var string
35 */
36 public const KEYPHRASE_DELETE_URL = 'https://api.wincher.com/beta/websites/%s/keywords/%s';
37
38 /**
39 * The Wincher_Client instance.
40 *
41 * @var Wincher_Client
42 */
43 protected $client;
44
45 /**
46 * The Options_Helper instance.
47 *
48 * @var Options_Helper
49 */
50 protected $options_helper;
51
52 /**
53 * The Indexable_Repository instance.
54 *
55 * @var Indexable_Repository
56 */
57 protected $indexable_repository;
58
59 /**
60 * Wincher_Keyphrases_Action constructor.
61 *
62 * @param Wincher_Client $client The API client.
63 * @param Options_Helper $options_helper The options helper.
64 * @param Indexable_Repository $indexable_repository The indexables repository.
65 */
66 public function __construct(
67 Wincher_Client $client,
68 Options_Helper $options_helper,
69 Indexable_Repository $indexable_repository
70 ) {
71 $this->client = $client;
72 $this->options_helper = $options_helper;
73 $this->indexable_repository = $indexable_repository;
74 }
75
76 /**
77 * Sends the tracking API request for one or more keyphrases.
78 *
79 * @param string|array $keyphrases One or more keyphrases that should be tracked.
80 * @param Object $limits The limits API call response data.
81 *
82 * @return Object The reponse object.
83 */
84 public function track_keyphrases( $keyphrases, $limits ) {
85 try {
86 $endpoint = \sprintf(
87 self::KEYPHRASES_ADD_URL,
88 $this->options_helper->get( 'wincher_website_id' ),
89 );
90
91 // Enforce arrrays to ensure a consistent way of preparing the request.
92 if ( ! \is_array( $keyphrases ) ) {
93 $keyphrases = [ $keyphrases ];
94 }
95
96 // Calculate if the user would exceed their limit.
97 // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- To ensure JS code style, this can be ignored.
98 if ( ! $limits->canTrack || $this->would_exceed_limits( $keyphrases, $limits ) ) {
99 $response = [
100 'limit' => $limits->limit,
101 'error' => 'Account limit exceeded',
102 'status' => 400,
103 ];
104
105 return $this->to_result_object( $response );
106 }
107
108 $formatted_keyphrases = \array_values(
109 \array_map(
110 static function ( $keyphrase ) {
111 return [
112 'keyword' => $keyphrase,
113 'groups' => [],
114 ];
115 },
116 $keyphrases,
117 ),
118 );
119
120 $results = $this->client->post( $endpoint, WPSEO_Utils::format_json_encode( $formatted_keyphrases ) );
121
122 if ( ! \array_key_exists( 'data', $results ) ) {
123 return $this->to_result_object( $results );
124 }
125
126 // The endpoint returns a lot of stuff that we don't want/need.
127 $results['data'] = \array_map(
128 static function ( $keyphrase ) {
129 return [
130 'id' => $keyphrase['id'],
131 'keyword' => $keyphrase['keyword'],
132 ];
133 },
134 $results['data'],
135 );
136
137 $results['data'] = \array_combine(
138 \array_column( $results['data'], 'keyword' ),
139 \array_values( $results['data'] ),
140 );
141
142 return $this->to_result_object( $results );
143 } catch ( Exception $e ) {
144 return (object) [
145 'error' => $e->getMessage(),
146 'status' => $e->getCode(),
147 ];
148 }
149 }
150
151 /**
152 * Sends an untrack request for the passed keyword ID.
153 *
154 * @param int $keyphrase_id The ID of the keyphrase to untrack.
155 *
156 * @return object The response object.
157 */
158 public function untrack_keyphrase( $keyphrase_id ) {
159 try {
160 $endpoint = \sprintf(
161 self::KEYPHRASE_DELETE_URL,
162 $this->options_helper->get( 'wincher_website_id' ),
163 $keyphrase_id,
164 );
165
166 $this->client->delete( $endpoint );
167
168 return (object) [
169 'status' => 200,
170 ];
171 } catch ( Exception $e ) {
172 return (object) [
173 'error' => $e->getMessage(),
174 'status' => $e->getCode(),
175 ];
176 }
177 }
178
179 /**
180 * Gets the keyphrase data for the passed keyphrases.
181 * Retrieves all available data if no keyphrases are provided.
182 *
183 * @param array|null $used_keyphrases The currently used keyphrases. Optional.
184 * @param string|null $permalink The current permalink. Optional.
185 * @param string|null $start_at The position start date. Optional.
186 *
187 * @return object The keyphrase chart data.
188 */
189 public function get_tracked_keyphrases( $used_keyphrases = null, $permalink = null, $start_at = null ) {
190 try {
191 $used_keyphrases ??= $this->collect_all_keyphrases();
192
193 // If we still have no keyphrases the API will return an error, so
194 // don't even bother sending a request.
195 if ( empty( $used_keyphrases ) ) {
196 return $this->to_result_object(
197 [
198 'data' => [],
199 'status' => 200,
200 ],
201 );
202 }
203
204 $endpoint = \sprintf(
205 self::KEYPHRASES_URL,
206 $this->options_helper->get( 'wincher_website_id' ),
207 );
208
209 $results = $this->client->post(
210 $endpoint,
211 WPSEO_Utils::format_json_encode(
212 [
213 'keywords' => $used_keyphrases,
214 'url' => $permalink,
215 'start_at' => $start_at,
216 ],
217 ),
218 [
219 'timeout' => 60,
220 ],
221 );
222
223 if ( ! \array_key_exists( 'data', $results ) ) {
224 return $this->to_result_object( $results );
225 }
226
227 $results['data'] = $this->filter_results_by_used_keyphrases( $results['data'], $used_keyphrases );
228
229 // Extract the positional data and assign it to the keyphrase.
230 $results['data'] = \array_combine(
231 \array_column( $results['data'], 'keyword' ),
232 \array_values( $results['data'] ),
233 );
234
235 return $this->to_result_object( $results );
236 } catch ( Exception $e ) {
237 return (object) [
238 'error' => $e->getMessage(),
239 'status' => $e->getCode(),
240 ];
241 }
242 }
243
244 /**
245 * Collects the keyphrases associated with the post.
246 *
247 * @param WP_Post $post The post object.
248 *
249 * @return array The keyphrases.
250 */
251 public function collect_keyphrases_from_post( $post ) {
252 $keyphrases = [];
253 $primary_keyphrase = $this->indexable_repository
254 ->query()
255 ->select( 'primary_focus_keyword' )
256 ->where( 'object_id', $post->ID )
257 ->find_one();
258
259 if ( $primary_keyphrase ) {
260 $keyphrases[] = $primary_keyphrase->primary_focus_keyword;
261 }
262
263 /**
264 * Filters the keyphrases collected by the Wincher integration from the post.
265 *
266 * @param array $keyphrases The keyphrases array.
267 * @param int $post_id The ID of the post.
268 */
269 return \apply_filters( 'wpseo_wincher_keyphrases_from_post', $keyphrases, $post->ID );
270 }
271
272 /**
273 * Collects all keyphrases known to Yoast.
274 *
275 * @return array
276 */
277 protected function collect_all_keyphrases() {
278 // Collect primary keyphrases first.
279 $keyphrases = \array_column(
280 $this->indexable_repository
281 ->query()
282 ->select( 'primary_focus_keyword' )
283 ->where_not_null( 'primary_focus_keyword' )
284 ->where( 'object_type', 'post' )
285 ->where_not_equal( 'post_status', 'trash' )
286 ->distinct()
287 ->find_array(),
288 'primary_focus_keyword',
289 );
290
291 /**
292 * Filters the keyphrases collected by the Wincher integration from all the posts.
293 *
294 * @param array $keyphrases The keyphrases array.
295 */
296 $keyphrases = \apply_filters( 'wpseo_wincher_all_keyphrases', $keyphrases );
297
298 // Filter out empty entries.
299 return \array_filter( $keyphrases );
300 }
301
302 /**
303 * Filters the results based on the passed keyphrases.
304 *
305 * @param array $results The results to filter.
306 * @param array $used_keyphrases The used keyphrases.
307 *
308 * @return array The filtered results.
309 */
310 protected function filter_results_by_used_keyphrases( $results, $used_keyphrases ) {
311 return \array_filter(
312 $results,
313 static function ( $result ) use ( $used_keyphrases ) {
314 return \in_array( $result['keyword'], \array_map( 'strtolower', $used_keyphrases ), true );
315 },
316 );
317 }
318
319 /**
320 * Determines whether the amount of keyphrases would mean the user exceeds their account limits.
321 *
322 * @param string|array $keyphrases The keyphrases to be added.
323 * @param object $limits The current account limits.
324 *
325 * @return bool Whether the limit is exceeded.
326 */
327 protected function would_exceed_limits( $keyphrases, $limits ) {
328 if ( ! \is_array( $keyphrases ) ) {
329 $keyphrases = [ $keyphrases ];
330 }
331
332 if ( $limits->limit === null ) {
333 return false;
334 }
335
336 return ( \count( $keyphrases ) + $limits->usage ) > $limits->limit;
337 }
338
339 /**
340 * Converts the passed dataset to an object.
341 *
342 * @param array $result The result dataset to convert to an object.
343 *
344 * @return object The result object.
345 */
346 protected function to_result_object( $result ) {
347 if ( \array_key_exists( 'data', $result ) ) {
348 $result['results'] = (object) $result['data'];
349
350 unset( $result['data'] );
351 }
352
353 if ( \array_key_exists( 'message', $result ) ) {
354 $result['error'] = $result['message'];
355
356 unset( $result['message'] );
357 }
358
359 return (object) $result;
360 }
361 }
362