Skip to content

v1.0.1 #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
],
"require": {
"php": ">=8.0",
"michaelj2324/php-rest-client": ">=3.0.2"
"michaelj2324/php-rest-client": ">=3.0.5"
},
"require-dev": {
"phpunit/phpunit": "9.*",
Expand Down
59 changes: 59 additions & 0 deletions examples/IntegrateApi.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

/**
* ©[2025] SugarCRM Inc. Licensed by SugarCRM under the Apache 2.0 license.
*/

require_once 'include.php';

$SugarAPI = new \Sugarcrm\REST\Client\SugarApi($server, $credentials);
$logger = new \ColinODell\PsrTestLogger\TestLogger();
$SugarAPI->getAuth()->setLogger($logger);
try {
if ($SugarAPI->isAuthenticated()) {
echo "Logged In: " . json_encode($SugarAPI->getAuth()->getToken(), JSON_PRETTY_PRINT) . "\n";

$account = $SugarAPI->module('Accounts');
$account->set([
'name' => 'Upsert Test Account',
'sync_key' => 'foobar',
]);
$account->upsert();
echo "Record: " . json_encode($account->toArray(), JSON_PRETTY_PRINT) . "\n";

$contact = $SugarAPI->module('Contacts');
$contact->set([
'first_name' => 'Upsert',
'last_name' => 'Test Contact',
]);
//Create a contact
$contact->save();
echo "Created Contact: " . $contact->getId() . "\n";

$integrate = $SugarAPI->integrate();
$integrate->fromBean($contact);
$integrate->setSyncKey('uniqueSyncKey');
if ($integrate->getResponse()->getStatusCode() == 200) {
echo "Contact Sync Key set: " . $contact->getSyncKey() . "\n";
}

$samecontact = $SugarAPI->integrate('Contacts');
$samecontact->getBySyncKey('uniqueSyncKey');
echo "Retrieved Contact by Sync Key: " . $samecontact->getId() . "\n";

$integrate->deleteBySyncKey();
echo "Deleted Contact: " . json_encode($account->toArray(), JSON_PRETTY_PRINT) . "\n";
} else {
echo "Could not login.";
print_r($logger->records);
$oauthEndpoint = $SugarAPI->getAuth()->getActionEndpoint('authenticate');
$response = $oauthEndpoint->getResponse();
if ($response) {
$statusCode = $oauthEndpoint->getResponse()->getStatusCode();
echo "[$statusCode] - " . $oauthEndpoint->getResponse()->getBody()->getContents();
}
}
} catch (Exception $ex) {
echo "Exception Occurred: " . $ex->getMessage();
echo $ex->getTraceAsString();
}
8 changes: 8 additions & 0 deletions src/Client/SugarApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@

namespace Sugarcrm\REST\Client;

use GuzzleHttp\Client;
use MRussell\REST\Auth\AuthControllerInterface;
use Psr\Http\Message\MessageInterface;
use Sugarcrm\REST\Endpoint\Generic;
use Sugarcrm\REST\Endpoint\Integrate;
use Sugarcrm\REST\Endpoint\MLPackage;
use Sugarcrm\REST\Endpoint\ModuleLoader;
use Sugarcrm\REST\Endpoint\Ping;
Expand Down Expand Up @@ -45,6 +47,7 @@
* @method Note note(string $id = null) -
* @method ModuleLoader moduleLoader() -
* @method MLPackage mlp(string $id = null)
* @method Integrate integrate(string $module = '', string $id = '')
*/
class SugarApi extends AbstractClient implements PlatformAwareInterface
{
Expand Down Expand Up @@ -108,6 +111,11 @@ public function __construct($server = '', array $credentials = [])
}
}

protected function initHttpClient(): void
{
$this->httpClient = new Client(['handler' => $this->getHandlerStack(),'verify' => false]);
}

/**
* Setup the default Auth Controller and EndpointProvider
*/
Expand Down
15 changes: 8 additions & 7 deletions src/Endpoint/Abstracts/AbstractSugarBeanCollectionEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,17 @@ abstract class AbstractSugarBeanCollectionEndpoint extends AbstractSugarCollecti

protected string $_modelInterface = SugarBean::class;

public function getCollectionResponseProp(): string
public function setUrlArgs(array $args): static
{
$prop = parent::getCollectionResponseProp();
return empty($prop) ? self::SUGAR_COLLECTION_RESP_PROP : $prop;
parent::setUrlArgs($args);
$this->syncModuleAndUrlArgs();
return $this;
}

public function setUrlArgs(array $args): static
public function getCollectionResponseProp(): string
{
$args = $this->configureModuleUrlArg($args);
return parent::setUrlArgs($args);
$prop = parent::getCollectionResponseProp();
return empty($prop) ? self::SUGAR_COLLECTION_RESP_PROP : $prop;
}

/**
Expand Down Expand Up @@ -102,7 +103,7 @@ protected function configurePayload(): mixed
*/
protected function configureURL(array $urlArgs): string
{
$urlArgs['module'] = $this->getModule();
$urlArgs = $this->addModuleToUrlArgs($urlArgs);
return parent::configureURL($urlArgs);
}

Expand Down
130 changes: 79 additions & 51 deletions src/Endpoint/Abstracts/AbstractSugarBeanEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@
use MRussell\REST\Traits\PsrLoggerTrait;
use Sugarcrm\REST\Endpoint\Data\FilterData;
use Sugarcrm\REST\Endpoint\AuditLog;
use Sugarcrm\REST\Endpoint\Integrate;
use Sugarcrm\REST\Endpoint\SugarEndpointInterface;
use Sugarcrm\REST\Endpoint\Traits\CompileRequestTrait;
use Sugarcrm\REST\Endpoint\Traits\FieldsDataTrait;
use Sugarcrm\REST\Endpoint\Traits\IntegrateSyncKeyTrait;
use Sugarcrm\REST\Endpoint\Traits\ModuleAwareTrait;

/**
Expand All @@ -39,14 +41,18 @@
* @method $this audit()
* @method $this file()
* @method $this duplicateCheck()
* @method $this upsert()
*/
abstract class AbstractSugarBeanEndpoint extends ModelEndpoint implements SugarEndpointInterface
{
use CompileRequestTrait;
use CompileRequestTrait {
compileRequest as private doCompileRequest;
}
use PsrLoggerTrait;
use ModuleAwareTrait;
use FieldsDataTrait;
use FileUploadsTrait;
use IntegrateSyncKeyTrait;

public const MODEL_ACTION_VAR = 'action';

Expand Down Expand Up @@ -80,19 +86,21 @@ abstract class AbstractSugarBeanEndpoint extends ModelEndpoint implements SugarE

public const BEAN_ACTION_DUPLICATE_CHECK = 'duplicateCheck';

public const BEAN_ACTION_ARG1_VAR = 'actionArg1';
public const BEAN_ACTION_UPSERT = 'upsert';

public const BEAN_ACTION_ARG1_VAR = 'actArg1';

public const BEAN_ACTION_ARG2_VAR = 'actionArg2';
public const BEAN_ACTION_ARG2_VAR = 'actArg2';

public const BEAN_ACTION_ARG3_VAR = 'actionArg3';
public const BEAN_ACTION_ARG3_VAR = 'actArg3';

public const BEAN_MODULE_URL_ARG = 'module';

/**
* @inheritdoc
*/
protected static array $_DEFAULT_PROPERTIES = [
self::PROPERTY_URL => '$module/$id/$:action/$:actionArg1/$:actionArg2/$:actionArg3',
self::PROPERTY_URL => '$module/$:id/$:action/$:actArg1/$:actArg2/$:actArg3',
self::PROPERTY_HTTP_METHOD => 'GET',
self::PROPERTY_AUTH => true,
];
Expand All @@ -116,6 +124,7 @@ abstract class AbstractSugarBeanEndpoint extends ModelEndpoint implements SugarE
self::BEAN_ACTION_ATTACH_FILE => "POST",
self::BEAN_ACTION_TEMP_FILE_UPLOAD => "POST",
self::BEAN_ACTION_DUPLICATE_CHECK => "POST",
self::BEAN_ACTION_UPSERT => "PATCH",
];

/**
Expand All @@ -139,21 +148,16 @@ public function __construct(array $urlArgs = [], array $properties = [])
}

/**
* Passed in options get changed such that 1st Option (key 0) becomes Module
* 2nd Option (Key 1) becomes ID
* @inheritdoc
*/
public function setUrlArgs(array $args): static
{
$args = $this->configureModuleUrlArg($args);
if (isset($args[1])) {
$this->set($this->getKeyProperty(), $args[1]);
unset($args[1]);
}

return parent::setUrlArgs($args);
parent::setUrlArgs($args);
$this->syncModuleAndUrlArgs();
return $this;
}


/**
* Configure Uploads on Request
* @inheritdoc
Expand All @@ -179,6 +183,16 @@ protected function configurePayload(): mixed
{
$data = $this->getData();
switch ($this->getCurrentAction()) {
case self::BEAN_ACTION_UPSERT:
$data->reset();
$data->set($this->toArray());
$syncKeyField = $this->getSyncKeyField();
if (!empty($syncKeyField)) {
$data[Integrate::DATA_SYNC_KEY_FIELD] = $syncKeyField;
}

$data[Integrate::DATA_SYNC_KEY_VALUE] = $this->getSyncKey();
return $data;
case self::MODEL_ACTION_CREATE:
case self::MODEL_ACTION_UPDATE:
$data->reset();
Expand Down Expand Up @@ -220,6 +234,10 @@ protected function parseResponse(Response $response): void
$this->clear();
$this->syncFromApi($this->parseResponseBodyToArray($body, $this->getModelResponseProp()));
return;
case self::BEAN_ACTION_UPSERT:
$body = $this->getResponseContent($response);
$this->syncFromApi($this->parseResponseBodyToArray($body, Integrate::INTEGRATE_RESPONSE_PROP));
return;
}
}

Expand Down Expand Up @@ -266,13 +284,21 @@ protected function resetUploads(): void
protected function configureURL(array $urlArgs): string
{
$action = null;
$urlArgs = $this->configureModuleUrlArg($urlArgs);
$urlArgs = $this->addModuleToUrlArgs($urlArgs);
switch ($this->getCurrentAction()) {
case self::BEAN_ACTION_CREATE_RELATED:
case self::BEAN_ACTION_MASS_RELATE:
case self::BEAN_ACTION_UNLINK:
case self::BEAN_ACTION_FILTER_RELATED:
$action = self::BEAN_ACTION_RELATE;
break;
case self::BEAN_ACTION_UPSERT:
$urlArgs[self::MODEL_ID_VAR] = Integrate::SYNC_KEY;
$syncKey = $this->getSyncKey();
if (!empty($syncKey)) {
$action = $syncKey;
}

break;
case self::BEAN_ACTION_TEMP_FILE_UPLOAD:
$urlArgs[self::MODEL_ID_VAR] = 'temp';
Expand Down Expand Up @@ -310,39 +336,43 @@ protected function configureURL(array $urlArgs): string
protected function configureAction(string $action, array $arguments = []): void
{
$urlArgs = $this->getUrlArgs();
if (isset($urlArgs[self::BEAN_ACTION_ARG1_VAR])) {
unset($urlArgs[self::BEAN_ACTION_ARG1_VAR]);
}

if (isset($urlArgs[self::BEAN_ACTION_ARG2_VAR])) {
unset($urlArgs[self::BEAN_ACTION_ARG2_VAR]);
}

if (isset($urlArgs[self::BEAN_ACTION_ARG3_VAR])) {
unset($urlArgs[self::BEAN_ACTION_ARG3_VAR]);
if (isset($urlArgs[self::MODEL_ACTION_VAR]) && $urlArgs[self::MODEL_ACTION_VAR] != $action) {
unset($urlArgs[self::MODEL_ACTION_VAR]);
}

if (!empty($arguments)) {
switch ($action) {
case self::BEAN_ACTION_TEMP_FILE_UPLOAD:
case self::BEAN_ACTION_ATTACH_FILE:
$this->_upload = true;
// no break
case self::BEAN_ACTION_RELATE:
case self::BEAN_ACTION_DOWNLOAD_FILE:
case self::BEAN_ACTION_UNLINK:
case self::BEAN_ACTION_CREATE_RELATED:
case self::BEAN_ACTION_FILTER_RELATED:
if (isset($arguments[0])) {
$urlArgs[self::BEAN_ACTION_ARG1_VAR] = $arguments[0];
if (isset($arguments[1])) {
$urlArgs[self::BEAN_ACTION_ARG2_VAR] = $arguments[1];
if (isset($arguments[2])) {
$urlArgs[self::BEAN_ACTION_ARG3_VAR] = $arguments[2];
}
switch ($action) {
case self::BEAN_ACTION_TEMP_FILE_UPLOAD:
case self::BEAN_ACTION_ATTACH_FILE:
$this->_upload = true;
// no break
case self::BEAN_ACTION_RELATE:
case self::BEAN_ACTION_DOWNLOAD_FILE:
case self::BEAN_ACTION_UNLINK:
case self::BEAN_ACTION_CREATE_RELATED:
case self::BEAN_ACTION_FILTER_RELATED:
if (isset($arguments[0])) {
$urlArgs[self::BEAN_ACTION_ARG1_VAR] = $arguments[0];
if (isset($arguments[1])) {
$urlArgs[self::BEAN_ACTION_ARG2_VAR] = $arguments[1];
if (isset($arguments[2])) {
$urlArgs[self::BEAN_ACTION_ARG3_VAR] = $arguments[2];
}
}
}
}

break;
default:
//If action is not defined above, remove action args
$actionArgs = [
self::BEAN_ACTION_ARG1_VAR,
self::BEAN_ACTION_ARG2_VAR,
self::BEAN_ACTION_ARG3_VAR,
];
foreach ($actionArgs as $actionArg) {
if (isset($urlArgs[$actionArg])) {
unset($urlArgs[$actionArg]);
}
}
}

$this->setUrlArgs($urlArgs);
Expand Down Expand Up @@ -542,13 +572,11 @@ protected function configureFileUploadQueryParams(): array
'delete_if_fails' => $this->_deleteFileOnFail,
];

if ($this->_deleteFileOnFail) {
if (!empty($this->_client)) {
$data['platform'] = $this->getClient()->getPlatform();
$token = $this->getClient()->getAuth()->getTokenProp('access_token');
if ($token) {
$data['oauth_token'] = $this->getClient()->getAuth()->getTokenProp('access_token');
}
if ($this->_deleteFileOnFail && !empty($this->_client)) {
$data['platform'] = $this->getClient()->getPlatform();
$token = $this->getClient()->getAuth()->getTokenProp('access_token');
if ($token) {
$data['oauth_token'] = $this->getClient()->getAuth()->getTokenProp('access_token');
}
}

Expand Down
Loading