1
0
mirror of synced 2024-11-28 06:06:02 +03:00

Response models

This commit is contained in:
Pavel 2019-06-14 08:56:11 +03:00
parent 282d00b81a
commit 1a07ae9fe8
24 changed files with 2262 additions and 327 deletions

1
.gitignore vendored
View File

@ -61,6 +61,7 @@ cmake-build-release/
# IntelliJ # IntelliJ
out/ out/
.idea/
# mpeltonen/sbt-idea plugin # mpeltonen/sbt-idea plugin
.idea_modules/ .idea_modules/

View File

@ -18,7 +18,8 @@
"jms/serializer": "1.13.*", "jms/serializer": "1.13.*",
"symfony/validator": "^4.2", "symfony/validator": "^4.2",
"doctrine/annotations": "^1.6", "doctrine/annotations": "^1.6",
"doctrine/cache": "^1.8" "doctrine/cache": "^1.8",
"guzzlehttp/guzzle": "6.0"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "6.5.*", "phpunit/phpunit": "6.5.*",

274
composer.lock generated
View File

@ -1,10 +1,10 @@
{ {
"_readme": [ "_readme": [
"This file locks the dependencies of your project to a known state", "This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "e2dc59137064db9a4933e3049f8e0c34", "content-hash": "eecd765e939fea19d4d181bafd7384a2",
"packages": [ "packages": [
{ {
"name": "doctrine/annotations", "name": "doctrine/annotations",
@ -259,6 +259,186 @@
], ],
"time": "2014-09-09T13:34:57+00:00" "time": "2014-09-09T13:34:57+00:00"
}, },
{
"name": "guzzlehttp/guzzle",
"version": "6.0.0",
"source": {
"type": "git",
"url": "https://github.com/guzzle/guzzle.git",
"reference": "df897ae757ad329d2affc38ffb5bbce782b2b510"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/guzzle/zipball/df897ae757ad329d2affc38ffb5bbce782b2b510",
"reference": "df897ae757ad329d2affc38ffb5bbce782b2b510",
"shasum": ""
},
"require": {
"guzzlehttp/promises": "^1.0.0",
"guzzlehttp/psr7": "^1.0.0",
"php": ">=5.5.0"
},
"require-dev": {
"ext-curl": "*",
"phpunit/phpunit": "^4.0",
"psr/log": "^1.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "6.0-dev"
}
},
"autoload": {
"files": [
"src/functions.php"
],
"psr-4": {
"GuzzleHttp\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"description": "Guzzle is a PHP HTTP client library",
"homepage": "http://guzzlephp.org/",
"keywords": [
"client",
"curl",
"framework",
"http",
"http client",
"rest",
"web service"
],
"time": "2015-05-26T18:22:06+00:00"
},
{
"name": "guzzlehttp/promises",
"version": "v1.3.1",
"source": {
"type": "git",
"url": "https://github.com/guzzle/promises.git",
"reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/promises/zipball/a59da6cf61d80060647ff4d3eb2c03a2bc694646",
"reference": "a59da6cf61d80060647ff4d3eb2c03a2bc694646",
"shasum": ""
},
"require": {
"php": ">=5.5.0"
},
"require-dev": {
"phpunit/phpunit": "^4.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.4-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Promise\\": "src/"
},
"files": [
"src/functions_include.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
}
],
"description": "Guzzle promises library",
"keywords": [
"promise"
],
"time": "2016-12-20T10:07:11+00:00"
},
{
"name": "guzzlehttp/psr7",
"version": "1.5.2",
"source": {
"type": "git",
"url": "https://github.com/guzzle/psr7.git",
"reference": "9f83dded91781a01c63574e387eaa769be769115"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/guzzle/psr7/zipball/9f83dded91781a01c63574e387eaa769be769115",
"reference": "9f83dded91781a01c63574e387eaa769be769115",
"shasum": ""
},
"require": {
"php": ">=5.4.0",
"psr/http-message": "~1.0",
"ralouphie/getallheaders": "^2.0.5"
},
"provide": {
"psr/http-message-implementation": "1.0"
},
"require-dev": {
"phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.8"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.5-dev"
}
},
"autoload": {
"psr-4": {
"GuzzleHttp\\Psr7\\": "src/"
},
"files": [
"src/functions_include.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Michael Dowling",
"email": "mtdowling@gmail.com",
"homepage": "https://github.com/mtdowling"
},
{
"name": "Tobias Schultze",
"homepage": "https://github.com/Tobion"
}
],
"description": "PSR-7 message implementation that also provides common utility methods",
"keywords": [
"http",
"message",
"psr-7",
"request",
"response",
"stream",
"uri",
"url"
],
"time": "2018-12-04T20:46:45+00:00"
},
{ {
"name": "jms/metadata", "name": "jms/metadata",
"version": "1.7.0", "version": "1.7.0",
@ -531,6 +711,96 @@
], ],
"time": "2015-07-25T16:39:46+00:00" "time": "2015-07-25T16:39:46+00:00"
}, },
{
"name": "psr/http-message",
"version": "1.0.1",
"source": {
"type": "git",
"url": "https://github.com/php-fig/http-message.git",
"reference": "f6561bf28d520154e4b0ec72be95418abe6d9363"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363",
"reference": "f6561bf28d520154e4b0ec72be95418abe6d9363",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Http\\Message\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interface for HTTP messages",
"homepage": "https://github.com/php-fig/http-message",
"keywords": [
"http",
"http-message",
"psr",
"psr-7",
"request",
"response"
],
"time": "2016-08-06T14:39:51+00:00"
},
{
"name": "ralouphie/getallheaders",
"version": "2.0.5",
"source": {
"type": "git",
"url": "https://github.com/ralouphie/getallheaders.git",
"reference": "5601c8a83fbba7ef674a7369456d12f1e0d0eafa"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/5601c8a83fbba7ef674a7369456d12f1e0d0eafa",
"reference": "5601c8a83fbba7ef674a7369456d12f1e0d0eafa",
"shasum": ""
},
"require": {
"php": ">=5.3"
},
"require-dev": {
"phpunit/phpunit": "~3.7.0",
"satooshi/php-coveralls": ">=1.0"
},
"type": "library",
"autoload": {
"files": [
"src/getallheaders.php"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Ralph Khattar",
"email": "ralph.khattar@gmail.com"
}
],
"description": "A polyfill for getallheaders.",
"time": "2016-02-11T07:05:27+00:00"
},
{ {
"name": "symfony/contracts", "name": "symfony/contracts",
"version": "v1.0.2", "version": "v1.0.2",

View File

@ -13,13 +13,17 @@
namespace RetailCrm\Mg\Bot; namespace RetailCrm\Mg\Bot;
use RetailCrm\Common\Deserializer;
use RetailCrm\Common\Exception\CurlException; use RetailCrm\Common\Exception\CurlException;
use RetailCrm\Common\Exception\InvalidJsonException; use RetailCrm\Common\Exception\InvalidJsonException;
use RetailCrm\Common\Url; use RetailCrm\Common\Url;
use RetailCrm\Common\Serializer; use RetailCrm\Common\Serializer;
use RetailCrm\Mg\Bot\Model; use RetailCrm\Mg\Bot\Model\Response\AssignResponse;
use RetailCrm\Mg\Bot\Model\Response\GenericListResponse;
use RetailCrm\Mg\Bot\Model\Response\ErrorOnlyResponse;
use Exception; use Exception;
use InvalidArgumentException; use InvalidArgumentException;
use RetailCrm\Mg\Bot\Model\Response\MessageSendResponse;
/** /**
* PHP version 7.0 * PHP version 7.0
@ -35,6 +39,11 @@ class Client
{ {
const VERSION = 'v1'; const VERSION = 'v1';
const ENTITY_CLASSPATH = 'RetailCrm\\Mg\\Bot\\Model\\Entity\\';
const RESPONSE_MODEL_CLASSPATH = 'RetailCrm\\Mg\\Bot\\Model\\Response\\';
const GENERIC_LIST_RESPONSE = self::RESPONSE_MODEL_CLASSPATH . 'GenericListResponse';
const ERROR_ONLY_RESPONSE = self::RESPONSE_MODEL_CLASSPATH . 'ErrorOnlyResponse';
protected $client; protected $client;
/** /**
@ -47,7 +56,40 @@ class Client
public function __construct($url, $token, $debug = false) public function __construct($url, $token, $debug = false)
{ {
$url = sprintf("%sapi/bot/%s", Url::normalizeUrl($url), self::VERSION); $url = sprintf("%sapi/bot/%s", Url::normalizeUrl($url), self::VERSION);
$this->client = new Request($url, $token, $debug); $this->client = new HttpClient($url, $token, $debug);
}
/**
* @param string $path
* @param string $method
* @param object $request
* @param string $responseType
* @param int $serializeTo
* @param string $deserializeType
*
* @return object|null
* @throws \Exception
*/
private function getData(
$path,
$method,
$request,
$responseType = self::GENERIC_LIST_RESPONSE,
$serializeTo = Serializer::S_JSON,
$deserializeType = Deserializer::DS_JSON
) {
$response = $this->client->makeRequest(
$path,
$method,
$request,
$serializeTo
);
return Deserializer::deserialize(
(string) $response->getBody(),
$responseType,
$deserializeType
);
} }
/** /**
@ -60,11 +102,17 @@ class Client
* @throws InvalidJsonException * @throws InvalidJsonException
* @throws Exception * @throws Exception
* *
* @return Response * @return array
*/ */
public function bots(Model\Request\BotsRequest $request) public function bots(Model\Request\BotsRequest $request)
{ {
return $this->client->makeRequest('/bots', Request::METHOD_GET, $request, Serializer::S_ARRAY); return $this->getData(
'/bots',
HttpClient::METHOD_GET,
$request,
self::GENERIC_LIST_RESPONSE,
Serializer::S_ARRAY
);
} }
/** /**
@ -77,11 +125,11 @@ class Client
* @throws CurlException * @throws CurlException
* @throws Exception * @throws Exception
* *
* @return Response * @return ErrorOnlyResponse|object|null
*/ */
public function info(Model\Request\InfoRequest $request) public function info(Model\Request\InfoRequest $request)
{ {
return $this->client->makeRequest('/my/info', Request::METHOD_PATCH, $request); return $this->getData('/my/info', HttpClient::METHOD_PATCH, $request, self::ERROR_ONLY_RESPONSE);
} }
/** /**
@ -89,12 +137,17 @@ class Client
* *
* @param Model\Request\ChannelsRequest $request * @param Model\Request\ChannelsRequest $request
* *
* @return Response * @return array|object|null
* @throws \Exception * @throws \Exception
*/ */
public function channels(Model\Request\ChannelsRequest $request) public function channels(Model\Request\ChannelsRequest $request)
{ {
return $this->client->makeRequest('/channels', Request::METHOD_GET, $request, Serializer::S_ARRAY); return $this->getData(
'/channels',
HttpClient::METHOD_GET, $request,
\sprintf("array<%s%s>", self::ENTITY_CLASSPATH, 'Channel\\Channel'),
Serializer::S_ARRAY
);
} }
/** /**
@ -107,11 +160,17 @@ class Client
* @throws InvalidJsonException * @throws InvalidJsonException
* @throws Exception * @throws Exception
* *
* @return Response * @return GenericListResponse|object|null
*/ */
public function chats(Model\Request\ChatsRequest $request) public function chats(Model\Request\ChatsRequest $request)
{ {
return $this->client->makeRequest('/chats', Request::METHOD_GET, $request, Serializer::S_ARRAY); return $this->getData(
'/chats',
HttpClient::METHOD_GET,
$request,
self::GENERIC_LIST_RESPONSE,
Serializer::S_ARRAY
);
} }
/** /**
@ -124,11 +183,16 @@ class Client
* @throws InvalidJsonException * @throws InvalidJsonException
* @throws Exception * @throws Exception
* *
* @return Response * @return GenericListResponse|object|null
*/ */
public function commands(Model\Request\CommandsRequest $request) public function commands(Model\Request\CommandsRequest $request)
{ {
return $this->client->makeRequest('/my/commands', Request::METHOD_GET, $request, Serializer::S_ARRAY); return $this->getData(
'/my/commands',
HttpClient::METHOD_GET, $request,
self::GENERIC_LIST_RESPONSE,
Serializer::S_ARRAY
);
} }
/** /**
@ -141,14 +205,15 @@ class Client
* @throws InvalidJsonException * @throws InvalidJsonException
* @throws Exception * @throws Exception
* *
* @return Response * @return ErrorOnlyResponse|object|null
*/ */
public function commandEdit(Model\Request\CommandEditRequest $request) public function commandEdit(Model\Request\CommandEditRequest $request)
{ {
return $this->client->makeRequest( return $this->getData(
sprintf("/my/commands/%s", $request->getName()), sprintf("/my/commands/%s", $request->getName()),
Request::METHOD_PUT, HttpClient::METHOD_PUT,
$request $request,
self::ERROR_ONLY_RESPONSE
); );
} }
@ -162,11 +227,17 @@ class Client
* @throws InvalidJsonException * @throws InvalidJsonException
* @throws Exception * @throws Exception
* *
* @return Response * @return ErrorOnlyResponse|object|null
*/ */
public function commandDelete(string $request) public function commandDelete(string $request)
{ {
return $this->client->makeRequest(sprintf("/my/commands/%s", $request), Request::METHOD_DELETE); $response = $this->client->makeRequest(sprintf("/my/commands/%s", $request), HttpClient::METHOD_DELETE);
return Deserializer::deserialize(
$response->getResponse(),
self::ERROR_ONLY_RESPONSE,
Deserializer::DS_ARRAY
);
} }
/** /**
@ -179,11 +250,17 @@ class Client
* @throws InvalidJsonException * @throws InvalidJsonException
* @throws Exception * @throws Exception
* *
* @return Response * @return GenericListResponse|object|null
*/ */
public function customers(Model\Request\CustomersRequest $request) public function customers(Model\Request\CustomersRequest $request)
{ {
return $this->client->makeRequest('/customers', Request::METHOD_GET, $request, Serializer::S_ARRAY); return $this->getData(
'/customers',
HttpClient::METHOD_GET,
$request,
self::GENERIC_LIST_RESPONSE,
Serializer::S_ARRAY
);
} }
/** /**
@ -196,11 +273,17 @@ class Client
* @throws InvalidJsonException * @throws InvalidJsonException
* @throws Exception * @throws Exception
* *
* @return Response * @return GenericListResponse|object|null
*/ */
public function dialogs(Model\Request\DialogsRequest $request) public function dialogs(Model\Request\DialogsRequest $request)
{ {
return $this->client->makeRequest('/dialogs', Request::METHOD_GET, $request, Serializer::S_ARRAY); return $this->getData(
'/dialogs',
HttpClient::METHOD_GET,
$request,
self::GENERIC_LIST_RESPONSE,
Serializer::S_ARRAY
);
} }
/** /**
@ -213,14 +296,15 @@ class Client
* @throws InvalidJsonException * @throws InvalidJsonException
* @throws Exception * @throws Exception
* *
* @return Response * @return AssignResponse|object|null
*/ */
public function dialogAssign(Model\Request\DialogAssignRequest $request) public function dialogAssign(Model\Request\DialogAssignRequest $request)
{ {
return $this->client->makeRequest( return $this->getData(
sprintf("/dialogs/%d/assign", $request->getDialogId()), sprintf("/dialogs/%d/assign", $request->getDialogId()),
Request::METHOD_PATCH, HttpClient::METHOD_PATCH,
$request $request,
self::RESPONSE_MODEL_CLASSPATH . 'AssignResponse'
); );
} }
@ -234,11 +318,16 @@ class Client
* @throws InvalidJsonException * @throws InvalidJsonException
* @throws Exception * @throws Exception
* *
* @return Response * @return ErrorOnlyResponse|object|null
*/ */
public function dialogClose(string $request) public function dialogClose(string $request)
{ {
return $this->client->makeRequest(sprintf("/dialogs/%d/close", $request), Request::METHOD_DELETE); return $this->getData(
sprintf("/dialogs/%d/close", $request),
HttpClient::METHOD_DELETE,
null,
self::ERROR_ONLY_RESPONSE
);
} }
/** /**
@ -251,11 +340,17 @@ class Client
* @throws InvalidJsonException * @throws InvalidJsonException
* @throws Exception * @throws Exception
* *
* @return Response * @return GenericListResponse|object|null
*/ */
public function members(Model\Request\MembersRequest $request) public function members(Model\Request\MembersRequest $request)
{ {
return $this->client->makeRequest('/members', Request::METHOD_GET, $request, Serializer::S_ARRAY); return $this->getData(
'/members',
HttpClient::METHOD_GET,
$request,
self::GENERIC_LIST_RESPONSE,
Serializer::S_ARRAY
);
} }
/** /**
@ -268,11 +363,17 @@ class Client
* @throws InvalidJsonException * @throws InvalidJsonException
* @throws Exception * @throws Exception
* *
* @return Response * @return GenericListResponse|object|null
*/ */
public function messages(Model\Request\MessagesRequest $request) public function messages(Model\Request\MessagesRequest $request)
{ {
return $this->client->makeRequest('/messages', Request::METHOD_GET, $request, Serializer::S_ARRAY); return $this->getData(
'/messages',
HttpClient::METHOD_GET,
$request,
self::GENERIC_LIST_RESPONSE,
Serializer::S_ARRAY
);
} }
/** /**
@ -285,11 +386,16 @@ class Client
* @throws InvalidJsonException * @throws InvalidJsonException
* @throws Exception * @throws Exception
* *
* @return Response * @return MessageSendResponse|object|null
*/ */
public function messageSend(Model\Request\MessageSendRequest $request) public function messageSend(Model\Request\MessageSendRequest $request)
{ {
return $this->client->makeRequest('/messages', Request::METHOD_POST, $request); return $this->getData(
'/messages',
HttpClient::METHOD_POST,
$request,
self::RESPONSE_MODEL_CLASSPATH . 'MessageSendResponse'
);
} }
/** /**
@ -302,11 +408,16 @@ class Client
* @throws InvalidJsonException * @throws InvalidJsonException
* @throws Exception * @throws Exception
* *
* @return Response * @return MessageSendResponse|object|null
*/ */
public function messageEdit(Model\Request\MessageEditRequest $request) public function messageEdit(Model\Request\MessageEditRequest $request)
{ {
return $this->client->makeRequest('/messages/%d', Request::METHOD_PATCH, $request->getId()); return $this->getData(
sprintf("/messages/%d", $request->getId()),
HttpClient::METHOD_PATCH,
$request,
self::RESPONSE_MODEL_CLASSPATH . 'MessageSendResponse'
);
} }
/** /**
@ -319,11 +430,16 @@ class Client
* @throws InvalidJsonException * @throws InvalidJsonException
* @throws Exception * @throws Exception
* *
* @return Response * @return ErrorOnlyResponse|object|null
*/ */
public function messageDelete(string $request) public function messageDelete(string $request)
{ {
return $this->client->makeRequest(sprintf("/messages/%d", $request), Request::METHOD_DELETE); return $this->getData(
sprintf("/messages/%d", $request),
HttpClient::METHOD_DELETE,
null,
self::ERROR_ONLY_RESPONSE
);
} }
/** /**
@ -336,10 +452,16 @@ class Client
* @throws InvalidJsonException * @throws InvalidJsonException
* @throws Exception * @throws Exception
* *
* @return Response * @return GenericListResponse|object|null
*/ */
public function users(Model\Request\UsersRequest $request) public function users(Model\Request\UsersRequest $request)
{ {
return $this->client->makeRequest('/users', Request::METHOD_GET, $request, Serializer::S_ARRAY); return $this->getData(
'/users',
HttpClient::METHOD_GET,
$request,
self::GENERIC_LIST_RESPONSE,
Serializer::S_ARRAY
);
} }
} }

View File

@ -3,7 +3,7 @@
/** /**
* PHP version 7.0 * PHP version 7.0
* *
* Request * HttpClient
* *
* @package RetailCrm\Mg\Bot * @package RetailCrm\Mg\Bot
* @author retailCRM <integration@retailcrm.ru> * @author retailCRM <integration@retailcrm.ru>
@ -13,25 +13,30 @@
namespace RetailCrm\Mg\Bot; namespace RetailCrm\Mg\Bot;
use RetailCrm\Common\Exception\CurlException; use RetailCrm\Common\Exception\InvalidJsonException;
use RetailCrm\Common\Exception\LimitException; use RetailCrm\Common\Exception\LimitException;
use Exception;
use InvalidArgumentException; use InvalidArgumentException;
use RetailCrm\Common\Serializer; use RetailCrm\Common\Serializer;
use RetailCrm\Common\Url; use RetailCrm\Common\Url;
use Symfony\Component\Validator\Validation; use Symfony\Component\Validator\Validation;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\ResponseInterface;
use function GuzzleHttp\Psr7\stream_for;
/** /**
* PHP version 7.0 * PHP version 7.0
* *
* Request class * HttpClient class
* *
* @package RetailCrm\Mg\Bot * @package RetailCrm\Mg\Bot
* @author retailCRM <integration@retailcrm.ru> * @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License * @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers * @link http://help.retailcrm.pro/docs/Developers
*/ */
class Request class HttpClient
{ {
const METHOD_GET = 'GET'; const METHOD_GET = 'GET';
const METHOD_POST = 'POST'; const METHOD_POST = 'POST';
@ -39,30 +44,34 @@ class Request
const METHOD_PATCH = 'PATCH'; const METHOD_PATCH = 'PATCH';
const METHOD_DELETE = 'DELETE'; const METHOD_DELETE = 'DELETE';
protected $url; protected $basePath;
protected $token; protected $token;
private $debug;
private $allowedMethods; private $allowedMethods;
private $stdout; private $stdout;
private $client;
/** /**
* Client constructor. * Client constructor.
* *
* @param string $url api url * @param string $url api url
* @param string $token api token * @param string $token api token
* @param bool $debug make request verbose
* @param bool|resource $stdout default output for debug * @param bool|resource $stdout default output for debug
* @param HandlerStack $handler
*/ */
public function __construct($url, $token, $debug, $stdout = STDOUT) public function __construct($url, $token, $stdout = STDOUT, $handler = null)
{ {
if (false === stripos($url, 'https://')) { if (false === stripos($url, 'https://')) {
throw new InvalidArgumentException('API schema requires HTTPS protocol'); throw new InvalidArgumentException('API schema requires HTTPS protocol');
} }
$this->url = $url; $this->basePath = parse_url($url, PHP_URL_PATH);
$this->token = $token; $this->token = $token;
$this->debug = $debug;
$this->stdout = $stdout; $this->stdout = $stdout;
$this->client = new Client(array_filter([
'base_uri' => Url::normalizeUrl($url),
'timeout' => 60,
'handler' => $handler
]));
$this->allowedMethods = [ $this->allowedMethods = [
self::METHOD_GET, self::METHOD_GET,
self::METHOD_POST, self::METHOD_POST,
@ -80,7 +89,7 @@ class Request
* @param mixed $request (default: null) * @param mixed $request (default: null)
* @param int $serializeTo * @param int $serializeTo
* *
* @return Response * @return ResponseInterface
* @throws \Exception * @throws \Exception
*/ */
public function makeRequest($path, $method, $request = null, $serializeTo = Serializer::S_JSON) public function makeRequest($path, $method, $request = null, $serializeTo = Serializer::S_JSON)
@ -91,40 +100,38 @@ class Request
$this->validateRequest($request); $this->validateRequest($request);
} }
$urlBuilder = new Url();
$parameters = is_null($request) ? null : Serializer::serialize($request, $serializeTo); $parameters = is_null($request) ? null : Serializer::serialize($request, $serializeTo);
$url = $method == self::METHOD_GET $request = new Request(
? $this->url . $urlBuilder->buildUrl($path, $parameters, Url::RFC_CUSTOM) $method,
: $this->url . $path \sprintf("%s%s", $this->basePath, $path),
; [
'Content-Type' => 'application/json',
$curlHandler = curl_init(); 'X-Bot-Token' => $this->token
curl_setopt($curlHandler, CURLOPT_URL, $url); ]
curl_setopt($curlHandler, CURLOPT_RETURNTRANSFER, 1); );
curl_setopt($curlHandler, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curlHandler, CURLOPT_FAILONERROR, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curlHandler, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curlHandler, CURLOPT_TIMEOUT, 60);
curl_setopt($curlHandler, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($curlHandler, CURLOPT_VERBOSE, $this->debug);
curl_setopt($curlHandler, CURLOPT_STDERR, $this->stdout);
curl_setopt($curlHandler, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
sprintf("X-Bot-Token: %s", $this->token)
]);
if (in_array($method, [self::METHOD_POST, self::METHOD_PUT, self::METHOD_PATCH, self::METHOD_DELETE])) { if (in_array($method, [self::METHOD_POST, self::METHOD_PUT, self::METHOD_PATCH, self::METHOD_DELETE])) {
curl_setopt($curlHandler, CURLOPT_CUSTOMREQUEST, $method); $request = $request->withBody(stream_for($parameters));
curl_setopt($curlHandler, CURLOPT_POSTFIELDS, $parameters);
} }
$responseBody = curl_exec($curlHandler); $responseObject = null;
$statusCode = curl_getinfo($curlHandler, CURLINFO_HTTP_CODE);
$response = Response::parseJSON($responseBody); try {
$responseObject = $this->client->send(
$request,
[
'debug' => $this->stdout,
'allow_redirects' => true,
'http_errors' => false,
'verify' => false
]
);
} catch (GuzzleException $exception) {
throw new \Exception($exception->getMessage(), $exception->getCode(), $exception);
}
$statusCode = $responseObject->getStatusCode();
$response = self::parseJSON((string) $responseObject->getBody());
$errorMessage = !empty($response['errorMsg']) ? $response['errorMsg'] : ''; $errorMessage = !empty($response['errorMsg']) ? $response['errorMsg'] : '';
$errorMessage = !empty($response['errors']) ? $this->getErrors($response['errors']) : $errorMessage; $errorMessage = !empty($response['errors']) ? $this->getErrors($response['errors']) : $errorMessage;
@ -132,25 +139,15 @@ class Request
* responses with 400 & 460 http codes contains extended error data * responses with 400 & 460 http codes contains extended error data
* therefore they are not handled as exceptions * therefore they are not handled as exceptions
*/ */
if (in_array($statusCode, [403, 404, 500])) { if (in_array($statusCode, [403, 404, 500])) {
throw new Exception($errorMessage); throw new \Exception($errorMessage);
} }
if ($statusCode == 503) { if ($statusCode == 503) {
throw new LimitException($errorMessage); throw new LimitException($errorMessage);
} }
$errno = curl_errno($curlHandler); return $responseObject;
$error = curl_error($curlHandler);
curl_close($curlHandler);
if ($errno) {
throw new CurlException($error, $errno);
}
return new Response($statusCode, $responseBody);
} }
/** /**
@ -202,4 +199,26 @@ class Request
return $errorString; return $errorString;
} }
/**
* @param string $responseBody
*
* @return array
*/
public static function parseJSON($responseBody): array
{
$result = [];
if (!empty($responseBody)) {
$response = json_decode($responseBody, true);
if (!$response && JSON_ERROR_NONE !== ($error = json_last_error())) {
throw new InvalidJsonException("Invalid JSON in the API response body. Error code #$error", $error);
}
$result = $response;
}
return $result;
}
} }

View File

@ -0,0 +1,184 @@
<?php
/**
* PHP version 7.0
*
* Channel entity
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Entity\Channel;
use JMS\Serializer\Annotation as Serializer;
use JMS\Serializer\Annotation\SerializedName;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\SkipWhenEmpty;
use JMS\Serializer\Annotation\Type;
use RetailCrm\Mg\Bot\Model\Entity\Channel\ChannelSettings;
use RetailCrm\Mg\Bot\Model\Entity\CommonFields;
/**
* PHP version 7.0
*
* Channel class
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class Channel
{
use CommonFields;
/**
* @var \DateTime
*
* @Type("DateTime<'Y-m-d\TH:i:s.u\Z'>")
* @Accessor(setter="setActivatedAt", getter="getActivatedAt")
*/
private $activatedAt;
/**
* @var \DateTime
*
* @Type("DateTime<'Y-m-d\TH:i:s.u\Z'>")
* @Accessor(setter="setDeactivatedAt", getter="getDeactivatedAt")
* @SkipWhenEmpty()
*/
private $deactivatedAt;
/**
* @var bool
*
* @Type("bool")
* @Accessor(setter="getIsActive", getter="setIsActive")
* @SerializedName("is_active")
*/
private $isActive;
/**
* @var array
*
* @Type("array")
* @Accessor(setter="setSettings", getter="getSettings")
*/
private $settings;
/**
* @var string
*
* @Type("string")
* @Accessor(setter="setType", getter="getType")
*/
private $type;
/**
* @var string
*
* @Type("string")
* @Accessor(setter="setName", getter="getName")
* @SkipWhenEmpty()
*/
private $name;
/**
* @return \DateTime
*/
public function getActivatedAt(): \DateTime
{
return $this->activatedAt;
}
/**
* @param \DateTime $activatedAt
*/
public function setActivatedAt(\DateTime $activatedAt)
{
$this->activatedAt = $activatedAt;
}
/**
* @return \DateTime
*/
public function getDeactivatedAt(): \DateTime
{
return $this->deactivatedAt;
}
/**
* @param \DateTime $deactivatedAt
*/
public function setDeactivatedAt($deactivatedAt)
{
$this->deactivatedAt = $deactivatedAt;
}
/**
* @return bool
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* @param bool $isActive
*/
public function setIsActive(bool $isActive)
{
$this->isActive = $isActive;
}
/**
* @return array
*/
public function getSettings(): array
{
return $this->settings;
}
/**
* @param array $settings
*/
public function setSettings(array $settings)
{
$this->settings = $settings;
}
/**
* @return string
*/
public function getType(): string
{
return $this->type;
}
/**
* @param string $type
*/
public function setType(string $type)
{
$this->type = $type;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
}

View File

@ -0,0 +1,126 @@
<?php
/**
* PHP version 7.0
*
* ChannelProductSettings entity
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Entity\Channel;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\Type;
/**
* PHP version 7.0
*
* ChannelProductSettings class
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class ChannelProductSettings
{
/**
* @var string
*
* @Type("string")
* @Accessor(setter="setCreating", getter="getCreating")
*/
private $creating;
/**
* @var string
*
* @Type("string")
* @Accessor(setter="setEditing", getter="getEditing")
*/
private $editing;
/**
* @var string
*
* @Type("string")
* @Accessor(setter="setDeleting", getter="getDeleting")
*/
private $deleting;
/**
* @var string
*
* @Type("string")
* @Accessor(setter="setQuoting", getter="getQuoting")
*/
private $quoting;
/**
* @return string
*/
public function getCreating(): string
{
return $this->creating;
}
/**
* @param string $creating
*/
public function setCreating(string $creating)
{
$this->creating = $creating;
}
/**
* @return string
*/
public function getEditing(): string
{
return $this->editing;
}
/**
* @param string $editing
*/
public function setEditing(string $editing)
{
$this->editing = $editing;
}
/**
* @return string
*/
public function getDeleting(): string
{
return $this->deleting;
}
/**
* @param string $deleting
*/
public function setDeleting(string $deleting)
{
$this->deleting = $deleting;
}
/**
* @return string
*/
public function getQuoting(): string
{
return $this->quoting;
}
/**
* @param string $quoting
*/
public function setQuoting(string $quoting)
{
$this->quoting = $quoting;
}
}

View File

@ -0,0 +1,104 @@
<?php
/**
* PHP version 7.0
*
* ChannelSettings entity
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Entity\Channel;
use JMS\Serializer\Annotation as Serializer;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\SkipWhenEmpty;
use JMS\Serializer\Annotation\Type;
/**
* PHP version 7.0
*
* ChannelSettings class
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class ChannelSettings
{
/**
* @var int
*
* @Type("int")
* @Accessor(setter="setSpamAllowed", getter="getSpamAllowed")
*/
private $spamAllowed;
/**
* @var ChannelSettingsStatus
*
* @Type("RetailCrm\Mg\Bot\Model\Entity\Channel\ChannelSettingsStatus")
* @Accessor(setter="setStatus", getter="getStatus")
*/
private $status;
/**
* @var ChannelTextSettings
*
* @Type("RetailCrm\Mg\Bot\Model\Entity\Channel\ChannelTextSettings")
* @Accessor(setter="setText", getter="getText")
*/
private $text;
/**
* @return int
*/
public function getSpamAllowed(): int
{
return $this->spamAllowed;
}
/**
* @param int $spamAllowed
*/
public function setSpamAllowed(int $spamAllowed)
{
$this->spamAllowed = $spamAllowed;
}
/**
* @return ChannelSettingsStatus
*/
public function getStatus(): ChannelSettingsStatus
{
return $this->status;
}
/**
* @param ChannelSettingsStatus $status
*/
public function setStatus(ChannelSettingsStatus $status)
{
$this->status = $status;
}
/**
* @return ChannelTextSettings
*/
public function getText(): ChannelTextSettings
{
return $this->text;
}
/**
* @param ChannelTextSettings $text
*/
public function setText(ChannelTextSettings $text)
{
$this->text = $text;
}
}

View File

@ -0,0 +1,78 @@
<?php
/**
* PHP version 7.0
*
* ChannelSettingsStatus entity
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Entity\Channel;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\Type;
/**
* PHP version 7.0
*
* ChannelSettingsStatus class
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class ChannelSettingsStatus
{
/**
* @var string
*
* @Type("string")
* @Accessor(setter="setDelivered", getter="getDelivered")
*/
private $delivered;
/**
* @var string
*
* @Type("string")
* @Accessor(setter="setRead", getter="getRead")
*/
private $read;
/**
* @return string
*/
public function getDelivered(): string
{
return $this->delivered;
}
/**
* @param string $delivered
*/
public function setDelivered(string $delivered)
{
$this->delivered = $delivered;
}
/**
* @return string
*/
public function getRead(): string
{
return $this->read;
}
/**
* @param string $read
*/
public function setRead(string $read)
{
$this->read = $read;
}
}

View File

@ -0,0 +1,126 @@
<?php
/**
* PHP version 7.0
*
* ChannelTextSettings entity
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Entity\Channel;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\Type;
/**
* PHP version 7.0
*
* ChannelTextSettings class
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class ChannelTextSettings
{
/**
* @var string
*
* @Type("string")
* @Accessor(setter="setCreating", getter="getCreating")
*/
private $creating;
/**
* @var string
*
* @Type("string")
* @Accessor(setter="setEditing", getter="getEditing")
*/
private $editing;
/**
* @var string
*
* @Type("string")
* @Accessor(setter="setDeleting", getter="getDeleting")
*/
private $deleting;
/**
* @var string
*
* @Type("string")
* @Accessor(setter="setQuoting", getter="getQuoting")
*/
private $quoting;
/**
* @return string
*/
public function getCreating(): string
{
return $this->creating;
}
/**
* @param string $creating
*/
public function setCreating(string $creating)
{
$this->creating = $creating;
}
/**
* @return string
*/
public function getEditing(): string
{
return $this->editing;
}
/**
* @param string $editing
*/
public function setEditing(string $editing)
{
$this->editing = $editing;
}
/**
* @return string
*/
public function getDeleting(): string
{
return $this->deleting;
}
/**
* @param string $deleting
*/
public function setDeleting(string $deleting)
{
$this->deleting = $deleting;
}
/**
* @return string
*/
public function getQuoting(): string
{
return $this->quoting;
}
/**
* @param string $quoting
*/
public function setQuoting(string $quoting)
{
$this->quoting = $quoting;
}
}

View File

@ -0,0 +1,106 @@
<?php
/**
* PHP version 7.0
*
* CommonFields trait
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Entity;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\SkipWhenEmpty;
use JMS\Serializer\Annotation\Type;
/**
* PHP version 7.0
*
* CommonFields trait
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
trait CommonFields
{
/**
* @var int
*
* @Type("int")
* @Accessor(setter="setId", getter="getId")
* @SkipWhenEmpty()
*/
private $id;
/**
* @var DateTime
*
* @Type("DateTime<'Y-m-d\TH:i:s.u\Z'>")
* @Accessor(setter="setCreatedAt", getter="getCreatedAt")
* @SkipWhenEmpty()
*/
private $createdAt;
/**
* @var string
*
* @Type("DateTime<'Y-m-d\TH:i:s.u\Z'>")
* @Accessor(setter="setUpdatedAt", getter="getUpdatedAt")
* @SkipWhenEmpty()
*/
private $updatedAt;
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
*/
public function setId(int $id)
{
$this->id = $id;
}
/**
* @return \DateTime
*/
public function getCreatedAt(): \DateTime
{
return $this->createdAt;
}
/**
* @param \DateTime $createdAt
*/
public function setCreatedAt(\DateTime $createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return \DateTime
*/
public function getUpdatedAt(): \DateTime
{
return $this->updatedAt;
}
/**
* @param \DateTime $updatedAt
*/
public function setUpdatedAt(\DateTime $updatedAt)
{
$this->updatedAt = $updatedAt;
}
}

View File

@ -0,0 +1,56 @@
<?php
/**
* PHP version 7.0
*
* Error entity
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Entity;
use JMS\Serializer\Annotation as Serializer;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\Type;
/**
* PHP version 7.0
*
* Error class
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class Error
{
/**
* @var array $messages
*
* @Type("array")
* @Accessor(getter="getMessages",setter="setMessages")
* @Serializer\SkipWhenEmpty()
*/
private $messages;
/**
* @return array
*/
public function getMessages(): array
{
return $this->messages;
}
/**
* @param array $messages
*/
public function setMessages(array $messages)
{
$this->messages = $messages;
}
}

View File

@ -0,0 +1,81 @@
<?php
/**
* PHP version 7.0
*
* Responsible entity
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Entity;
use JMS\Serializer\Annotation\SkipWhenEmpty;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\Type;
/**
* PHP version 7.0
*
* Responsible class
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class FileMeta
{
/**
* @var int $height
*
* @Type("int")
* @Accessor(setter="setHeight", getter="getHeight")
* @SkipWhenEmpty()
*/
private $height;
/**
* @var int $width
*
* @Type("int")
* @Accessor(setter="setWidth", getter="getWidth")
* @SkipWhenEmpty()
*/
private $width;
/**
* @return int
*/
public function getHeight(): int
{
return $this->height;
}
/**
* @param int $height
*/
public function setHeight(int $height)
{
$this->height = $height;
}
/**
* @return int
*/
public function getWidth(): int
{
return $this->width;
}
/**
* @param int $width
*/
public function setWidth(int $width)
{
$this->width = $width;
}
}

View File

@ -0,0 +1,102 @@
<?php
/**
* PHP version 7.0
*
* Responsible entity
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Entity;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\Type;
/**
* PHP version 7.0
*
* Responsible class
*
* @package RetailCrm\Mg\Bot\Model\Entity
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class Responsible
{
/**
* @var string $assignedAt
*
* @Type("string")
* @Accessor(getter="getAssignedAt",setter="setAssignedAt")
*/
private $assignedAt;
/**
* @var int $id
*
* @Type("int")
* @Accessor(getter="getId",setter="setId")
*/
private $id;
/**
* @var string $type
*
* @Type("string")
* @Accessor(getter="getType",setter="setType")
*/
private $type;
/**
* @return string
*/
public function getAssignedAt()
{
return $this->assignedAt;
}
/**
* @param string $assignedAt
*/
public function setAssignedAt(string $assignedAt)
{
$this->assignedAt = $assignedAt;
}
/**
* @return int
*/
public function getId(): int
{
return $this->id;
}
/**
* @param int $id
*/
public function setId(int $id)
{
$this->id = $id;
}
/**
* @return string
*/
public function getType(): string
{
return $this->type;
}
/**
* @param string $type
*/
public function setType(string $type)
{
$this->type = $type;
}
}

View File

@ -0,0 +1,131 @@
<?php
/**
* PHP version 7.0
*
* AssignResponse
*
* @package RetailCrm\Mg\Bot\Model\Response
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Response;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\SkipWhenEmpty;
use JMS\Serializer\Annotation\Type;
use RetailCrm\Mg\Bot\Model\Entity\Responsible;
use RetailCrm\Mg\Bot\Model\Response\ErrorTrait;
/**
* PHP version 7.0
*
* AssignResponse class
*
* @package RetailCrm\Mg\Bot\Model\Response
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class AssignResponse
{
use ErrorTrait;
/**
* @var bool
*
* @Type("bool")
* @Accessor(setter="setIsReassign", getter="getIsReassign")
*/
private $isReassign;
/**
* @var int
*
* @Type("int")
* @Accessor(setter="setLeftManagerId", getter="getLeftManagerId")
* @SkipWhenEmpty()
*/
private $leftManagerId;
/**
* @var Responsible $previousResponsible
*
* @Accessor(setter="setPreviousResponsible", getter="getPreviousResponsible")
* @SkipWhenEmpty()
*/
private $previousResponsible;
/**
* @var Responsible $responsible
*
* @Accessor(setter="setResponsible", getter="getResponsible")
*/
private $responsible;
/**
* @return bool
*/
public function getIsReassign()
{
return $this->isReassign;
}
/**
* @param bool $isReassign
*/
public function setIsReassign(bool $isReassign)
{
$this->isReassign = $isReassign;
}
/**
* @return int
*/
public function getLeftManagerId(): int
{
return $this->leftManagerId;
}
/**
* @param int $leftManagerId
*/
public function setLeftManagerId(int $leftManagerId)
{
$this->leftManagerId = $leftManagerId;
}
/**
* @return Responsible
*/
public function getPreviousResponsible(): Responsible
{
return $this->previousResponsible;
}
/**
* @param Responsible $previousResponsible
*/
public function setPreviousResponsible(Responsible $previousResponsible)
{
$this->previousResponsible = $previousResponsible;
}
/**
* @return Responsible
*/
public function getResponsible(): Responsible
{
return $this->responsible;
}
/**
* @param Responsible $responsible
*/
public function setResponsible(Responsible $responsible)
{
$this->responsible = $responsible;
}
}

View File

@ -0,0 +1,31 @@
<?php
/**
* PHP version 7.0
*
* ErrorOnlyResponse
*
* @package RetailCrm\Mg\Bot\Model\Response
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Response;
use RetailCrm\Mg\Bot\Model\Response\ErrorTrait;
/**
* PHP version 7.0
*
* ErrorOnlyResponse class
*
* @package RetailCrm\Mg\Bot\Model\Response
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class ErrorOnlyResponse
{
use ErrorTrait;
}

View File

@ -0,0 +1,66 @@
<?php
/**
* PHP version 7.0
*
* ErrorTrait
*
* @package RetailCrm\Mg\Bot\Model\Response
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Response;
use JMS\Serializer\Annotation as Serializer;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\SkipWhenEmpty;
use RetailCrm\Mg\Bot\Model\Entity\Error;
/**
* PHP version 7.0
*
* Error trait
*
* @package RetailCrm\Mg\Bot\Model\Response
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
trait ErrorTrait
{
/**
* @var array $error
*
* @Serializer\Type("array<string>")
* @Accessor(setter="getError", setter="setError")
* @Serializer\SerializedName("errors")
* @SkipWhenEmpty()
*/
private $error;
/**
* @return array
*/
public function getError()
{
return $this->error;
}
/**
* @param array $error
*/
public function setError(array $error)
{
$this->error = $error;
}
/**
* @return bool
*/
public function isError()
{
return !empty($this->error);
}
}

View File

@ -0,0 +1,134 @@
<?php
/**
* PHP version 7.0
*
* FullFileResponse
*
* @package RetailCrm\Mg\Bot\Model\Response
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Response;
use JMS\Serializer\Annotation\SkipWhenEmpty;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\Type;
use RetailCrm\Mg\Bot\Model\Response\ErrorTrait;
/**
* PHP version 7.0
*
* FullFileResponse class
*
* @package RetailCrm\Mg\Bot\Model\Response
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class FullFileResponse
{
use ErrorTrait;
/**
* @var string $id
*
* @Type("string")
* @Accessor(setter="setId", getter="getId")
* @SkipWhenEmpty()
*/
private $id;
/**
* @var int $size
*
* @Type("int")
* @Accessor(setter="setSize", getter="getSize")
* @SkipWhenEmpty()
*/
private $size;
/**
* @var string $type
*
* @Type("string")
* @Accessor(setter="setType", getter="getType")
* @SkipWhenEmpty()
*/
private $type;
/**
* @var string $url
*
* @Type("string")
* @Accessor(setter="setUrl", getter="getUrl")
* @SkipWhenEmpty()
*/
private $url;
/**
* @return string
*/
public function getId(): string
{
return $this->id;
}
/**
* @param string $id
*/
public function setId(string $id)
{
$this->id = $id;
}
/**
* @return int
*/
public function getSize(): int
{
return $this->size;
}
/**
* @param int $size
*/
public function setSize(int $size)
{
$this->size = $size;
}
/**
* @return string
*/
public function getType(): string
{
return $this->type;
}
/**
* @param string $type
*/
public function setType(string $type)
{
$this->type = $type;
}
/**
* @return string
*/
public function getUrl(): string
{
return $this->url;
}
/**
* @param string $url
*/
public function setUrl(string $url)
{
$this->url = $url;
}
}

View File

@ -0,0 +1,57 @@
<?php
/**
* PHP version 7.0
*
* GenericListResponse
*
* @package RetailCrm\Mg\Bot\Model\Response
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Response;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\Type;
use RetailCrm\Mg\Bot\Model\Response\ErrorTrait;
/**
* PHP version 7.0
*
* GenericListResponse class
*
* @package RetailCrm\Mg\Bot\Model\Response
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class GenericListResponse
{
use ErrorTrait;
/**
* @var array $result
*
* @Type("array")
* @Accessor(setter="setResult", getter="getResult")
*/
private $result;
/**
* @return array
*/
public function getResult()
{
return $this->result;
}
/**
* @param array $result
*/
public function setResult(array $result)
{
$this->result = $result;
}
}

View File

@ -0,0 +1,83 @@
<?php
/**
* PHP version 7.0
*
* MessageSendResponse
*
* @package RetailCrm\Mg\Bot\Model\Response
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Response;
use JMS\Serializer\Annotation as Serializer;
use JMS\Serializer\Annotation\SkipWhenEmpty;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\Type;
use RetailCrm\Mg\Bot\Model\Response\ErrorTrait;
/**
* PHP version 7.0
*
* MessageSendResponse class
*
* @package RetailCrm\Mg\Bot\Model\Response
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class MessageSendResponse
{
/**
* @var int $messageId
*
* @Type("int")
* @Accessor(setter="setMessageId", getter="getMessageId")
* @SkipWhenEmpty()
*/
private $messageId;
/**
* @var string $time
*
* @Type("string")
* @Accessor(setter="setTime", getter="getTime")
* @SkipWhenEmpty()
*/
private $time;
/**
* @return int
*/
public function getMessageId(): int
{
return $this->messageId;
}
/**
* @param int $messageId
*/
public function setMessageId(int $messageId)
{
$this->messageId = $messageId;
}
/**
* @return string
*/
public function getTime(): string
{
return $this->time;
}
/**
* @param string $time
*/
public function setTime(string $time)
{
$this->time = $time;
}
}

View File

@ -0,0 +1,225 @@
<?php
/**
* PHP version 7.0
*
* UploadFileResponse
*
* @package RetailCrm\Mg\Bot\Model\Response
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot\Model\Response;
use JMS\Serializer\Annotation\Accessor;
use JMS\Serializer\Annotation\Type;
use RetailCrm\Mg\Bot\Model\Response\ErrorTrait;
use RetailCrm\Mg\Bot\Model\Entity\FileMeta;
/**
* PHP version 7.0
*
* UploadFileResponse class
*
* @package RetailCrm\Mg\Bot\Model\Response
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class UploadFileResponse
{
use ErrorTrait;
/**
* @var string $createdAt
*
* @Type("string")
* @Accessor(setter="setCreatedAt", getter="getCreatedAt")
*/
private $createdAt;
/**
* @var string $hash
*
* @Type("string")
* @Accessor(setter="setHash", getter="getHash")
*/
private $hash;
/**
* @var string $id
*
* @Type("string")
* @Accessor(setter="setId", getter="getId")
*/
private $id;
/**
* @var FileMeta
*
* @Accessor(setter="setMeta", getter="getMeta")
*/
private $meta;
/**
* @var string $mimeType
*
* @Type("string")
* @Accessor(setter="setMimeType", getter="getMimeType")
*/
private $mimeType;
/**
* @var int $size
*
* @Type("string")
* @Accessor(setter="setSize", getter="getSize")
*/
private $size;
/**
* @var string $sourceUrl
*
* @Type("string")
* @Accessor(setter="setSourceUrl", getter="getSourceUrl")
*/
private $sourceUrl;
/**
* @var string $type
*
* @Type("string")
* @Accessor(setter="setType", getter="getType")
*/
private $type;
/**
* @return string
*/
public function getCreatedAt(): string
{
return $this->createdAt;
}
/**
* @param string $createdAt
*/
public function setCreatedAt(string $createdAt)
{
$this->createdAt = $createdAt;
}
/**
* @return string
*/
public function getHash(): string
{
return $this->hash;
}
/**
* @param string $hash
*/
public function setHash(string $hash)
{
$this->hash = $hash;
}
/**
* @return string
*/
public function getId(): string
{
return $this->id;
}
/**
* @param string $id
*/
public function setId(string $id)
{
$this->id = $id;
}
/**
* @return FileMeta
*/
public function getMeta(): FileMeta
{
return $this->meta;
}
/**
* @param FileMeta $meta
*/
public function setMeta(FileMeta $meta)
{
$this->meta = $meta;
}
/**
* @return string
*/
public function getMimeType(): string
{
return $this->mimeType;
}
/**
* @param string $mimeType
*/
public function setMimeType(string $mimeType)
{
$this->mimeType = $mimeType;
}
/**
* @return int
*/
public function getSize(): int
{
return $this->size;
}
/**
* @param int $size
*/
public function setSize(int $size)
{
$this->size = $size;
}
/**
* @return string
*/
public function getSourceUrl(): string
{
return $this->sourceUrl;
}
/**
* @param string $sourceUrl
*/
public function setSourceUrl(string $sourceUrl)
{
$this->sourceUrl = $sourceUrl;
}
/**
* @return string
*/
public function getType(): string
{
return $this->type;
}
/**
* @param string $type
*/
public function setType(string $type)
{
$this->type = $type;
}
}

View File

@ -1,229 +0,0 @@
<?php
/**
* PHP version 7.0
*
* Request
*
* @package RetailCrm\Mg\Bot
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Mg\Bot;
use ArrayAccess;
use BadMethodCallException;
use InvalidArgumentException;
use RetailCrm\Common\Exception\InvalidJsonException;
/**
* PHP version 7.0
*
* Request class
*
* @package RetailCrm\Mg\Bot
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class Response implements ArrayAccess
{
// HTTP response status code
protected $statusCode;
// response assoc array
protected $response;
// response body
protected $raw;
/**
* ApiResponse constructor.
*
* @param int $statusCode HTTP status code
* @param mixed $responseBody HTTP body
*
* @throws InvalidJsonException
*/
public function __construct($statusCode, $responseBody = null)
{
$this->statusCode = $statusCode;
$this->raw = $responseBody;
$this->response = self::parseJSON($responseBody);
}
/**
* Return raw HTTP response
*
* @return string|null
*/
public function getRawResponse()
{
return $this->raw;
}
/**
* Return HTTP response
*
* @return array
*/
public function getResponse()
{
return $this->response;
}
/**
* Return HTTP response status code
*
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* HTTP request was successful
*
* @return bool
*/
public function isSuccessful()
{
return $this->statusCode < 400;
}
/**
* Allow to access for the property throw class method
*
* @param string $name method name
* @param mixed $arguments method parameters
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function __call($name, $arguments)
{
// convert getSomeProperty to someProperty
$propertyName = strtolower(substr($name, 3, 1)) . substr($name, 4);
if (!isset($this->response[$propertyName])) {
throw new InvalidArgumentException("Method \"$name\" not found");
}
return $this->response[$propertyName];
}
/**
* Allow to access for the property throw object property
*
* @param string $name property name
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function __get($name)
{
if (!isset($this->response[$name])) {
throw new InvalidArgumentException("Property \"$name\" not found");
}
return $this->response[$name];
}
/**
* Allow to check if the property exists through object property
*
* @param string $name property name
*
* @return bool
*/
public function __isset($name)
{
return isset($this->response[$name]);
}
/**
* Offset set
*
* @param mixed $offset offset
* @param mixed $value value
*
* @throws BadMethodCallException
* @return void
*/
public function offsetSet($offset, $value)
{
$message = sprintf("This call not allowed. Offset given: %s. Value given: %s", $offset, $value);
throw new BadMethodCallException($message);
}
/**
* Offset unset
*
* @param mixed $offset offset
*
* @throws BadMethodCallException
* @return void
*/
public function offsetUnset($offset)
{
$message = sprintf("This call not allowed. Offset given: %s", $offset);
throw new BadMethodCallException($message);
}
/**
* Check offset
*
* @param mixed $offset offset
*
* @return bool
*/
public function offsetExists($offset)
{
return isset($this->response[$offset]);
}
/**
* Get offset
*
* @param mixed $offset offset
*
* @throws \InvalidArgumentException
*
* @return mixed
*/
public function offsetGet($offset)
{
if (!isset($this->response[$offset])) {
throw new InvalidArgumentException("Property \"$offset\" not found");
}
return $this->response[$offset];
}
/**
* @param string $responseBody
*
* @return array
*/
public static function parseJSON($responseBody): array
{
$result = [];
if (!empty($responseBody)) {
$response = json_decode($responseBody, true);
if (!$response && JSON_ERROR_NONE !== ($error = json_last_error())) {
throw new InvalidJsonException("Invalid JSON in the API response body. Error code #$error", $error);
}
$result = $response;
}
return $result;
}
}

59
src/Deserializer.php Normal file
View File

@ -0,0 +1,59 @@
<?php
/**
* PHP version 7.0
*
* Deserializer
*
* @package RetailCrm\Common
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Common;
use JMS\Serializer\SerializerBuilder;
/**
* PHP version 7.0
*
* Deserializer class
*
* @package RetailCrm\Common
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class Deserializer
{
const DS_JSON = "json";
const DS_XML = "xml";
const DS_ARRAY = "array";
/**
* Serialize given object to JSON or Array
*
* @param array|string $data
* @param string $deserialize
*
* @return object
*/
public static function deserialize($data, $type, $deserialize = self::S_JSON)
{
$deserialized = null;
$serializer = SerializerBuilder::create()->build();
switch ($deserialize) {
case self::DS_ARRAY:
$deserialized = $serializer->fromArray($data, $type);
break;
case self::DS_JSON:
case self::DS_XML:
$deserialized = $serializer->deserialize($data, $type, $deserialize);
break;
}
return $deserialized;
}
}

View File

@ -15,6 +15,7 @@ namespace RetailCrm\Mg\Bot\Tests;
use RetailCrm\Mg\Bot\Model\Constants; use RetailCrm\Mg\Bot\Model\Constants;
use RetailCrm\Mg\Bot\Model\Request; use RetailCrm\Mg\Bot\Model\Request;
use RetailCrm\Mg\Bot\Model\Response;
use RetailCrm\Mg\Bot\Test\TestCase; use RetailCrm\Mg\Bot\Test\TestCase;
/** /**
@ -43,8 +44,9 @@ class ClientListTest extends TestCase
$request->setTypes([Constants::CHANNEL_TYPE_FACEBOOK, Constants::CHANNEL_TYPE_INSTAGRAM]); $request->setTypes([Constants::CHANNEL_TYPE_FACEBOOK, Constants::CHANNEL_TYPE_INSTAGRAM]);
$response = $client->channels($request); $response = $client->channels($request);
var_dump($response[0]);
self::assertTrue($response->isSuccessful() == true); //self::assertTrue($response->isSuccessful() == true);
} }
/** /**
@ -122,9 +124,9 @@ class ClientListTest extends TestCase
$request->setActive(1); $request->setActive(1);
$request->setRoles([Constants::BOT_ROLE_RESPONSIBLE]); $request->setRoles([Constants::BOT_ROLE_RESPONSIBLE]);
$response = $client->bots($request); $data = $client->bots($request);
self::assertTrue($response->isSuccessful() == true); self::assertTrue($data instanceof \RetailCrm\Mg\Bot\Model\Response\GenericListResponse);
} }
/** /**