| 1 |
<?php |
| 2 |
|
| 3 |
namespace Yoast\WP\SEO\Actions\SEMrush; |
| 4 |
|
| 5 |
use Exception; |
| 6 |
use Yoast\WP\SEO\Config\SEMrush_Client; |
| 7 |
|
| 8 |
/** |
| 9 |
* Class SEMrush_Phrases_Action |
| 10 |
*/ |
| 11 |
class SEMrush_Phrases_Action { |
| 12 |
|
| 13 |
/** |
| 14 |
* The transient cache key. |
| 15 |
*/ |
| 16 |
const TRANSIENT_CACHE_KEY = 'wpseo_semrush_related_keyphrases_%s_%s'; |
| 17 |
|
| 18 |
/** |
| 19 |
* The SEMrush keyphrase URL. |
| 20 |
* |
| 21 |
* @var string |
| 22 |
*/ |
| 23 |
const KEYPHRASES_URL = 'https://oauth.semrush.com/api/v1/keywords/phrase_fullsearch'; |
| 24 |
|
| 25 |
/** |
| 26 |
* The SEMrush_Client instance. |
| 27 |
* |
| 28 |
* @var SEMrush_Client |
| 29 |
*/ |
| 30 |
protected $client; |
| 31 |
|
| 32 |
/** |
| 33 |
* SEMrush_Phrases_Action constructor. |
| 34 |
* |
| 35 |
* @param SEMrush_Client $client The API client. |
| 36 |
*/ |
| 37 |
public function __construct( SEMrush_Client $client ) { |
| 38 |
$this->client = $client; |
| 39 |
} |
| 40 |
|
| 41 |
/** |
| 42 |
* Gets the related keyphrases and data based on the passed keyphrase and database country code. |
| 43 |
* |
| 44 |
* @param string $keyphrase The keyphrase to search for. |
| 45 |
* @param string $database The database's country code. |
| 46 |
* |
| 47 |
* @return object The response object. |
| 48 |
*/ |
| 49 |
public function get_related_keyphrases( $keyphrase, $database ) { |
| 50 |
try { |
| 51 |
$transient_key = \sprintf( static::TRANSIENT_CACHE_KEY, $keyphrase, $database ); |
| 52 |
$transient = \get_transient( $transient_key ); |
| 53 |
|
| 54 |
if ( $transient !== false ) { |
| 55 |
return $this->to_result_object( $transient ); |
| 56 |
} |
| 57 |
|
| 58 |
$options = [ |
| 59 |
'params' => [ |
| 60 |
'phrase' => $keyphrase, |
| 61 |
'database' => $database, |
| 62 |
'export_columns' => 'Ph,Nq,Td', |
| 63 |
'display_limit' => 10, |
| 64 |
'display_offset' => 0, |
| 65 |
'display_sort' => 'nq_desc', |
| 66 |
'display_filter' => '%2B|Nq|Lt|1000', |
| 67 |
], |
| 68 |
]; |
| 69 |
|
| 70 |
$results = $this->client->get( self::KEYPHRASES_URL, $options ); |
| 71 |
|
| 72 |
\set_transient( $transient_key, $results, \DAY_IN_SECONDS ); |
| 73 |
|
| 74 |
return $this->to_result_object( $results ); |
| 75 |
} catch ( Exception $e ) { |
| 76 |
return (object) [ |
| 77 |
'error' => $e->getMessage(), |
| 78 |
'status' => $e->getCode(), |
| 79 |
]; |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
/** |
| 84 |
* Converts the passed dataset to an object. |
| 85 |
* |
| 86 |
* @param array $result The result dataset to convert to an object. |
| 87 |
* |
| 88 |
* @return object The result object. |
| 89 |
*/ |
| 90 |
protected function to_result_object( $result ) { |
| 91 |
return (object) [ |
| 92 |
'results' => $result['data'], |
| 93 |
'status' => $result['status'], |
| 94 |
]; |
| 95 |
} |
| 96 |
} |
| 97 |
|
| 98 |
|