From c68aefb847b09daa0697de7684d3451e2e68ce1e Mon Sep 17 00:00:00 2001
From: Jake Vanderwerf <get@jakevanderwerf.ca>
Date: Thu, 09 Jul 2026 23:10:23 +0000
Subject: [PATCH] =Refactor of Integrations.php to be a bit more useful with a suite of methods for create, update, delete back and forths for integrations where sharing is enabled. Also considering a single instance with a connect method to connect as the site (no user) vs connecting as an individual user - rather than recreating instances for every user.
---
inc/integrations/Integrations.php | 671 +++++++++++++++++++++++++++++++++++++++++++++++--------
1 files changed, 567 insertions(+), 104 deletions(-)
diff --git a/inc/integrations/Integrations.php b/inc/integrations/Integrations.php
index 54f4cf4..f7ce033 100644
--- a/inc/integrations/Integrations.php
+++ b/inc/integrations/Integrations.php
@@ -3,6 +3,9 @@
use Exception;
use JVBase\managers\Cache;
+use JVBase\managers\queue\executors\IntegrationExecutor;
+use JVBase\managers\queue\mergers\DefaultMerger;
+use JVBase\managers\queue\TypeConfig;
use JVBase\meta\Form;
use JVBase\meta\Meta;
use JVBase\managers\ErrorHandler;
@@ -10,8 +13,11 @@
use JVBase\registrar\Registrar;
use WP_Error;
use WP_Post;
+use WP_Query;
use WP_REST_Request;
use WP_REST_Response;
+use WP_Term;
+use WP_User;
if (!defined('ABSPATH')) {
exit;
@@ -28,6 +34,21 @@
*/
abstract class Integrations
{
+ //Flag to allow for custom settings (defaults, etc) for an integration in the dashboard
+ public static bool $hasExtraOptions = false;
+ public bool $hasBatchCreate = false;
+ public bool $hasBatchUpdate = false;
+ public bool $hasBatchDelete = false;
+ public bool $canCreateOnUpdate = false;
+ /**
+ * Queue types
+ * These types match with IntegrationExecutor
+ */
+ protected static string $syncTo;
+ protected static string $deleteFrom;
+ protected static string $syncFrom;
+ protected static string $syncCustomer;
+ protected static string $import;
/**
* API Configuration
* These properties define how the integration connects to external services
@@ -57,7 +78,7 @@
* Used for UI rendering in admin interfaces
*/
public string $title; // Human-readable service name (e.g., 'Google My Business')
- public string $icon; // Phosphoricons icon slug
+ public string $icon = ''; // Phosphoricons icon slug
/**
* Credentials & State
@@ -166,7 +187,7 @@
protected bool $is_healthy = true;
protected bool $handleWebhooks = false;
- public function __construct(?int $userID = null)
+ protected function __construct(?int $userID = null)
{
$this->cacheName = $this->cacheName ?: $this->service_name;
$this->userID = $userID;
@@ -197,9 +218,20 @@
];
}
+ self::$syncTo = $this->service_name.'_sync_to';
+ self::$deleteFrom = $this->service_name.'_delete_from';
+ self::$syncFrom = $this->service_name.'_sync_from';
+ //TODO: What is the difference between sync_from and import?
+ self::$import = $this->service_name.'import_from';
+
add_filter('jvbShouldRenderMeta', [$this, 'checkRenderField'], 10, 4);
}
+ protected function addFilters():bool
+ {
+ return is_null($this->userID);
+ }
+
protected function setContentTypes():void
{
@@ -294,21 +326,7 @@
protected function getPostTypes(): void
{
- $key = BASE . $this->service_name . '_sync_post_types';
- $postTypes = get_option($key, false);
- if (!$postTypes) {
- $postTypes = [];
- foreach (Registrar::getRegistered('post') as $registrar) {
- $registrar = Registrar::getInstance($registrar);
- if ($registrar->hasIntegration($this->service_name)) {
- $postTypes[] = $registrar->getSlug();
- }
- }
-
- update_option($key, $postTypes);
- }
-
- $this->syncPostTypes = $postTypes;
+ $this->syncPostTypes = Registrar::withIntegration($this->service_name);
}
protected function getTaxonomies():void
@@ -319,7 +337,8 @@
if (!$taxonomies) {
// Combine both content and taxonomy filtering
$taxonomies = [];
- foreach (Registrar::getFeatured('is_content', 'term') as $registrar) {
+ foreach (Registrar::withFeature('is_content', 'term') as $type) {
+ $registrar = Registrar::getInstance($type);
if ($registrar->hasIntegration($this->service_name)) {
$taxonomies[] = $registrar->getSlug();
}
@@ -668,9 +687,9 @@
protected function clearCache():array
{
- $success = $this->cache->flush();
+ $this->cache->flush();
return [
- 'success' => $success,
+ 'success' => true,
];
}
@@ -1039,11 +1058,8 @@
):bool {
$queue = JVB()->queue();
- // Add service prefix to operation type
- $operation_type = strtolower($this->service_name) . '_' . $type;
-
$queued = $queue->queueOperation(
- $operation_type,
+ $type,
$this->userID ?? 0,
array_merge($data, ['service' => $this->service_name, 'user' => $this->userID??0]),
array_merge([
@@ -1185,31 +1201,85 @@
*/
protected function registerHooks(): void
{
- add_filter(BASE . 'handle_bulk_operation', [$this, 'processOperation'], 10, 3);
- add_action( 'wp_ajax_'.BASE.$this->service_name.'_oauth_callback', [$this, 'handleAjaxResponse'] );
- add_action( 'wp_ajax_nopriv_'.BASE.$this->service_name.'_oauth_callback', [$this, 'handleAjaxResponse'] );
- if ($this->handleWebhooks){
+ //Handled by IntegrationExecutor now
+// add_filter(BASE . 'handle_bulk_operation', [$this, 'processOperation'], 10, 3);
+ if (is_null($this->userID)) {
+ add_action( 'wp_ajax_'.BASE.$this->service_name.'_oauth_callback', [$this, 'handleAjaxResponse'] );
+ add_action( 'wp_ajax_nopriv_'.BASE.$this->service_name.'_oauth_callback', [$this, 'handleAjaxResponse'] );
+ }
+
+ if ($this->handleWebhooks && is_null($this->userID)){
$this->registerWebhookEndpoint();
}
// Let child classes register additional hooks if needed
$this->registerAdditionalHooks();
- if (!empty($this->syncPostTypes)) {
- add_action('save_post', [$this, 'handleSavePost'], 20, 3);
+ if (!empty($this->syncPostTypes) && is_null($this->userID)) {
+ $this->addSavePost();
add_action('transition_post_status', [$this, 'handlePostStatusTransition'], 10, 3);
if ($this->canSync['delete']) {
add_action('before_delete_post', [$this, 'handleDeletePost'], 10, 1);
}
}
- if (!empty($this->syncTaxonomies)) {
+ if (!empty($this->syncTaxonomies) && is_null($this->userID)) {
add_action('saved_term', [$this, 'handleSaveTerm'], 20, 5);
if ($this->canSync['delete']) {
add_action('pre_delete_term', [$this, 'handleDeleteTerm'], 10, 2);
}
}
- }
+ add_action('init', [$this, 'registerQueueTypes'], 10);
+ }
+ public function addSavePost():void
+ {
+ if (!has_action('save_post', [$this, 'handleSavePost'])) {
+ add_action('save_post', [$this, 'handleSavePost'], 20, 3);
+ }
+ }
+ public function removeSavePost():void
+ {
+ remove_action('save_post', [$this, 'handleSavePost'], 20, 3);
+ }
+
+
+ public function registerQueueTypes():void
+ {
+ if (empty($this->syncTaxonomies) && empty($this->syncPostTypes)) {
+ return;
+ }
+ $queue = JVB()->queue();
+ $executor = new IntegrationExecutor();
+
+ $queue->registry()->register(self::$syncTo, new TypeConfig(
+ mergeable: new DefaultMerger('items'),
+ executor: $executor,
+ chunkKey: 'items',
+ chunkSize: 50,
+ maxRetries: 3,
+ ));
+
+ if ($this->canSync['delete']) {
+ $queue->registry()->register(self::$deleteFrom, new TypeConfig(
+ mergeable: new DefaultMerger('external_ids'),
+ executor: $executor,
+ chunkKey: 'external_ids',
+ chunkSize: 200,
+ maxRetries: 2
+ ));
+ }
+
+ $queue->registry()->register(self::$syncFrom, new TypeConfig(
+ executor: $executor,
+ maxRetries: 3
+ ));
+
+ $this->registerAdditionalQueueTypes($executor);
+ }
+ protected function registerAdditionalQueueTypes(IntegrationExecutor $executor):void
+ {
+ //Empty. Integration extensions can register additional operation types from here.
+ }
public function handleAjaxResponse()
{
@@ -1412,51 +1482,6 @@
}
- /**
- * Switch user context
- */
- public function switchUser(int $user_id): void
- {
- if ($this->userID === $user_id) {
- return;
- }
-
- // Clean up current context
- $this->cleanup();
-
- // Switch context
- $this->userID = $user_id;
- $this->credentials = [];
- $this->resetTokenRefreshFlag(); // ADD THIS LINE
-
- $this->ensureInitialized();
- }
-
- public function getAsUser(int $user_id) {
- return new $this($user_id);
- }
-
- /**
- * Clean up resources
- */
- protected function cleanup(): void
- {
- // Clear sensitive data
- $this->credentials = [];
-
- // Clear request history
- $this->request_history = [];
- }
-
- /**
- * Destructor - ensure cleanup
- */
- public function __destruct()
- {
- $this->cleanup();
- }
-
-
/***************************************************************
ERROR HANDLING
***************************************************************/
@@ -2123,6 +2148,11 @@
*/
public function handleSavePost(int $postID, WP_Post $post, bool $update): void
{
+ if (!is_null($this->userID)) {
+ return;
+ }
+ error_log('=== ['.$this->service_name.']::handleSavePost called');
+
if (!$postID || $postID === 0) {
return;
}
@@ -2131,40 +2161,50 @@
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if (wp_is_post_revision($postID)) return;
+
+ if (empty($this->syncPostTypes) || !in_array(jvbNoBase($postType), $this->syncPostTypes)) {
+ error_log('Not handling save for '.$this->service_name.' because there are no syncPostTypes: '.print_r($this->syncPostTypes, true));
+ return;
+ }
+
$registrar = Registrar::getInstance($postType);
if (!$registrar){
return;
}
- if (empty($this->syncPostTypes)) {
- return;
- }
-
$settings = $registrar->hasIntegration($this->service_name)??null;
if (!$settings) {
+ error_log('Not handling save for '.$this->service_name.' because of no registrar settings');
return;
}
$settings = $registrar->getIntegrationConfig($this->service_name);
if (!$settings){
+ error_log('Not handling save for '.$this->service_name.' because of no integration config '.print_r($settings, true));
return;
}
$fields = $this->getSyncFields($postID, 'post', ['schedule_'.$this->service_name]);
if (!$fields['share_to_'.$this->service_name]) {
+ error_log('Not handling save for '.$this->service_name.' because of no share_to_'.$this->service_name.' '.print_r($fields, true));
return;
}
$isShared = isset($fields["_{$this->service_name}_item_id"]);
if ($update && $isShared && !$fields['_keep_synced_'.$this->service_name]) {
+ error_log('Not handling save for '.$this->service_name.' because it is already shared, and not set to keep synced. ');
return;
}
if ($post->post_status !== 'publish' && !$isShared) {
+ error_log('Not handling save for '.$this->service_name.' because post status is not publish, and it is not already shared.');
return;
}
+ error_log('==== Sending to integration\'s handleTheSavePost '.$this->service_name.' ====');
+ $this->removeSavePost();
$this->handleTheSavePost($postID, $post, $update, $settings);
+ $this->addSavePost();
}
@@ -2704,6 +2744,20 @@
return $this->title;
}
+ public static function title():string
+ {
+ return static::getInstance()->getTitle();
+ }
+ public static function icon():string
+ {
+ return static::getInstance()->getIcon();
+ }
+
+ public static function hasExtraOptions():bool
+ {
+ return static::getInstance()::$hasExtraOptions;
+ }
+
/*********************************************************************
RENDERING
*********************************************************************/
@@ -2944,7 +2998,7 @@
?>
<form id="<?=$this->service_name?>" class="integration <?php echo $is_connected ? 'connected' : 'disconnected'; ?>"
data-service="<?php echo esc_attr($this->service_name); ?>">
- <div class="header row btw">
+ <div class="header row x-btw">
<h3><?php echo esc_html($this->title); ?></h3>
<div class="setup">
<?php if ($is_connected): ?>
@@ -3055,7 +3109,7 @@
}
?>
</div>
- <div class="actions row btw wrap">
+ <div class="actions row x-btw wrap">
<?php
foreach ($this->buttons as $action => $label) {
if (!$is_connected && $action !== 'save_credentials') {
@@ -3339,27 +3393,10 @@
return [];
}
- $key = BASE.$this->service_name.'_enabled_content_types';
- $enabled = get_option($key);
- if (!$enabled) {
- $enabled = [];
- foreach (Registrar::getRegistered() as $registrar) {
- $registrar = Registrar::getInstance($registrar);
- if (!$registrar->hasIntegration($this->service_name)) {
- continue;
- }
- $type = $registrar->getIntegration($this->service_name)->getContent_type();
- if (!$type) {
- continue;
- }
-
- if (!in_array($type, $enabled)) {
- $enabled[] = $type;
- }
- }
- update_option($key, $enabled);
- }
- return $enabled;
+ return array_filter(array_map(function($registrar) {
+ $registrar = Registrar::getInstance($registrar);
+ return $registrar->getIntegration($this->service_name)->getContentType();
+ }, Registrar::withIntegration($this->service_name)));
}
protected function getSupportedImage(int $imgID):int
@@ -3542,4 +3579,430 @@
{
return [];
}
+
+ public function getIcon():string
+ {
+ return $this->icon;
+ }
+
+ public function getServiceItemID(int $itemID, string $type = 'post'):string
+ {
+ return match($type) {
+ 'post' => Meta::forPost($itemID)->get("_{$this->service_name}_item_id"),
+ 'term','taxonomy' => Meta::forTerm($itemID)->get("_{$this->service_name}_item_id"),
+ 'user' => Meta::forUser($itemID)->get("_{$this->service_name}_item_id"),
+ default => ''
+ };
+ }
+
+ public function canBatchUpdate():bool
+ {
+ return $this->hasBatchUpdate;
+ }
+ public function canBatchCreate():bool
+ {
+ return $this->hasBatchCreate;
+ }
+ public function canBatchDelete():bool
+ {
+ return $this->hasBatchDelete;
+ }
+
+ protected function updateItemStatus(int|array $items, string $status = 'pending', string $type = 'post'):void
+ {
+ if (!is_array($items)) {
+ $items = [$items];
+ }
+ foreach ($items as $ID) {
+ match ($type) {
+ 'post' => Meta::forPost($ID)->set('_'.$this->service_name.'_sync_status', $status),
+ 'term' => Meta::forTerm($ID)->set('_'.$this->service_name.'_sync_status', $status),
+ 'user' => Meta::forUser($ID)->set('_'.$this->service_name.'_sync_status', $status),
+ default => false
+ };
+ }
+ }
+
+ public function updateBatchToService(array $data):array
+ {
+ $type = $data['type']??'post';
+
+ $newlyCreated = [];
+ if (!$this->canCreateOnUpdate) {
+ $created = array_filter($data['items'], function($ID) use ($type) {
+ return !empty($this->getServiceItemID($ID, $type));
+ });
+
+ //Test to see if we have any that haven't been created yet.
+ //For some services, items may have to be created before they can be updated
+ if (count($created) !== count($data['items'])) {
+ $notCreated = array_filter($data['items'], function($ID) use ($type) {
+ return empty($this->getServiceItemID($ID, $type));
+ });
+ $newData = $data;
+ $newData['items'] = $notCreated;
+ $newlyCreated = $this->createBatchToService($newData);
+ }
+
+ // If we don't have any that are created, just send the noUpdatedItems response, with any newly created items added
+ if (empty($created)) {
+ return $this->noUpdatedItems($newlyCreated);
+ }
+ $data['items'] = $created;
+ }
+
+
+ $items = $this->formatItems($data['items'], $type);
+
+ if (empty($items)) {
+ return $this->noUpdatedItems($newlyCreated);
+ }
+
+ if ($this->hasBatchUpdate) {
+ $response = $this->sendBatchUpdate($items);
+ if (!is_wp_error($response)) {
+ $result = $this->processBatchUpdateResponse($data, $response);
+ } else {
+ $this->logError('Batch update failed',[
+ 'method' => 'updateBatchToService',
+ 'item_ids' => $data['items'],
+ 'error' => $response
+ ]);
+ $this->updateItemStatus($data['items'], 'error');
+
+ $result = [
+ 'outcome' => 'failed_permanent',
+ 'result' => 'Could not update items'
+ ];
+ }
+ } else {
+ $success = $errors = [];
+ //Does not have batch update, manually update each one
+ foreach ($items as $item) {
+ $itemResult = $this->updateOne($item);
+ if (!is_wp_error($itemResult)) {
+ $success[] = $itemResult;
+ } else {
+ $errors[] = $itemResult;
+ }
+ }
+
+ $result = [
+ 'outcome' => empty($errors) ? 'success' : (empty($success) ? 'failed' : 'partial'),
+ 'result' => [
+ 'success' => $success,
+ 'errors' => $errors
+ ]
+ ];
+ }
+
+ return array_merge($result, $newlyCreated);
+ }
+
+ /**
+ * To be implemented by integration extension. Updates a single item
+ * @param array $item
+ * @return array|WP_Error
+ */
+ protected function updateOne(array $item):array|WP_Error
+ {
+ return new WP_Error('invalid', 'Integration '.$this->service_name.' must implement its own updateOne method');
+ }
+
+ /**
+ * Overridden by child classes
+ * @param array $items
+ * @return array|WP_Error
+ */
+ protected function sendBatchUpdate(array $items):array|WP_Error
+ {
+ return new WP_Error('invalid', 'Integration '.$this->service_name.' must implement its own sendBatchUpdate');
+ }
+ /**
+ * Overridden by child classes
+ * @param array $items
+ * @return array|WP_Error
+ */
+ protected function sendBatchCreate(array $items):array|WP_Error
+ {
+ return new WP_Error('invalid', 'Integration '.$this->service_name.' must implement its own sendBatchCreate');
+ }
+
+ /**
+ * To be implemented by extensions
+ * @param array $data
+ * @param array $response
+ * @return array
+ */
+ protected function processBatchUpdateResponse(array $data, array $response):array
+ {
+ return [
+ 'outcome' => 'failed',
+ 'result' => [
+ 'message' => $this->service_name.' should implement processBatchUpdateResponse.'
+ ]
+ ];
+ }
+ /**
+ * To be implemented by extensions
+ * @param array $data
+ * @param array $response
+ * @return array
+ */
+ protected function processBatchCreateResponse(array $data, array $response):array
+ {
+ return [
+ 'outcome' => 'failed',
+ 'result' => [
+ 'message' => $this->service_name.' should implement processBatchCreateResponse.'
+ ]
+ ];
+ }
+
+ /**
+ * Defaults to an array of formatted items. Can be overridden in child classes
+ * @param array $itemIDs
+ * @param string $type
+ * @return array
+ */
+ protected function formatItems(array $itemIDs, string $type):array
+ {
+ $items = [];
+ foreach ($itemIDs as $ID) {
+ try {
+ $items[] = $this->formatForService($ID, $type);
+ } catch (Exception $e){
+ $this->logError('Could not format Item for service',[
+ 'itemID' => $ID,
+ 'type' => $type,
+ 'message' => $e->getMessage(),
+ ]);
+ }
+ }
+ return $items;
+ }
+
+ /**
+ * Must be defined according to how each service needs it to be
+ * @param int $itemID
+ * @param string $type
+ * @return array
+ * @throws Exception
+ */
+ protected function formatForService(int $itemID, string $type = 'post'):array
+ {
+ throw new Exception('formatForService must be implemented by child class');
+ }
+ protected function noUpdatedItems(array $created):array
+ {
+ $result = [
+ 'outcome' => 'success',
+ 'result' => [
+ 'message' => 'No items to update',
+ 'updated' => [],
+ 'errors' => [],
+ ]
+ ];
+
+ if (!empty($created)) {
+ error_log('Result before: '.print_r($result, true));
+ $result = array_merge($result, $created);
+ error_log('Result after merge: '.print_r($result, true));
+ }
+ return $result;
+ }
+
+ protected function noCreatedItems(array $updated):array
+ {
+ $result = [
+ 'outcome' => 'success',
+ 'result' => [
+ 'message' => 'No items to create',
+ 'created' => [],
+ 'errors' => [],
+ ]
+ ];
+ if (!empty($updated)) {
+ $result = array_merge($result, $updated);
+ }
+ return $result;
+ }
+
+ public function createBatchToService($data):array
+ {
+ $type = $data['type']??'post';
+
+ //Check if any of the submitted ids are already created
+ $created = array_filter($data['items'],
+ function($ID) use ($type) {
+ return !empty($this->getServiceItemID($ID, $type));
+ });
+
+ $updated = [];
+ if (!empty($created)) {
+ $updateData = $data;
+ $updateData['items'] = $created;
+ $updated = $this->updateBatchToService($data);
+
+ //remove any updated items from the original items to process
+ $data['items'] = array_filter($data['items'], function ($ID) use ($created) {
+ return !in_array($ID, $created);
+ });
+ }
+
+ $items = $this->formatItems($data['items'], $type);
+ if (empty($items)) {
+ return $this->noCreatedItems($updated);
+ }
+
+ $response = [
+ 'outcome' => 'failed',
+ 'result' => [
+ 'message' => 'No result'
+ ]
+ ];
+ if ($this->hasBatchCreate) {
+ $response = $this->sendBatchCreate($items);
+ if (!is_wp_error($response)) {
+ $result = $this->processBatchCreateResponse($data, $response);
+ } else {
+ $this->logError('Batch create failed',[
+ 'method' => 'createBatchToService',
+ 'item_ids' => $data['items'],
+ 'error' => $response
+ ]);
+ $this->updateItemStatus($data['items'], 'error');
+
+ $result = [
+ 'outcome' => 'failed_permanent',
+ 'result' => 'Could not update items'
+ ];
+ }
+ } else {
+ $success = $errors = [];
+ foreach ($items as $item) {
+ $itemResult = $this->createOne($item);
+ if (!is_wp_error($itemResult)) {
+ $success[] = $itemResult;
+ } else {
+ $errors[] = $itemResult;
+ }
+ }
+ $result = [
+ 'outcome' => empty($errors) ? 'success' : (empty($success) ? 'failed' : 'partial'),
+ 'result' => [
+ 'success' => $success,
+ 'errors' => $errors
+ ]
+ ];
+ }
+
+ return array_merge($result, $updated);
+ }
+
+ /**
+ * To be implemented by integration extension. Updates a single item
+ * @param array $item
+ * @return array|WP_Error
+ */
+ protected function createOne(array $item):array|WP_Error
+ {
+ return new WP_Error('invalid', 'Integration '.$this->service_name.' must implement its own createOne');
+ }
+
+ public function findWPItem(string $integrationID, ?string $type = null):array|false
+ {
+ if (empty($integrationID)) {
+ error_log('Integrations::findWPItem No Integration ID received.');
+ return false;
+ }
+ $types = ['post', 'term', 'user'];
+ if (!is_null($type) && !in_array($type, $types)) {
+ error_log('Integrations::findWPItem invalid type sent: '.$type.'; defaulting to checking all');
+ $type = null;
+ }
+ if (!is_null($type)) {
+ return $this->queryWPType($integrationID, $type);
+ } else {
+ foreach ($types as $type) {
+ $check = $this->queryWPType($integrationID, $type);
+ if ($check) {
+ return $check;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * @param string $integrationID
+ * @param string|null $type
+ * @return array|false if success, an array of $ID and $type
+ */
+ public function queryWPType(string $integrationID, ?string $type = null):array|false
+ {
+ if (!in_array($type, ['post', 'term', 'user'])) {
+ return $this->findWPItem($integrationID);
+ }
+ return match($type) {
+ 'post' => $this->findWPPost($integrationID),
+ 'term' => $this->findWPTerm($integrationID),
+ 'user' => $this->findWPUser($integrationID),
+ default => false
+ };
+ }
+ public function findWPPost(string $integrationID):array|false
+ {
+ if (empty($integrationID)) {
+ return false;
+ }
+ $get = new WP_Query([
+ 'meta_query' => [
+ 'key' => BASE."_{$this->service_name}_item_id",
+ 'value' => $integrationID,
+ ],
+ 'fields' => 'ids',
+ 'posts_per_page' => 1,
+ ]);
+ return $get->have_posts() && !empty($get->posts) ? [$get->posts[0], 'post'] : false;
+ }
+ public function findWPTerm(string $integrationID):array|false
+ {
+ if (empty($integrationID)) {
+ return false;
+ }
+ $get = get_terms([
+ 'meta_query' => [
+ 'key' => BASE."_{$this->service_name}_item_id",
+ 'value' => $integrationID,
+ ],
+ 'fields' => 'ids',
+ 'hide_empty'=> true,
+ 'number' => 1
+ ]);
+ return is_wp_error($get) || empty($get) ? false : [$get[0], 'term'];
+ }
+ public function findWPUser(string $integrationID):array|false
+ {
+ if (empty($integrationID)) {
+ return false;
+ }
+ $get = get_users([
+ 'meta_query' => [
+ 'key' => BASE."_{$this->service_name}_item_id",
+ 'value' => $integrationID,
+ ],
+ 'fields' => 'ids',
+ 'number' => 1,
+ ]);
+ return is_wp_error($get) || empty($get) ? false : [$get[0], 'user'];
+ }
+
+ /*********************************************************************************
+ * Syncing WP items from Service
+ *********************************************************************************/
+ protected function createItemFromService(array $itemData):bool
+ {
+
+ }
}
--
Gitblit v1.10.0