Skip to content

Commit

Permalink
Merge pull request #57 from rarus/dev
Browse files Browse the repository at this point in the history
Task#55
  • Loading branch information
rarus-web authored Aug 22, 2018
2 parents 5963640 + 3860d3f commit 56835a4
Show file tree
Hide file tree
Showing 20 changed files with 310 additions and 88 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
.idea/*
vendor
tests/logs/*
composer.phar
phpunit.xml
composer.lock
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# bonus-server-php-sdk change log

## 0.5.1 (20.08.2018)
- исправлена ошибка с точностью в парсере timestamp `Rarus\BonusServer\Util\DateTimeParser` [issue#55](https://github.com/rarus/bonus-server-php-sdk/issues/55)
- исправлена ошибка с некорректными датами рождения при добавлении новых пользователей [issue#55](https://github.com/rarus/bonus-server-php-sdk/issues/55)
- исправлена ошибка с получением пустого логина для всех пользователей [issue#55](https://github.com/rarus/bonus-server-php-sdk/issues/55)
- подробный лог работы юнит-тестов теперь сохраняется в папке `/tests/logs/`
- в ApiClient добавлена поддержка таймзон и метод `setTimezone` который позволяет указать нужную таймзону

## 0.5.0 (6.08.2018)
- исправлен ошибочный 404 статус если нет скидок, результаты рассчёта скидок стали опциональными [issue#36](https://github.com/rarus/bonus-server-php-sdk/issues/36)
- для сущности `Cards` для роли `Organization` добавлен метод `getByBarcode` [issue#31](https://github.com/rarus/bonus-server-php-sdk/issues/31)
Expand Down
56 changes: 50 additions & 6 deletions src/Rarus/BonusServer/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ class ApiClient
* @var float number of seconds to wait while trying to connect to a server. Use 0 to wait indefinitely (the default behavior).
*/
protected $connectTimeout;
/**
* @var \DateTimeZone временная зона в которой работает API-клиент, по умолчанию берётся зона установленная на сервере
*/
protected $timezone;

/**
* ApiClient constructor.
Expand All @@ -67,22 +71,24 @@ class ApiClient
*/
public function __construct(string $apiEndpointUrl, GuzzleHttp\ClientInterface $obHttpClient, LoggerInterface $obLogger = null)
{
$this->apiEndpoint = $apiEndpointUrl;
$this->httpClient = $obHttpClient;
$this->setConnectTimeout(2.0);

if ($obLogger !== null) {
$this->log = $obLogger;
} else {
$this->log = new NullLogger();
}
$this->apiEndpoint = $apiEndpointUrl;
$this->httpClient = $obHttpClient;
$this->setConnectTimeout(2.0);
$this->setTimezone(new \DateTimeZone(date_default_timezone_get()));

$this->guzzleHandlerStack = GuzzleHttp\HandlerStack::create();

$this->log->debug(
'rarus.bonus.server.apiClient.init',
[
'url' => $apiEndpointUrl,
'connect_timeout' => $this->getConnectTimeout(),
'timezone' => $this->getTimezone()->getName(),
]
);
}
Expand All @@ -97,10 +103,42 @@ public function getConnectTimeout(): float

/**
* @param float $connectTimeout
*
* @return ApiClient
*/
public function setConnectTimeout(float $connectTimeout): void
public function setConnectTimeout(float $connectTimeout): ApiClient
{
$this->log->debug('rarus.bonus.server.apiClient.setConnectTimeout.start', [
'connectTimeout' => $connectTimeout,
]);
$this->connectTimeout = $connectTimeout;
$this->log->debug('rarus.bonus.server.apiClient.setConnectTimeout.finish');

return $this;
}

/**
* @return \DateTimeZone
*/
public function getTimezone(): \DateTimeZone
{
return $this->timezone;
}

/**
* @param \DateTimeZone $timezone
*
* @return ApiClient
*/
public function setTimezone(\DateTimeZone $timezone): ApiClient
{
$this->log->debug('rarus.bonus.server.apiClient.setTimezone.start', [
'name' => $timezone->getName(),
]);
$this->timezone = $timezone;
$this->log->debug('rarus.bonus.server.apiClient.setTimezone.finish');

return $this;
}

/**
Expand Down Expand Up @@ -381,9 +419,15 @@ protected function getGuzzleHandlerStack(): GuzzleHttp\HandlerStack

/**
* @param GuzzleHttp\HandlerStack $guzzleHandlerStack
*
* @return ApiClient
*/
public function setGuzzleHandlerStack(GuzzleHttp\HandlerStack $guzzleHandlerStack): void
public function setGuzzleHandlerStack(GuzzleHttp\HandlerStack $guzzleHandlerStack): ApiClient
{
$this->log->debug('rarus.bonus.server.apiClient.setGuzzleHandlerStack.start');
$this->guzzleHandlerStack = $guzzleHandlerStack;
$this->log->debug('rarus.bonus.server.apiClient.setGuzzleHandlerStack.finish');

return $this;
}
}
11 changes: 6 additions & 5 deletions src/Rarus/BonusServer/Cards/DTO/Fabric.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,14 @@
class Fabric
{
/**
* @param array $arCard
* @param Currency $currency
* @param array $arCard
* @param Currency $currency
* @param \DateTimeZone $dateTimeZone
*
* @return Card
* @throws \Rarus\BonusServer\Exceptions\ApiClientException
*/
public static function initCardFromServerResponse(array $arCard, \Money\Currency $currency): Card
public static function initCardFromServerResponse(array $arCard, \Money\Currency $currency, \DateTimeZone $dateTimeZone): Card
{
$currencies = new ISOCurrencies();
$moneyParser = new DecimalMoneyParser($currencies);
Expand All @@ -39,10 +40,10 @@ public static function initCardFromServerResponse(array $arCard, \Money\Currency
->setDescription((string)$arCard['description'])
->setCardLevelId(new LevelId((string)$arCard['card_level_id']))
->setAccumSaleAmount($moneyParser->parse((string)$arCard['accum_sale_amount'], $currency->getCode()))
->setCardStatus(Status\Fabric::initFromServerResponse($arCard));
->setCardStatus(Status\Fabric::initFromServerResponse($arCard, $dateTimeZone));

if ($arCard['date_last_transaction'] !== 0) {
$card->setDateLastTransaction(DateTimeParser::parseTimestampFromServerResponse((string)$arCard['date_last_transaction']));
$card->setDateLastTransaction(DateTimeParser::parseTimestampFromServerResponse((string)$arCard['date_last_transaction'], $dateTimeZone));
}
if ($arCard['last_transaction'] !== '') {
$card->setLastTransaction((string)$arCard['last_transaction']);
Expand Down
9 changes: 5 additions & 4 deletions src/Rarus/BonusServer/Cards/DTO/Status/Fabric.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,24 @@
class Fabric
{
/**
* @param array $arCard
* @param array $arCard
* @param \DateTimeZone $dateTimeZone
*
* @return CardStatus
* @throws \Rarus\BonusServer\Exceptions\ApiClientException
*/
public static function initFromServerResponse(array $arCard): CardStatus
public static function initFromServerResponse(array $arCard, \DateTimeZone $dateTimeZone): CardStatus
{
$cardStatus = (new CardStatus())
->setIsActive((bool)$arCard['active'])
->setIsBlocked((bool)$arCard['blocked'])
->setBlockedDescription((string)$arCard['blockeddescription']);

if ($arCard['date_active'] !== 0) {
$cardStatus->setDateActivate(DateTimeParser::parseTimestampFromServerResponse((string)$arCard['date_active']));
$cardStatus->setDateActivate(DateTimeParser::parseTimestampFromServerResponse((string)$arCard['date_active'], $dateTimeZone));
}
if ($arCard['date_deactivate'] !== 0) {
$cardStatus->setDateDeactivate(DateTimeParser::parseTimestampFromServerResponse((string)$arCard['date_deactivate']));
$cardStatus->setDateDeactivate(DateTimeParser::parseTimestampFromServerResponse((string)$arCard['date_deactivate'], $dateTimeZone));
}

return $cardStatus;
Expand Down
9 changes: 5 additions & 4 deletions src/Rarus/BonusServer/Cards/DTO/TransactionAmount/Fabric.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,19 @@
class Fabric
{
/**
* @param Currency $currency
* @param array $arTransactionAmount
* @param Currency $currency
* @param array $arTransactionAmount
* @param \DateTimeZone $dateTimeZone
*
* @return TransactionAmount
* @throws \Rarus\BonusServer\Exceptions\ApiClientException
*/
public static function initFromServerResponse(Currency $currency, array $arTransactionAmount): TransactionAmount
public static function initFromServerResponse(Currency $currency, array $arTransactionAmount, \DateTimeZone $dateTimeZone): TransactionAmount
{
$moneyParser = new DecimalMoneyParser(new ISOCurrencies());

return (new TransactionAmount())
->setTransactionSum($moneyParser->parse((string)$arTransactionAmount['sum'], $currency->getCode()))
->setDate(DateTimeParser::parseTimestampFromServerResponse((string)$arTransactionAmount['date']));
->setDate(DateTimeParser::parseTimestampFromServerResponse((string)$arTransactionAmount['date'], $dateTimeZone));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public function list(BonusServer\Transport\DTO\Pagination $pagination): BonusSer

$cardCollection = new BonusServer\Cards\DTO\CardCollection();
foreach ((array)$requestResult['cards'] as $card) {
$cardCollection->attach(BonusServer\Cards\DTO\Fabric::initCardFromServerResponse($card, $this->getDefaultCurrency()));
$cardCollection->attach(BonusServer\Cards\DTO\Fabric::initCardFromServerResponse($card, $this->getDefaultCurrency(), $this->apiClient->getTimezone()));
}

$paginationResponse = new BonusServer\Cards\Transport\DTO\PaginationResponse(
Expand Down Expand Up @@ -146,19 +146,25 @@ public function getByUser(BonusServer\Users\DTO\User $user, ?BonusServer\Transpo
'phone' => $user->getPhone(),
]);

$requestResult = $this->apiClient->executeApiRequest(
sprintf('/organization/card?%s&calculate_count=true&user_id=%s',
BonusServer\Transport\Formatters\Pagination::toRequestUri($pagination),
$user->getUserId()->getId()
),
RequestMethodInterface::METHOD_GET
);

$cardCollection = new BonusServer\Cards\DTO\CardCollection();
foreach ((array)$requestResult['cards'] as $card) {
$cardCollection->attach(BonusServer\Cards\DTO\Fabric::initCardFromServerResponse($card, $this->getDefaultCurrency()));
try {
$requestResult = $this->apiClient->executeApiRequest(
sprintf('/organization/card?%s&calculate_count=true&user_id=%s',
BonusServer\Transport\Formatters\Pagination::toRequestUri($pagination),
$user->getUserId()->getId()
),
RequestMethodInterface::METHOD_GET
);
foreach ((array)$requestResult['cards'] as $card) {
$cardCollection->attach(BonusServer\Cards\DTO\Fabric::initCardFromServerResponse($card, $this->getDefaultCurrency(), $this->apiClient->getTimezone()));
}
$cardCollection->rewind();
} catch (BonusServer\Exceptions\ApiClientException $exception) {
// если карты не найдены, то сервер возврашает 404 статус выставив 114 код в данном случае мы его подавляем
if ($exception->getCode() !== 114) {
throw $exception;
}
}
$cardCollection->rewind();

$this->log->debug('rarus.bonus.server.cards.transport.organization.getByUser.finish', [
'itemsCount' => $cardCollection->count(),
Expand Down Expand Up @@ -216,7 +222,7 @@ public function getByCardId(BonusServer\Cards\DTO\CardId $cardId): BonusServer\C
RequestMethodInterface::METHOD_GET
);

$card = BonusServer\Cards\DTO\Fabric::initCardFromServerResponse($requestResult['card'], $this->getDefaultCurrency());
$card = BonusServer\Cards\DTO\Fabric::initCardFromServerResponse($requestResult['card'], $this->getDefaultCurrency(), $this->apiClient->getTimezone());

$this->log->debug('rarus.bonus.server.cards.transport.organization.getByCardId.finish', [
'cardId' => $card->getCardId()->getId(),
Expand Down Expand Up @@ -546,7 +552,7 @@ public function getByBarcode(BonusServer\Cards\DTO\Barcode\Barcode $cardBarcode)
RequestMethodInterface::METHOD_GET
);

$card = BonusServer\Cards\DTO\Fabric::initCardFromServerResponse($requestResult['cards'][0], $this->getDefaultCurrency());
$card = BonusServer\Cards\DTO\Fabric::initCardFromServerResponse($requestResult['cards'][0], $this->getDefaultCurrency(), $this->apiClient->getTimezone());

$this->log->debug('rarus.bonus.server.cards.transport.organization.getByBarcode.finish', [
'cardId' => $card->getCardId()->getId(),
Expand Down Expand Up @@ -579,7 +585,7 @@ public function getByFilter(BonusServer\Cards\DTO\CardFilter $cardFilter): Bonus
);

foreach ((array)$requestResult['cards'] as $card) {
$cardCollection->attach(BonusServer\Cards\DTO\Fabric::initCardFromServerResponse($card, $this->getDefaultCurrency()));
$cardCollection->attach(BonusServer\Cards\DTO\Fabric::initCardFromServerResponse($card, $this->getDefaultCurrency(), $this->apiClient->getTimezone()));
}

$this->log->debug('rarus.bonus.server.cards.transport.organization.getByFilter.finish', [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public function list(): BonusServer\Cards\DTO\CardCollection

$cardCollection = new BonusServer\Cards\DTO\CardCollection();
foreach ((array)$requestResult['cards'] as $card) {
$cardCollection->attach(BonusServer\Cards\DTO\Fabric::initCardFromServerResponse($card, $this->getDefaultCurrency()));
$cardCollection->attach(BonusServer\Cards\DTO\Fabric::initCardFromServerResponse($card, $this->getDefaultCurrency(), $this->apiClient->getTimezone()));
}

$this->log->debug('rarus.bonus.server.cards.transport.list.finish', [
Expand Down
26 changes: 14 additions & 12 deletions src/Rarus/BonusServer/Transactions/DTO/Points/Fabric.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,14 @@
class Fabric
{
/**
* @param Currency $currency
* @param array $arPointTransaction
* @param Currency $currency
* @param array $arPointTransaction
* @param \DateTimeZone $dateTimeZone
*
* @return PointTransaction
* @throws \Rarus\BonusServer\Exceptions\ApiClientException
*/
public static function initPointTransactionFromServerResponse(Currency $currency, array $arPointTransaction): PointTransaction
public static function initPointTransactionFromServerResponse(Currency $currency, array $arPointTransaction, \DateTimeZone $dateTimeZone): PointTransaction
{
$currencies = new ISOCurrencies();
$moneyParser = new DecimalMoneyParser($currencies);
Expand All @@ -41,7 +42,7 @@ public static function initPointTransactionFromServerResponse(Currency $currency
->setPointId(new PointId((string)$arPointTransaction['id']))
->setCardId(new CardId((string)$arPointTransaction['card_id']))
->setMastercardId(new CardId((string)$arPointTransaction['mastercard_id']))
->setTime(DateTimeParser::parseTimestampFromServerResponse((string)$arPointTransaction['time']))
->setTime(DateTimeParser::parseTimestampFromServerResponse((string)$arPointTransaction['time'], $dateTimeZone))
->setSum($moneyParser->parse((string)$arPointTransaction['sum'], $currency->getCode()))
->setType($arPointTransaction['type'] === 0 ? Type\Fabric::getRefund() : Type\Fabric::getSale())
->setAuthor((string)$arPointTransaction['author'])
Expand All @@ -50,34 +51,35 @@ public static function initPointTransactionFromServerResponse(Currency $currency
->setCashRegisterId(new CashRegisterId((string)$arPointTransaction['kkm_id']))
->setShopId(new ShopId((string)$arPointTransaction['shop_id']))
->setDocumentTypeId((string)$arPointTransaction['doc_type'])
->setInvalidatePeriod(DateTimeParser::parseTimestampFromServerResponse((string)$arPointTransaction['invalidate_period']))
->setActivationPeriod(DateTimeParser::parseTimestampFromServerResponse((string)$arPointTransaction['activation_period']))
->setInvalidatePeriod(DateTimeParser::parseTimestampFromServerResponse((string)$arPointTransaction['invalidate_period'], $dateTimeZone))
->setActivationPeriod(DateTimeParser::parseTimestampFromServerResponse((string)$arPointTransaction['activation_period'], $dateTimeZone))
->setDiscountId(new DiscountId((string)$arPointTransaction['discount_id']));

return $pointTrx;
}

/**
* @param Currency $currency
* @param array $arPoint
* @param Currency $currency
* @param array $arPoint
* @param \DateTimeZone $dateTimeZone
*
* @return Point
* @throws \Rarus\BonusServer\Exceptions\ApiClientException
*/
public static function initPointFromServerResponse(Currency $currency, array $arPoint): Point
public static function initPointFromServerResponse(Currency $currency, array $arPoint, \DateTimeZone $dateTimeZone): Point
{
$moneyParser = new DecimalMoneyParser(new ISOCurrencies());

$point = new Point();
$point
->setSum($moneyParser->parse((string)$arPoint['sum'], $currency->getCode()))
->setDateCreate(DateTimeParser::parseTimestampFromServerResponse((string)$arPoint['date']));
->setDateCreate(DateTimeParser::parseTimestampFromServerResponse((string)$arPoint['date'], $dateTimeZone));

if ($arPoint['active_from'] !== 0) {
$point->setActiveFrom(DateTimeParser::parseTimestampFromServerResponse((string)$arPoint['active_from']));
$point->setActiveFrom(DateTimeParser::parseTimestampFromServerResponse((string)$arPoint['active_from'], $dateTimeZone));
}
if ($arPoint['active_to'] !== 0) {
$point->setActiveFrom(DateTimeParser::parseTimestampFromServerResponse((string)$arPoint['active_to']));
$point->setActiveFrom(DateTimeParser::parseTimestampFromServerResponse((string)$arPoint['active_to'], $dateTimeZone));
}

return $point;
Expand Down
13 changes: 10 additions & 3 deletions src/Rarus/BonusServer/Users/DTO/Fabric.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,17 @@ class Fabric
{

/**
* @param array $arUser
* @param array $arUser
* @param \DateTimeZone $dateTimeZone
*
* @return User
* @throws \Rarus\BonusServer\Exceptions\ApiClientException
*/
public static function initUserFromServerResponse(array $arUser): User
public static function initUserFromServerResponse(array $arUser, \DateTimeZone $dateTimeZone): User
{
$user = (new User())
->setUserId(new UserId($arUser['id']))
->setLogin($arUser['login'])
->setName($arUser['name'])
->setPhone($arUser['phone'])
->setStatus(Users\DTO\Status\Fabric::initFromServerResponse($arUser))
Expand All @@ -33,7 +35,12 @@ public static function initUserFromServerResponse(array $arUser): User
$user->setGender(Users\DTO\Gender\Fabric::initFromServerResponse($arUser['gender']));
}
if ($arUser['birthdate'] !== 0) {
$user->setBirthdate(DateTimeParser::parseTimestampFromServerResponse((string)$arUser['birthdate']));
$gmtOffsetInSeconds = $dateTimeZone->getOffset(new \DateTime('now', $dateTimeZone));
$realTimestamp = (int)$arUser['birthdate'];
$birthdateWithGmt = DateTimeParser::parseTimestampFromServerResponse((string)$realTimestamp, $dateTimeZone);
$birthday = \DateTime::createFromFormat('U', (string)($birthdateWithGmt->getTimestamp() + $gmtOffsetInSeconds), $dateTimeZone);
$birthday->setTimezone($dateTimeZone);
$user->setBirthdate($birthday);
}

return $user;
Expand Down
Loading

0 comments on commit 56835a4

Please sign in to comment.