Skip to content
This repository has been archived by the owner on Jun 1, 2021. It is now read-only.

Commit

Permalink
Merge pull request #10 from lpedretti/master
Browse files Browse the repository at this point in the history
Improved error handling/logging on api requests and added Opportunity resource
  • Loading branch information
lpedretti authored Oct 12, 2017
2 parents 7cf571e + cf594bd commit 7a74ed9
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 13 deletions.
17 changes: 15 additions & 2 deletions src/CRM.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
use Doctrine\Common\Inflector\Inflector;
use GuzzleHttp\Client;
use ProsperWorks\Endpoints\Endpoint;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;

/**
* CRM API entry-point.
Expand Down Expand Up @@ -71,10 +73,20 @@ abstract class CRM
const RES_TASK = 'Task';
const RES_PROJECT = 'Project';
const RES_ACTIVITY = 'Activity';


static $container;

public static function client()
{
static $client;

self::$container = [];
$history = Middleware::history(self::$container);

$stack = HandlerStack::create();
// Add the history middleware to the handler stack.
$stack->push($history);

if (!$client) {
$client = new Client([
'base_uri' => 'https://api.prosperworks.com/developer_api/v1/',
Expand All @@ -83,7 +95,8 @@ public static function client()
'X-PW-UserEmail' => Config::email(),
'X-PW-AccessToken' => Config::token(),
'Content-Type' => 'application/json'
]
],
'handler' => $stack
]);
}
return $client;
Expand Down
23 changes: 21 additions & 2 deletions src/Endpoints/BaseEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
use ProsperWorks\RateLimit;
use ProsperWorks\Resources\BareResource;
use Psr\Http\Message\ResponseInterface;
use Phalcon\Logger;
use Phalcon\Logger\Adapter\File as FileLogger;

/**
* Provides normalization and HTTP request methods to real resources.
Expand Down Expand Up @@ -88,6 +90,8 @@ public function getUri() { return $this->uri; }
*/
protected function request(string $method, $path = '', array $options = [])
{
$config = $this->di->get('config');

//TODO: replace with is_iterable() at PHP 7.1
if (is_array($path) || $path instanceof \Traversable) {
return $this->requestMany($method, $path);
Expand All @@ -97,7 +101,22 @@ protected function request(string $method, $path = '', array $options = [])
} elseif (Config::debugLevel() >= Config::DEBUG_BASIC) {
echo strtoupper($method) . " $this->uri/$path\n";
}
$response = $this->client->$method("$this->uri/$path", $options);

try {
$response = $this->client->$method("$this->uri/$path", $options);
} catch (\RuntimeException $e) {
// Log the error and the last request info
$logger = new FileLogger($config['application']['loggingDir'] . date("d_m_y") . "-pwintegration.log");
$error = "Exception " . $e->getMessage() . "\n";

$transaction = end(CRM::$container);
$error .= ( (string) $transaction['request']->getBody() ); // Hello World
foreach ($transaction['request']->getHeaders() as $header) {
$error .= print_r($header, true);
}
$logger->log("Sync exception: " . $error, Logger::INFO);
}

RateLimit::do()->pushRequest();
return $this->processResponse($response);
}
Expand Down Expand Up @@ -204,4 +223,4 @@ protected function processError(ClientException $error)
{
return $this->processResponse($error->getResponse());
}
}
}
16 changes: 16 additions & 0 deletions src/Resources/Opportunity.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php
namespace ProsperWorks\Resources;

use ProsperWorks\SubResources\Address;
use ProsperWorks\SubResources\CustomField;
use ProsperWorks\SubResources\Phone;
use ProsperWorks\SubResources\URL;

/**
* Opportunity resource object.
* @author lpedretti
*/
class Opportunity extends BareResource
{
}

25 changes: 16 additions & 9 deletions src/SubResources/CustomField.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,31 +69,38 @@ public function __construct(string $idOrName, $value = null, $resource = null)
$this->options = $field->options ?? [];

//validating $resource and options, if available
if ($resource && !in_array($resource, $this->resources)) {
throw new InvalidArg("You requested a field ($idOrName) that is not available for ($resource).");
}

if (is_array($value) && $this->type != "MultiSelect") {
throw new InvalidArg("Invalid multiple values for field $name that is not a MultiSelect field.");
}

if ($resource && !in_array($resource, $this->resources)) {
throw new InvalidArg("You requested a field ($idOrName) that is not available for ($resource).");
}

if ($this->options && $value) {
if (!is_array($value)) $value = [$value];

foreach ($value as $val) {
if (!is_numeric($val)) {
$valueName = $val;
$val = array_flip($this->options)[$val] ?? false;
if ($val == "") {
$valueName = "";
$id = null;
} else {
$valueName = $val;
$id = array_flip($this->options)[$val] ?? false;
}
} else {
$valueName = $this->options[$val] ?? false;
$id = $val;
}

if (!$val || !$valueName) {
if ( $valueName !== "" && (!$id || !$valueName) ) {
$name = ($resource ? "$resource." : '') . $idOrName;
$options = implode(', ', $this->options);
throw new InvalidArg("Invalid value ($value) for field $name. Valid options are: $options");

throw new InvalidArg("Invalid value ($val) for field $name. Valid options are: $options");
} else {
$values[] = $val;
$values[] = $id;
}
}

Expand Down

0 comments on commit 7a74ed9

Please sign in to comment.