Removing Dependency from SDK Core Project

- Copied files required for Rest API SDK
- Removed PPApiContext and directly connected APIContext with PPConfigManager
- Removed duplicate data storage of configuration and credentials.
- Code Style Fixes
- Remove build.xml file as it is not required anymore
- Updated the samples
- Updated the documentations
This commit is contained in:
japatel
2014-10-06 11:16:47 -05:00
parent bb7654b0b8
commit 49b80f76af
150 changed files with 10975 additions and 6525 deletions

View File

@@ -0,0 +1,163 @@
<?php
namespace PayPal\Core;
/**
* Class PPConfigManager
*
* PPConfigManager loads the SDK configuration file and
* hands out appropriate config params to other classes
*
* @package PayPal\Core
*/
class PPConfigManager
{
/**
* Configuration Options
*
* @var array
*/
private $configs = array(
"http.ConnectionTimeOut" => "30",
"http.Retry" => "5",
);
/**
* Singleton Object
*
* @var $this
*/
private static $instance;
/**
* Private Constructor
*/
private function __construct()
{
if (defined('PP_CONFIG_PATH')) {
$configFile = constant('PP_CONFIG_PATH') . '/sdk_config.ini';
} else {
$configFile = implode(DIRECTORY_SEPARATOR,
array(dirname(__FILE__), "..", "config", "sdk_config.ini"));
}
$this->addConfigFromIni($configFile);
}
/**
* Returns the singleton object
*
* @return $this
*/
public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Add Configuration from configuration.ini files
*
* @param string $fileName
* @return $this
*/
public function addConfigFromIni($fileName)
{
if ($configs = @parse_ini_file($fileName)) {
$this->addConfigs($configs);
}
return $this;
}
/**
* If a configuration exists in both arrays,
* then the element from the first array will be used and
* the matching key's element from the second array will be ignored.
*
* @param [] $config
* @return $this
*/
public function addConfigs($configs = [])
{
$this->configs = $configs + $this->configs;
return $this;
}
/**
* Simple getter for configuration params
* If an exact match for key is not found,
* does a "contains" search on the key
*
* @param string $searchKey
* @return array
*/
public function get($searchKey)
{
if (array_key_exists($searchKey, $this->configs)) {
return $this->configs[$searchKey];
} else {
$arr = array();
foreach ($this->configs as $k => $v) {
if (strstr($k, $searchKey)) {
$arr[$k] = $v;
}
}
return $arr;
}
}
/**
* Utility method for handling account configuration
* return config key corresponding to the API userId passed in
*
* If $userId is null, returns config keys corresponding to
* all configured accounts
*
* @param string|null $userId
* @return array|string
*/
public function getIniPrefix($userId = null)
{
if ($userId == null) {
$arr = array();
foreach ($this->configs as $key => $value) {
$pos = strpos($key, '.');
if (strstr($key, "acct")) {
$arr[] = substr($key, 0, $pos);
}
}
return array_unique($arr);
} else {
$iniPrefix = array_search($userId, $this->configs);
$pos = strpos($iniPrefix, '.');
$acct = substr($iniPrefix, 0, $pos);
return $acct;
}
}
/**
* returns the config file hashmap
*/
public function getConfigHashmap()
{
return $this->configs;
}
/**
* Disabling __clone call
*/
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace PayPal\Core;
/**
* Class PPConstants
* Placeholder for Paypal Constants
*
* @package PayPal\Core
*/
class PPConstants
{
const SDK_NAME = 'rest-api-sdk-php';
const SDK_VERSION = '0.11.0';
const REST_SANDBOX_ENDPOINT = "https://api.sandbox.paypal.com/";
const REST_LIVE_ENDPOINT = "https://api.paypal.com/";
}

View File

@@ -0,0 +1,167 @@
<?php
namespace PayPal\Core;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Exception\PPInvalidCredentialException;
/**
* Class PPCredentialManager
*
* PPCredentialManager holds all the credential information in one place.
*
* @package PayPal\Core
*/
class PPCredentialManager
{
/**
* Singleton Object
*
* @var self
*/
private static $instance;
/**
* Hashmap to contain credentials for accounts.
*
* @var array
*/
private $credentialHashmap = array();
/**
* Contains the API username of the default account to use
* when authenticating API calls
*
* @var string
*/
private $defaultAccountName;
/**
* Constructor initialize credential for multiple accounts specified in property file
*
* @param $config
* @throws \Exception
*/
private function __construct($config)
{
try {
$this->initCredential($config);
} catch (\Exception $e) {
$this->credentialHashmap = array();
throw $e;
}
}
/**
* Create singleton instance for this class.
*
* @param array|null $config
* @return PPCredentialManager
*/
public static function getInstance($config = null)
{
if (!self::$instance) {
self::$instance = new self($config == null ? PPConfigManager::getInstance()->getConfigHashmap() : $config);
}
return self::$instance;
}
/**
* Load credentials for multiple accounts, with priority given to Signature credential.
*
* @param [] $config
*/
private function initCredential($config)
{
$suffix = 1;
$prefix = "acct";
$arr = array();
foreach ($config as $k => $v) {
if (strstr($k, $prefix)) {
$arr[$k] = $v;
}
}
$credArr = $arr;
$arr = array();
foreach ($config as $key => $value) {
$pos = strpos($key, '.');
if (strstr($key, "acct")) {
$arr[] = substr($key, 0, $pos);
}
}
$arrayPartKeys = array_unique($arr);
$key = $prefix . $suffix;
$userName = null;
while (in_array($key, $arrayPartKeys)) {
if (isset($credArr[$key . ".ClientId"]) && isset($credArr[$key . ".ClientId"])) {
$userName = $key;
$this->credentialHashmap[$userName] = new OAuthTokenCredential(
$credArr[$key . ".ClientId"],
$credArr[$key . ".ClientSecret"]
);
}
if ($userName && $this->defaultAccountName == null) {
if (array_key_exists($key . '.UserName', $credArr)) {
$this->defaultAccountName = $credArr[$key . '.UserName'];
} else {
$this->defaultAccountName = $key;
}
}
$suffix++;
$key = $prefix . $suffix;
}
}
/**
* Sets credential object for users
*
* @param \PayPal\Auth\OAuthTokenCredential $credential
* @param string|null $userId User Id associated with the account
* @param bool $default If set, it would make it as a default credential for all requests
*
* @return $this
*/
public function setCredentialObject(OAuthTokenCredential $credential, $userId = null, $default = true)
{
$key = $userId == null ? 'default' : $userId;
$this->credentialHashmap[$key] = $credential;
if ($default) {
$this->defaultAccountName = $key;
}
return $this;
}
/**
* Obtain Credential Object based on UserId provided.
*
* @param null $userId
* @return OAuthTokenCredential
* @throws PPInvalidCredentialException
*/
public function getCredentialObject($userId = null)
{
if ($userId == null) {
$credObj = $this->credentialHashmap[$this->defaultAccountName];
} else if (array_key_exists($userId, $this->credentialHashmap)) {
$credObj = $this->credentialHashmap[$userId];
}
if (empty($credObj)) {
throw new PPInvalidCredentialException("Invalid userId $userId");
}
return $credObj;
}
/**
* Disabling __clone call
*/
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}

View File

@@ -0,0 +1,258 @@
<?php
namespace PayPal\Core;
use PayPal\Exception\PPConfigurationException;
/**
* Class PPHttpConfig
* Http Configuration Class
*
* @package PayPal\Core
*/
class PPHttpConfig
{
/**
* Some default options for curl
* These are typically overridden by PPConnectionManager
*
* @var array
*/
public static $defaultCurlOptions = array(
CURLOPT_SSLVERSION => 3,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 60, // maximum number of seconds to allow cURL functions to execute
CURLOPT_USERAGENT => 'PayPal-PHP-SDK',
CURLOPT_HTTPHEADER => array(),
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_SSL_VERIFYPEER => 1
);
const HEADER_SEPARATOR = ';';
const HTTP_GET = 'GET';
const HTTP_POST = 'POST';
private $headers = array();
private $curlOptions;
private $url;
private $method;
/***
* Number of times to retry a failed HTTP call
*/
private $retryCount = 0;
/**
* Default Constructor
*
* @param string $url
* @param string $method HTTP method (GET, POST etc) defaults to POST
*/
public function __construct($url = null, $method = self::HTTP_POST)
{
$this->url = $url;
$this->method = $method;
$this->curlOptions = self::$defaultCurlOptions;
}
/**
* Gets Url
*
* @return null|string
*/
public function getUrl()
{
return $this->url;
}
/**
* Gets Method
*
* @return string
*/
public function getMethod()
{
return $this->method;
}
/**
* Gets all Headers
*
* @return array
*/
public function getHeaders()
{
return $this->headers;
}
/**
* Get Header by Name
*
* @param $name
* @return string|null
*/
public function getHeader($name)
{
if (array_key_exists($name, $this->headers)) {
return $this->headers[$name];
}
return null;
}
/**
* Sets Url
*
* @param $url
*/
public function setUrl($url)
{
$this->url = $url;
}
/**
* Set Headers
*
* @param array $headers
*/
public function setHeaders(array $headers = [])
{
$this->headers = $headers;
}
/**
* Adds a Header
*
* @param $name
* @param $value
* @param bool $overWrite allows you to override header value
*/
public function addHeader($name, $value, $overWrite = true)
{
if (!array_key_exists($name, $this->headers) || $overWrite) {
$this->headers[$name] = $value;
} else {
$this->headers[$name] = $this->headers[$name] . self::HEADER_SEPARATOR . $value;
}
}
/**
* Removes a Header
*
* @param $name
*/
public function removeHeader($name)
{
unset($this->headers[$name]);
}
/**
* Gets all curl options
*
* @return array
*/
public function getCurlOptions()
{
return $this->curlOptions;
}
/**
* Add Curl Option
*
* @param string $name
* @param mixed $value
*/
public function addCurlOption($name, $value)
{
$this->curlOptions[$name] = $value;
}
/**
* Set Curl Options. Overrides all curl options
*
* @param $options
*/
public function setCurlOptions($options)
{
$this->curlOptions = $options;
}
/**
* Set ssl parameters for certificate based client authentication
*
* @param $certPath
* @param null $passPhrase
*/
public function setSSLCert($certPath, $passPhrase = null)
{
$this->curlOptions[CURLOPT_SSLCERT] = realpath($certPath);
if (isset($passPhrase) && trim($passPhrase) != "") {
$this->curlOptions[CURLOPT_SSLCERTPASSWD] = $passPhrase;
}
}
/**
* Set connection timeout in seconds
*
* @param integer $timeout
*/
public function setHttpTimeout($timeout)
{
$this->curlOptions[CURLOPT_CONNECTTIMEOUT] = $timeout;
}
/**
* Set HTTP proxy information
*
* @param string $proxy
* @throws PPConfigurationException
*/
public function setHttpProxy($proxy)
{
$urlParts = parse_url($proxy);
if ($urlParts == false || !array_key_exists("host", $urlParts)) {
throw new PPConfigurationException("Invalid proxy configuration " . $proxy);
}
$this->curlOptions[CURLOPT_PROXY] = $urlParts["host"];
if (isset($urlParts["port"])) {
$this->curlOptions[CURLOPT_PROXY] .= ":" . $urlParts["port"];
}
if (isset($urlParts["user"])) {
$this->curlOptions[CURLOPT_PROXYUSERPWD] = $urlParts["user"] . ":" . $urlParts["pass"];
}
}
/**
* Set Http Retry Counts
*
* @param int $retryCount
*/
public function setHttpRetryCount($retryCount)
{
$this->retryCount = $retryCount;
}
/**
* Get Http Retry Counts
*
* @return int
*/
public function getHttpRetryCount()
{
return $this->retryCount;
}
/**
* Sets the User-Agent string on the HTTP request
*
* @param string $userAgentString
*/
public function setUserAgent($userAgentString)
{
$this->curlOptions[CURLOPT_USERAGENT] = $userAgentString;
}
}

View File

@@ -0,0 +1,171 @@
<?php
namespace PayPal\Core;
use PayPal\Exception\PPConfigurationException;
use PayPal\Exception\PPConnectionException;
/**
* A wrapper class based on the curl extension.
* Requires the PHP curl module to be enabled.
* See for full requirements the PHP manual: http://php.net/curl
*/
class PPHttpConnection
{
/**
* @var PPHttpConfig
*/
private $httpConfig;
/**
* HTTP status codes for which a retry must be attempted
* retry is currently attempted for Request timeout, Bad Gateway,
* Service Unavailable and Gateway timeout errors.
*/
private static $retryCodes = array('408', '502', '503', '504',);
/**
* LoggingManager
*
* @var PPLoggingManager
*/
private $logger;
/**
* Default Constructor
*
* @param PPHttpConfig $httpConfig
* @param array $config
* @throws PPConfigurationException
*/
public function __construct(PPHttpConfig $httpConfig, array $config)
{
if (!function_exists("curl_init")) {
throw new PPConfigurationException("Curl module is not available on this system");
}
$this->httpConfig = $httpConfig;
$this->logger = new PPLoggingManager(__CLASS__, $config);
}
/**
* Gets all Http Headers
*
* @return array
*/
private function getHttpHeaders()
{
$ret = array();
foreach ($this->httpConfig->getHeaders() as $k => $v) {
$ret[] = "$k: $v";
}
return $ret;
}
/**
* Executes an HTTP request
*
* @param string $data query string OR POST content as a string
* @throws PPConnectionException
*/
/**
* Executes an HTTP request
*
* @param string $data query string OR POST content as a string
* @return mixed
* @throws PPConnectionException
*/
public function execute($data)
{
//Initialize the logger
$this->logger->fine("Connecting to " . $this->httpConfig->getUrl());
$this->logger->fine("Payload " . $data);
//Initialize Curl Options
$ch = curl_init($this->httpConfig->getUrl());
curl_setopt_array($ch, $this->httpConfig->getCurlOptions());
curl_setopt($ch, CURLOPT_URL, $this->httpConfig->getUrl());
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHttpHeaders());
//Determine Curl Options based on Method
switch ($this->httpConfig->getMethod()) {
case 'POST':
curl_setopt($ch, CURLOPT_POST, true);
case 'PUT':
case 'PATCH':
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
break;
}
//Default Option if Method not of given types in switch case
if ($this->httpConfig->getMethod() != NULL) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->httpConfig->getMethod());
}
//Logging Each Headers for debugging purposes
foreach ($this->getHttpHeaders() as $header) {
//TODO: Strip out credentials and other secure info when logging.
$this->logger->info("Adding header $header");
}
//Execute Curl Request
$result = curl_exec($ch);
//Retry if Certificate Exception
if (curl_errno($ch) == 60) {
$this->logger->info("Invalid or no certificate authority found - Retrying using bundled CA certs file");
curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
$result = curl_exec($ch);
}
//Retrieve Response Status
$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//Retry if Failing
$retries = 0;
if (in_array($httpStatus, self::$retryCodes) && $this->httpConfig->getHttpRetryCount() != null) {
$this->logger->info("Got $httpStatus response from server. Retrying");
do {
$result = curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
} while (in_array($httpStatus, self::$retryCodes) && (++$retries < $this->httpConfig->getHttpRetryCount()));
}
//Throw Exception if Retries and Certificates doenst work
if (curl_errno($ch)) {
$ex = new PPConnectionException(
$this->httpConfig->getUrl(),
curl_error($ch),
curl_errno($ch)
);
curl_close($ch);
throw $ex;
}
//Close the curl request
curl_close($ch);
//More Exceptions based on HttpStatus Code
if (in_array($httpStatus, self::$retryCodes)) {
$ex = new PPConnectionException(
$this->httpConfig->getUrl(),
"Got Http response code $httpStatus when accessing {$this->httpConfig->getUrl()}. " .
"Retried $retries times."
);
$ex->setData($result);
throw $ex;
} else if ($httpStatus < 200 || $httpStatus >= 300) {
$ex = new PPConnectionException(
$this->httpConfig->getUrl(),
"Got Http response code $httpStatus when accessing {$this->httpConfig->getUrl()}."
);
$ex->setData($result);
throw $ex;
}
//Return result object
return $result;
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace PayPal\Core;
/**
* Logging Levels.
* Class containing all the constants for Logging Levels.
*/
class PPLoggingLevel
{
// FINE Logging Level
const FINE = 3;
// INFO Logging Level
const INFO = 2;
// WARN Logging Level
const WARN = 1;
// ERROR Logging Level
const ERROR = 0;
}

View File

@@ -0,0 +1,119 @@
<?php
namespace PayPal\Core;
/**
* Simple Logging Manager.
* This does an error_log for now
* Potential frameworks to use are PEAR logger, log4php from Apache
*/
class PPLoggingManager
{
/**
* Default Logging Level
*/
const DEFAULT_LOGGING_LEVEL = 0;
/**
* Logger Name
* @var string
*/
private $loggerName;
/**
* Log Enabled
*
* @var bool
*/
private $isLoggingEnabled;
/**
* Configured Logging Level
*
* @var int|mixed
*/
private $loggingLevel;
/**
* Configured Logging File
*
* @var string
*/
private $loggerFile;
/**
* @param $loggerName
* @param array|null $config
*/
public function __construct($loggerName, $config = null)
{
$this->loggerName = $loggerName;
$config = PPConfigManager::getInstance()->getConfigHashmap();
$this->isLoggingEnabled = (array_key_exists('log.LogEnabled', $config) && $config['log.LogEnabled'] == '1');
if ($this->isLoggingEnabled) {
$this->loggerFile = ($config['log.FileName']) ? $config['log.FileName'] : ini_get('error_log');
$loggingLevel = strtoupper($config['log.LogLevel']);
$this->loggingLevel =
(isset($loggingLevel) && defined(__NAMESPACE__ . "\\PPLoggingLevel::$loggingLevel")) ?
constant(__NAMESPACE__ . "\\PPLoggingLevel::$loggingLevel") :
PPLoggingManager::DEFAULT_LOGGING_LEVEL;
}
}
/**
* Default Logger
*
* @param string $message
* @param int $level
*/
private function log($message, $level = PPLoggingLevel::INFO)
{
if ($this->isLoggingEnabled && ($level <= $this->loggingLevel)) {
error_log($this->loggerName . ": $message\n", 3, $this->loggerFile);
}
}
/**
* Log Error
*
* @param string $message
*/
public function error($message)
{
$this->log($message, PPLoggingLevel::ERROR);
}
/**
* Log Warning
*
* @param string $message
*/
public function warning($message)
{
$this->log($message, PPLoggingLevel::WARN);
}
/**
* Log Info
*
* @param string $message
*/
public function info($message)
{
$this->log($message, PPLoggingLevel::INFO);
}
/**
* Log Fine
*
* @param string $message
*/
public function fine($message)
{
$this->log($message, PPLoggingLevel::FINE);
}
}