first commit

This commit is contained in:
2026-03-05 13:07:40 +01:00
commit 64ba0721ee
25709 changed files with 4691006 additions and 0 deletions

View File

@@ -0,0 +1,35 @@
{
"name": "wpdesk\/wp-api-client",
"authors": [
{
"name": "Krzysiek",
"email": "krzysiek@wpdesk.pl"
}
],
"require": {
"php": ">=5.5",
"psr\/log": "^1.0.1",
"wpdesk\/wp-cache": "^1.1",
"wpdesk\/wp-http-client": "^1.0",
"psr\/simple-cache": "^1.0"
},
"require-dev": {
"phpunit\/phpunit": "<7",
"wp-coding-standards\/wpcs": "^0.14.1",
"squizlabs\/php_codesniffer": "^3.0.2",
"mockery\/mockery": "*",
"10up\/wp_mock": "*"
},
"autoload": {
"psr-4": {
"DPDVendor\\WPDesk\\ApiClient\\": "src\/"
}
},
"autoload-dev": {},
"scripts": {
"phpunit-unit": "phpunit --configuration phpunit-unit.xml --coverage-text --colors=never",
"phpunit-unit-fast": "phpunit --configuration phpunit-unit.xml --no-coverage",
"phpunit-integration": "phpunit --configuration phpunit-integration.xml --coverage-text --colors=never",
"phpunit-integration-fast": "phpunit --configuration phpunit-integration.xml --no-coverage"
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Authentication;
class JWTSaasToken implements \DPDVendor\WPDesk\ApiClient\Authentication\Token
{
const SHOP_ID_PARAM = 'shop';
const ROLE_PARAM = 'ROLE_SHOP';
/** @var JWTToken */
private $token;
/**
* JWTToken constructor.
* @param string $token
*/
public function __construct(\DPDVendor\WPDesk\ApiClient\Authentication\JWTToken $token)
{
$this->token = $token;
}
public function getAuthString()
{
return $this->token->getAuthString();
}
public function isExpired()
{
return $this->token->isExpired();
}
public function isSignatureValid()
{
return $this->token->isSignatureValid();
}
public function __toString()
{
return $this->token->__toString();
}
/**
* If there is shop id in the token
*
* @return bool
*/
public function hasShopId()
{
$info = $this->token->getDecodedPublicTokenInfo();
return !empty($info[self::SHOP_ID_PARAM]) && \in_array(self::ROLE_PARAM, $info['roles']);
}
/**
* Get shop id from token
*
* @return int
*/
public function getShopId()
{
$info = $this->token->getDecodedPublicTokenInfo();
return (int) $info[self::SHOP_ID_PARAM];
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Authentication;
class JWTToken implements \DPDVendor\WPDesk\ApiClient\Authentication\Token
{
const CONSIDER_EXPIRED_WHEN_LESS = 2;
const EXPIRED_IN_SECONDS_PARAM = 'exp';
/** @var string */
private $token;
/**
* JWTToken constructor.
* @param string $token
*/
public function __construct($token)
{
$this->token = $token;
}
/**
* @return string
*/
public function __toString()
{
return $this->token;
}
/**
* Get string to perform authentication
*
* @return string
*/
public function getAuthString()
{
return 'Bearer ' . $this->__toString();
}
/**
* Returns public data from token
*
* @return array
*/
public function getDecodedPublicTokenInfo()
{
$tokenParts = \explode('.', $this->__toString());
if (!empty($tokenParts[1])) {
$infoPart = \base64_decode($tokenParts[1]);
return \json_decode($infoPart, \true);
}
return [];
}
/**
* Is token expired or very soon to be expired?
*
* @return bool
*/
public function isExpired()
{
$tokenInfo = $this->getDecodedPublicTokenInfo();
if (!empty($tokenInfo[self::EXPIRED_IN_SECONDS_PARAM])) {
return $tokenInfo[self::EXPIRED_IN_SECONDS_PARAM] - \time() < self::CONSIDER_EXPIRED_WHEN_LESS;
}
return \true;
}
/**
* Validates token signature
*
* @return bool
*/
public function isSignatureValid()
{
// @TODO
return \true;
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Authentication;
/**
* Null object pattern
*
* @package WPDesk\SaasPlatformClient\Authentication
*/
class NullToken implements \DPDVendor\WPDesk\ApiClient\Authentication\Token
{
public function __construct()
{
}
/**
* @return string
*/
public function __toString()
{
return '';
}
/**
* Get string to perform authentication
*
* @return string
*/
public function getAuthString()
{
return '';
}
/**
* Is token expired or very soon to be expired?
*
* @return bool
*/
public function isExpired()
{
return \true;
}
/**
* Validates token signature
*
* @return bool
*/
public function isSignatureValid()
{
return \false;
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Authentication;
interface Token
{
/**
* Get string to perform authentication
*
* @return string
*/
public function getAuthString();
/**
* Is token expired or very soon to be expired?
*
* @return bool
*/
public function isExpired();
/**
* Validates token signature
*
* @return bool
*/
public function isSignatureValid();
/**
* @return string
*/
public function __toString();
}

View File

@@ -0,0 +1,30 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Client;
use DPDVendor\Psr\Log\LoggerInterface;
use DPDVendor\WPDesk\ApiClient\Serializer\SerializerOptions;
use DPDVendor\WPDesk\HttpClient\HttpClientOptions;
interface ApiClientOptions extends \DPDVendor\WPDesk\HttpClient\HttpClientOptions, \DPDVendor\WPDesk\ApiClient\Serializer\SerializerOptions
{
/**
* @return LoggerInterface
*/
public function getLogger();
/**
* @return string
*/
public function getApiUrl();
/**
* @return array
*/
public function getDefaultRequestHeaders();
/**
* @return bool
*/
public function isCachedClient();
/**
* @return string
*/
public function getApiClientClass();
}

View File

@@ -0,0 +1,11 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Client;
interface ApiClientOptionsTimeout extends \DPDVendor\WPDesk\ApiClient\Client\ApiClientOptions
{
/**
* @return int
*/
public function getTimeout();
}

View File

@@ -0,0 +1,113 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Client;
use DPDVendor\Psr\SimpleCache\CacheInterface;
use DPDVendor\WPDesk\Cache\CacheDispatcher;
use DPDVendor\WPDesk\Cache\CacheInfoResolverCreator;
use DPDVendor\WPDesk\Cache\CacheItemCreator;
use DPDVendor\WPDesk\Cache\CacheItemVerifier;
use DPDVendor\WPDesk\HttpClient\HttpClient;
use DPDVendor\WPDesk\ApiClient\Request\Request;
use DPDVendor\WPDesk\ApiClient\Response\Response;
use DPDVendor\WPDesk\ApiClient\Serializer\Serializer;
class CachedClient implements \DPDVendor\WPDesk\ApiClient\Client\Client, \DPDVendor\WPDesk\Cache\CacheItemCreator, \DPDVendor\WPDesk\Cache\CacheItemVerifier
{
/** @var Client */
private $client;
/** @var CacheInterface */
private $cache;
/**
* @var CacheDispatcher
*/
private $cacheDispatcher;
/**
* CachedClient constructor.
*
* @param Client $decorated Decorated client
* @param CacheInterface $cache
*/
public function __construct(\DPDVendor\WPDesk\ApiClient\Client\Client $decorated, \DPDVendor\Psr\SimpleCache\CacheInterface $cache)
{
$this->client = $decorated;
$this->cache = $cache;
$this->cacheDispatcher = new \DPDVendor\WPDesk\Cache\CacheDispatcher($cache, $this->getCacheInfoResolvers());
}
/**
* Get cache info resolvers.
*
* @return RequestCacheInfoResolver[]
*/
protected function getCacheInfoResolvers()
{
if ($this->client instanceof \DPDVendor\WPDesk\Cache\CacheInfoResolverCreator) {
return $this->client->createResolvers();
} else {
return [new \DPDVendor\WPDesk\ApiClient\Client\RequestCacheInfoResolver()];
}
}
/**
* Create item to cache.
*
* @param Request $request
* @return Response
*/
public function createCacheItem($request)
{
return $this->client->sendRequest($request);
}
/**
* Verify cache item.
*
* @param $object
* @return Response;
*/
public function getVerifiedItemOrNull($object)
{
if ($object instanceof \DPDVendor\WPDesk\ApiClient\Response\Response) {
return $object;
}
return null;
}
/**
* Send request.
*
* @param Request $request
* @return mixed|Response
* @throws \Psr\SimpleCache\InvalidArgumentException
*/
public function sendRequest(\DPDVendor\WPDesk\ApiClient\Request\Request $request)
{
$response = $this->cacheDispatcher->dispatch($request, $this, $this);
return $response;
}
/**
* @return HttpClient
*/
public function getHttpClient()
{
return $this->client->getHttpClient();
}
/**
* @param HttpClient $client
* @return mixed
*/
public function setHttpClient(\DPDVendor\WPDesk\HttpClient\HttpClient $client)
{
return $this->client->setHttpClient($client);
}
/**
* @return Serializer
*/
public function getSerializer()
{
return $this->client->getSerializer();
}
/**
* @return string
*/
public function getApiUrl()
{
return $this->client->getApiUrl();
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Client;
use DPDVendor\WPDesk\HttpClient\HttpClient;
use DPDVendor\WPDesk\ApiClient\Request\Request;
use DPDVendor\WPDesk\ApiClient\Response\Response;
use DPDVendor\WPDesk\ApiClient\Serializer\Serializer;
interface Client
{
/**
* Send given request trough HttpClient
*
* @param Request $request
* @return Response
*/
public function sendRequest(\DPDVendor\WPDesk\ApiClient\Request\Request $request);
/**
* @return HttpClient
*/
public function getHttpClient();
/**
* @param HttpClient $client
*/
public function setHttpClient(\DPDVendor\WPDesk\HttpClient\HttpClient $client);
/**
* @return Serializer
*/
public function getSerializer();
/**
* Returns api url. Always without ending /
*
* @return string
*/
public function getApiUrl();
}

View File

@@ -0,0 +1,25 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Client;
use DPDVendor\WPDesk\Cache\WordpressCache;
use DPDVendor\WPDesk\HttpClient\HttpClientFactory;
use DPDVendor\WPDesk\ApiClient\Serializer\SerializerFactory;
class ClientFactory
{
/**
* @param ApiClientOptions $options
* @return Client
*/
public function createClient(\DPDVendor\WPDesk\ApiClient\Client\ApiClientOptions $options)
{
$httpClientFactory = new \DPDVendor\WPDesk\HttpClient\HttpClientFactory();
$serializerFactory = new \DPDVendor\WPDesk\ApiClient\Serializer\SerializerFactory();
$className = $options->getApiClientClass();
$client = new $className($httpClientFactory->createClient($options), $serializerFactory->createSerializer($options), $options->getLogger(), $options->getApiUrl(), $options->getDefaultRequestHeaders(), $options instanceof \DPDVendor\WPDesk\ApiClient\Client\ApiClientOptionsTimeout ? $options->getTimeout() : null);
if ($options->isCachedClient()) {
$client = new \DPDVendor\WPDesk\ApiClient\Client\CachedClient($client, new \DPDVendor\WPDesk\Cache\WordpressCache());
}
return $client;
}
}

View File

@@ -0,0 +1,167 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Client;
use DPDVendor\Psr\Log\LoggerAwareInterface;
use DPDVendor\Psr\Log\LoggerInterface;
use DPDVendor\WPDesk\HttpClient\HttpClient;
use DPDVendor\WPDesk\HttpClient\HttpClientResponse;
use DPDVendor\WPDesk\ApiClient\Request\Request;
use DPDVendor\WPDesk\ApiClient\Response\RawResponse;
use DPDVendor\WPDesk\ApiClient\Response\Response;
use DPDVendor\WPDesk\ApiClient\Serializer\Serializer;
use DPDVendor\WPDesk\HttpClient\HttpClientRequestException;
class ClientImplementation implements \DPDVendor\WPDesk\ApiClient\Client\Client, \DPDVendor\Psr\Log\LoggerAwareInterface
{
const CLIENT_VERSION = '1.6.5';
const LIBRARY_LOGIN_CONTEXT = 'wp-api-client';
/** @var HttpClient */
private $client;
/** @var Serializer */
private $serializer;
/** @var LoggerInterface */
private $logger;
/** @var string */
private $apiUrl;
/** @var array */
private $defaultRequestHeaders;
/** @var int */
private $timeout;
/**
* Client constructor.
* @param HttpClient $client
* @param Serializer $serializer
* @param LoggerInterface $logger
* @param string $apiUri
* @param array $defaultRequestHeaders
* @param int $timeout
*/
public function __construct(\DPDVendor\WPDesk\HttpClient\HttpClient $client, \DPDVendor\WPDesk\ApiClient\Serializer\Serializer $serializer, \DPDVendor\Psr\Log\LoggerInterface $logger, $apiUri, array $defaultRequestHeaders, $timeout = 10)
{
$this->client = $client;
$this->serializer = $serializer;
$this->logger = $logger;
$this->apiUrl = $apiUri;
$this->defaultRequestHeaders = $defaultRequestHeaders;
$this->timeout = $timeout;
}
/**
* Send given request trough HttpClient
*
* @param Request $request
* @throws HttpClientRequestException
* @return Response
*/
public function sendRequest(\DPDVendor\WPDesk\ApiClient\Request\Request $request)
{
$this->logger->debug("Sends request with METHOD: {$request->getMethod()}; to ENDPOINT {$request->getEndpoint()}", $this->getLoggerContext());
try {
$httpResponse = $this->client->send($fullUrl = $this->prepareFullUrl($request), $method = $request->getMethod(), $body = $this->prepareRequestBody($request), $headers = $this->prepareRequestHeaders($request), $this->timeout);
$this->logger->debug("Sent request with: URL: {$fullUrl};\n METHOD: {$method};\n BODY: {$body};\n" . "HEADERS: " . \json_encode($headers) . "\n\n and got response as CODE: {$httpResponse->getResponseCode()};\n" . "with RESPONSE BODY {$httpResponse->getBody()}", $this->getLoggerContext());
return $this->mapHttpResponseToApiResponse($httpResponse);
} catch (\DPDVendor\WPDesk\HttpClient\HttpClientRequestException $e) {
$this->logger->error("Exception {$e->getMessage()}; {$e->getCode()} occurred while sending request");
throw $e;
}
}
/**
* Returns full request url with endpoint
*
* @param Request $request
* @return string
*/
private function prepareFullUrl(\DPDVendor\WPDesk\ApiClient\Request\Request $request)
{
$endpoint = $request->getEndpoint();
if (\strpos('http', $endpoint) === 0) {
return $endpoint;
}
return $this->getApiUrl() . $endpoint;
}
/**
* Map response from http client to api response using serializer
*
* @param HttpClientResponse $response
* @return RawResponse
*/
private function mapHttpResponseToApiResponse(\DPDVendor\WPDesk\HttpClient\HttpClientResponse $response)
{
$apiResponse = new \DPDVendor\WPDesk\ApiClient\Response\RawResponse($this->serializer->unserialize($response->getBody()), $response->getResponseCode(), $response->getHeaders());
return $apiResponse;
}
/**
* Prepare serialized request body
*
* @param Request $request
* @return string
*/
private function prepareRequestBody(\DPDVendor\WPDesk\ApiClient\Request\Request $request)
{
return $this->serializer->serialize($request->getBody());
}
/**
* Prepares array of http headers
*
* @param Request $request
* @return array
*/
private function prepareRequestHeaders(\DPDVendor\WPDesk\ApiClient\Request\Request $request)
{
$headers = array('User-Agent' => 'saas-client-' . self::CLIENT_VERSION, 'Accept-Encoding' => '*', 'Content-Type' => $this->serializer->getMime());
$headers = \array_merge($headers, $this->defaultRequestHeaders);
return \array_merge($headers, $request->getHeaders());
}
/**
* @return HttpClient
*/
public function getHttpClient()
{
return $this->client;
}
/**
* @param HttpClient $client
*/
public function setHttpClient(\DPDVendor\WPDesk\HttpClient\HttpClient $client)
{
$this->client = $client;
}
/**
* @return Serializer
*/
public function getSerializer()
{
return $this->serializer;
}
/**
* Returns api url. Always without ending /
*
* @return string
*/
public function getApiUrl()
{
return \trim($this->apiUrl, '/');
}
/**
* Sets logger
*
* @param LoggerInterface $logger
*/
public function setLogger(\DPDVendor\Psr\Log\LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* Returns logger context for
*
* @param string $additional_context Optional additional context
* @return array
*/
protected function getLoggerContext($additional_context = '')
{
$context = [self::LIBRARY_LOGIN_CONTEXT, self::class];
if ($additional_context !== '') {
$context[] = $additional_context;
}
return $context;
}
}

View File

@@ -0,0 +1,127 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Client;
use DPDVendor\WPDesk\Cache\CacheInfoResolver;
use DPDVendor\WPDesk\Cache\HowToCache;
use DPDVendor\WPDesk\SaasPlatformClient\Request\AuthRequest;
use DPDVendor\WPDesk\SaasPlatformClient\Request\BasicRequest;
use DPDVendor\WPDesk\SaasPlatformClient\Request\Request;
use DPDVendor\WPDesk\SaasPlatformClient\Request\ShippingServicesSettings\PutSettingsRequest;
use DPDVendor\WPDesk\SaasPlatformClient\Request\Status\GetStatusRequest;
use DPDVendor\WPDesk\SaasPlatformClient\Response\ApiResponse;
use DPDVendor\WPDesk\SaasPlatformClient\Response\RawResponse;
class RequestCacheInfoResolver implements \DPDVendor\WPDesk\Cache\CacheInfoResolver
{
const DEFAULT_CACHE_TTL = 86400;
//24 hours
const CACHE_TTL_ONE_MINUTE = 60;
const OPTION_FS_SAAS_PLATFORM_VERSION_HASH = 'fs-saas-platform-version-hash';
/**
*
* @param Request $request
*
* @return bool
*/
private function prepareCacheKey($request)
{
return \md5($request->getEndpoint());
}
/**
*
* @param Request $request
*
* @return bool
*/
public function isSupported($request)
{
if ($request instanceof \DPDVendor\WPDesk\SaasPlatformClient\Request\BasicRequest) {
return \true;
}
return \false;
}
/**
*
* @param Request $request
*
* @return bool
*/
public function shouldCache($request)
{
if ($request instanceof \DPDVendor\WPDesk\ApiClient\Client\ConnectKeyInfoRequest) {
return \false;
}
if ($request instanceof \DPDVendor\WPDesk\SaasPlatformClient\Request\Status\GetStatusRequest) {
return \false;
}
if ($request instanceof \DPDVendor\WPDesk\SaasPlatformClient\Request\BasicRequest) {
if ('GET' === $request->getMethod()) {
return \true;
}
}
return \false;
}
/**
*
* @param Request $request
*
* @return HowToCache
*/
public function prepareHowToCache($request)
{
$howToCache = new \DPDVendor\WPDesk\Cache\HowToCache($this->prepareCacheKey($request), self::DEFAULT_CACHE_TTL);
return $howToCache;
}
/**
* @param ApiResponse $response
*
* @return bool
*/
private function isPlatformVersionFromResponseChanged(\DPDVendor\WPDesk\SaasPlatformClient\Response\ApiResponse $response)
{
$stored_hash = \get_option(self::OPTION_FS_SAAS_PLATFORM_VERSION_HASH, '');
if ($stored_hash !== $response->getPlatformVersionHash()) {
return \true;
}
return \false;
}
/**
* @param ApiResponse $response
*/
private function storePlatformVersionHashFromResponse(\DPDVendor\WPDesk\SaasPlatformClient\Response\ApiResponse $response)
{
\update_option(self::OPTION_FS_SAAS_PLATFORM_VERSION_HASH, $response->getPlatformVersionHash());
}
/**
*
* @param Request $request
* @param mixed $item
*
* @return bool
*/
public function shouldClearCache($request, $item)
{
if ($request instanceof \DPDVendor\WPDesk\SaasPlatformClient\Request\ShippingServicesSettings\PutSettingsRequest) {
return \true;
}
if ($item instanceof \DPDVendor\WPDesk\SaasPlatformClient\Response\ApiResponse && $this->isPlatformVersionFromResponseChanged($item)) {
$this->storePlatformVersionHashFromResponse($item);
return \true;
}
return \false;
}
/**
*
* @param Request $request
* @param mixed $item
*
* @return string[]
*/
public function shouldClearKeys($request, $item)
{
if ('GET' !== $request->getMethod()) {
return [$this->prepareCacheKey($request)];
}
return [];
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Request;
class BasicRequest implements \DPDVendor\WPDesk\ApiClient\Request\Request
{
/** @var string */
protected $method;
/** @var array */
protected $data;
/** @var string */
protected $endPoint;
/**
* @return string
*/
public function getMethod()
{
return $this->method;
}
/**
* Return endpoint in format /[^/]+/
*
* @return string
*/
public function getEndpoint()
{
return '/' . \trim($this->endPoint, '/');
}
/**
* Returns array of http headers
*
* @return array
*/
public function getHeaders()
{
return array();
}
/**
* Return unserialized request body as array
*
* @return array
*/
public function getBody()
{
return $this->data;
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Request;
interface Request
{
/**
* @return string
*/
public function getMethod();
/**
* @return array
*/
public function getHeaders();
/**
* @return array
*/
public function getBody();
/**
* @return string
*/
public function getEndpoint();
}

View File

@@ -0,0 +1,31 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Response;
interface ApiResponse extends \DPDVendor\WPDesk\ApiClient\Response\Response
{
/**
* Get links structure to the other request
*
* @return array
*/
public function getLinks();
/**
* Is it a BAD REQUEST response
*
* @return bool
*/
public function isBadRequest();
/**
* Is it a FATAL ERROR response
*
* @return bool
*/
public function isServerFatalError();
/**
* Is requested resource exists
*
* @return bool
*/
public function isNotExists();
}

View File

@@ -0,0 +1,11 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Response;
use DPDVendor\WPDesk\ApiClient\Response\Traits\AuthApiResponseDecorator;
class AuthApiResponse implements \DPDVendor\WPDesk\ApiClient\Response\ApiResponse
{
const RESPONSE_CODE_BAD_CREDENTIALS = 401;
const RESPONSE_CODE_NOT_EXISTS = 404;
use AuthApiResponseDecorator;
}

View File

@@ -0,0 +1,23 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Response;
use DPDVendor\WPDesk\ApiClient\Response\Exception\TriedExtractDataFromErrorResponse;
use DPDVendor\WPDesk\ApiClient\Response\Traits\ApiResponseDecorator;
/**
* Response is protected in a way so when you try to get body of the response when an error occured you will get an exception
*
* Class ProtectedResponse
* @package WPDesk\ApiClient\Response
*/
class ProtectedResponse implements \DPDVendor\WPDesk\ApiClient\Response\Response
{
use ApiResponseDecorator;
public function getResponseBody()
{
if ($this->isError()) {
throw \DPDVendor\WPDesk\ApiClient\Response\Exception\TriedExtractDataFromErrorResponse::createWithClassInfo(\get_class($this->rawResponse), $this->getResponseCode());
}
return $this->rawResponse->getResponseBody();
}
}

View File

@@ -0,0 +1,100 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Response;
class RawResponse implements \DPDVendor\WPDesk\ApiClient\Response\Response
{
const RESPONSE_CODE_SUCCESS = 200;
const RESPONSE_CODE_CREATED = 201;
const RESPONSE_CODE_ERROR_BAD_REQUEST = 400;
const RESPONSE_CODE_DOMAIN_NOT_ALLOWED = 462;
const RESPONSE_CODE_ERROR_FATAL = 500;
const RESPONSE_CODE_MAINTENANCE = 503;
const HEADER_X_PLATFORM_VERSION_HASH = 'X-Platform-Version-Hash';
/** @var array */
private $data;
/** @var int */
private $code;
/** @var array */
private $headers;
/**
* RawResponse constructor.
* @param array $body
* @param int $code
* @param array $headers
*/
public function __construct(array $body, $code, array $headers)
{
$this->data = $body;
$this->code = (int) $code;
$this->headers = $headers;
}
/**
* Returns response http code
*
* @return int
*/
public function getResponseCode()
{
return $this->code;
}
/**
* Returns response body as array
*
* @return array
*/
public function getResponseBody()
{
return $this->data;
}
/**
* Returns response body as array
*
* @return array
*/
public function getResponseErrorBody()
{
return $this->data;
}
/**
* Returns response body as array
*
* @return array
*/
public function getResponseHeaders()
{
return $this->headers;
}
/**
* Is any error occured
*
* @return bool
*/
public function isError()
{
$code = $this->getResponseCode();
return ($code < 200 || $code >= 300) && !$this->isMaintenance();
}
/**
* Is maintenance.
*
* @return bool
*/
public function isMaintenance()
{
$code = $this->getResponseCode();
return self::RESPONSE_CODE_MAINTENANCE === $code;
}
/**
* Get platform version hash string.
*
* @return bool|string
*/
public function getPlatformVersionHash()
{
if (isset($this->headers[self::HEADER_X_PLATFORM_VERSION_HASH])) {
return $this->headers[self::HEADER_X_PLATFORM_VERSION_HASH];
}
return \false;
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Response;
interface Response
{
/**
* @return int
*/
public function getResponseCode();
/** @return array */
public function getResponseBody();
/** @return array */
public function getResponseHeaders();
/** @return array */
public function getResponseErrorBody();
/**
* Is any error occured
*
* @return bool
*/
public function isError();
/**
* Is maintenance
*
* @return bool
*/
public function isMaintenance();
/**
* Get platform version hash string.
*
* @return bool|string
*/
public function getPlatformVersionHash();
}

View File

@@ -0,0 +1,129 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Response\Traits;
use DPDVendor\WPDesk\ApiClient\Response\AuthApiResponse;
use DPDVendor\WPDesk\ApiClient\Response\RawResponse;
use DPDVendor\WPDesk\ApiClient\Response\Response;
trait ApiResponseDecorator
{
/** @var RawResponse */
private $rawResponse;
/**
* RawResponseDecorator constructor.
* @param Response $rawResponse
*/
public function __construct(\DPDVendor\WPDesk\ApiClient\Response\Response $rawResponse)
{
$this->rawResponse = $rawResponse;
}
/**
* Returns response http code
*
* @return int
*/
public function getResponseCode()
{
return $this->rawResponse->getResponseCode();
}
/**
* Returns response body as array
*
* @return array
*/
public function getResponseBody()
{
return $this->rawResponse->getResponseBody();
}
/**
* Returns response body as array
*
* @return array
*/
public function getResponseErrorBody()
{
return $this->rawResponse->getResponseErrorBody();
}
/**
* Returns response body as array
*
* @return array
*/
public function getResponseHeaders()
{
return $this->rawResponse->getResponseHeaders();
}
/**
* Get links structure to the other request
*
* @return array
*/
public function getLinks()
{
$body = $this->getResponseBody();
return $body['_links'];
}
/**
* Is it a BAD REQUEST response
*
* @return bool
*/
public function isBadRequest()
{
return $this->getResponseCode() === \DPDVendor\WPDesk\ApiClient\Response\RawResponse::RESPONSE_CODE_ERROR_BAD_REQUEST;
}
/**
* Is it a DOMAIN NOT ALLOWED response
*
* @return bool
*/
public function isDomainNotAllowed()
{
return $this->getResponseCode() === \DPDVendor\WPDesk\ApiClient\Response\RawResponse::RESPONSE_CODE_DOMAIN_NOT_ALLOWED;
}
/**
* Is it a FATAL ERROR response
*
* @return bool
*/
public function isServerFatalError()
{
return $this->getResponseCode() === \DPDVendor\WPDesk\ApiClient\Response\RawResponse::RESPONSE_CODE_ERROR_FATAL;
}
/**
* Is any error occured
*
* @return bool
*/
public function isError()
{
return $this->rawResponse->isError();
}
/**
* Is requested resource exists
*
* @return bool
*/
public function isNotExists()
{
return $this->getResponseCode() === \DPDVendor\WPDesk\ApiClient\Response\AuthApiResponse::RESPONSE_CODE_NOT_EXISTS;
}
/**
* Is maintenance.
*
* @return bool
*/
public function isMaintenance()
{
return $this->rawResponse->isMaintenance();
}
/**
* Get platform version hash string.
*
* @return bool|string
*/
public function getPlatformVersionHash()
{
return $this->rawResponse->getPlatformVersionHash();
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Response\Traits;
use DPDVendor\WPDesk\ApiClient\Response\AuthApiResponse;
trait AuthApiResponseDecorator
{
use ApiResponseDecorator;
/**
* @return bool
*/
public function isBadCredentials()
{
return $this->getResponseCode() === \DPDVendor\WPDesk\ApiClient\Response\AuthApiResponse::RESPONSE_CODE_BAD_CREDENTIALS;
}
/**
* Is bad credential because token expires
*
* @return bool
*/
public function isTokenExpired()
{
return $this->isBadCredentials();
}
/**
* Is bad credential because token is invalid
*
* @return bool
*/
public function isTokenInvalid()
{
return $this->isBadCredentials();
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Response\Traits;
trait PagedListImplementation
{
/*
* @return array
*/
public function getRawPage()
{
$body = $this->getResponseBody();
if ($body['_embedded'] !== null && $body['_embedded']['item'] !== null) {
return $body['_embedded']['item'];
}
return [];
}
/**
* @return int
*/
public function getPageCount()
{
return (int) \floor($this->getItemCount() / $this->getItemsPerPage());
}
/**
* @return int
*/
public function getItemsPerPage()
{
$body = $this->getResponseBody();
return (int) $body['itemsPerPage'];
}
/**
* @return int
*/
public function getItemCount()
{
$body = $this->getResponseBody();
return (int) $body['totalItems'];
}
}

View File

@@ -0,0 +1,12 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Serializer\Exception;
/**
* Thrown when serializer cannot unserialize string data
*
* @package WPDesk\ApiClient\Serializer\Exception
*/
class CannotUnserializeException extends \RuntimeException
{
}

View File

@@ -0,0 +1,39 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Serializer;
use DPDVendor\WPDesk\ApiClient\Serializer\Exception\CannotUnserializeException;
class JsonSerializer implements \DPDVendor\WPDesk\ApiClient\Serializer\Serializer
{
/**
* Convert data to string
*
* @param mixed $data
* @return string
*/
public function serialize($data)
{
return \json_encode($data, \JSON_FORCE_OBJECT);
}
/**
* Convert string to php data
*
* @param string $data
* @return mixed
*/
public function unserialize($data)
{
$unserializedResult = \json_decode($data, \true);
if ($unserializedResult === null) {
throw new \DPDVendor\WPDesk\ApiClient\Serializer\Exception\CannotUnserializeException("Cannot unserialize data: {$data}");
}
return $unserializedResult;
}
/**
* @return string
*/
public function getMime()
{
return 'application/json';
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Serializer;
interface Serializer
{
/**
* @param mixed $data
* @return string
*/
public function serialize($data);
/**
* @param string $data
* @return mixed
*/
public function unserialize($data);
/**
* @return string
*/
public function getMime();
}

View File

@@ -0,0 +1,16 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Serializer;
class SerializerFactory
{
/**
* @param SerializerOptions $options
* @return Serializer
*/
public function createSerializer(\DPDVendor\WPDesk\ApiClient\Serializer\SerializerOptions $options)
{
$className = $options->getSerializerClass();
return new $className();
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace DPDVendor\WPDesk\ApiClient\Serializer;
interface SerializerOptions
{
/**
* @return string
*/
public function getSerializerClass();
}