create TwingleProjecr.sync api

This commit is contained in:
Marc Michalsky forumZFD 2021-01-26 14:53:06 +01:00
commit 7a520e850c
Signed by untrusted user who does not match committer: marc.koch
GPG key ID: 12406554CFB028B9
5 changed files with 650 additions and 283 deletions

View file

@ -1,6 +1,8 @@
<?php
use CRM_TwingleCampaign_BAO_TwingleProject as TwingleProject;
use CRM_TwingleCampaign_ExtensionUtil as E;
class CRM_TwingleCampaign_BAO_TwingleApiCall {
@ -14,6 +16,8 @@ class CRM_TwingleCampaign_BAO_TwingleApiCall {
private $limit;
private $extensionName;
/**
* TwingleApiCall constructor.
*
@ -25,30 +29,39 @@ class CRM_TwingleCampaign_BAO_TwingleApiCall {
*
* @throws API_Exception
*/
public function __construct(string $apiKey, int $limit) {
public function __construct(string $apiKey, int $limit = 20) {
$this->apiKey = $apiKey;
$this->limit = $limit;
$this->extensionName = E::LONG_NAME;
// Get organisation id
$curl = curl_init($this->protocol . 'organisation' . $this->baseUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
"x-access-code: $apiKey",
'Content-Type: application/json',
]);
// Try to retrieve organisation id from cache
$this->organisationId = Civi::cache()
->get('twinglecampaign_organisation_id');
$response = json_decode(curl_exec($curl), TRUE);
curl_close($curl);
// else: retrieve organisation id via Twingle api
if (NULL === $this->organisationId) {
if (empty($response)) {
// Delete api key from cache
Civi::cache()->delete('twinglecampaign_twingle_api');
// Throw exception
throw new API_Exception(
"Twingle API call failed. Please check your api key.");
$curl = curl_init($this->protocol . 'organisation' . $this->baseUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
"x-access-code: $apiKey",
'Content-Type: application/json',
]);
$response = json_decode(curl_exec($curl), TRUE);
curl_close($curl);
if (empty($response)) {
// Delete api key from cache
Civi::cache()->delete('twinglecampaign_twingle_api');
// Throw exception
throw new API_Exception(
"Twingle API call failed. Please check your api key.");
}
$this->organisationId = array_column($response, 'id')[0];
Civi::cache('long')->set('twinglecampaign_organisation_id',
$this->organisationId);
}
$this->organisationId = array_column($response, 'id')[0];
}
/**
@ -60,10 +73,8 @@ class CRM_TwingleCampaign_BAO_TwingleApiCall {
* @param int|null $projectId
*
* @return mixed
* @throws \Exception
*/
public function getProject(int $projectId = NULL) {
$response = [];
$url = empty($projectId)
? $this->protocol . 'project' . $this->baseUrl . 'by-organisation/' . $this->organisationId
@ -81,22 +92,11 @@ class CRM_TwingleCampaign_BAO_TwingleApiCall {
*
* @return array
* Returns a response array that contains title, id, project_id and status
* @throws \Exception
*/
public function pushProject(TwingleProject &$project) {
try {
$values = $project->export();
} catch (Exception $e) {
// Log Exception
$errorMessage = $e->getMessage();
Civi::log()->error(
"Could not export TwingleProject values: $errorMessage"
);
// Return result array with error description
return $project->getResponse(
"Could not export TwingleProject values: $errorMessage"
);
}
$values = $project->export();
// Prepare url for curl
if ($values['id']) {
@ -121,8 +121,7 @@ class CRM_TwingleCampaign_BAO_TwingleApiCall {
*
* @return array
*/
public
function getEvent($projectId, $eventId = NULL) {
public function getEvent($projectId, $eventId = NULL) {
$result = [];
$url = empty($eventId)
@ -144,13 +143,22 @@ class CRM_TwingleCampaign_BAO_TwingleApiCall {
'public' => 0,
];
$response = $this->curlGet($url, $params);
$finished = ($eventId) || count($response['data']) < $this->limit;
$offset = $offset + $this->limit;
// If no $eventId was given, expect one or more events.
// Store the events, increase the offset and ask again until there
// are no more events incoming.
if ($response['data'] && !$eventId) {
$result = array_merge($result, $response['data']);
$offset = $offset + $this->limit;
$finished = count($response['data']) < $this->limit;
}
// If $eventId was given, expect only one event
else {
$result = $response['data'];
// If result the array contains 'message', the $eventId does not exist
if (!$result['message']) {
$result = $response;
}
$finished = TRUE;
}
}
return $result;
@ -160,9 +168,10 @@ class CRM_TwingleCampaign_BAO_TwingleApiCall {
* @param $projectId
*
* @return array|NULL
* @throws \Exception
*/
public
function getProjectEmbedData($projectId) {
function getProjectEmbedData($projectId): array {
$result = $this->getProject($projectId);
@ -173,8 +182,9 @@ class CRM_TwingleCampaign_BAO_TwingleApiCall {
return $result['embed'];
}
else {
Civi::log()->error("Could not get embed data for project $projectId.");
return NULL;
throw new Exception(
"Could not get embed data for project $projectId."
);
}
}

View file

@ -2,7 +2,7 @@
use CRM_TwingleCampaign_Utils_ExtensionCache as Cache;
use CRM_TwingleCampaign_BAO_Campaign as Campaign;
use CRM_TwingleCampaign_BAO_TwingleApiCall as TwingleApiCall;
class CRM_TwingleCampaign_BAO_TwingleProject extends Campaign {
@ -12,176 +12,19 @@ class CRM_TwingleCampaign_BAO_TwingleProject extends Campaign {
* @param array $project
* Result array of Twingle API call to
* https://project.twingle.de/api/by-organisation/$organisation_id
*
* @param int|null $id
*
* @throws \Exception
*/
function __construct(array $project, int $id = NULL) {
parent::__construct($project);
public function __construct(array $project, int $id = NULL) {
parent::__construct($project, $id);
$this->id = $id;
$this->prefix = 'twingle_project_';
$this->values['campaign_type_id'] = 'twingle_project';
$this->id_custom_field = Cache::getInstance()
->getCustomFieldMapping()['twingle_project_id'];
}
/**
* Synchronizes projects between Twingle and CiviCRM (both directions)
* based on the timestamp.
*
* @param array $values
* @param TwingleApiCall $twingleApi
* @param bool $is_test
* If TRUE, don't do any changes
*
* @return array|null
* Returns a response array that contains title, id, project_id and status or
* NULL if $values is not an array
*
* @throws CiviCRM_API3_Exception
*/
public static function sync(
array $values,
TwingleApiCall $twingleApi,
bool $is_test = FALSE
): ?array {
// If $values is an array
if (is_array($values)) {
// Instantiate TwingleProject
try {
$project = new self($values);
} catch (Exception $e) {
$errorMessage = $e->getMessage();
// Log Exception
Civi::log()->error(
"Failed to instantiate TwingleProject: $errorMessage"
);
// Return result array with error description
return [
"title" => $values['name'],
"project_id" => (int) $values['id'],
"status" =>
"Failed to instantiate TwingleProject: $errorMessage",
];
}
// Check if the TwingleProject campaign already exists
if (!$project->exists()) {
// ... if not, get embed data and create project
try {
$project->setEmbedData(
$twingleApi->getProjectEmbedData($project->getProjectId())
);
$result = $project->create($is_test);
} catch (Exception $e) {
$errorMessage = $e->getMessage();
// Log Exception
Civi::log()->error(
"Could not create campaign from TwingleProject: $errorMessage"
);
// Return result array with error description
return [
"title" => $values['name'],
"project_id" => (int) $values['id'],
"status" =>
"Could not create campaign from TwingleProject: $errorMessage",
];
}
}
else {
$result = $project->getResponse('TwingleProject exists');
// If Twingle's version of the project is newer than the CiviCRM
// TwingleProject campaign update the campaign
if ($values['last_update'] > $project->lastUpdate()) {
try {
$project->update($values);
$project->setEmbedData(
$twingleApi->getProjectEmbedData($project->getProjectId())
);
$result = $project->create();
$result['status'] = $result['status'] == 'TwingleProject created'
? 'TwingleProject updated'
: 'TwingleProject Update failed';
} catch (Exception $e) {
$errorMessage = $e->getMessage();
// Log Exception
Civi::log()->error(
"Could not update TwingleProject campaign: $errorMessage"
);
// Return result array with error description
$result = $project->getResponse(
"Could not update TwingleProject campaign: $errorMessage"
);
}
}
// If the CiviCRM TwingleProject campaign was changed, update the project
// on Twingle's side
elseif ($values['last_update'] < $project->lastUpdate()) {
// If this is a test do not make database changes
if ($is_test) {
$result = $project->getResponse(
'TwingleProject ready to push'
);
}
else {
$result = $twingleApi->pushProject($project);
// Update TwingleProject in Civi with results from api call
if (is_array($result) && !array_key_exists('message', $result)) {
// Try to update the local TwingleProject campaign
try {
$project->update($result);
$project->create();
return $project->getResponse('TwingleProject pushed to Twingle');
} catch (Exception $e) {
// Log Exception
$errorMessage = $e->getMessage();
Civi::log()->error(
"Could not push TwingleProject campaign: $errorMessage"
);
// Return result array with error description
return $project->getResponse(
"TwingleProject was likely pushed to Twingle but the local " .
"update of the campaign failed: $errorMessage"
);
}
}
else {
$message = $result['message'];
return $project->getResponse(
$message
? "TwingleProject could not get pushed to Twingle: $message"
: 'TwingleProject could not get pushed to Twingle'
);
}
}
}
elseif ($result['status'] == 'TwingleProject exists') {
$result = $project->getResponse('TwingleProject up to date');
}
}
// Return the result of the synchronization
return $result;
}
else {
return NULL;
}
}
/**
* Export values. Ensures that only those values will be exported which the
@ -214,59 +57,52 @@ class CRM_TwingleCampaign_BAO_TwingleProject extends Campaign {
/**
* Create the Campaign as a campaign in CiviCRM if it does not exist
*
* @param bool $is_test
* If true: don't do any changes
* @param bool $no_hook
* Do not trigger postSave hook to prevent recursion
*
* @return array
* Returns a response array that contains title, id, project_id and status
* @return bool
* Returns a boolean
*
* @throws CiviCRM_API3_Exception
* @throws Exception
* @throws \Exception
*/
public function create(bool $is_test = FALSE): array {
public function create(bool $no_hook = FALSE): bool {
// Create campaign only if this is not a test
if (!$is_test) {
// Prepare project values for import into database
$values_prepared_for_import = $this->values;
self::formatValues(
$values_prepared_for_import,
self::IN
);
self::translateKeys(
$values_prepared_for_import,
self::IN
);
$this->translateCustomFields(
$values_prepared_for_import,
self::IN
);
// Prepare project values for import into database
$values_prepared_for_import = $this->values;
self::formatValues(
$values_prepared_for_import,
self::IN
);
self::translateKeys(
$values_prepared_for_import,
self::IN
);
$this->translateCustomFields(
$values_prepared_for_import,
self::IN
);
// Set id
$values_prepared_for_import['id'] = $this->id;
// Create campaign
$result = civicrm_api3('Campaign', 'create', $values_prepared_for_import);
// Update id
$this->id = $result['id'];
// Check if campaign was created successfully
if ($result['is_error'] == 0) {
$response = $this->getResponse("$this->className created");
}
else {
$response = $this->getResponse("$this->className creation failed");
}
// Set id
$values_prepared_for_import['id'] = $this->id;
// Set a flag to not trigger the hook
if ($no_hook) {
$_SESSION['CiviCRM']['de.forumzfd.twinglecampaign']['no_hook'] = TRUE;
}
// Create campaign
$result = civicrm_api3('Campaign', 'create', $values_prepared_for_import);
// Update id
$this->id = $result['id'];
// Check if campaign was created successfully
if ($result['is_error'] == 0) {
return TRUE;
}
// If this is a test, do not create campaign
else {
$response = $this->getResponse("$this->className not yet created");
throw new Exception($result['error_message']);
}
return $response;
}
@ -313,8 +149,8 @@ class CRM_TwingleCampaign_BAO_TwingleProject extends Campaign {
// Set default for 'allow_more'
$values['allow_more'] = empty($values['allow_more'])
? False
: True;
? FALSE
: TRUE;
}
else {
@ -388,21 +224,25 @@ class CRM_TwingleCampaign_BAO_TwingleProject extends Campaign {
/**
* Get a response that describes the status of a TwingleProject
*
* @param string $status
* status of the TwingleProject you want the response for
* @param string|null $status
* status of the TwingleProject you want to give back along with the response
*
* @return array
* Returns a response array that contains title, id, project_id and status
*/
public function getResponse(string $status): array {
public function getResponse(string $status = NULL): array {
$project_type = empty($this->values['type']) ? 'default' : $this->values['type'];
return [
'title' => $this->values['name'],
'id' => (int) $this->id,
'project_id' => (int) $this->values['id'],
'project_type' => $project_type,
'status' => $status,
];
$response =
[
'title' => $this->values['name'],
'id' => (int) $this->id,
'project_id' => (int) $this->values['id'],
'project_type' => $project_type,
];
if ($status) {
$response['status'] = $status;
}
return $response;
}
/**