Compare commits

...

46 Commits

Author SHA1 Message Date
Daniel Seifert 6331080e8b
use assertion library 2023-02-02 22:34:18 +01:00
Daniel Seifert 3d0578bd9a
use assertion library 2023-02-02 00:18:09 +01:00
Daniel Seifert 5683c6fd6e
adjust version informations 2023-01-20 09:10:24 +01:00
Daniel Seifert 0231890129
remove unused ApiException, check for non status 200 errors 2023-01-18 09:10:48 +01:00
Daniel Seifert 637ef9669d
preconfigure loggerhandler with current OXID logger, use logger handler to get logger instance 2023-01-17 15:44:15 +01:00
Daniel Seifert bd466266cc
improve code syntax 2023-01-17 09:15:27 +01:00
Daniel Seifert 2897097076
don't show recipient issues and detailed request errors in frontend 2023-01-16 21:04:14 +01:00
Daniel Seifert 358805d12b
update dependencies 2023-01-16 09:18:54 +01:00
Daniel Seifert 888a99b99d
adjust readme informations 2023-01-15 22:42:48 +01:00
Daniel Seifert f61d77e489
improve code 2023-01-15 22:38:33 +01:00
Daniel Seifert 4632fe1df7
move message content to CMS items 2023-01-15 22:24:35 +01:00
Daniel Seifert ae8e04c23c
add integration test for preconfigured triggers 2023-01-14 22:08:05 +01:00
Daniel Seifert bb03bb1dee
improve integration tests 2023-01-13 22:19:55 +01:00
Daniel Seifert ea3489eaf3
add integration tests for Admin User and Admin Order controllers 2023-01-13 14:10:02 +01:00
Daniel Seifert 653b75c164
adjust test 2023-01-12 23:13:10 +01:00
Daniel Seifert 55bf8b9eab
fix successfully sent message 2023-01-12 23:04:50 +01:00
Daniel Seifert d84983001f
add missing service 2023-01-12 22:49:27 +01:00
Daniel Seifert 88571ad8ed
remove setParameter in DIC because of frozen parameter bag 2023-01-12 22:30:17 +01:00
Daniel Seifert 6651d892dd
remove outdated test files 2023-01-10 23:58:07 +01:00
Daniel Seifert a383976e49
apply code style rules 2023-01-10 23:35:52 +01:00
Daniel Seifert 2312af010a
apply static code analysis changes 2023-01-10 23:33:48 +01:00
Daniel Seifert fb124c1f1a
add tests for setup actions class 2023-01-10 21:53:27 +01:00
Daniel Seifert 890c5dfc10
add tests for module classes 2023-01-09 22:17:30 +01:00
Daniel Seifert 5ebe4009dd
add tests for SMS message type classes 2023-01-08 22:22:45 +01:00
Daniel Seifert 2460281434
use RecipientsList object instead of recipient objects array 2023-01-07 22:44:37 +01:00
Daniel Seifert 32ea723301
add tests for exception classes 2023-01-07 21:13:32 +01:00
Daniel Seifert 26a6223442
add tests for Configuration class 2023-01-07 13:49:27 +01:00
Daniel Seifert f7418e06b0
add tests for MessageClient class 2023-01-06 23:42:17 +01:00
Daniel Seifert 339af80a2d
add tests for MessageSender class 2023-01-05 23:33:29 +01:00
Daniel Seifert 2f76fa37b6
add tests for OrderRecipients class 2023-01-05 22:43:58 +01:00
Daniel Seifert c117e9509d
move shared code to separate classes to prevent errors while phpunit coverage test run 2023-01-04 23:58:37 +01:00
Daniel Seifert e4393803bf
add tests for RequestFactory class 2023-01-04 23:08:05 +01:00
Daniel Seifert e4699d4d19
add tests for UserRecipients class 2023-01-04 01:08:35 +01:00
Daniel Seifert 9de541eb6c
use DI getter shorthand 2023-01-03 11:20:12 +01:00
Daniel Seifert 1558e0275e
Merge branch 'rel_1.x' into dev_1.x_tests
# Conflicts:
#	composer.json
2023-01-03 09:38:09 +01:00
Daniel Seifert f21293084e
add DI services 2023-01-02 22:46:34 +01:00
Daniel Seifert c1f088985a
improve docblocks 2022-12-28 00:11:00 +01:00
Daniel Seifert d88dee4876
remove dupclicates, add tests 2022-12-28 00:09:24 +01:00
Daniel Seifert 506bbd648e
add tests, improve code 2022-12-26 00:20:16 +01:00
Daniel Seifert bf77b65ad5
Merge branch 'rel_1.x' into dev_1.x_tests 2022-12-25 13:00:44 +01:00
Daniel Seifert 524a2bd57f
change sms tests 2022-07-17 23:37:57 +02:00
Daniel Seifert 81b7fab1c1
use generated example phone number 2022-07-15 23:45:16 +02:00
Daniel Seifert 42be99c268
Merge branch 'rel_1.x' into dev_1.x_tests 2022-07-15 22:56:41 +02:00
Daniel Seifert 7d54e545e7
add initial test for SMS model 2022-07-15 10:52:54 +02:00
Daniel Seifert a4889fe4bc
add initial test structure 2022-07-14 23:09:30 +02:00
Daniel Seifert 407ac49a17
allow sender country is null 2022-07-14 16:04:26 +02:00
64 changed files with 8050 additions and 322 deletions

View File

@ -6,6 +6,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased](https://git.d3data.de/D3Private/linkmobility4oxid/compare/1.1.1.0...rel_1.x)
## [1.1.2.0](https://git.d3data.de/D3Private/linkmobility4oxid/compare/1.1.1.0...1.1.2.0) - 2023-01-20
### Added
- more test scripts
- preconfigure loggerhandler with current OXID logger
### Changed
- move message contents to CMS items
- improve code
- don't show recipient issues and detailed request errors in shop frontend
### Removed
- unused ApiException class
## [1.1.1.0](https://git.d3data.de/D3Private/linkmobility4oxid/compare/1.1.0.1...1.1.1.0) - 2023-01-01
### Added
- make installable in OXID 6.5.1 (CE 6.13)

View File

@ -39,7 +39,7 @@ composer require d3/linkmobility4oxid
Activate the module in the admin area of the shop in "Extensions -> Modules".
The necessary configuration can be found in the same area in the "Settings" tab.
The necessary configuration can be found in the same area in the "Settings" tab. You can adapt the texts for the standard messages to your requirements under "Customer information -> CMS pages" with the title "Linkmobility".
## Changelog

View File

@ -39,7 +39,7 @@ composer require d3/linkmobility4oxid
Aktivieren Sie das Modul im Shopadmin unter "Erweiterungen -> Module".
Die nötige Konfiguration finden Sie im selben Bereich im Tab "Einstell.".
Die nötige Konfiguration finden Sie im selben Bereich im Tab "Einstell.". Die Texte für die Standardnachrichten können Sie unter "Kundeninformationen -> CMS-Seiten" mit dem Titel "Linkmobility" an Ihre Anforderungen anpassen.
## Changelog

View File

@ -21,9 +21,12 @@
"GPL-3.0-or-later"
],
"require": {
"php": "^7.1 || ^8.0",
"oxid-esales/oxideshop-ce": "~6.7.0 || ~6.9.0 || 6.10 - 6.13",
"d3/linkmobility-php-client": "^1.2.0 || ^2.0.0"
"php": "^7.1 || ^8.0",
"oxid-esales/oxideshop-ce": "~6.7.0 || ~6.9.0 || 6.10 - 6.13",
"d3/linkmobility-php-client": "^1.2.0 || ^2.0.0",
"d3/oxid-dic-handler": "^1.0",
"d3/testingtools": "^1.1",
"beberlei/assert": "^3.3"
},
"require-dev": {
"oxid-esales/oxideshop-ce": "~6.10.0",
@ -38,7 +41,8 @@
},
"autoload": {
"psr-4": {
"D3\\Linkmobility4OXID\\": "src"
"D3\\Linkmobility4OXID\\": "src",
"D3\\Linkmobility4OXID\\Tests\\": "tests"
}
}
}

View File

@ -4,7 +4,11 @@ parameters:
- ../../oxid-esales/oxideshop-ce/source/oxfunctions.php
paths:
- src
excludePaths:
- src/tests
level: 9
phpVersion: 70100
ignoreErrors:
- '#Psr\\Container\\ContainerExceptionInterface is not subtype of Throwable#'
- '#Psr\\Container\\ContainerExceptionInterface is not subtype of Throwable#'
- '#Cannot cast mixed to string.#'
- '#Method D3\\Linkmobility4OXID\\Setup\\Actions::getUniqueFieldTypes\(\) should return array\<string\> but returns array\<int, string\|null\>.#'

View File

@ -15,53 +15,104 @@ declare(strict_types=1);
namespace D3\Linkmobility4OXID\Application\Controller\Admin;
use Assert\Assert;
use Assert\AssertionFailedException;
use Assert\InvalidArgumentException;
use D3\Linkmobility4OXID\Application\Model\Exceptions\noRecipientFoundException;
use D3\Linkmobility4OXID\Application\Model\Exceptions\successfullySentException;
use D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms;
use D3\Linkmobility4OXID\Application\Model\OrderRecipients;
use D3\LinkmobilityClient\LoggerHandler;
use D3\LinkmobilityClient\Response\ResponseInterface;
use D3\LinkmobilityClient\ValueObject\Recipient;
use D3\TestingTools\Production\IsMockable;
use Exception;
use OxidEsales\Eshop\Application\Controller\Admin\AdminController;
use OxidEsales\Eshop\Application\Model\Order;
use OxidEsales\Eshop\Core\Language;
use OxidEsales\Eshop\Core\Registry;
use OxidEsales\Eshop\Core\Request;
use OxidEsales\Eshop\Core\UtilsView;
class AdminOrder extends AdminController
{
use IsMockable;
protected $_sThisTemplate = 'd3adminorder.tpl';
/**
* @var Sms
*/
protected $sms;
/** @var Order */
protected $item;
/**
* @var Order
*/
protected $order;
/** @var OrderRecipients */
protected $itemRecipients;
public function __construct()
{
$this->order = $order = oxNew(Order::class);
$order->load($this->getEditObjectId());
/** @var Order $item */
$item = d3GetOxidDIC()->get('d3ox.linkmobility.'.Order::class);
$this->item = $item;
d3GetOxidDIC()->set(OrderRecipients::class.'.args.order', $item);
/** @var OrderRecipients $itemRecipients */
$itemRecipients = d3GetOxidDIC()->get(OrderRecipients::class);
$this->itemRecipients = $itemRecipients;
$item->load($this->getEditObjectId());
$this->addTplParam('recipient', $this->getRecipientFromCurrentOrder());
$this->addTplParam('recipient', $this->getRecipientFromCurrentItem());
parent::__construct();
}
/**
* @return Recipient|false
* @return string
* @throws Exception
*/
public function getRecipientFromCurrentOrder()
protected function sendMessage(): string
{
try {
return oxNew(OrderRecipients::class, $this->order)->getSmsRecipient();
$sms = $this->getSms($this->getMessageBody());
return $sms->sendOrderMessage($this->item) ?
$this->getSuccessSentMessage($sms)->getMessage() :
$this->getUnsuccessfullySentMessage($sms);
} catch (noRecipientFoundException $e) {
/** @var string $message */
$message = Registry::getLang()->translateString($e->getMessage());
Registry::getUtilsView()->addErrorToDisplay($message);
/** @var LoggerHandler $loggerHandler */
$loggerHandler = d3GetOxidDIC()->get(LoggerHandler::class);
$loggerHandler->getLogger()->warning($e->getMessage(), [$this->item]);
/** @var UtilsView $utilsView */
$utilsView = d3GetOxidDIC()->get('d3ox.linkmobility.'.UtilsView::class);
$utilsView->addErrorToDisplay($e);
}
return '';
}
/**
* @param string $message
* @return Sms
*/
protected function getSms(string $message): Sms
{
return oxNew(Sms::class, $message);
}
/*** duplicated code but errors while phpunit coverage run if code is in shared abstract class or trait ***/
/**
* @return Recipient|false
*/
public function getRecipientFromCurrentItem()
{
try {
return $this->itemRecipients->getSmsRecipient();
} catch (noRecipientFoundException $e) {
/** @var Language $lang */
$lang = d3GetOxidDIC()->get('d3ox.linkmobility.'.Language::class);
/** @var string $message */
$message = $lang->translateString($e->getMessage());
/** @var UtilsView $utilsView */
$utilsView = d3GetOxidDIC()->get('d3ox.linkmobility.'.UtilsView::class);
$utilsView->addErrorToDisplay($message);
}
return false;
}
@ -71,33 +122,53 @@ class AdminOrder extends AdminController
*/
public function send(): void
{
$messageBody = Registry::getRequest()->getRequestEscapedParameter('messagebody');
if (false === is_string($messageBody) || strlen($messageBody) <= 1) {
/** @var string $message */
$message = Registry::getLang()->translateString('D3LM_EXC_MESSAGE_NO_LENGTH');
Registry::getUtilsView()->addErrorToDisplay($message);
return;
}
$order = oxNew(Order::class);
$order->load($this->getEditObjectId());
/** @var UtilsView $utilsView */
$utilsView = d3GetOxidDIC()->get('d3ox.linkmobility.'.UtilsView::class);
try {
$sms = oxNew(Sms::class, $messageBody);
if ($sms->sendOrderMessage($order)) {
$smsCount = $sms->getResponse() ? $sms->getResponse()->getSmsCount() : 0;
Registry::getUtilsView()->addErrorToDisplay(
oxNew(successfullySentException::class, $smsCount)
);
} else {
$errorMsg = $sms->getResponse() instanceof ResponseInterface ? $sms->getResponse()->getErrorMessage() : 'no response';
/** @var string $format */
$format = Registry::getLang()->translateString('D3LM_EXC_MESSAGE_UNEXPECTED_ERR_SEND');
Registry::getUtilsView()->addErrorToDisplay(sprintf($format, $errorMsg));
}
} catch (noRecipientFoundException $e) {
Registry::getUtilsView()->addErrorToDisplay($e);
$utilsView->addErrorToDisplay($this->sendMessage());
} catch (AssertionFailedException $e) {
$utilsView->addErrorToDisplay($e->getMessage());
}
}
/**
* @return string
* @throws InvalidArgumentException
*/
protected function getMessageBody(): string
{
/** @var Request $request */
$request = d3GetOxidDIC()->get('d3ox.linkmobility.'.Request::class);
$messageBody = $request->getRequestEscapedParameter('messagebody');
$excMessage = Registry::getLang()->translateString('D3LM_EXC_MESSAGE_NO_LENGTH');
Assert::that($messageBody)->string($excMessage)->minLength(2, $excMessage);
return $messageBody;
}
/**
* @param Sms $sms
* @return successfullySentException
*/
protected function getSuccessSentMessage(Sms $sms): successfullySentException
{
$smsCount = $sms->getResponse() ? $sms->getResponse()->getSmsCount() : 0;
/** @var successfullySentException $exc */
$exc = oxNew(successfullySentException::class, $smsCount);
return $exc;
}
/**
* @param Sms $sms
* @return string
*/
protected function getUnsuccessfullySentMessage(Sms $sms): string
{
$errorMsg = $sms->getResponse() instanceof ResponseInterface ? $sms->getResponse()->getErrorMessage() : 'no response';
/** @var string $format */
$format = Registry::getLang()->translateString('D3LM_EXC_MESSAGE_UNEXPECTED_ERR_SEND');
return sprintf($format, $errorMsg);
}
}

View File

@ -15,15 +15,23 @@ declare(strict_types=1);
namespace D3\Linkmobility4OXID\Application\Controller\Admin;
use Assert\Assert;
use Assert\AssertionFailedException;
use Assert\InvalidArgumentException;
use D3\Linkmobility4OXID\Application\Model\Exceptions\noRecipientFoundException;
use D3\Linkmobility4OXID\Application\Model\Exceptions\successfullySentException;
use D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms;
use D3\Linkmobility4OXID\Application\Model\UserRecipients;
use D3\LinkmobilityClient\LoggerHandler;
use D3\LinkmobilityClient\Response\ResponseInterface;
use D3\LinkmobilityClient\ValueObject\Recipient;
use Exception;
use OxidEsales\Eshop\Application\Controller\Admin\AdminController;
use OxidEsales\Eshop\Application\Model\User;
use OxidEsales\Eshop\Core\Language;
use OxidEsales\Eshop\Core\Registry;
use OxidEsales\Eshop\Core\Request;
use OxidEsales\Eshop\Core\UtilsView;
class AdminUser extends AdminController
{
@ -34,33 +42,80 @@ class AdminUser extends AdminController
*/
protected $sms;
/**
* @var User
*/
protected $user;
/** @var User */
protected $item;
/** @var UserRecipients */
protected $itemRecipients;
public function __construct()
{
$this->user = $user = oxNew(User::class);
$user->load($this->getEditObjectId());
/** @var User $item */
$item = d3GetOxidDIC()->get('d3ox.linkmobility.'.User::class);
$this->item = $item;
d3GetOxidDIC()->set(UserRecipients::class.".args.user", $item);
/** @var UserRecipients $itemRecipients */
$itemRecipients = d3GetOxidDIC()->get(UserRecipients::class);
$this->itemRecipients = $itemRecipients;
$item->load($this->getEditObjectId());
$this->addTplParam('recipient', $this->getRecipientFromCurrentUser());
$this->addTplParam('recipient', $this->getRecipientFromCurrentItem());
parent::__construct();
}
/**
* @return Recipient|false
* @return string
* @throws Exception
*/
public function getRecipientFromCurrentUser()
protected function sendMessage(): string
{
try {
return oxNew(UserRecipients::class, $this->user)->getSmsRecipient();
$sms = $this->getSms($this->getMessageBody());
return $sms->sendUserAccountMessage($this->item) ?
$this->getSuccessSentMessage($sms)->getMessage() :
$this->getUnsuccessfullySentMessage($sms);
} catch (noRecipientFoundException $e) {
/** @var string $message */
$message = Registry::getLang()->translateString($e->getMessage());
Registry::getUtilsView()->addErrorToDisplay($message);
/** @var LoggerHandler $loggerHandler */
$loggerHandler = d3GetOxidDIC()->get(LoggerHandler::class);
$loggerHandler->getLogger()->warning($e->getMessage());
/** @var UtilsView $utilsView */
$utilsView = d3GetOxidDIC()->get('d3ox.linkmobility.'.UtilsView::class);
$utilsView->addErrorToDisplay($e);
}
return '';
}
/**
* @param string $message
* @return Sms
*/
protected function getSms(string $message): Sms
{
return oxNew(Sms::class, $message);
}
/*** duplicated code but errors while phpunit coverage run if code is in shared abstract class or trait ***/
/**
* @return Recipient|false
*/
public function getRecipientFromCurrentItem()
{
try {
return $this->itemRecipients->getSmsRecipient();
} catch (noRecipientFoundException $e) {
/** @var Language $lang */
$lang = d3GetOxidDIC()->get('d3ox.linkmobility.'.Language::class);
/** @var string $message */
$message = $lang->translateString($e->getMessage());
/** @var UtilsView $utilsView */
$utilsView = d3GetOxidDIC()->get('d3ox.linkmobility.'.UtilsView::class);
$utilsView->addErrorToDisplay($message);
}
return false;
}
@ -70,30 +125,53 @@ class AdminUser extends AdminController
*/
public function send(): void
{
/** @var string $messageBody */
$messageBody = Registry::getRequest()->getRequestEscapedParameter('messagebody');
/** @var UtilsView $utilsView */
$utilsView = d3GetOxidDIC()->get('d3ox.linkmobility.'.UtilsView::class);
if (strlen($messageBody) <= 1) {
/** @var string $message */
$message = Registry::getLang()->translateString('D3LM_EXC_MESSAGE_NO_LENGTH');
Registry::getUtilsView()->addErrorToDisplay($message);
return;
}
$user = oxNew(User::class);
$user->load($this->getEditObjectId());
$sms = oxNew(Sms::class, $messageBody);
if ($sms->sendUserAccountMessage($user)) {
/** @var string $format */
$format = Registry::getLang()->translateString('D3LM_EXC_SMS_SUCC_SENT');
$smsCount = $sms->getResponse() ? $sms->getResponse()->getSmsCount() : 0;
Registry::getUtilsView()->addErrorToDisplay(sprintf($format, $smsCount));
} else {
$errorMsg = $sms->getResponse() instanceof ResponseInterface ? $sms->getResponse()->getErrorMessage() : 'no response';
/** @var string $format */
$format = Registry::getLang()->translateString('D3LM_EXC_MESSAGE_UNEXPECTED_ERR_SEND');
Registry::getUtilsView()->addErrorToDisplay(sprintf($format, $errorMsg));
try {
$utilsView->addErrorToDisplay($this->sendMessage());
} catch (AssertionFailedException $e) {
$utilsView->addErrorToDisplay($e->getMessage());
}
}
/**
* @return string
* @throws InvalidArgumentException
*/
protected function getMessageBody(): string
{
/** @var Request $request */
$request = d3GetOxidDIC()->get('d3ox.linkmobility.'.Request::class);
$messageBody = $request->getRequestEscapedParameter('messagebody');
$excMessage = Registry::getLang()->translateString('D3LM_EXC_MESSAGE_NO_LENGTH');
Assert::that($messageBody)->string($excMessage)->minLength(2, $excMessage);
return $messageBody;
}
/**
* @param Sms $sms
* @return successfullySentException
*/
protected function getSuccessSentMessage(Sms $sms): successfullySentException
{
$smsCount = $sms->getResponse() ? $sms->getResponse()->getSmsCount() : 0;
/** @var successfullySentException $exc */
$exc = oxNew(successfullySentException::class, $smsCount);
return $exc;
}
/**
* @param Sms $sms
* @return string
*/
protected function getUnsuccessfullySentMessage(Sms $sms): string
{
$errorMsg = $sms->getResponse() instanceof ResponseInterface ? $sms->getResponse()->getErrorMessage() : 'no response';
/** @var string $format */
$format = Registry::getLang()->translateString('D3LM_EXC_MESSAGE_UNEXPECTED_ERR_SEND');
return sprintf($format, $errorMsg);
}
}

View File

@ -16,9 +16,10 @@ declare(strict_types=1);
namespace D3\Linkmobility4OXID\Application\Model;
use Assert\Assert;
use Assert\InvalidArgumentException;
use OxidEsales\Eshop\Application\Model\Order;
use OxidEsales\Eshop\Application\Model\User;
use OxidEsales\Eshop\Core\Registry;
use OxidEsales\Eshop\Core\Config;
class Configuration
{
@ -40,14 +41,15 @@ class Configuration
/**
* @return string
* @throws InvalidArgumentException
*/
public function getApiToken(): string
{
/** @var string $token */
$token = Registry::getConfig()->getConfigParam(self::GENERAL_APITOKEN);
$token = $this->getConfig()->getConfigParam(self::GENERAL_APITOKEN);
Assert::that($token)->string();
$token = trim($token);
Assert::that($token)->string()->notEmpty();
Assert::that($token)->notEmpty();
return $token;
}
@ -57,16 +59,18 @@ class Configuration
*/
public function getTestMode(): bool
{
return (bool) Registry::getConfig()->getConfigParam(self::GENERAL_DEBUG);
return (bool) $this->getConfig()->getConfigParam(self::GENERAL_DEBUG);
}
/**
* @return string|null
* @throws InvalidArgumentException
*/
public function getSmsSenderNumber()
public function getSmsSenderNumber(): ?string
{
/** @var string $number */
$number = Registry::getConfig()->getConfigParam(self::SMS_SENDERNR);
$number = $this->getConfig()->getConfigParam(self::SMS_SENDERNR);
Assert::that($number)->string();
$number = trim($number);
return strlen($number) ? $number : null;
@ -74,56 +78,78 @@ class Configuration
/**
* @return string|null
* @throws InvalidArgumentException
*/
public function getSmsSenderCountry(): ?string
{
/** @var string $country */
$country = Registry::getConfig()->getConfigParam(self::SMS_SENDERCOUNTRY);
$country = $this->getConfig()->getConfigParam(self::SMS_SENDERCOUNTRY);
Assert::that($country)->string();
$country = trim($country);
$country = strlen($country) ? strtoupper($country) : null;
Assert::that($country)->nullOr()->string()->length(2);
Assert::thatNullOr($country)->string()->length(2);
return $country;
}
/**
* @return string[]
* @throws InvalidArgumentException
*/
public function getOrderRecipientFields(): array
{
/** @var string[] $customFields */
$customFields = Registry::getConfig()->getConfigParam(self::ORDER_RECFIELDS) ?: [];
$customFields = $this->getConfig()->getConfigParam(self::ORDER_RECFIELDS) ?: [];
Assert::that($customFields)->isArray();
array_walk(
$customFields,
[$this, 'checkFieldExists'],
[self::ARGS_CHECKKEYS => true, self::ARGS_CHECKCLASS => Order::class]
);
$customFields = array_filter($customFields);
Assert::that($customFields)->isArray();
return $customFields;
// remove all false values and trim keys
return array_filter($this->sanitizeKeys($customFields));
}
/**
* @return string[]
* @throws InvalidArgumentException
*/
public function getUserRecipientFields(): array
{
/** @var string[] $customFields */
$customFields = Registry::getConfig()->getConfigParam(self::USER_RECFIELDS) ?: [];
$customFields = $this->getConfig()->getConfigParam(self::USER_RECFIELDS) ?: [];
Assert::that($customFields)->isArray();
array_walk(
$customFields,
[$this, 'checkFieldExists'],
[self::ARGS_CHECKKEYS => false, self::ARGS_CHECKCLASS => User::class]
);
$customFields = array_filter($customFields);
Assert::that($customFields)->isArray();
// remove all false values
return array_filter($customFields);
}
/**
* @param string[] $customFields
* @return string[]
*/
public function sanitizeKeys(array $customFields): array
{
foreach ($customFields as $key => $value) {
$sanitizedKey = trim($key);
if ($key !== $sanitizedKey) {
$customFields[$sanitizedKey] = $value;
unset($customFields[$key]);
}
}
return $customFields;
}
@ -138,6 +164,7 @@ class Configuration
{
$checkCountryFieldName = $args[self::ARGS_CHECKKEYS] ? trim($checkCountryFieldName) : $checkCountryFieldName;
$checkPhoneFieldName = trim($checkPhoneFieldName);
$allFieldNames = oxNew($args[self::ARGS_CHECKCLASS])->getFieldNames() ?: [];
array_walk($allFieldNames, function (&$value) {
@ -155,7 +182,7 @@ class Configuration
*/
public function sendOrderFinishedMessage(): bool
{
return (bool) Registry::getConfig()->getConfigParam(self::SENDBY_ORDERED);
return (bool) $this->getConfig()->getConfigParam(self::SENDBY_ORDERED);
}
/**
@ -163,7 +190,7 @@ class Configuration
*/
public function sendOrderSendedNowMessage(): bool
{
return (bool) Registry::getConfig()->getConfigParam(self::SENDBY_SENDEDNOW);
return (bool) $this->getConfig()->getConfigParam(self::SENDBY_SENDEDNOW);
}
/**
@ -171,6 +198,16 @@ class Configuration
*/
public function sendOrderCanceledMessage(): bool
{
return (bool) Registry::getConfig()->getConfigParam(self::SENDBY_CANCELED);
return (bool) $this->getConfig()->getConfigParam(self::SENDBY_CANCELED);
}
/**
* @return Config
*/
protected function getConfig(): Config
{
/** @var Config $config */
$config = d3GetOxidDIC()->get('d3ox.linkmobility.'.Config::class);
return $config;
}
}

View File

@ -15,6 +15,8 @@ declare(strict_types=1);
namespace D3\Linkmobility4OXID\Application\Model\Exceptions;
interface abortSendingExceptionInterface extends \Throwable
use Throwable;
interface abortSendingExceptionInterface extends Throwable
{
}

View File

@ -17,7 +17,7 @@ namespace D3\Linkmobility4OXID\Application\Model\Exceptions;
use Exception;
use OxidEsales\Eshop\Core\Exception\StandardException;
use OxidEsales\Eshop\Core\Registry;
use OxidEsales\Eshop\Core\Language;
class successfullySentException extends StandardException
{
@ -28,8 +28,10 @@ class successfullySentException extends StandardException
*/
public function __construct($messageCount = 1, $code = 0, Exception $previous = null)
{
/** @var Language $language */
$language = d3GetOxidDIC()->get('d3ox.linkmobility.'.Language::class);
/** @var string $format */
$format = Registry::getLang()->translateString('D3LM_EXC_SMS_SUCC_SENT');
$format = $language->translateString('D3LM_EXC_SMS_SUCC_SENT');
$message = sprintf($format, $messageCount);
parent::__construct($message, $code, $previous);

View File

@ -16,8 +16,6 @@ declare(strict_types=1);
namespace D3\Linkmobility4OXID\Application\Model;
use D3\LinkmobilityClient\Client;
use D3\LinkmobilityClient\LoggerHandler;
use OxidEsales\Eshop\Core\Registry;
class MessageClient
{
@ -26,8 +24,11 @@ class MessageClient
*/
public function getClient(): Client
{
$client = oxNew(Client::class, oxNew(Configuration::class)->getApiToken());
LoggerHandler::getInstance()->setLogger(Registry::getLogger());
/** @var Configuration $configuration */
$configuration = d3GetOxidDIC()->get(Configuration::class);
/** @var Client $client */
$client = oxNew(Client::class, $configuration->getApiToken());
return $client;
}

View File

@ -17,6 +17,7 @@ namespace D3\Linkmobility4OXID\Application\Model;
use D3\Linkmobility4OXID\Application\Model\Exceptions\noRecipientFoundException;
use D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms;
use D3\LinkmobilityClient\LoggerHandler;
use Exception;
use OxidEsales\Eshop\Application\Model\Order;
@ -30,8 +31,14 @@ class MessageSender
*/
public function sendOrderFinishedMessage(Order $order, string $messageBody): void
{
if ((oxNew(Configuration::class))->sendOrderFinishedMessage()) {
$this->sendMessageByOrder($order, $messageBody);
try {
if ($this->getConfiguration()->sendOrderFinishedMessage()) {
$this->sendMessageByOrder($order, $messageBody);
}
} catch (noRecipientFoundException $e) {
/** @var LoggerHandler $loggerHandler */
$loggerHandler = d3GetOxidDIC()->get(LoggerHandler::class);
$loggerHandler->getLogger()->debug($e->getMessage(), [$order]);
}
}
@ -43,8 +50,14 @@ class MessageSender
*/
public function sendSendedNowMessage(Order $order, string $messageBody): void
{
if ((oxNew(Configuration::class))->sendOrderSendedNowMessage()) {
$this->sendMessageByOrder($order, $messageBody);
try {
if ($this->getConfiguration()->sendOrderSendedNowMessage()) {
$this->sendMessageByOrder($order, $messageBody);
}
} catch (noRecipientFoundException $e) {
/** @var LoggerHandler $loggerHandler */
$loggerHandler = d3GetOxidDIC()->get(LoggerHandler::class);
$loggerHandler->getLogger()->debug($e->getMessage(), [$order]);
}
}
@ -56,16 +69,23 @@ class MessageSender
*/
public function sendCancelOrderMessage(Order $order, string $messageBody): void
{
if ((oxNew(Configuration::class))->sendOrderCanceledMessage()) {
$this->sendMessageByOrder($order, $messageBody);
try {
if ($this->getConfiguration()->sendOrderCanceledMessage()) {
$this->sendMessageByOrder($order, $messageBody);
}
} catch (noRecipientFoundException $e) {
/** @var LoggerHandler $loggerHandler */
$loggerHandler = d3GetOxidDIC()->get(LoggerHandler::class);
$loggerHandler->getLogger()->debug($e->getMessage(), [$order]);
}
}
/**
* @param Order $order
* @param Order $order
* @param string $messageBody
*
* @return void
* @throws Exception
* @throws noRecipientFoundException
*/
public function sendMessageByOrder(Order $order, string $messageBody): void
{
@ -73,10 +93,26 @@ class MessageSender
return;
}
try {
$sms = oxNew(Sms::class, $messageBody);
$sms->sendOrderMessage($order);
} catch (noRecipientFoundException $e) {
}
$sms = $this->getSms($messageBody);
$sms->sendOrderMessage($order);
}
/**
* @param string $message
* @return Sms
*/
protected function getSms(string $message): Sms
{
return oxNew(Sms::class, $message);
}
/**
* @return Configuration
*/
protected function getConfiguration(): Configuration
{
/** @var Configuration $configuration */
$configuration = d3GetOxidDIC()->get(Configuration::class);
return $configuration;
}
}

View File

@ -15,6 +15,7 @@ declare(strict_types=1);
namespace D3\Linkmobility4OXID\Application\Model\MessageTypes;
use D3\LinkmobilityClient\RecipientsList\RecipientsListInterface;
use D3\LinkmobilityClient\Response\ResponseInterface;
use D3\LinkmobilityClient\ValueObject\Recipient;
use Exception;
@ -26,15 +27,18 @@ abstract class AbstractMessage
/** @var string */
protected $message;
/** @var bool */
protected $removeLineBreaks = true;
/** @var bool */
protected $removeMultipleSpaces = true;
/** @var ResponseInterface */
protected $response;
/** @var Recipient[] */
protected $recipients = [];
/** @var RecipientsListInterface */
protected $recipients;
/**
* @param string $message
@ -62,7 +66,8 @@ abstract class AbstractMessage
*/
protected function setRemark(string $userId, string $recipients, string $message): void
{
$remark = oxNew(Remark::class);
/** @var Remark $remark */
$remark = d3GetOxidDIC()->get('d3ox.linkmobility.'.Remark::class);
$remark->assign([
'oxtype' => self::REMARK_IDENT,
'oxparentid' => $userId,
@ -74,16 +79,16 @@ abstract class AbstractMessage
/**
* @return ResponseInterface|null
*/
public function getResponse()
public function getResponse(): ?ResponseInterface
{
return $this->response;
}
/**
* @param array<Recipient> $recipients
* @param RecipientsListInterface $recipients
* @return void
*/
protected function setRecipients(array $recipients)
protected function setRecipients(RecipientsListInterface $recipients)
{
$this->recipients = $recipients;
}
@ -95,7 +100,7 @@ abstract class AbstractMessage
{
$list = [];
/** @var Recipient $recipient */
foreach ($this->recipients as $recipient) {
foreach ($this->recipients->getRecipientsList() as $recipient) {
$list[] = $recipient->get();
}
@ -111,7 +116,7 @@ abstract class AbstractMessage
{
$message = trim(strip_tags($message));
$message = $this->removeLineBreaks ? str_replace(["\r", "\n"], ' ', $message) : $message;
$regexp = '/\s{2,}/m';
$regexp = '/[^\S\r\n]{2,}/m';
return $this->removeMultipleSpaces ? (string) preg_replace($regexp, ' ', $message) : $message;
}

View File

@ -15,24 +15,31 @@ declare(strict_types=1);
namespace D3\Linkmobility4OXID\Application\Model\MessageTypes;
use Assert\AssertionFailedException;
use D3\Linkmobility4OXID\Application\Model\Configuration;
use D3\Linkmobility4OXID\Application\Model\Exceptions\abortSendingExceptionInterface;
use D3\Linkmobility4OXID\Application\Model\Exceptions\noRecipientFoundException;
use D3\Linkmobility4OXID\Application\Model\MessageClient;
use D3\Linkmobility4OXID\Application\Model\OrderRecipients;
use D3\Linkmobility4OXID\Application\Model\RequestFactory;
use D3\Linkmobility4OXID\Application\Model\UserRecipients;
use D3\LinkmobilityClient\Exceptions\ApiException;
use D3\LinkmobilityClient\Client;
use D3\LinkmobilityClient\Exceptions\RecipientException;
use D3\LinkmobilityClient\LoggerHandler;
use D3\LinkmobilityClient\RecipientsList\RecipientsList;
use D3\LinkmobilityClient\RecipientsList\RecipientsListInterface;
use D3\LinkmobilityClient\Request\RequestInterface;
use D3\LinkmobilityClient\Response\ResponseInterface;
use D3\LinkmobilityClient\SMS\SmsRequestInterface;
use D3\LinkmobilityClient\ValueObject\Recipient;
use D3\LinkmobilityClient\ValueObject\Sender;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use InvalidArgumentException;
use libphonenumber\NumberParseException;
use OxidEsales\Eshop\Application\Model\Order;
use OxidEsales\Eshop\Application\Model\User;
use OxidEsales\Eshop\Core\Registry;
use OxidEsales\Eshop\Core\Language;
use OxidEsales\Eshop\Core\UtilsView;
use Psr\Log\LoggerInterface;
class Sms extends AbstractMessage
{
@ -40,26 +47,39 @@ class Sms extends AbstractMessage
* @param User $user
*
* @return bool
* @throws Exception
* @throws noRecipientFoundException
*/
public function sendUserAccountMessage(User $user): bool
{
try {
Registry::getLogger()->debug('startRequest', ['userId' => $user->getId()]);
$return = $this->sendCustomRecipientMessage(
[ oxNew(UserRecipients::class, $user)->getSmsRecipient() ]
);
if ($return) {
$this->setRemark($user->getId(), $this->getRecipientsList(), $this->getMessage());
}
Registry::getLogger()->debug('finishRequest', ['userId' => $user->getId()]);
return $return;
} catch (noRecipientFoundException $e) {
Registry::getLogger()->warning($e->getMessage());
Registry::getUtilsView()->addErrorToDisplay($e);
$this->getLogger()->debug('Linkmobility: startRequest', ['userId' => $user->getId()]);
$return = $this->sendCustomRecipientMessage($this->getUserRecipientsList($user));
if ($return) {
$this->setRemark($user->getId(), $this->getRecipientsList(), $this->getMessage());
}
$this->getLogger()->debug('Linkmobility: finishRequest', ['userId' => $user->getId()]);
return $return;
}
return false;
/**
* @param User $user
* @return RecipientsListInterface
* @throws noRecipientFoundException
*/
protected function getUserRecipientsList(User $user): RecipientsListInterface
{
/** @var MessageClient $messageClient */
$messageClient = d3GetOxidDIC()->get(MessageClient::class);
d3GetOxidDIC()->set(RecipientsList::class.'.args.client', $messageClient->getClient());
/** @var RecipientsList $recipientsList */
$recipientsList = d3GetOxidDIC()->get(RecipientsList::class);
d3GetOxidDIC()->set(UserRecipients::class.'.args.user', $user);
/** @var UserRecipients $userRecipients */
$userRecipients = d3GetOxidDIC()->get(UserRecipients::class);
return $recipientsList->add(
$userRecipients->getSmsRecipient()
);
}
/**
@ -71,78 +91,146 @@ class Sms extends AbstractMessage
*/
public function sendOrderMessage(Order $order): bool
{
try {
Registry::getLogger()->debug('startRequest', ['orderId' => $order->getId()]);
$return = $this->sendCustomRecipientMessage(
[ oxNew(OrderRecipients::class, $order)->getSmsRecipient() ]
);
if ($return) {
$this->setRemark($order->getOrderUser()->getId(), $this->getRecipientsList(), $this->getMessage());
}
Registry::getLogger()->debug('finishRequest', ['orderId' => $order->getId()]);
return $return;
} catch (noRecipientFoundException $e) {
Registry::getLogger()->warning($e->getMessage());
throw $e;
$this->getLogger()->debug('Linkmobility: startRequest', ['orderId' => $order->getId()]);
$return = $this->sendCustomRecipientMessage($this->getOrderRecipientsList($order));
if ($return) {
$this->setRemark($order->getOrderUser()->getId(), $this->getRecipientsList(), $this->getMessage());
}
$this->getLogger()->debug('Linkmobility: finishRequest', ['orderId' => $order->getId()]);
return $return;
}
/**
* @param array<Recipient> $recipientsArray
* @param Order $order
* @return RecipientsListInterface
* @throws noRecipientFoundException
*/
protected function getOrderRecipientsList(Order $order): RecipientsListInterface
{
/** @var MessageClient $messageClient */
$messageClient = d3GetOxidDIC()->get(MessageClient::class);
d3GetOxidDIC()->set(RecipientsList::class.'.args.client', $messageClient->getClient());
/** @var RecipientsList $recipientsList */
$recipientsList = d3GetOxidDIC()->get(RecipientsList::class);
return $recipientsList->add(
$this->getOrderRecipient(($order))
);
}
/**
* @param Order $order
* @return Recipient
* @throws noRecipientFoundException
*/
protected function getOrderRecipient(Order $order): Recipient
{
d3GetOxidDIC()->set(OrderRecipients::class.'.args.order', $order);
/** @var OrderRecipients $orderRecipients */
$orderRecipients = d3GetOxidDIC()->get(OrderRecipients::class);
return $orderRecipients->getSmsRecipient();
}
/**
* @param RecipientsListInterface $recipientsList
*
* @return bool
*/
public function sendCustomRecipientMessage(array $recipientsArray): bool
public function sendCustomRecipientMessage(RecipientsListInterface $recipientsList): bool
{
try {
$this->setRecipients($recipientsArray);
$configuration = oxNew(Configuration::class);
$client = oxNew(MessageClient::class)->getClient();
/** @var SmsRequestInterface $request */
$request = oxNew(RequestFactory::class, $this->getMessage(), $client)->getSmsRequest();
$request->setTestMode($configuration->getTestMode())->setMethod(RequestInterface::METHOD_POST)
->setSenderAddress(
oxNew(
Sender::class,
$configuration->getSmsSenderNumber(),
$configuration->getSmsSenderCountry()
)
)
->setSenderAddressType(RequestInterface::SENDERADDRESSTYPE_INTERNATIONAL);
$recipientsList = $request->getRecipientsList();
foreach ($recipientsArray as $recipient) {
$recipientsList->add($recipient);
}
$response = $client->request($request);
$this->response = $response;
if (false === $response->isSuccessful()) {
Registry::getLogger()->warning($response->getErrorMessage(), [$request->getBody()]);
}
$this->response = $response = $this->submitMessage($recipientsList);
return $response->isSuccessful();
} catch (abortSendingExceptionInterface $e) {
Registry::getLogger()->warning($e->getMessage());
// Oxid does not accept throwable interface only exceptions according by definition
Registry::getUtilsView()->addErrorToDisplay($e->getMessage());
} catch (GuzzleException $e) {
Registry::getLogger()->warning($e->getMessage());
Registry::getUtilsView()->addErrorToDisplay($e->getMessage());
} catch (ApiException $e) {
Registry::getLogger()->warning($e->getMessage());
Registry::getUtilsView()->addErrorToDisplay($e->getMessage());
} catch (InvalidArgumentException $e) {
Registry::getLogger()->warning($e->getMessage());
Registry::getUtilsView()->addErrorToDisplay($e->getMessage());
} catch (GuzzleException|AssertionFailedException $e) {
$this->getLogger()->error($e->getMessage());
// Oxid does not accept throwable interface only exceptions according to definition
/** @var UtilsView $utilsView */
$utilsView = d3GetOxidDIC()->get('d3ox.linkmobility.'.UtilsView::class);
/** @var Language $language */
$language = d3GetOxidDIC()->get('d3ox.linkmobility.'.Language::class);
/** @var string $message */
$message = $language->translateString('D3LM_EXC_REQUESTERROR', null, true);
$utilsView->addErrorToDisplay($message);
}
return false;
}
/**
* @param Configuration $configuration
* @param Client $client
* @return SmsRequestInterface
* @throws NumberParseException
* @throws RecipientException
*/
protected function getRequest(Configuration $configuration, Client $client): SmsRequestInterface
{
$requestFactory = $this->getRequestFactory($this->getMessage(), $client);
$sender = $this->getSender((string) $configuration->getSmsSenderNumber(), (string) $configuration->getSmsSenderCountry());
$request = $requestFactory->getSmsRequest();
$request->setTestMode($configuration->getTestMode())->setMethod(RequestInterface::METHOD_POST)
->setSenderAddress($sender)
->setSenderAddressType(RequestInterface::SENDERADDRESSTYPE_INTERNATIONAL);
return $request;
}
/**
* @param string $message
* @param Client $client
* @return RequestFactory
*/
protected function getRequestFactory(string $message, Client $client): RequestFactory
{
return oxNew(RequestFactory::class, $message, $client);
}
/**
* @param string $number
* @param string $countryCode
* @throws NumberParseException
* @throws RecipientException
* @return Sender
*/
protected function getSender(string $number, string $countryCode): Sender
{
return oxNew(Sender::class, $number, $countryCode);
}
/**
* @param RecipientsListInterface $recipientsList
* @return ResponseInterface
* @throws GuzzleException
* @throws NumberParseException
* @throws RecipientException
*/
protected function submitMessage(RecipientsListInterface $recipientsList): ResponseInterface
{
$this->setRecipients($recipientsList);
/** @var Configuration $configuration */
$configuration = d3GetOxidDIC()->get(Configuration::class);
/** @var MessageClient $messageClient */
$messageClient = d3GetOxidDIC()->get(MessageClient::class);
$client = $messageClient->getClient();
$request = $this->getRequest($configuration, $client);
$requestRecipientsList = $request->getRecipientsList();
foreach ($recipientsList->getRecipientsList() as $recipient) {
$requestRecipientsList->add($recipient);
}
$response = $client->request($request);
if (false === $response->isSuccessful()) {
$this->getLogger()->warning($response->getErrorMessage(), [$request->getBody()]);
}
return $response;
}
/**
* @return string
*/
@ -150,4 +238,14 @@ class Sms extends AbstractMessage
{
return 'SMS';
}
/**
* @return LoggerInterface
*/
public function getLogger(): LoggerInterface
{
/** @var LoggerHandler $loggerHandler */
$loggerHandler = d3GetOxidDIC()->get(LoggerHandler::class);
return $loggerHandler->getLogger();
}
}

View File

@ -28,7 +28,7 @@ class OrderRecipients
/**
* @var Order
*/
private $order;
protected $order;
public function __construct(Order $order)
{
@ -42,22 +42,8 @@ class OrderRecipients
public function getSmsRecipient(): Recipient
{
foreach ($this->getSmsRecipientFields() as $phoneFieldName => $countryIdFieldName) {
/** @var string $content */
$content = $this->order->getFieldData($phoneFieldName) ?: '';
$content = trim($content);
$country = oxNew(Country::class);
try {
if (strlen($content)) {
/** @var string $countryId */
$countryId = $this->order->getFieldData(trim($countryIdFieldName));
$country->load($countryId);
return oxNew(Recipient::class, $content, $country->getFieldData('oxisoalpha2'));
}
} catch (NumberParseException $e) {
LoggerHandler::getInstance()->getLogger()->info($e->getMessage(), [$content, $country->getFieldData('oxisoalpha2')]);
} catch (RecipientException $e) {
LoggerHandler::getInstance()->getLogger()->info($e->getMessage(), [$content, $country->getFieldData('oxisoalpha2')]);
if ($recipient = $this->getSmsRecipientByField($phoneFieldName, $countryIdFieldName)) {
return $recipient;
}
}
@ -66,12 +52,58 @@ class OrderRecipients
throw $exc;
}
/**
* @param string $phoneFieldName
* @param string $countryIdFieldName
* @return Recipient|null
*/
protected function getSmsRecipientByField(string $phoneFieldName, string $countryIdFieldName): ?Recipient
{
/** @var Country $country */
$country = d3GetOxidDIC()->get('d3ox.linkmobility.'.Country::class);
try {
/** @var string $content */
$content = $this->order->getFieldData($phoneFieldName) ?: '';
$content = trim($content);
if (strlen($content)) {
/** @var string $countryId */
$countryId = $this->order->getFieldData(trim($countryIdFieldName));
$country->load($countryId);
return $this->getRecipient($content, (string) $country->getFieldData('oxisoalpha2'));
}
} catch (NumberParseException|RecipientException $e) {
/** @var LoggerHandler $loggerHandler */
$loggerHandler = d3GetOxidDIC()->get(LoggerHandler::class);
$loggerHandler->getLogger()->info(
$e->getMessage(),
[$content, $country->getFieldData('oxisoalpha2')]
);
}
return null;
}
/**
* @param string $content
* @param string $countryCode
* @throws NumberParseException
* @throws RecipientException
* @return Recipient
*/
protected function getRecipient(string $content, string $countryCode): Recipient
{
return oxNew(Recipient::class, $content, $countryCode);
}
/**
* @return string[]
*/
public function getSmsRecipientFields(): array
{
$customFields = (oxNew(Configuration::class))->getOrderRecipientFields();
/** @var Configuration $configuration */
$configuration = d3GetOxidDIC()->get(Configuration::class);
$customFields = $configuration->getOrderRecipientFields();
return count($customFields) ?
$customFields :

View File

@ -15,24 +15,48 @@ declare(strict_types=1);
namespace D3\Linkmobility4OXID\Application\Model;
use D3\LinkmobilityClient\Exceptions\RecipientException;
use D3\LinkmobilityClient\Request\RequestInterface;
use D3\LinkmobilityClient\SMS\SmsRequestInterface;
use D3\LinkmobilityClient\ValueObject\Sender;
use D3\TestingTools\Production\IsMockable;
use libphonenumber\NumberParseException;
class RequestFactory extends \D3\LinkmobilityClient\SMS\RequestFactory
{
use IsMockable;
/**
* @return SmsRequestInterface
* @throws NumberParseException
* @throws RecipientException
*/
public function getSmsRequest(): SmsRequestInterface
{
$configuration = oxNew(Configuration::class);
/** @var Configuration $configuration */
$configuration = d3GetOxidDIC()->get(Configuration::class);
/** parent call */
/** @var SmsRequestInterface $request */
$request = parent::getSmsRequest();
$request = $this->d3CallMockableFunction([\D3\LinkmobilityClient\SMS\RequestFactory::class, 'getSmsRequest']);
$sender = $this->getSender((string) $configuration->getSmsSenderNumber(), (string) $configuration->getSmsSenderCountry());
$request->setTestMode($configuration->getTestMode())
->setSenderAddress(
oxNew(Sender::class, $configuration->getSmsSenderNumber(), $configuration->getSmsSenderCountry())
)
->setSenderAddress($sender)
->setSenderAddressType(RequestInterface::SENDERADDRESSTYPE_INTERNATIONAL);
return $request;
}
/**
* @param string $number
* @param string $countryCode
* @throws NumberParseException
* @throws RecipientException
* @return Sender
*/
protected function getSender(string $number, string $countryCode): Sender
{
return oxNew(Sender::class, $number, $countryCode);
}
}

View File

@ -28,7 +28,7 @@ class UserRecipients
/**
* @var User
*/
private $user;
protected $user;
public function __construct(User $user)
{
@ -42,36 +42,68 @@ class UserRecipients
public function getSmsRecipient(): Recipient
{
foreach ($this->getSmsRecipientFields() as $fieldName) {
/** @var string $content */
$content = $this->user->getFieldData($fieldName) ?: '';
$content = trim($content);
$country = oxNew(Country::class);
try {
if (strlen($content)) {
/** @var string $countryId */
$countryId = $this->user->getFieldData('oxcountryid');
$country->load($countryId);
return oxNew(Recipient::class, $content, $country->getFieldData('oxisoalpha2'));
}
} catch (NumberParseException $e) {
LoggerHandler::getInstance()->getLogger()->info($e->getMessage(), [$content, $country->getFieldData('oxisoalpha2')]);
} catch (RecipientException $e) {
LoggerHandler::getInstance()->getLogger()->info($e->getMessage(), [$content, $country->getFieldData('oxisoalpha2')]);
if ($recipient = $this->getSmsRecipientByField($fieldName)) {
return $recipient;
}
}
/** @var noRecipientFoundException $exc */
$exc = oxNew(noRecipientFoundException::class);
$exc = d3GetOxidDIC()->get(noRecipientFoundException::class);
throw $exc;
}
/**
* @param string $fieldName
* @return Recipient|null
*/
protected function getSmsRecipientByField(string $fieldName): ?Recipient
{
/** @var Country $country */
$country = d3GetOxidDIC()->get('d3ox.linkmobility.'.Country::class);
try {
/** @var string $content */
$content = $this->user->getFieldData($fieldName) ?: '';
$content = trim($content);
if (strlen($content)) {
/** @var string $countryId */
$countryId = $this->user->getFieldData('oxcountryid');
$country->load($countryId);
return $this->getRecipient($content, (string) $country->getFieldData('oxisoalpha2'));
}
} catch (NumberParseException|RecipientException $e) {
/** @var LoggerHandler $loggerHandler */
$loggerHandler = d3GetOxidDIC()->get(LoggerHandler::class);
$loggerHandler->getLogger()->info(
$e->getMessage(),
[$content, $country->getFieldData('oxisoalpha2')]
);
}
return null;
}
/**
* @param string $content
* @param string $countryCode
* @throws NumberParseException
* @throws RecipientException
* @return Recipient
*/
protected function getRecipient(string $content, string $countryCode): Recipient
{
return oxNew(Recipient::class, $content, $countryCode);
}
/**
* @return string[]
*/
public function getSmsRecipientFields(): array
{
$customFields = (oxNew(Configuration::class))->getUserRecipientFields();
/** @var Configuration $configuration */
$configuration = d3GetOxidDIC()->get(Configuration::class);
$customFields = $configuration->getUserRecipientFields();
return count($customFields) ?
$customFields :

View File

@ -0,0 +1,29 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
// @codeCoverageIgnoreStart
$sLangName = "Deutsch";
$aLang = [
'charset' => 'UTF-8',
'D3LM_EXC_MESSAGE_NO_LENGTH' => 'Die Benachrichtigung kann ohne Inhalt nicht versendet werden.',
'D3LM_EXC_SMS_SUCC_SENT' => 'Die Mitteilung wurde erfolgreich versendet.',
'D3LM_EXC_MESSAGE_UNEXPECTED_ERR_SEND' => 'Beim Versenden der Nachricht(en) ist ein Fehler aufgetreten.',
'D3LM_EXC_NO_RECIPIENT_SET' => 'Kein (verwendbarer) Empfänger für die Benachrichtigung vorhanden.',
];
// @codeCoverageIgnoreEnd

View File

@ -0,0 +1,29 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
// @codeCoverageIgnoreStart
$sLangName = "English";
$aLang = [
'charset' => 'UTF-8',
'D3LM_EXC_MESSAGE_NO_LENGTH' => 'The message cannot be sent without content.',
'D3LM_EXC_SMS_SUCC_SENT' => 'The message was sent successfully.',
'D3LM_EXC_MESSAGE_UNEXPECTED_ERR_SEND' => 'An error occurred while sending the message(s).',
'D3LM_EXC_NO_RECIPIENT_SET' => 'No (usable) recipient for the message available.',
];
// @codeCoverageIgnoreEnd

View File

@ -13,13 +13,11 @@
declare(strict_types=1);
$sLangName = "Deutsch";
// -------------------------------
// RESOURCE IDENTITFIER = STRING
// -------------------------------
$aLang = [
// @codeCoverageIgnoreStart
//Navigation
$sLangName = "Deutsch";
$aLang = [
'charset' => 'UTF-8',
'SHOP_MODULE_GROUP_d3linkmobility_general' => 'Grundeinstellungen',
@ -54,9 +52,12 @@ $aLang = [
'D3LM_EXC_SMS_SUCC_SENT' => 'Die Mitteilung wurde erfolgreich versendet. (%1$s Nachricht(en) verwendet)',
'D3LM_EXC_MESSAGE_UNEXPECTED_ERR_SEND' => 'Beim Versenden der Nachricht(en) ist dieser Fehler aufgetreten: %1$s',
'D3LM_EXC_NO_RECIPIENT_SET' => 'Kein (verwendbarer) Empfänger gesetzt.',
'D3LM_EXC_REQUESTERROR' => 'Es ist ein Fehler beim Abfragen des Nachrichtenservices aufgetreten.',
'D3LM_REMARK_SMS' => 'SMS-Nachr.',
'tbcluser_linkmobility' => 'SMS-Versand',
'tbclorder_linkmobility' => 'SMS-Versand'
];
// @codeCoverageIgnoreEnd

View File

@ -13,13 +13,11 @@
declare(strict_types=1);
$sLangName = "English";
// -------------------------------
// RESOURCE IDENTITFIER = STRING
// -------------------------------
$aLang = [
// @codeCoverageIgnoreStart
//Navigation
$sLangName = "English";
$aLang = [
'charset' => 'UTF-8',
'SHOP_MODULE_GROUP_d3linkmobility_general' => 'Basic settings',
@ -54,9 +52,12 @@ $aLang = [
'D3LM_EXC_SMS_SUCC_SENT' => 'The message was sent successfully. (%1$s message(s) used)',
'D3LM_EXC_MESSAGE_UNEXPECTED_ERR_SEND' => 'This error occurred while sending the message(s): %1$s',
'D3LM_EXC_NO_RECIPIENT_SET' => 'No (usable) recipient number is set.',
'D3LM_EXC_REQUESTERROR' => 'An error occurred while querying the message service.',
'D3LM_REMARK_SMS' => 'SMS message',
'tbcluser_linkmobility' => 'sending SMS',
'tbclorder_linkmobility' => 'sending SMS'
];
// @codeCoverageIgnoreEnd

View File

@ -1,7 +1,3 @@
[{assign var="shop" value=$oEmailView->getShop()}]
Hallo [{$order->getFieldData('oxbillfname')}] [{$order->getFieldData('oxbilllname')}],
vielen Dank für Ihre Bestellung. Wir haben diese unter der Bestellnummer [{$order->oxorder__oxordernr->value}] angelegt und werden diese schnellstmöglich bearbeiten.
Ihr Team von [{$shop->getFieldData('oxname')}].
[{oxcontent ident="d3linkmobilityfinishedorder"}]

View File

@ -1,8 +1,3 @@
[{assign var="shop" value=$oEmailView->getShop()}]
Hallo [{$order->getFieldData('oxbillfname')}] [{$order->getFieldData('oxbilllname')}],
Ihre Bestellung [{$order->oxorder__oxordernr->value}] wurde storniert.
Ihr Team von [{$shop->getFieldData('oxname')}].
[{oxcontent ident="d3linkmobilityordercanceled"}]

View File

@ -1,7 +1,3 @@
[{assign var="shop" value=$oEmailView->getShop()}]
Hallo [{$order->getFieldData('oxbillfname')}] [{$order->getFieldData('oxbilllname')}],
Ihre Bestellung [{$order->oxorder__oxordernr->value}] wurde eben versendet. [{if $order->getFieldData('oxtrackcode')}]Der Trackingcode dazu ist: [{$order->getFieldData('oxtrackcode')}].[{/if}]
Ihr Team von [{$shop->getFieldData('oxname')}].
[{oxcontent ident="d3linkmobilityordersendednow"}]

View File

@ -0,0 +1,103 @@
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
# https://www.d3data.de
#
# @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
# @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
# @link https://www.oxidmodule.com
parameters:
D3\Linkmobility4OXID\Application\Model\RequestFactory.args.message:
D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms.args.message:
D3\Linkmobility4OXID\Application\Model\Exceptions\successfullySentException.args.smscount:
services:
_defaults:
autowire: false
public: true
D3\Linkmobility4OXID\Application\Model\OrderRecipients:
class: D3\Linkmobility4OXID\Application\Model\OrderRecipients
factory: 'oxNew'
shared: false
arguments:
- D3\Linkmobility4OXID\Application\Model\OrderRecipients
- '@D3\Linkmobility4OXID\Application\Model\OrderRecipients.args.order'
D3\Linkmobility4OXID\Application\Model\OrderRecipients.args.order:
synthetic: true
shared: false
D3\Linkmobility4OXID\Application\Model\UserRecipients:
class: D3\Linkmobility4OXID\Application\Model\UserRecipients
factory: 'oxNew'
shared: false
arguments:
- D3\Linkmobility4OXID\Application\Model\UserRecipients
- '@D3\Linkmobility4OXID\Application\Model\UserRecipients.args.user'
D3\Linkmobility4OXID\Application\Model\UserRecipients.args.user:
synthetic: true
shared: false
D3\Linkmobility4OXID\Application\Model\Configuration:
class: D3\Linkmobility4OXID\Application\Model\Configuration
factory: 'oxNew'
shared: true
arguments:
- D3\Linkmobility4OXID\Application\Model\Configuration
D3\Linkmobility4OXID\Application\Model\MessageClient:
class: D3\Linkmobility4OXID\Application\Model\MessageClient
factory: 'oxNew'
shared: true
arguments:
- D3\Linkmobility4OXID\Application\Model\MessageClient
D3\Linkmobility4OXID\Application\Model\MessageSender:
class: D3\Linkmobility4OXID\Application\Model\MessageSender
factory: 'oxNew'
shared: true
arguments:
- D3\Linkmobility4OXID\Application\Model\MessageSender
D3\Linkmobility4OXID\Application\Model\RequestFactory:
class: D3\Linkmobility4OXID\Application\Model\RequestFactory
factory: 'oxNew'
shared: true
arguments:
- D3\Linkmobility4OXID\Application\Model\RequestFactory
- '%D3\Linkmobility4OXID\Application\Model\RequestFactory.args.message%'
- '@D3\Linkmobility4OXID\Application\Model\RequestFactory.args.client'
D3\Linkmobility4OXID\Application\Model\RequestFactory.args.client:
synthetic: true
shared: false
D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms:
class: D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms
factory: 'oxNew'
shared: false
arguments:
- D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms
- '%D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms.args.message%'
D3\Linkmobility4OXID\Application\Model\Exceptions\successfullySentException:
class: D3\Linkmobility4OXID\Application\Model\Exceptions\successfullySentException
factory: 'oxNew'
shared: false
arguments:
- D3\Linkmobility4OXID\Application\Model\Exceptions\successfullySentException
- '%D3\Linkmobility4OXID\Application\Model\Exceptions\successfullySentException.args.smscount%'
D3\Linkmobility4OXID\Application\Model\Exceptions\noRecipientFoundException:
class: D3\Linkmobility4OXID\Application\Model\Exceptions\noRecipientFoundException
factory: 'oxNew'
shared: false
arguments:
- D3\Linkmobility4OXID\Application\Model\Exceptions\noRecipientFoundException
D3\Linkmobility4OXID\Setup\Actions:
class: D3\Linkmobility4OXID\Setup\Actions
factory: 'oxNew'
shared: false
arguments:
- D3\Linkmobility4OXID\Setup\Actions

View File

@ -0,0 +1,73 @@
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
# https://www.d3data.de
#
# @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
# @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
# @link https://www.oxidmodule.com
parameters:
D3\LinkmobilityClient\Client.args.accesstoken:
D3\LinkmobilityClient\ValueObject\Recipient.args.number:
D3\LinkmobilityClient\ValueObject\Recipient.args.iso2countrycode:
D3\LinkmobilityClient\ValueObject\Sender.args.number:
D3\LinkmobilityClient\ValueObject\Sender.args.iso2countrycode:
services:
_defaults:
autowire: false
public: true
D3\LinkmobilityClient\LoggerHandler:
class: D3\LinkmobilityClient\LoggerHandler
factory:
- 'D3\LinkmobilityClient\LoggerHandler'
- 'getInstance'
calls:
- [setLogger, ['@d3ox.linkmobility.Psr\Log\LoggerInterface']]
shared: true
D3\LinkmobilityClient\Client:
class: D3\LinkmobilityClient\Client
factory: 'oxNew'
shared: false
arguments:
- D3\LinkmobilityClient\Client
- '%D3\LinkmobilityClient\Client.args.accesstoken%'
D3\LinkmobilityClient\ValueObject\Recipient:
class: D3\LinkmobilityClient\ValueObject\Recipient
factory: 'oxNew'
shared: false
arguments:
- D3\LinkmobilityClient\ValueObject\Recipient
- '%D3\LinkmobilityClient\ValueObject\Recipient.args.number%'
- '%D3\LinkmobilityClient\ValueObject\Recipient.args.iso2countrycode%'
D3\LinkmobilityClient\RecipientsList\RecipientsList:
class: D3\LinkmobilityClient\RecipientsList\RecipientsList
factory: 'oxNew'
shared: false
arguments:
- D3\LinkmobilityClient\RecipientsList\RecipientsList
- '@D3\LinkmobilityClient\RecipientsList\RecipientsList.args.client'
D3\LinkmobilityClient\RecipientsList\RecipientsList.args.client:
synthetic: true
shared: false
D3\LinkmobilityClient\ValueObject\Sender:
class: D3\LinkmobilityClient\ValueObject\Sender
factory: 'oxNew'
shared: false
arguments:
- D3\LinkmobilityClient\ValueObject\Sender
- '%D3\LinkmobilityClient\ValueObject\Sender.args.number%'
- '%D3\LinkmobilityClient\ValueObject\Sender.args.iso2countrycode%'
D3\LinkmobilityClient\Exceptions\RecipientException:
class: D3\LinkmobilityClient\Exceptions\RecipientException
factory: 'oxNew'
shared: false
arguments:
- D3\LinkmobilityClient\Exceptions\RecipientException

114
src/Config/oxid.yaml Normal file
View File

@ -0,0 +1,114 @@
# This Software is the property of Data Development and is protected
# by copyright law - it is NOT Freeware.
#
# Any unauthorized use of this software without a valid license
# is a violation of the license agreement and will be prosecuted by
# civil and criminal law.
#
# https://www.d3data.de
#
# @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
# @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
# @link https://www.oxidmodule.com
services:
_defaults:
autowire: false
public: true
# config
d3ox.linkmobility.OxidEsales\Eshop\Core\Config:
class: 'OxidEsales\Eshop\Core\Config'
factory:
- 'OxidEsales\Eshop\Core\Registry'
- 'getConfig'
shared: true
# config
d3ox.linkmobility.OxidEsales\Eshop\Core\Request:
class: 'OxidEsales\Eshop\Core\Request'
factory:
- 'OxidEsales\Eshop\Core\Registry'
- 'getRequest'
shared: true
# lang
d3ox.linkmobility.OxidEsales\Eshop\Core\Language:
class: 'OxidEsales\Eshop\Core\Session'
factory:
- 'OxidEsales\Eshop\Core\Registry'
- 'getLang'
shared: true
# UtilsView
d3ox.linkmobility.OxidEsales\Eshop\Core\UtilsView:
class: 'OxidEsales\Eshop\Core\UtilsView'
factory:
- 'OxidEsales\Eshop\Core\Registry'
- 'getUtilsView'
shared: true
# Email
d3ox.linkmobility.OxidEsales\Eshop\Core\DbMetaDataHandler:
class: 'OxidEsales\Eshop\Core\DbMetaDataHandler'
factory: 'oxNew'
arguments:
- 'OxidEsales\Eshop\Core\DbMetaDataHandler'
shared: false
# Email
d3ox.linkmobility.OxidEsales\Eshop\Core\Email:
class: 'OxidEsales\Eshop\Core\Email'
factory: 'oxNew'
arguments:
- 'OxidEsales\Eshop\Core\Email'
shared: false
# Order
d3ox.linkmobility.OxidEsales\Eshop\Application\Model\Order:
class: 'OxidEsales\Eshop\Application\Model\Order'
factory: 'oxNew'
arguments:
- 'OxidEsales\Eshop\Application\Model\Order'
shared: false
# User
d3ox.linkmobility.OxidEsales\Eshop\Application\Model\User:
class: 'OxidEsales\Eshop\Application\Model\User'
factory: 'oxNew'
arguments:
- 'OxidEsales\Eshop\Application\Model\User'
shared: false
# Country
d3ox.linkmobility.OxidEsales\Eshop\Application\Model\Country:
class: 'OxidEsales\Eshop\Application\Model\Country'
factory: 'oxNew'
arguments:
- 'OxidEsales\Eshop\Application\Model\Country'
shared: false
# Remark
d3ox.linkmobility.OxidEsales\Eshop\Application\Model\Remark:
class: 'OxidEsales\Eshop\Application\Model\Remark'
factory: 'oxNew'
arguments:
- 'OxidEsales\Eshop\Application\Model\Remark'
shared: false
d3ox.linkmobility.Psr\Log\LoggerInterface:
class: Psr\Log\LoggerInterface
factory:
- 'OxidEsales\Eshop\Core\Registry'
- 'getLogger'
shared: true
# DB_assoc
d3ox.linkmobility.OxidEsales\Eshop\Core\Database\Adapter\DatabaseInterface.assoc:
class: 'OxidEsales\Eshop\Core\Database\Adapter\DatabaseInterface'
factory:
- 'OxidEsales\Eshop\Core\DatabaseProvider'
- 'getDb'
arguments:
- 2
shared: true

28
src/Config/packages.yaml Normal file
View File

@ -0,0 +1,28 @@
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
# https://www.d3data.de
#
# @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
# @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
# @link https://www.oxidmodule.com
parameters:
libphonenumber\NumberParseException.args.errorType:
libphonenumber\NumberParseException.args.message:
libphonenumber\NumberParseException.args.previous:
services:
_defaults:
autowire: false
public: true
libphonenumber\NumberParseException:
class: libphonenumber\NumberParseException
factory: 'oxNew'
shared: false
arguments:
- libphonenumber\NumberParseException
- '%libphonenumber\NumberParseException.args.errorType%'
- '%libphonenumber\NumberParseException.args.message%'
- '%libphonenumber\NumberParseException.args.previous%'

29
src/Config/php.yaml Normal file
View File

@ -0,0 +1,29 @@
# This Software is the property of Data Development and is protected
# by copyright law - it is NOT Freeware.
#
# Any unauthorized use of this software without a valid license
# is a violation of the license agreement and will be prosecuted by
# civil and criminal law.
#
# https://www.d3data.de
#
# @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
# @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
# @link https://www.oxidmodule.com
parameters:
d3ox.linkmobility.InvalidArgumentException.args.message:
services:
_defaults:
autowire: false
public: true
# InvalidArgumentException
d3ox.linkmobility.InvalidArgumentException:
class: InvalidArgumentException
factory: 'oxNew'
arguments:
- InvalidArgumentException
- '%d3ox.linkmobility.InvalidArgumentException.args.message%'
shared: false

18
src/Config/services.yaml Normal file
View File

@ -0,0 +1,18 @@
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.
#
# https://www.d3data.de
#
# @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
# @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
# @link https://www.oxidmodule.com
imports:
- { resource: php.yaml }
- { resource: packages.yaml }
- { resource: oxid.yaml }
- { resource: linkmobilityphpclient.yaml }
- { resource: linkmobility4oxid.yaml }

View File

@ -13,6 +13,15 @@
declare(strict_types=1);
namespace D3\Linkmobility4OXID\Modules {
use D3\DIContainerHandler\definitionFileContainer;
class LinkmobilityServices_parent extends definitionFileContainer
{
}
}
namespace D3\Linkmobility4OXID\Modules\Application\Model {
use OxidEsales\Eshop\Application\Model\Order;

View File

@ -16,24 +16,30 @@ declare(strict_types=1);
namespace D3\Linkmobility4OXID\Modules\Application\Model;
use D3\Linkmobility4OXID\Modules\Core\EmailCore;
use D3\TestingTools\Production\IsMockable;
use Exception;
use OxidEsales\Eshop\Core\Email;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
class OrderModel extends OrderModel_parent
{
use IsMockable;
/**
* @return void
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws Exception
*/
public function cancelOrder(): void
{
parent::cancelOrder();
// parent::cancelOrder();
$this->d3CallMockableFunction([OrderModel_parent::class, 'cancelOrder']);
if ((bool) $this->getFieldData('oxstorno') === true) {
/** @var EmailCore $Email */
$Email = oxNew(Email::class);
$Email = d3GetOxidDIC()->get('d3ox.linkmobility.'.Email::class);
$Email->d3SendCancelMessage($this);
}
}

View File

@ -16,6 +16,7 @@ declare(strict_types=1);
namespace D3\Linkmobility4OXID\Modules\Core;
use D3\Linkmobility4OXID\Application\Model\MessageSender;
use D3\TestingTools\Production\IsMockable;
use Exception;
use OxidEsales\Eshop\Application\Model\Order;
use OxidEsales\EshopCommunity\Internal\Container\ContainerFactory;
@ -26,6 +27,8 @@ use Psr\Container\NotFoundExceptionInterface;
class EmailCore extends EmailCore_parent
{
use IsMockable;
/** @var string */
protected $d3OrderCustSmsTemplate = 'd3sms_ordercust.tpl';
/** @var string */
@ -40,10 +43,13 @@ class EmailCore extends EmailCore_parent
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws Exception
*/
public function sendOrderEmailToUser($order, $subject = null)
{
$ret = parent::sendOrderEmailToUser($order, $subject);
// $ret = parent::sendOrderEmailToUser($order, $subject);
/** @var bool $ret */
$ret = $this->d3CallMockableFunction([EmailCore_parent::class, 'sendOrderEmailToUser'], [$order, $subject]);
$this->d3SendOrderFinishedMessageToUser($order);
@ -57,10 +63,13 @@ class EmailCore extends EmailCore_parent
* @return bool
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws Exception
*/
public function sendSendedNowMail($order, $subject = null)
{
$ret = parent::sendSendedNowMail($order, $subject);
// $ret = parent::sendSendedNowMail($order, $subject);
/** @var bool $ret */
$ret = $this->d3CallMockableFunction([EmailCore_parent::class, 'sendSendedNowMail'], [$order, $subject]);
$this->d3SendedNowMessage($order);
@ -77,7 +86,8 @@ class EmailCore extends EmailCore_parent
*/
public function d3SendOrderFinishedMessageToUser(Order $order): void
{
$messageSender = oxNew(MessageSender::class);
/** @var MessageSender $messageSender */
$messageSender = d3GetOxidDIC()->get(MessageSender::class);
$messageSender->sendOrderFinishedMessage($order, $this->d3GetOrderFinishedSmsMessageBody($order));
}
@ -106,7 +116,8 @@ class EmailCore extends EmailCore_parent
*/
public function d3SendedNowMessage(Order $order): void
{
$messageSender = oxNew(MessageSender::class);
/** @var MessageSender $messageSender */
$messageSender = d3GetOxidDIC()->get(MessageSender::class);
$messageSender->sendSendedNowMessage($order, $this->d3GetSendedNowSmsMessageBody($order));
}
@ -135,7 +146,8 @@ class EmailCore extends EmailCore_parent
*/
public function d3SendCancelMessage(Order $order): void
{
$messageSender = oxNew(MessageSender::class);
/** @var MessageSender $messageSender */
$messageSender = d3GetOxidDIC()->get(MessageSender::class);
$messageSender->sendCancelOrderMessage($order, $this->d3GetCancelOrderSmsMessageBody($order));
}

View File

@ -0,0 +1,29 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\Modules;
use D3\TestingTools\Production\IsMockable;
class LinkmobilityServices extends LinkmobilityServices_parent
{
use IsMockable;
public function __construct()
{
$this->d3CallMockableFunction([LinkmobilityServices_parent::class, '__construct']);
$this->addYamlDefinitions('d3/linkmobility/Config/services.yaml');
}
}

View File

@ -16,18 +16,26 @@ declare(strict_types=1);
namespace D3\Linkmobility4OXID\Setup;
use D3\Linkmobility4OXID\Application\Model\MessageTypes\AbstractMessage;
use D3\LinkmobilityClient\LoggerHandler;
use Doctrine\DBAL\Driver\Exception as DoctrineDriverException;
use Doctrine\DBAL\Exception as DoctrineException;
use Doctrine\DBAL\Query\QueryBuilder;
use OxidEsales\Eshop\Core\DatabaseProvider;
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Statement;
use Monolog\Logger;
use OxidEsales\Eshop\Application\Model\Content;
use OxidEsales\Eshop\Core\Config;
use OxidEsales\Eshop\Core\Database\Adapter\DatabaseInterface;
use OxidEsales\Eshop\Core\Database\Adapter\Doctrine\Database;
use OxidEsales\Eshop\Core\DbMetaDataHandler;
use OxidEsales\Eshop\Core\Exception\DatabaseConnectionException;
use OxidEsales\Eshop\Core\Exception\DatabaseErrorException;
use OxidEsales\Eshop\Core\Exception\DatabaseException;
use OxidEsales\Eshop\Core\Registry;
use OxidEsales\Eshop\Core\Exception\StandardException;
use OxidEsales\Eshop\Core\UtilsView;
use OxidEsales\EshopCommunity\Internal\Container\ContainerFactory;
use OxidEsales\EshopCommunity\Internal\Framework\Database\QueryBuilderFactory;
use OxidEsales\EshopCommunity\Internal\Framework\Database\QueryBuilderFactoryInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
class Actions
@ -43,9 +51,13 @@ class Actions
if (!$this->hasRemarkTypeEnumValue()) {
$this->addRemarkTypeEnumValue();
}
} catch (DatabaseException|DoctrineDriverException|DoctrineException $e) {
Registry::getLogger()->error($e->getMessage());
Registry::getUtilsView()->addErrorToDisplay($e);
} catch (StandardException|DoctrineDriverException|DoctrineException $e) {
/** @var LoggerHandler $loggerHandler */
$loggerHandler = d3GetOxidDIC()->get(LoggerHandler::class);
$loggerHandler->getLogger()->error($e->getMessage());
/** @var UtilsView $utilsView */
$utilsView = d3GetOxidDIC()->get('d3ox.linkmobility.'.UtilsView::class);
$utilsView->addErrorToDisplay($e->getMessage());
}
}
@ -54,9 +66,10 @@ class Actions
/**
* Regenerate views for changed tables
*/
public function regenerateViews()
public function regenerateViews(): void
{
$oDbMetaDataHandler = oxNew(DbMetaDataHandler::class);
/** @var DbMetaDataHandler $oDbMetaDataHandler */
$oDbMetaDataHandler = d3GetOxidDIC()->get('d3ox.linkmobility.'.DbMetaDataHandler::class);
$oDbMetaDataHandler->updateViews();
}
@ -73,7 +86,7 @@ class Actions
$patternEnumCheck = '/^\b(enum)\b/mi';
if (!preg_match($patternEnumCheck, $fieldType)) {
throw oxNew(DatabaseException::class, 'remark type field has not the expected enum type');
throw oxNew(StandardException::class, 'remark type field has not the expected enum type');
}
$patternValueCheck = '/\b('.preg_quote(AbstractMessage::REMARK_IDENT).')\b/mi';
@ -90,15 +103,16 @@ class Actions
*/
protected function getRemarkTypeFieldType(): string
{
/** @var QueryBuilder $qb */
$qb = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
/** @var QueryBuilderFactory $queryBuilderFactory */
$queryBuilderFactory = $this->getContainer()->get(QueryBuilderFactoryInterface::class);
$qb = $queryBuilderFactory->create();
$qb->select('column_type')
->from('INFORMATION_SCHEMA.COLUMNS')
->where(
$qb->expr()->and(
$qb->expr()->eq(
'table_schema',
$qb->createNamedParameter(Registry::getConfig()->getConfigParam('dbName'))
$qb->createNamedParameter($this->getConfig()->getConfigParam('dbName'))
),
$qb->expr()->eq(
'table_name',
@ -111,7 +125,10 @@ class Actions
)
);
return (string) $qb->execute()->fetchOne();
/** @var Statement $statement */
$statement = $qb->execute();
return (string) $statement->fetchOne();
}
/**
@ -125,17 +142,9 @@ class Actions
*/
protected function addRemarkTypeEnumValue()
{
$valuePattern = '/(?<=enum\().*(?=\))/i';
preg_match($valuePattern, $this->getRemarkTypeFieldType(), $matches);
$items = $this->getUniqueFieldTypes();
$items = array_unique(
array_merge(
str_getcsv($matches[0], ',', "'"),
[AbstractMessage::REMARK_IDENT]
)
);
$db = DatabaseProvider::getDb();
$db = $this->getDb();
$query = 'ALTER TABLE '.$db->quoteIdentifier('oxremark').
' CHANGE '.$db->quoteIdentifier('OXTYPE'). ' '.$db->quoteIdentifier('OXTYPE') .
@ -144,4 +153,195 @@ class Actions
$db->execute($query);
}
}
/**
* @return string[]
* @throws DoctrineDriverException
* @throws DoctrineException
*/
protected function getUniqueFieldTypes(): array
{
$valuePattern = '/(?<=enum\().*(?=\))/i';
preg_match($valuePattern, $this->getRemarkTypeFieldType(), $matches);
return array_unique(
array_merge(
str_getcsv($matches[0], ',', "'"),
[AbstractMessage::REMARK_IDENT]
)
);
}
/**
* @return void
* @throws DoctrineDriverException
* @throws DoctrineException
*/
public function checkCmsItems()
{
foreach (
[
'd3linkmobilityordercanceled' => 'addCms1Item',
'd3linkmobilityfinishedorder' => 'addCms2Item',
'd3linkmobilityordersendednow' => 'addCms3Item'
] as $checkIdent => $methodName
) {
if ($this->cmsMissing($checkIdent)) {
call_user_func([$this, $methodName]);
}
}
}
/**
* @param string $checkIdent
* @return bool
* @throws DoctrineDriverException
* @throws DoctrineException
*/
protected function cmsMissing(string $checkIdent): bool
{
/** @var QueryBuilderFactory $queryBuilderFactory */
$queryBuilderFactory = $this->getContainer()->get(QueryBuilderFactoryInterface::class);
$qb = $queryBuilderFactory->create();
$qb->select('count(oxid)')
->from(oxNew(Content::class)->getViewName())
->where(
$qb->expr()->and(
$qb->expr()->eq(
'oxloadid',
$qb->createNamedParameter($checkIdent)
),
$qb->expr()->eq(
'oxshopid',
$qb->createNamedParameter($this->getConfig()->getShopId())
)
)
)
->getFirstResult();
/** @var Statement $statement */
$statement = $qb->execute();
return !$statement->fetchOne();
}
/**
* @return void
* @throws DatabaseConnectionException
* @throws DatabaseErrorException
*/
protected function addCms1Item()
{
/** @var QueryBuilderFactory $queryBuilderFactory */
$queryBuilderFactory = $this->getContainer()->get(QueryBuilderFactoryInterface::class);
$qb = $queryBuilderFactory->create();
$qb->insert('oxcontents')
->values([
'oxid' => 'MD5(CONCAT('.$qb->createNamedParameter(__FUNCTION__).', NOW()))',
'oxloadid' => $qb->createNamedParameter('d3linkmobilityordercanceled'),
'oxshopid' => $qb->createNamedParameter($this->getConfig()->getShopId()),
'oxsnippet' => $qb->createNamedParameter(1, ParameterType::INTEGER),
'oxtype' => $qb->createNamedParameter(0, ParameterType::INTEGER),
'oxactive' => $qb->createNamedParameter(1, ParameterType::INTEGER),
'oxactive_1'=> $qb->createNamedParameter(1, ParameterType::INTEGER),
'oxposition'=> $qb->createNamedParameter(''),
'oxtitle' => $qb->createNamedParameter('Linkmobility: Bestellung storniert'),
'oxcontent' => $qb->createNamedParameter('Hallo [{$order->getFieldData(\'oxbillfname\')}] [{$order->getFieldData(\'oxbilllname\')}],'.PHP_EOL.PHP_EOL.'Ihre Bestellung [{$order->getFieldData(\'oxordernr\')}] wurde storniert.'.PHP_EOL.PHP_EOL.'Ihr Team von [{$shop->getFieldData(\'oxname\')}].'),
'oxtitle_1' => $qb->createNamedParameter('Linkmobility: order canceled'),
'oxcontent_1'=> $qb->createNamedParameter('Hello [{$order->getFieldData(\'oxbillfname\')}] [{$order->getFieldData(\'oxbilllname\')}],'.PHP_EOL.PHP_EOL.'Your order [{$order->getFieldData(\'oxordernr\')}] has been cancelled.'.PHP_EOL.PHP_EOL.'Your team at [{$shop->getFieldData(\'oxname\')}].'),
'oxcatid' => $qb->createNamedParameter('943a9ba3050e78b443c16e043ae60ef3'),
'oxfolder' => $qb->createNamedParameter('')
]);
$qb->execute();
}
/**
* @return void
* @throws DatabaseConnectionException
* @throws DatabaseErrorException
*/
protected function addCms2Item()
{
/** @var QueryBuilderFactory $queryBuilderFactory */
$queryBuilderFactory = $this->getContainer()->get(QueryBuilderFactoryInterface::class);
$qb = $queryBuilderFactory->create();
$qb->insert('oxcontents')
->values([
'oxid' => 'MD5(CONCAT('.$qb->createNamedParameter(__FUNCTION__).', NOW()))',
'oxloadid' => $qb->createNamedParameter('d3linkmobilityfinishedorder'),
'oxshopid' => $qb->createNamedParameter($this->getConfig()->getShopId()),
'oxsnippet' => $qb->createNamedParameter(1, ParameterType::INTEGER),
'oxtype' => $qb->createNamedParameter(0, ParameterType::INTEGER),
'oxactive' => $qb->createNamedParameter(1, ParameterType::INTEGER),
'oxactive_1'=> $qb->createNamedParameter(1, ParameterType::INTEGER),
'oxposition'=> $qb->createNamedParameter(''),
'oxtitle' => $qb->createNamedParameter('Linkmobility: Bestellung eingegangen'),
'oxcontent' => $qb->createNamedParameter('Hallo [{$order->getFieldData(\'oxbillfname\')}] [{$order->getFieldData(\'oxbilllname\')}],'.PHP_EOL.PHP_EOL.'vielen Dank für Ihre Bestellung. Wir haben diese unter der Bestellnummer [{$order->getFieldData(\'oxordernr\')}] angelegt und werden diese schnellstmöglich bearbeiten.'.PHP_EOL.PHP_EOL.'Ihr Team von [{$shop->getFieldData(\'oxname\')}].'),
'oxtitle_1' => $qb->createNamedParameter('Linkmobility: order recieved'),
'oxcontent_1'=> $qb->createNamedParameter('Hello [{$order->getFieldData(\'oxbillfname\')}] [{$order->getFieldData(\'oxbilllname\')}],'.PHP_EOL.PHP_EOL.'Thank you for your order. We have saved it under the order number [{$order->getFieldData(\'oxordernr\')}] and will process it as soon as possible.'.PHP_EOL.PHP_EOL.'Your team at [{$shop->getFieldData(\'oxname\')}].'),
'oxcatid' => $qb->createNamedParameter('943a9ba3050e78b443c16e043ae60ef3'),
'oxfolder' => $qb->createNamedParameter('')
]);
$qb->execute();
}
/**
* @return void
* @throws DatabaseConnectionException
* @throws DatabaseErrorException
*/
protected function addCms3Item()
{
/** @var QueryBuilderFactory $queryBuilderFactory */
$queryBuilderFactory = $this->getContainer()->get(QueryBuilderFactoryInterface::class);
$qb = $queryBuilderFactory->create();
$qb->insert('oxcontents')
->values([
'oxid' => 'MD5(CONCAT('.$qb->createNamedParameter(__FUNCTION__).', NOW()))',
'oxloadid' => $qb->createNamedParameter('d3linkmobilityordersendednow'),
'oxshopid' => $qb->createNamedParameter($this->getConfig()->getShopId()),
'oxsnippet' => $qb->createNamedParameter(1, ParameterType::INTEGER),
'oxtype' => $qb->createNamedParameter(0, ParameterType::INTEGER),
'oxactive' => $qb->createNamedParameter(1, ParameterType::INTEGER),
'oxactive_1'=> $qb->createNamedParameter(1, ParameterType::INTEGER),
'oxposition'=> $qb->createNamedParameter(''),
'oxtitle' => $qb->createNamedParameter('Linkmobility: Bestellung versendet'),
'oxcontent' => $qb->createNamedParameter('Hallo [{$order->getFieldData(\'oxbillfname\')}] [{$order->getFieldData(\'oxbilllname\')}],'.PHP_EOL.PHP_EOL.'Ihre Bestellung [{$order->getFieldData(\'oxordernr\')}] wurde eben versendet. [{if $order->getFieldData(\'oxtrackcode\')}]Der Trackingcode dazu ist: [{$order->getFieldData(\'oxtrackcode\')}].[{/if}]'.PHP_EOL.PHP_EOL.'Ihr Team von [{$shop->getFieldData(\'oxname\')}].'),
'oxtitle_1' => $qb->createNamedParameter('Linkmobility: order shipped'),
'oxcontent_1'=> $qb->createNamedParameter('Hello [{$order->getFieldData(\'oxbillfname\')}] [{$order->getFieldData(\'oxbilllname\')}],'.PHP_EOL.PHP_EOL.'Your order [{$order->getFieldData(\'oxordernr\')}] has just been shipped. [{if $order->getFieldData(\'oxtrackcode\')}]The tracking code for this is: [{$order->getFieldData(\'oxtrackcode\')}].[{/if}]'.PHP_EOL.PHP_EOL.'Your team at [{$shop->getFieldData(\'oxname\')}].'),
'oxcatid' => $qb->createNamedParameter('943a9ba3050e78b443c16e043ae60ef3'),
'oxfolder' => $qb->createNamedParameter('')
]);
$qb->execute();
}
/**
* @return ContainerInterface
*/
protected function getContainer(): ContainerInterface
{
return ContainerFactory::getInstance()->getContainer();
}
/**
* @return Database
*/
protected function getDb(): Database
{
/** @var Database $db */
$db = d3GetOxidDIC()->get('d3ox.linkmobility.'.DatabaseInterface::class.'.assoc');
return $db;
}
/**
* @return Config
*/
protected function getConfig(): Config
{
/** @var Config $config */
$config = d3GetOxidDIC()->get('d3ox.linkmobility.'.Config::class);
return $config;
}
}

View File

@ -17,13 +17,6 @@ declare(strict_types=1);
namespace D3\Linkmobility4OXID\Setup;
use D3\ModCfg\Application\Model\Exception\d3ShopCompatibilityAdapterException;
use D3\ModCfg\Application\Model\Install\d3install;
use Doctrine\DBAL\DBALException;
use OxidEsales\Eshop\Core\Exception\DatabaseConnectionException;
use OxidEsales\Eshop\Core\Exception\DatabaseErrorException;
use OxidEsales\Eshop\Core\Exception\StandardException;
use OxidEsales\Eshop\Core\Exception\SystemComponentException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
@ -33,15 +26,16 @@ class Events
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public static function onActivate()
public static function onActivate(): void
{
/** @var Actions $actions */
$actions = oxNew(Actions::class);
$actions = d3GetOxidDIC()->get(Actions::class);
$actions->setupDatabase();
$actions->checkCmsItems();
$actions->regenerateViews();
}
public static function onDeactivate()
public static function onDeactivate(): void
{
}
}

View File

@ -13,10 +13,12 @@
declare(strict_types=1);
use D3\DIContainerHandler\definitionFileContainer;
use D3\Linkmobility4OXID\Application\Controller\Admin\AdminOrder;
use D3\Linkmobility4OXID\Application\Controller\Admin\AdminUser;
use D3\Linkmobility4OXID\Modules\Application\Model\OrderModel;
use D3\Linkmobility4OXID\Modules\Core\EmailCore;
use D3\Linkmobility4OXID\Modules\LinkmobilityServices;
use D3\Linkmobility4OXID\Setup\Events;
use OxidEsales\Eshop\Application\Model\Order;
use OxidEsales\Eshop\Core\Email;
@ -41,8 +43,9 @@ $aModule = [
'email' => 'support@shopmodule.com',
'url' => 'https://www.oxidmodule.com/',
'extend' => [
Email::class => EmailCore::class,
Order::class => OrderModel::class
Email::class => EmailCore::class,
Order::class => OrderModel::class,
definitionFileContainer::class => LinkmobilityServices::class
],
'controllers' => [
'd3linkmobility_user' => AdminUser::class,

2
src/tests/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
.phpunit.result.cache
reports

52
src/tests/README.md Normal file
View File

@ -0,0 +1,52 @@
# D3 Linkmobility4OXID Tests
## Requirements
Both unit and acceptance tests require OXID Testing Library installed.
See https://github.com/OXID-eSales/testing_library.
### Configuration
Please install the packages listed in the composer.json in "require-dev". Unfortunately Composer does not provide an automatic installation.
Here is an example of Testing Library configuration file `oxideshop/test_config.yml`
```
# This file is auto-generated during the composer install
mandatory_parameters:
shop_path: /var/www/oxideshop/source
shop_tests_path: /var/www/oxideshop/tests
partial_module_paths: d3/linkmobility
optional_parameters:
shop_url: null
shop_serial: ''
enable_varnish: false
is_subshop: false
install_shop: false
remote_server_dir: null
shop_setup_path: null
restore_shop_after_tests_suite: false
test_database_name: null
restore_after_acceptance_tests: false
restore_after_unit_tests: false
tmp_path: /tmp/oxid_test_library/
database_restoration_class: DatabaseRestorer
activate_all_modules: false
run_tests_for_shop: false
run_tests_for_modules: true
screen_shots_path: null
screen_shots_url: null
browser_name: firefox
selenium_server_ip: 127.0.0.1
selenium_server_port: '4444'
additional_test_paths: null
```
## Unit Tests
To execute unit tests run the following:
```
cd /var/www/oxideshop/
PHPBIN=/usr/bin/php7.4 ./vendor/bin/runtests
```

View File

@ -0,0 +1,24 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests;
use D3\ModCfg\Tests\additional_abstract;
class additional extends additional_abstract
{
}
oxNew(additional::class);

View File

@ -0,0 +1,96 @@
<?php
/**
* This Software is the property of Data Development and is protected
* by copyright law - it is NOT Freeware.
* Any unauthorized use of this software without a valid license
* is a violation of the license agreement and will be prosecuted by
* civil and criminal law.
* http://www.shopmodule.com
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link http://www.oxidmodule.com
*/
namespace D3\Linkmobility4OXID\tests\integration;
use D3\Linkmobility4OXID\Application\Model\MessageClient;
use D3\Linkmobility4OXID\tests\unit\LMUnitTestCase;
use D3\LinkmobilityClient\Client;
use D3\LinkmobilityClient\LoggerHandler;
use Doctrine\DBAL\Exception;
use Doctrine\DBAL\Query\QueryBuilder;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use OxidEsales\Eshop\Application\Model\Remark;
use OxidEsales\EshopCommunity\Internal\Container\ContainerFactory;
use OxidEsales\EshopCommunity\Internal\Framework\Database\QueryBuilderFactoryInterface;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Log\NullLogger;
abstract class LMIntegrationTestCase extends LMUnitTestCase
{
/**
* @throws \Exception
*/
public function setUp(): void
{
parent::setUp();
d3GetOxidDIC()->get(LoggerHandler::class)->setLogger(new NullLogger());
}
/**
* @param $userId
*
* @throws Exception
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
protected function deleteAllRemarksFrom($userId)
{
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->delete(oxNew(Remark::class)->getCoreTableName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($userId)
)
);
$queryBuilder->execute();
}
/**
* @param ResponseInterface|RequestException $response
*/
protected function setClientResponse($response, callable $history = null)
{
$handlerMock = new MockHandler([$response]);
$handlerStack = HandlerStack::create($handlerMock);
if ($history) {
$handlerStack->push($history);
}
$guzzleMock = new GuzzleClient(['handler' => $handlerStack]);
/** @var Client $LMClient */
$LMClient = oxNew(Client::class, 'accessToken', null, $guzzleMock);
/** @var MessageClient|MockObject $messageClientMock */
$messageClientMock = $this->getMockBuilder(MessageClient::class)
->onlyMethods(['getClient'])
->getMock();
$messageClientMock->method('getClient')->willReturn($LMClient);
d3GetOxidDIC()->set(MessageClient::class, $messageClientMock);
}
}

View File

@ -0,0 +1,480 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\integration;
use D3\Linkmobility4OXID\Application\Controller\Admin\AdminOrder;
use D3\Linkmobility4OXID\Application\Model\Configuration;
use Doctrine\DBAL\Exception as DoctrineException;
use Doctrine\DBAL\Query\QueryBuilder;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use OxidEsales\Eshop\Application\Model\Order;
use OxidEsales\Eshop\Application\Model\Remark;
use OxidEsales\Eshop\Application\Model\User;
use OxidEsales\Eshop\Core\Registry;
use OxidEsales\EshopCommunity\Internal\Container\ContainerFactory;
use OxidEsales\EshopCommunity\Internal\Framework\Database\QueryBuilderFactoryInterface;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\RequestInterface;
class adminOrderTest extends LMIntegrationTestCase
{
/** @var Order */
protected $order;
protected $userId = 'testUserId';
protected $orderId = 'testOrderId';
public function setUp(): void
{
define('OX_IS_ADMIN', true);
parent::setUp();
/** @var Configuration|MockObject $configuration */
$configuration = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getTestMode', 'sendOrderFinishedMessage'])
->getMock();
$configuration->method('getTestMode')->willReturn(true);
$configuration->method('sendOrderFinishedMessage')->willReturn(false);
d3GetOxidDIC()->set(Configuration::class, $configuration);
/** @var Order $order */
$this->order = $order = oxNew(Order::class);
$order->setId($this->orderId);
$order->assign([
'oxbillfon' => '01512 3456789',
'oxbillcountryid' => 'a7c40f631fc920687.20179984',
'oxuserid' => $this->userId
]);
$order->save();
/** @var User $user */
$this->user = $user = oxNew(User::class);
$user->setId($this->userId);
$user->save();
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function succSending()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
['X-Foo' => 'Bar'],
'{"statusCode":2000,"statusMessage":"OK","clientMessageId":null,"transferId":"0063c11b0100eeda5a1d","smsCount":1}'
),
$history
);
$_POST['messagebody'] = 'testMessage';
$_POST['oxid'] = $this->orderId;
/** @var AdminOrder $controller */
$controller = oxNew(AdminOrder::class);
$controller->send();
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'testMessage')
);
// check return message
$search = sprintf(
Registry::getLang()->translateString('D3LM_EXC_SMS_SUCC_SENT'),
1
);
$this->assertTrue(
(bool) strpos(serialize(Registry::getSession()->getVariable('Errors')), $search)
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertNotEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function apiError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
[],
'{"statusCode": 4019, "statusMessage": "parameter \"messageContent\" invalid", "clientMessageId": null, "transferId": null, "smsCount": 0}'
),
$history
);
$_POST['messagebody'] = 'testMessage';
$_POST['oxid'] = $this->orderId;
/** @var AdminOrder $controller */
$controller = oxNew(AdminOrder::class);
$controller->send();
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'testMessage')
);
// check return message
$search = sprintf(
Registry::getLang()->translateString('D3LM_EXC_MESSAGE_UNEXPECTED_ERR_SEND'),
'parameter "messageContent" invalid'
);
$this->assertTrue(
(bool) strpos(serialize(Registry::getSession()->getVariable('Errors')), $search)
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function emptyMessage()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
[],
'{"statusCode": 4019, "statusMessage": "parameter \"messageContent\" invalid", "clientMessageId": null, "transferId": null, "smsCount": 0}'
),
$history
);
$_POST['messagebody'] = '';
$_POST['oxid'] = $this->orderId;
/** @var AdminOrder $controller */
$controller = oxNew(AdminOrder::class);
$controller->send();
// check requests
$this->assertCount(
0, // no request because of internal handling
$container
);
// check return message
$search = sprintf(
Registry::getLang()->translateString('D3LM_EXC_MESSAGE_NO_LENGTH'),
1
);
$this->assertTrue(
(bool) strpos(serialize(Registry::getSession()->getVariable('Errors')), $search)
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function serverError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
500,
[],
'{"statusCode": 4019, "statusMessage": "parameter \"messageContent\" invalid", "clientMessageId": null, "transferId": null, "smsCount": 0}'
),
$history
);
$_POST['messagebody'] = 'testMessage';
$_POST['oxid'] = $this->orderId;
/** @var AdminOrder $controller */
try{
$controller = oxNew(AdminOrder::class);
$controller->send();
} catch (Exception $e) {
dumpvar(get_class($e));
}
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'testMessage')
);
// check return message
$search = 'no response';
$this->assertTrue(
(bool) strpos(serialize(Registry::getSession()->getVariable('Errors')), $search)
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function recipientError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
['X-Foo' => 'Bar'],
'{"statusCode":2000,"statusMessage":"OK","clientMessageId":null,"transferId":"0063c11b0100eeda5a1d","smsCount":1}'
),
$history
);
$_POST['messagebody'] = 'testMessage';
$_POST['oxid'] = $this->orderId;
$this->order->assign([
'oxbillfon' => '',
'oxbillcountryid' => ''
]);
$this->order->save();
/** @var AdminOrder $controller */
$controller = oxNew(AdminOrder::class);
$controller->send();
// check requests
$this->assertCount(
0, // no request because of internal handling
$container
);
// check return message
$search = Registry::getLang()->translateString('D3LM_EXC_NO_RECIPIENT_SET', null, false);
$this->assertTrue(
(bool) strpos(serialize(Registry::getSession()->getVariable('Errors')), $search)
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function communicationError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new RequestException(
'Error Communicating with Server',
new Request('GET', 'test')
),
$history
);
$_POST['messagebody'] = 'testMessage';
$_POST['oxid'] = $this->orderId;
/** @var AdminOrder $controller */
$controller = oxNew(AdminOrder::class);
$controller->send();
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'testMessage')
);
// check return message
$search = sprintf(
Registry::getLang()->translateString('D3LM_EXC_MESSAGE_UNEXPECTED_ERR_SEND'),
'no response'
);
$this->assertTrue(
(bool) strpos(serialize(Registry::getSession()->getVariable('Errors')), $search)
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @throws Exception
*/
public function tearDown(): void
{
parent::tearDown();
$this->order->delete();
$this->user->delete();
}
}

View File

@ -0,0 +1,410 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\integration;
use D3\Linkmobility4OXID\Application\Model\Configuration;
use D3\Linkmobility4OXID\Application\Controller\Admin\AdminUser;
use D3\LinkmobilityClient\LoggerHandler;
use Doctrine\DBAL\Exception as DoctrineException;
use Doctrine\DBAL\Query\QueryBuilder;
use Exception;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Monolog\Logger;
use OxidEsales\Eshop\Application\Model\Remark;
use OxidEsales\Eshop\Application\Model\User;
use OxidEsales\Eshop\Core\Registry;
use OxidEsales\EshopCommunity\Internal\Container\ContainerFactory;
use OxidEsales\EshopCommunity\Internal\Framework\Database\QueryBuilderFactoryInterface;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\RequestInterface;
class adminUserTest extends LMIntegrationTestCase
{
/** @var User */
protected $user;
protected $userId = 'testUserId';
public function setUp(): void
{
define('OX_IS_ADMIN', true);
parent::setUp();
/** @var Configuration|MockObject $configuration */
$configuration = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getTestMode'])
->getMock();
$configuration->method('getTestMode')->willReturn(true);
d3GetOxidDIC()->set(Configuration::class, $configuration);
/** @var Logger|MockObject $loggerMock */
$loggerMock = $this->getMockBuilder(Logger::class)
->onlyMethods(['error'])
->disableOriginalConstructor()
->getMock();
$loggerMock->method('error');
d3GetOxidDIC()->get(LoggerHandler::class)->setLogger($loggerMock);
/** @var User $user */
$this->user = $user = oxNew(User::class);
$user->setId($this->userId);
$user->assign([
'oxfon' => '01512 3456789',
'oxcountryid' => 'a7c40f631fc920687.20179984'
]);
$user->save();
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function succSending()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
['X-Foo' => 'Bar'],
'{"statusCode":2000,"statusMessage":"OK","clientMessageId":null,"transferId":"0063c11b0100eeda5a1d","smsCount":1}'
),
$history
);
$_POST['messagebody'] = 'testMessage';
$_POST['oxid'] = $this->userId;
/** @var AdminUser $controller */
$controller = oxNew(AdminUser::class);
$controller->send();
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'testMessage')
);
// check return message
$search = sprintf(
Registry::getLang()->translateString('D3LM_EXC_SMS_SUCC_SENT'),
1
);
$this->assertTrue(
(bool) strpos(serialize(Registry::getSession()->getVariable('Errors')), $search)
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertNotEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function apiError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
[],
'{"statusCode": 4019, "statusMessage": "parameter \"messageContent\" invalid", "clientMessageId": null, "transferId": null, "smsCount": 0}'
),
$history
);
$_POST['messagebody'] = 'testMessage';
$_POST['oxid'] = $this->userId;
/** @var AdminUser $controller */
$controller = oxNew(AdminUser::class);
$controller->send();
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'testMessage')
);
// check return message
$search = sprintf(
Registry::getLang()->translateString('D3LM_EXC_MESSAGE_UNEXPECTED_ERR_SEND'),
'parameter "messageContent" invalid'
);
$this->assertTrue(
(bool) strpos(serialize(Registry::getSession()->getVariable('Errors')), $search)
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function emptyMessage()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
[],
'{"statusCode": 4019, "statusMessage": "parameter \"messageContent\" invalid", "clientMessageId": null, "transferId": null, "smsCount": 0}'
),
$history
);
$_POST['messagebody'] = '';
$_POST['oxid'] = $this->userId;
/** @var AdminUser $controller */
$controller = oxNew(AdminUser::class);
$controller->send();
// check requests
$this->assertCount(
0, // no request because of internal handling
$container
);
// check return message
$search = sprintf(
Registry::getLang()->translateString('D3LM_EXC_MESSAGE_NO_LENGTH'),
1
);
$this->assertTrue(
(bool) strpos(serialize(Registry::getSession()->getVariable('Errors')), $search)
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function recipientError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
['X-Foo' => 'Bar'],
'{"statusCode":2000,"statusMessage":"OK","clientMessageId":null,"transferId":"0063c11b0100eeda5a1d","smsCount":1}'
),
$history
);
$_POST['messagebody'] = 'testMessage';
$_POST['oxid'] = $this->userId;
$this->user->assign([
'oxfon' => '',
'oxcountryid' => ''
]);
$this->user->save();
/** @var AdminUser $controller */
$controller = oxNew(AdminUser::class);
$controller->send();
// check requests
$this->assertCount(
0, // no request because of internal handling
$container
);
// check return message
$search = Registry::getLang()->translateString('D3LM_EXC_NO_RECIPIENT_SET', null, false);
$this->assertTrue(
(bool) strpos(serialize(Registry::getSession()->getVariable('Errors')), $search)
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function communicationError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new RequestException(
'Error Communicating with Server',
new Request('GET', 'test')
),
$history
);
$_POST['messagebody'] = 'testMessage';
$_POST['oxid'] = $this->userId;
/** @var AdminUser $controller */
$controller = oxNew(AdminUser::class);
$controller->send();
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'testMessage')
);
// check return message
$search = sprintf(
Registry::getLang()->translateString('D3LM_EXC_MESSAGE_UNEXPECTED_ERR_SEND'),
'no response'
);
$this->assertTrue(
(bool) strpos(serialize(Registry::getSession()->getVariable('Errors')), $search)
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @throws Exception
*/
public function tearDown(): void
{
parent::tearDown();
$this->user->delete();
}
}

View File

@ -0,0 +1,419 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\integration;
use D3\Linkmobility4OXID\Application\Model\Configuration;
use D3\LinkmobilityClient\LoggerHandler;
use Doctrine\DBAL\Exception as DoctrineException;
use Doctrine\DBAL\Query\QueryBuilder;
use Exception;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Monolog\Logger;
use OxidEsales\Eshop\Application\Model\Order;
use OxidEsales\Eshop\Application\Model\Remark;
use OxidEsales\Eshop\Application\Model\User;
use OxidEsales\EshopCommunity\Internal\Container\ContainerFactory;
use OxidEsales\EshopCommunity\Internal\Framework\Database\QueryBuilderFactoryInterface;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\RequestInterface;
class canceledOrderTest extends LMIntegrationTestCase
{
/** @var Order */
protected $order;
protected $userId = 'testUserId';
protected $orderId = 'testOrderId';
public function setUp(): void
{
parent::setUp();
/** @var Configuration|MockObject $configuration */
$configuration = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getTestMode', 'sendOrderSendedNowMessage', 'sendOrderCanceledMessage', 'sendOrderFinishedMessage'])
->getMock();
$configuration->method('getTestMode')->willReturn(true);
$configuration->method('sendOrderSendedNowMessage')->willReturn(false);
$configuration->method('sendOrderCanceledMessage')->willReturn(true);
$configuration->method('sendOrderFinishedMessage')->willReturn(false);
d3GetOxidDIC()->set(Configuration::class, $configuration);
/** @var Logger|MockObject $loggerMock */
$loggerMock = $this->getMockBuilder(Logger::class)
->onlyMethods(['error'])
->disableOriginalConstructor()
->getMock();
$loggerMock->method('error');
d3GetOxidDIC()->get(LoggerHandler::class)->setLogger($loggerMock);
/** @var User $user */
$this->user = $user = oxNew(User::class);
$user->setId($this->userId);
$user->save();
/** @var Order $order */
$this->order = $order = oxNew(Order::class);
$order->setId($this->orderId);
$order->assign([
'oxbillfon' => '01512 3456789',
'oxbillcountryid' => 'a7c40f631fc920687.20179984',
'oxbillfname' => 'John',
'oxbilllname' => 'Doe',
'oxbillcompany' => '',
'oxbillstreet' => '',
'oxbillstreetnr' => '',
'oxbillzip' => '',
'oxbillcity' => '',
'oxuserid' => $this->userId
]);
$order->save();
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function succSending()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
['X-Foo' => 'Bar'],
'{"statusCode":2000,"statusMessage":"OK","clientMessageId":null,"transferId":"0063c11b0100eeda5a1d","smsCount":1}'
),
$history
);
$this->order->cancelOrder();
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'John Doe')
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertNotEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function unknownNumberError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
['X-Foo' => 'Bar'],
'{"statusCode":2000,"statusMessage":"OK","clientMessageId":null,"transferId":"0063c11b0100eeda5a1d","smsCount":1}'
),
$history
);
$this->order->assign([
'oxbillfon' => '222',
'oxbillcountryid' => 'a7c40f631fc920687.20179984',
]);
$this->order->save();
$this->order->cancelOrder();
// check requests
$this->assertCount(
0, // no request because of internal handling
$container
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function apiError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
[],
'{"statusCode": 4019, "statusMessage": "parameter \"messageContent\" invalid", "clientMessageId": null, "transferId": null, "smsCount": 0}'
),
$history
);
$this->order->cancelOrder();
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'John Doe')
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function notConfigured()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
[],
'{"statusCode": 4019, "statusMessage": "parameter \"messageContent\" invalid", "clientMessageId": null, "transferId": null, "smsCount": 0}'
),
$history
);
/** @var Configuration|MockObject $configuration */
$configuration = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getTestMode', 'sendOrderSendedNowMessage', 'sendOrderCanceledMessage', 'sendOrderFinishedMessage'])
->getMock();
$configuration->method('getTestMode')->willReturn(true);
$configuration->method('sendOrderSendedNowMessage')->willReturn(false);
$configuration->method('sendOrderCanceledMessage')->willReturn(false);
$configuration->method('sendOrderFinishedMessage')->willReturn(false);
d3GetOxidDIC()->set(Configuration::class, $configuration);
$this->order->cancelOrder();
// check requests
$this->assertCount(
0, // no request because of internal handling
$container
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function recipientError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
['X-Foo' => 'Bar'],
'{"statusCode":2000,"statusMessage":"OK","clientMessageId":null,"transferId":"0063c11b0100eeda5a1d","smsCount":1}'
),
$history
);
$this->order->assign([
'oxbillfon' => '',
'oxbillcountryid' => ''
]);
$this->order->save();
$this->order->cancelOrder();
// check requests
$this->assertCount(
0, // no request because of internal handling
$container
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function communicationError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new RequestException(
'Error Communicating with Server',
new Request('GET', 'test')
),
$history
);
$this->order->cancelOrder();
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'John Doe')
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @throws Exception
*/
public function tearDown(): void
{
parent::tearDown();
$this->order->delete();
$this->user->delete();
}
}

View File

@ -0,0 +1,465 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\integration;
use D3\Linkmobility4OXID\Application\Model\Configuration;
use D3\Linkmobility4OXID\Modules\Core\EmailCore;
use D3\Linkmobility4OXID\Modules\Core\EmailCore_parent;
use D3\LinkmobilityClient\LoggerHandler;
use Doctrine\DBAL\Exception as DoctrineException;
use Doctrine\DBAL\Query\QueryBuilder;
use Exception;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Monolog\Logger;
use OxidEsales\Eshop\Application\Model\Order;
use OxidEsales\Eshop\Application\Model\Remark;
use OxidEsales\Eshop\Application\Model\User;
use OxidEsales\Eshop\Core\Email;
use OxidEsales\EshopCommunity\Internal\Container\ContainerFactory;
use OxidEsales\EshopCommunity\Internal\Framework\Database\QueryBuilderFactoryInterface;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\RequestInterface;
class finishedOrderTest extends LMIntegrationTestCase
{
/** @var Order */
protected $order;
protected $userId = 'testUserId';
protected $orderId = 'testOrderId';
public function setUp(): void
{
parent::setUp();
/** @var Configuration|MockObject $configuration */
$configuration = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getTestMode', 'sendOrderSendedNowMessage', 'sendOrderCanceledMessage', 'sendOrderFinishedMessage'])
->getMock();
$configuration->method('getTestMode')->willReturn(true);
$configuration->method('sendOrderSendedNowMessage')->willReturn(false);
$configuration->method('sendOrderCanceledMessage')->willReturn(false);
$configuration->method('sendOrderFinishedMessage')->willReturn(true);
d3GetOxidDIC()->set(Configuration::class, $configuration);
/** @var Logger|MockObject $loggerMock */
$loggerMock = $this->getMockBuilder(Logger::class)
->onlyMethods(['error'])
->disableOriginalConstructor()
->getMock();
$loggerMock->method('error');
d3GetOxidDIC()->get(LoggerHandler::class)->setLogger($loggerMock);
/** @var User $user */
$this->user = $user = oxNew(User::class);
$user->setId($this->userId);
$user->save();
/** @var Order $order */
$this->order = $order = oxNew(Order::class);
$order->setId($this->orderId);
$order->assign([
'oxordernr' => '12345',
'oxbillfon' => '01512 3456789',
'oxbillcountryid' => 'a7c40f631fc920687.20179984',
'oxbillfname' => 'John',
'oxbilllname' => 'Doe',
'oxbillcompany' => '',
'oxbillstreet' => '',
'oxbillstreetnr' => '',
'oxbillzip' => '',
'oxbillcity' => '',
'oxuserid' => $this->userId
]);
$order->save();
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function succSending()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
['X-Foo' => 'Bar'],
'{"statusCode":2000,"statusMessage":"OK","clientMessageId":null,"transferId":"0063c11b0100eeda5a1d","smsCount":1}'
),
$history
);
/** @var EmailCore|MockObject $mail */
$mail = $this->getMockBuilder(Email::class)
->onlyMethods(['d3CallMockableFunction'])
->getMock();
$mail->method('d3CallMockableFunction')->with(
$this->identicalTo([EmailCore_parent::class, 'sendOrderEmailToUser'])
);
$mail->sendOrderEmailToUser($this->order);
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'John Doe')
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertNotEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function unknownNumberError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
['X-Foo' => 'Bar'],
'{"statusCode":2000,"statusMessage":"OK","clientMessageId":null,"transferId":"0063c11b0100eeda5a1d","smsCount":1}'
),
$history
);
$this->order->assign([
'oxbillfon' => '222',
'oxbillcountryid' => 'a7c40f631fc920687.20179984',
]);
$this->order->save();
/** @var EmailCore|MockObject $mail */
$mail = $this->getMockBuilder(Email::class)
->onlyMethods(['d3CallMockableFunction'])
->getMock();
$mail->method('d3CallMockableFunction')->with(
$this->identicalTo([EmailCore_parent::class, 'sendOrderEmailToUser'])
);
$mail->sendOrderEmailToUser($this->order);
// check requests
$this->assertCount(
0,
$container
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function apiError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
[],
'{"statusCode": 4019, "statusMessage": "parameter \"messageContent\" invalid", "clientMessageId": null, "transferId": null, "smsCount": 0}'
),
$history
);
/** @var EmailCore|MockObject $mail */
$mail = $this->getMockBuilder(Email::class)
->onlyMethods(['d3CallMockableFunction'])
->getMock();
$mail->method('d3CallMockableFunction')->with(
$this->identicalTo([EmailCore_parent::class, 'sendOrderEmailToUser'])
);
$mail->sendOrderEmailToUser($this->order);
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'John Doe')
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function notConfigured()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
[],
'{"statusCode": 4019, "statusMessage": "parameter \"messageContent\" invalid", "clientMessageId": null, "transferId": null, "smsCount": 0}'
),
$history
);
/** @var Configuration|MockObject $configuration */
$configuration = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getTestMode', 'sendOrderSendedNowMessage', 'sendOrderCanceledMessage', 'sendOrderFinishedMessage'])
->getMock();
$configuration->method('getTestMode')->willReturn(true);
$configuration->method('sendOrderSendedNowMessage')->willReturn(false);
$configuration->method('sendOrderCanceledMessage')->willReturn(false);
$configuration->method('sendOrderFinishedMessage')->willReturn(false);
d3GetOxidDIC()->set(Configuration::class, $configuration);
/** @var EmailCore|MockObject $mail */
$mail = $this->getMockBuilder(Email::class)
->onlyMethods(['d3CallMockableFunction'])
->getMock();
$mail->method('d3CallMockableFunction')->with(
$this->identicalTo([EmailCore_parent::class, 'sendOrderEmailToUser'])
);
$mail->sendOrderEmailToUser($this->order);
// check requests
$this->assertCount(
0, // no request because of internal handling
$container
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function recipientError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
['X-Foo' => 'Bar'],
'{"statusCode":2000,"statusMessage":"OK","clientMessageId":null,"transferId":"0063c11b0100eeda5a1d","smsCount":1}'
),
$history
);
$this->order->assign([
'oxbillfon' => '',
'oxbillcountryid' => ''
]);
$this->order->save();
/** @var EmailCore|MockObject $mail */
$mail = $this->getMockBuilder(Email::class)
->onlyMethods(['d3CallMockableFunction'])
->getMock();
$mail->method('d3CallMockableFunction')->with(
$this->identicalTo([EmailCore_parent::class, 'sendOrderEmailToUser'])
);
$mail->sendOrderEmailToUser($this->order);
// check requests
$this->assertCount(
0, // no request because of internal handling
$container
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function communicationError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new RequestException(
'Error Communicating with Server',
new Request('GET', 'test')
),
$history
);
/** @var EmailCore|MockObject $mail */
$mail = $this->getMockBuilder(Email::class)
->onlyMethods(['d3CallMockableFunction'])
->getMock();
$mail->method('d3CallMockableFunction')->with(
$this->identicalTo([EmailCore_parent::class, 'sendOrderEmailToUser'])
);
$mail->sendOrderEmailToUser($this->order);
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'John Doe')
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @throws Exception
*/
public function tearDown(): void
{
parent::tearDown();
$this->order->delete();
$this->user->delete();
}
}

View File

@ -0,0 +1,433 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\integration;
use D3\Linkmobility4OXID\Application\Model\Configuration;
use D3\Linkmobility4OXID\Modules\Core\EmailCore;
use D3\LinkmobilityClient\LoggerHandler;
use Doctrine\DBAL\Exception as DoctrineException;
use Doctrine\DBAL\Query\QueryBuilder;
use Exception;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Middleware;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Monolog\Logger;
use OxidEsales\Eshop\Application\Model\Order;
use OxidEsales\Eshop\Application\Model\Remark;
use OxidEsales\Eshop\Application\Model\User;
use OxidEsales\Eshop\Core\Email;
use OxidEsales\EshopCommunity\Internal\Container\ContainerFactory;
use OxidEsales\EshopCommunity\Internal\Framework\Database\QueryBuilderFactoryInterface;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\RequestInterface;
class sendedNowOrderTest extends LMIntegrationTestCase
{
/** @var Order */
protected $order;
protected $userId = 'testUserId';
protected $orderId = 'testOrderId';
public function setUp(): void
{
parent::setUp();
/** @var Configuration|MockObject $configuration */
$configuration = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getTestMode', 'sendOrderSendedNowMessage', 'sendOrderCanceledMessage', 'sendOrderFinishedMessage'])
->getMock();
$configuration->method('getTestMode')->willReturn(true);
$configuration->method('sendOrderSendedNowMessage')->willReturn(true);
$configuration->method('sendOrderCanceledMessage')->willReturn(false);
$configuration->method('sendOrderFinishedMessage')->willReturn(false);
d3GetOxidDIC()->set(Configuration::class, $configuration);
/** @var User $user */
$this->user = $user = oxNew(User::class);
$user->setId($this->userId);
$user->save();
/** @var Order $order */
$this->order = $order = oxNew(Order::class);
$order->setId($this->orderId);
$order->assign([
'oxbillfon' => '01512 3456789',
'oxbillcountryid' => 'a7c40f631fc920687.20179984',
'oxbillfname' => 'John',
'oxbilllname' => 'Doe',
'oxbillcompany' => '',
'oxbillstreet' => '',
'oxbillstreetnr' => '',
'oxbillzip' => '',
'oxbillcity' => '',
'oxuserid' => $this->userId
]);
$order->save();
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function succSending()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
['X-Foo' => 'Bar'],
'{"statusCode":2000,"statusMessage":"OK","clientMessageId":null,"transferId":"0063c11b0100eeda5a1d","smsCount":1}'
),
$history
);
/** @var EmailCore $mail */
$mail = oxNew(Email::class);
$mail->sendSendedNowMail($this->order);
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'John Doe')
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertNotEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function unknownNumberError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
['X-Foo' => 'Bar'],
'{"statusCode":2000,"statusMessage":"OK","clientMessageId":null,"transferId":"0063c11b0100eeda5a1d","smsCount":1}'
),
$history
);
$this->order->assign([
'oxbillfon' => '222',
'oxbillcountryid' => 'a7c40f631fc920687.20179984',
]);
$this->order->save();
/** @var EmailCore $mail */
$mail = oxNew(Email::class);
$mail->sendSendedNowMail($this->order);
// check requests
$this->assertCount(
0, // no request because of internal handling
$container
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function apiError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
[],
'{"statusCode": 4019, "statusMessage": "parameter \"messageContent\" invalid", "clientMessageId": null, "transferId": null, "smsCount": 0}'
),
$history
);
/** @var EmailCore $mail */
$mail = oxNew(Email::class);
$mail->sendSendedNowMail($this->order);
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'John Doe')
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function notConfigured()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
[],
'{"statusCode": 4019, "statusMessage": "parameter \"messageContent\" invalid", "clientMessageId": null, "transferId": null, "smsCount": 0}'
),
$history
);
/** @var Configuration|MockObject $configuration */
$configuration = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getTestMode', 'sendOrderSendedNowMessage', 'sendOrderCanceledMessage', 'sendOrderFinishedMessage'])
->getMock();
$configuration->method('getTestMode')->willReturn(true);
$configuration->method('sendOrderSendedNowMessage')->willReturn(false);
$configuration->method('sendOrderCanceledMessage')->willReturn(false);
$configuration->method('sendOrderFinishedMessage')->willReturn(false);
d3GetOxidDIC()->set(Configuration::class, $configuration);
/** @var EmailCore $mail */
$mail = oxNew(Email::class);
$mail->sendSendedNowMail($this->order);
// check requests
$this->assertCount(
0, // no request because of internal handling
$container
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function recipientError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
$this->setClientResponse(
new Response(
200,
['X-Foo' => 'Bar'],
'{"statusCode":2000,"statusMessage":"OK","clientMessageId":null,"transferId":"0063c11b0100eeda5a1d","smsCount":1}'
),
$history
);
$this->order->assign([
'oxbillfon' => '',
'oxbillcountryid' => ''
]);
$this->order->save();
/** @var EmailCore $mail */
$mail = oxNew(Email::class);
$mail->sendSendedNowMail($this->order);
// check requests
$this->assertCount(
0, // no request because of internal handling
$container
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @test
* @throws DoctrineException
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
*/
public function communicationError()
{
$container = [];
$history = Middleware::history($container);
$this->deleteAllRemarksFrom($this->userId);
/** @var Logger|MockObject $loggerMock */
$loggerMock = $this->getMockBuilder(Logger::class)
->onlyMethods(['error'])
->disableOriginalConstructor()
->getMock();
$loggerMock->method('error');
d3GetOxidDIC()->get(LoggerHandler::class)->setLogger($loggerMock);
$this->setClientResponse(
new RequestException(
'Error Communicating with Server',
new Request('GET', 'test')
),
$history
);
/** @var EmailCore $mail */
$mail = oxNew(Email::class);
$mail->sendSendedNowMail($this->order);
// check requests
$this->assertCount(
1,
$container
);
/** @var RequestInterface $request */
$request = $container[0]['request'];
$this->assertTrue(
(bool) strpos(serialize($request->getBody()->getContents()), 'John Doe')
);
// check remark
/** @var QueryBuilder $queryBuilder */
$queryBuilder = ContainerFactory::getInstance()->getContainer()->get(QueryBuilderFactoryInterface::class)->create();
$queryBuilder->select('oxid')
->from(oxNew(Remark::class)->getViewName())
->where(
$queryBuilder->expr()->eq(
'oxparentid',
$queryBuilder->createNamedParameter($this->userId)
)
);
$remarkIds = $queryBuilder->execute()->fetchAll();
$this->assertEmpty($remarkIds);
$this->deleteAllRemarksFrom($this->userId);
}
/**
* @throws Exception
*/
public function tearDown(): void
{
parent::tearDown();
$this->order->delete();
$this->user->delete();
}
}

28
src/tests/phpunit.xml Normal file
View File

@ -0,0 +1,28 @@
<phpunit backupGlobals="true"
backupStaticAttributes="false"
cacheTokens="true"
colors="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="false"
convertWarningsToExceptions="true"
forceCoversAnnotation="false"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
stopOnIncomplete="false"
stopOnSkipped="false"
verbose="false">
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">../Application</directory>
<directory suffix=".php">../Modules</directory>
<directory suffix=".php">../Setup</directory>
<exclude>
<directory suffix=".php">../Application/views</directory>
</exclude>
</whitelist>
</filter>
<logging>
<log type="junit" target="reports/logfile.xml"/>
</logging>
</phpunit>

View File

@ -0,0 +1,158 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Application\Controller\Admin;
use D3\Linkmobility4OXID\Application\Controller\Admin\AdminOrder;
use D3\Linkmobility4OXID\Application\Model\Exceptions\noRecipientFoundException;
use D3\Linkmobility4OXID\Application\Model\Exceptions\successfullySentException;
use D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms;
use D3\Linkmobility4OXID\Application\Model\OrderRecipients;
use D3\LinkmobilityClient\LoggerHandler;
use D3\TestingTools\Development\CanAccessRestricted;
use Monolog\Logger;
use OxidEsales\Eshop\Application\Model\Order;
use OxidEsales\Eshop\Core\UtilsView;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
class AdminOrderTest extends AdminSend
{
use CanAccessRestricted;
protected $subjectUnderTestClass = AdminOrder::class;
protected $itemClass = Order::class;
protected $itemRecipientClass = OrderRecipients::class;
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminOrder::__construct
*/
public function canConstruct()
{
/** @var Order|MockObject $itemMock */
$itemMock = $this->getMockBuilder($this->itemClass)
->onlyMethods(['load'])
->getMock();
$itemMock->method('load')->willReturn(true);
d3GetOxidDIC()->set('d3ox.linkmobility.'.Order::class, $itemMock);
$sut = parent::canConstruct();
$this->assertSame(
$itemMock,
$this->getValue(
$sut,
'item'
)
);
}
/**
* @test
*
* @param $canSendItemMessage
* @param $throwException
*
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminOrder::sendMessage
* @dataProvider canSendMessageDataProvider
*/
public function canSendMessage($canSendItemMessage, $throwException)
{
/** @var Sms|MockObject $smsMock */
$smsMock = $this->getMockBuilder(Sms::class)
->disableOriginalConstructor()
->onlyMethods(['sendOrderMessage'])
->getMock();
$smsMock->expects($this->once())->method('sendOrderMessage')->will(
$throwException ?
$this->throwException(oxNew(noRecipientFoundException::class)) :
$this->returnValue($canSendItemMessage)
);
/** @var Logger|MockObject $loggerMock */
$loggerMock = $this->getMockBuilder(Logger::class)
->onlyMethods(['warning'])
->disableOriginalConstructor()
->getMock();
$loggerMock->expects($this->exactly((int) $throwException))->method('warning');
/** @var LoggerHandler|MockObject $loggerHandlerMock */
$loggerHandlerMock = $this->getMockBuilder(LoggerHandler::class)
->onlyMethods(['getLogger'])
->getMock();
$loggerHandlerMock->method('getLogger')->willReturn($loggerMock);
d3GetOxidDIC()->set(LoggerHandler::class, $loggerHandlerMock);
/** @var UtilsView|MockObject $utilsViewMock */
$utilsViewMock = $this->getMockBuilder(UtilsView::class)
->onlyMethods(['addErrorToDisplay'])
->getMock();
$utilsViewMock->expects($this->exactly((int) $throwException))->method('addErrorToDisplay');
d3GetOxidDIC()->set('d3ox.linkmobility.'.UtilsView::class, $utilsViewMock);
/** @var AdminOrder|MockObject $sut */
$sut = $this->getMockBuilder(AdminOrder::class)
->disableOriginalConstructor()
->onlyMethods(['getMessageBody', 'getSuccessSentMessage', 'getUnsuccessfullySentMessage', 'getSms'])
->getMock();
$sut->method('getMessageBody')->willReturn('messageBodyFixture');
$sut->expects($this->exactly((int) $canSendItemMessage))->method('getSuccessSentMessage')
->willReturn(oxNew(successfullySentException::class, 'expectedReturn'));
$sut->expects($this->exactly((int) (!$canSendItemMessage && !$throwException)))->method('getUnsuccessfullySentMessage')
->willReturn('expectedReturn');
$sut->method('getSms')->willReturn($smsMock);
$this->setValue(
$sut,
'item',
oxNew($this->itemClass)
);
$this->assertIsString(
$this->callMethod(
$sut,
'sendMessage'
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminOrder::getSms
*/
public function canGetSms()
{
/** @var AdminOrder|MockObject $sut */
$sut = $this->getMockBuilder(AdminOrder::class)
->disableOriginalConstructor()
->getMock();
$this->assertInstanceOf(
Sms::class,
$this->callMethod(
$sut,
'getSms',
['messageFixture']
)
);
}
}

View File

@ -0,0 +1,388 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Application\Controller\Admin;
use D3\Linkmobility4OXID\Application\Controller\Admin\AdminOrder;
use D3\Linkmobility4OXID\Application\Controller\Admin\AdminUser;
use D3\Linkmobility4OXID\Application\Model\Exceptions\noRecipientFoundException;
use D3\Linkmobility4OXID\Application\Model\Exceptions\successfullySentException;
use D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms;
use D3\Linkmobility4OXID\Application\Model\OrderRecipients;
use D3\Linkmobility4OXID\Application\Model\UserRecipients;
use D3\Linkmobility4OXID\tests\unit\LMUnitTestCase;
use D3\LinkmobilityClient\SMS\Response;
use D3\LinkmobilityClient\ValueObject\Recipient;
use D3\TestingTools\Development\CanAccessRestricted;
use InvalidArgumentException;
use OxidEsales\Eshop\Core\Request;
use OxidEsales\Eshop\Core\UtilsView;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
class AdminSend extends LMUnitTestCase
{
use CanAccessRestricted;
protected $subjectUnderTestClass;
protected $itemClass;
protected $itemRecipientClass;
/**
* @return AdminOrder|MockObject
* @throws ReflectionException
*/
public function canConstruct()
{
/** @var Recipient|MockObject $recipientMock */
$recipientMock = $this->getMockBuilder(Recipient::class)
->disableOriginalConstructor()
->getMock();
/** @var AdminOrder|MockObject $sut */
$sut = $this->getMockBuilder($this->subjectUnderTestClass)
->disableOriginalConstructor()
->onlyMethods(['getEditObjectId', 'getRecipientFromCurrentItem'])
->getMock();
$sut->method('getEditObjectId')->willReturn('editObjId');
$sut->method('getRecipientFromCurrentItem')->willReturn($recipientMock);
$this->callMethod(
$sut,
'__construct'
);
$this->assertInstanceOf(
$this->itemRecipientClass,
$this->getValue(
$sut,
'itemRecipients'
)
);
$this->assertSame(
$recipientMock,
$this->callMethod(
$sut,
'getViewDataElement',
['recipient']
)
);
return $sut;
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminOrder::getRecipientFromCurrentItem
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminUser::getRecipientFromCurrentItem
*/
public function canGetRecipientFromCurrentItemPassed()
{
/** @var Recipient|MockObject $recipientMock */
$recipientMock = $this->getMockBuilder(Recipient::class)
->disableOriginalConstructor()
->getMock();
/** @var OrderRecipients|UserRecipients|MockObject $itemsRecipientsMock */
$itemsRecipientsMock = $this->getMockBuilder($this->itemRecipientClass)
->disableOriginalConstructor()
->onlyMethods(['getSmsRecipient'])
->getMock();
$itemsRecipientsMock->method('getSmsRecipient')->willReturn($recipientMock);
/** @var AdminOrder|AdminUser|MockObject $sut */
$sut = $this->getMockBuilder($this->subjectUnderTestClass)
->onlyMethods(['send'])
->disableOriginalConstructor()
->getMock();
$this->setValue(
$sut,
'item',
oxNew($this->itemClass)
);
$this->setValue(
$sut,
'itemRecipients',
$itemsRecipientsMock
);
$this->assertSame(
$recipientMock,
$this->callMethod(
$sut,
'getRecipientFromCurrentItem'
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminOrder::getRecipientFromCurrentItem
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminUser::getRecipientFromCurrentItem
*/
public function canGetRecipientFromCurrentItemThrowsException()
{
/** @var UtilsView|MockObject $utilsViewMock */
$utilsViewMock = $this->getMockBuilder(UtilsView::class)
->onlyMethods(['addErrorToDisplay'])
->getMock();
$utilsViewMock->expects($this->once())->method('addErrorToDisplay');
d3GetOxidDIC()->set('d3ox.linkmobility.'.UtilsView::class, $utilsViewMock);
/** @var OrderRecipients|MockObject $itemRecipientsMock */
$itemRecipientsMock = $this->getMockBuilder($this->itemRecipientClass)
->disableOriginalConstructor()
->onlyMethods(['getSmsRecipient'])
->getMock();
$itemRecipientsMock->method('getSmsRecipient')->willThrowException(
oxNew(noRecipientFoundException::class)
);
d3GetOxidDIC()->set(OrderRecipients::class, $itemRecipientsMock);
d3GetOxidDIC()->set(UserRecipients::class, $itemRecipientsMock);
/** @var AdminOrder|AdminUser|MockObject $sut */
$sut = $this->getMockBuilder($this->subjectUnderTestClass)
->onlyMethods(['__construct'])
->disableOriginalConstructor()
->getMock();
$this->setValue(
$sut,
'item',
oxNew($this->itemClass)
);
$this->setValue(
$sut,
'itemRecipients',
oxNew($this->itemRecipientClass, oxNew($this->itemClass))
);
$this->assertFalse(
$this->callMethod(
$sut,
'getRecipientFromCurrentItem'
)
);
}
/**
* @test
* @param $throwsException
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminOrder::send
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminUser::send
* @dataProvider canSendDataProvider
*/
public function canSend($throwsException)
{
/** @var UtilsView|MockObject $utilsViewMock */
$utilsViewMock = $this->getMockBuilder(UtilsView::class)
->onlyMethods(['addErrorToDisplay'])
->getMock();
$utilsViewMock->expects($this->once())->method('addErrorToDisplay');
d3GetOxidDIC()->set('d3ox.linkmobility.'.UtilsView::class, $utilsViewMock);
/** @var AdminOrder|AdminUser|MockObject $sut */
$sut = $this->getMockBuilder($this->subjectUnderTestClass)
->onlyMethods(['sendMessage'])
->disableOriginalConstructor()
->getMock();
$sut->method('sendMessage')->will(
$throwsException ?
$this->throwException(oxNew(InvalidArgumentException::class)) :
$this->returnValue('successfully sent message')
);
$this->callMethod(
$sut,
'send'
);
}
/**
* @return array
*/
public function canSendDataProvider(): array
{
return [
'can send message' => [false],
'can not send message' => [true],
];
}
/**
* @param $message
* @param $expectException
* @param $expected
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminOrder::getMessageBody
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminUser::getMessageBody
* @dataProvider canGetMessageBodyDataProvider
*/
public function canGetMessageBody($message, $expectException, $expected)
{
/** @var Request|MockObject $requestMock */
$requestMock = $this->getMockBuilder(Request::class)
->onlyMethods(['getRequestEscapedParameter'])
->getMock();
$requestMock->method('getRequestEscapedParameter')->willReturn($message);
d3GetOxidDIC()->set('d3ox.linkmobility.'.Request::class, $requestMock);
/** @var AdminOrder|AdminUser|MockObject $sut */
$sut = $this->getMockBuilder($this->subjectUnderTestClass)
->onlyMethods(['__construct'])
->disableOriginalConstructor()
->getMock();
if ($expectException) {
$this->expectException(InvalidArgumentException::class);
}
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'getMessageBody'
)
);
}
/**
* @return array[]
*/
public function canGetMessageBodyDataProvider(): array
{
return [
'message not string' => [[], true, ''],
'message empty string' => ['', true, ''],
'message whitespace string' => [' ', true, ''],
'message right string' => ['messagefixture', false, 'messagefixture'],
];
}
/**
* @return array
*/
public function canSendMessageDataProvider(): array
{
return [
'send item message' => [true, false],
'dont send item message' => [false, false],
'throw exception' => [false, true]
];
}
/**
* @test
* @param $hasResponse
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminOrder::getSuccessSentMessage
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminUser::getSuccessSentMessage
* @dataProvider canGetSuccessSentMessageDataProvider
*/
public function canGetSuccessSentMessage($hasResponse)
{
/** @var Response|MockObject $resonseMock */
$resonseMock = $this->getMockBuilder(Response::class)
->onlyMethods(['getSmsCount'])
->disableOriginalConstructor()
->getMock();
$resonseMock->expects($hasResponse ? $this->once() : $this->never())->method('getSmsCount')
->willReturn(20);
/** @var Sms|MockObject $smsMock */
$smsMock = $this->getMockBuilder(Sms::class)
->disableOriginalConstructor()
->onlyMethods(['getResponse'])
->getMock();
$smsMock->method('getResponse')->willReturn($hasResponse ? $resonseMock : null);
/** @var AdminOrder|AdminUser|MockObject $sut */
$sut = $this->getMockBuilder($this->subjectUnderTestClass)
->disableOriginalConstructor()
->onlyMethods(['__construct'])
->getMock();
$this->assertInstanceOf(
successfullySentException::class,
$this->callMethod(
$sut,
'getSuccessSentMessage',
[$smsMock]
)
);
}
/**
* @return array
*/
public function canGetSuccessSentMessageDataProvider(): array
{
return [
'has response' => [true],
'has no response' => [false],
];
}
/**
* @test
* @param $hasResponse
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminOrder::getUnsuccessfullySentMessage
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminUser::getUnsuccessfullySentMessage
* @dataProvider canGetSuccessSentMessageDataProvider
*/
public function canGetUnsuccessfullySentMessage($hasResponse)
{
/** @var Response|MockObject $resonseMock */
$resonseMock = $this->getMockBuilder(Response::class)
->onlyMethods(['getErrorMessage'])
->disableOriginalConstructor()
->getMock();
$resonseMock->expects($hasResponse ? $this->once() : $this->never())->method('getErrorMessage')
->willReturn('errorMessage');
/** @var Sms|MockObject $smsMock */
$smsMock = $this->getMockBuilder(Sms::class)
->disableOriginalConstructor()
->onlyMethods(['getResponse'])
->getMock();
$smsMock->method('getResponse')->willReturn($hasResponse ? $resonseMock : null);
/** @var AdminOrder|AdminUser|MockObject $sut */
$sut = $this->getMockBuilder($this->subjectUnderTestClass)
->disableOriginalConstructor()
->getMock();
$this->assertIsString(
$this->callMethod(
$sut,
'getUnsuccessfullySentMessage',
[$smsMock]
)
);
}
}

View File

@ -0,0 +1,158 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Application\Controller\Admin;
use D3\Linkmobility4OXID\Application\Controller\Admin\AdminUser;
use D3\Linkmobility4OXID\Application\Model\Exceptions\noRecipientFoundException;
use D3\Linkmobility4OXID\Application\Model\Exceptions\successfullySentException;
use D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms;
use D3\Linkmobility4OXID\Application\Model\UserRecipients;
use D3\LinkmobilityClient\LoggerHandler;
use D3\TestingTools\Development\CanAccessRestricted;
use Monolog\Logger;
use OxidEsales\Eshop\Application\Model\User;
use OxidEsales\Eshop\Core\UtilsView;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
class AdminUserTest extends AdminSend
{
use CanAccessRestricted;
protected $subjectUnderTestClass = AdminUser::class;
protected $itemClass = User::class;
protected $itemRecipientClass = UserRecipients::class;
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminUser::__construct
*/
public function canConstruct()
{
/** @var User|MockObject $itemMock */
$itemMock = $this->getMockBuilder($this->itemClass)
->onlyMethods(['load'])
->getMock();
$itemMock->method('load')->willReturn(true);
d3GetOxidDIC()->set('d3ox.linkmobility.'.User::class, $itemMock);
$sut = parent::canConstruct();
$this->assertSame(
$itemMock,
$this->getValue(
$sut,
'item'
)
);
}
/**
* @test
*
* @param $canSendItemMessage
* @param $throwException
*
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminUser::sendMessage
* @dataProvider canSendMessageDataProvider
*/
public function canSendMessage($canSendItemMessage, $throwException)
{
/** @var Sms|MockObject $smsMock */
$smsMock = $this->getMockBuilder(Sms::class)
->disableOriginalConstructor()
->onlyMethods(['sendUserAccountMessage'])
->getMock();
$smsMock->expects($this->once())->method('sendUserAccountMessage')->will(
$throwException ?
$this->throwException(oxNew(noRecipientFoundException::class)) :
$this->returnValue($canSendItemMessage)
);
/** @var Logger|MockObject $loggerMock */
$loggerMock = $this->getMockBuilder(Logger::class)
->onlyMethods(['warning'])
->disableOriginalConstructor()
->getMock();
$loggerMock->expects($this->exactly((int) $throwException))->method('warning');
/** @var LoggerHandler|MockObject $loggerHandlerMock */
$loggerHandlerMock = $this->getMockBuilder(LoggerHandler::class)
->onlyMethods(['getLogger'])
->getMock();
$loggerHandlerMock->method('getLogger')->willReturn($loggerMock);
d3GetOxidDIC()->set(LoggerHandler::class, $loggerHandlerMock);
/** @var UtilsView|MockObject $utilsViewMock */
$utilsViewMock = $this->getMockBuilder(UtilsView::class)
->onlyMethods(['addErrorToDisplay'])
->getMock();
$utilsViewMock->expects($this->exactly((int) $throwException))->method('addErrorToDisplay');
d3GetOxidDIC()->set('d3ox.linkmobility.'.UtilsView::class, $utilsViewMock);
/** @var AdminUser|MockObject $sut */
$sut = $this->getMockBuilder(AdminUser::class)
->disableOriginalConstructor()
->onlyMethods(['getMessageBody', 'getSuccessSentMessage', 'getUnsuccessfullySentMessage', 'getSms'])
->getMock();
$sut->method('getMessageBody')->willReturn('messageBodyFixture');
$sut->expects($this->exactly((int) $canSendItemMessage))->method('getSuccessSentMessage')
->willReturn(oxNew(successfullySentException::class, 'expectedReturn'));
$sut->expects($this->exactly((int) (!$canSendItemMessage && !$throwException)))->method('getUnsuccessfullySentMessage')
->willReturn('expectedReturn');
$sut->method('getSms')->willReturn($smsMock);
$this->setValue(
$sut,
'item',
oxNew($this->itemClass)
);
$this->assertIsString(
$this->callMethod(
$sut,
'sendMessage'
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Controller\Admin\AdminUser::getSms
*/
public function canGetSms()
{
/** @var AdminUser|MockObject $sut */
$sut = $this->getMockBuilder(AdminUser::class)
->disableOriginalConstructor()
->getMock();
$this->assertInstanceOf(
Sms::class,
$this->callMethod(
$sut,
'getSms',
['messageFixture']
)
);
}
}

View File

@ -0,0 +1,543 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Application\Model;
use Assert\InvalidArgumentException;
use D3\Linkmobility4OXID\Application\Model\Configuration;
use D3\Linkmobility4OXID\tests\unit\LMUnitTestCase;
use D3\TestingTools\Development\CanAccessRestricted;
use OxidEsales\Eshop\Core\Config;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
class ConfigurationTest extends LMUnitTestCase
{
use CanAccessRestricted;
/**
* @test
* @return void
* @throws ReflectionException
* @dataProvider canGetApiTokenDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\Configuration::getApiToken
*/
public function canGetApiToken($savedToken, $expected, $expectException)
{
/** @var Config|MockObject $configMock */
$configMock = $this->getMockBuilder(Config::class)
->onlyMethods(['getConfigParam'])
->getMock();
$configMock->method('getConfigParam')->willReturnCallback(
function () use ($savedToken) {
$aArgs = func_get_args();
switch ($aArgs[0]) {
case Configuration::GENERAL_APITOKEN:
return $savedToken;
}
$this->fail('Unknown variable '.$aArgs[0]);
}
);
/** @var Configuration|MockObject $sut */
$sut = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getConfig'])
->getMock();
$sut->method('getConfig')->willReturn($configMock);
if ($expectException) {
$this->expectException(InvalidArgumentException::class);
}
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'getApiToken'
)
);
}
/**
* @return array[]
*/
public function canGetApiTokenDataProvider(): array
{
return [
'token ok' => [' apiTokenFixture ', 'apiTokenFixture', false],
'array token' => [['apiTokenFixture'], 'aptTokenFixture', true],
'null token' => [null, 'aptTokenFixture', true],
'empty token' => ['', 'aptTokenFixture', true],
];
}
/**
* @test
* @param $testMode
* @param $expected
* @return void
* @throws ReflectionException
* @dataProvider trueFalseDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\Configuration::getTestMode
*/
public function canGetTestMode($testMode, $expected)
{
/** @var Config|MockObject $configMock */
$configMock = $this->getMockBuilder(Config::class)
->onlyMethods(['getConfigParam'])
->getMock();
$configMock->method('getConfigParam')->willReturnCallback(
function () use ($testMode) {
$aArgs = func_get_args();
switch ($aArgs[0]) {
case Configuration::GENERAL_DEBUG:
return $testMode;
}
$this->fail('Unknown variable '.$aArgs[0]);
}
);
/** @var Configuration|MockObject $sut */
$sut = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getConfig'])
->getMock();
$sut->method('getConfig')->willReturn($configMock);
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'getTestMode'
)
);
}
/**
* @test
* @param $config
* @param $expected
* @param $expectException
* @return void
* @throws ReflectionException
* @dataProvider canGetSmsSenderNumberDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\Configuration::getSmsSenderNumber
*/
public function canGetSmsSenderNumber($config, $expected, $expectException)
{
/** @var Config|MockObject $configMock */
$configMock = $this->getMockBuilder(Config::class)
->onlyMethods(['getConfigParam'])
->getMock();
$configMock->method('getConfigParam')->willReturnCallback(
function () use ($config) {
$aArgs = func_get_args();
switch ($aArgs[0]) {
case Configuration::SMS_SENDERNR:
return $config;
}
$this->fail('Unknown variable '.$aArgs[0]);
}
);
/** @var Configuration|MockObject $sut */
$sut = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getConfig'])
->getMock();
$sut->method('getConfig')->willReturn($configMock);
if ($expectException) {
$this->expectException(InvalidArgumentException::class);
}
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'getSmsSenderNumber'
)
);
}
/**
* @return array[]
*/
public function canGetSmsSenderNumberDataProvider(): array
{
return [
'number ok' => [' 0123456789 ', '0123456789', false],
'array number' => [['0123456789'], '0123456789', true],
'null number' => [null, null, true],
'empty number' => ['', null, false],
];
}
/**
* @test
* @param $config
* @param $expected
* @param $expectException
* @return void
* @throws ReflectionException
* @dataProvider canGetSmsSenderCountryDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\Configuration::getSmsSenderCountry
*/
public function canGetSmsSenderCountry($config, $expected, $expectException)
{
/** @var Config|MockObject $configMock */
$configMock = $this->getMockBuilder(Config::class)
->onlyMethods(['getConfigParam'])
->getMock();
$configMock->method('getConfigParam')->willReturnCallback(
function () use ($config) {
$aArgs = func_get_args();
switch ($aArgs[0]) {
case Configuration::SMS_SENDERCOUNTRY:
return $config;
}
$this->fail('Unknown variable '.$aArgs[0]);
}
);
/** @var Configuration|MockObject $sut */
$sut = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getConfig'])
->getMock();
$sut->method('getConfig')->willReturn($configMock);
if ($expectException) {
$this->expectException(InvalidArgumentException::class);
}
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'getSmsSenderCountry'
)
);
}
/**
* @return array[]
*/
public function canGetSmsSenderCountryDataProvider(): array
{
return [
'country ok' => [' at ', 'AT', false],
'country to short' => [' D ', 'D', true],
'country to long' => [' FRA ', 'FRA', true],
'array country' => [['DE'], 'DE', true],
'null country' => [null, null, true],
'empty number' => ['', null, false],
];
}
/**
* @test
* @param $config
* @param $expected
* @param $expectException
* @return void
* @throws ReflectionException
* @dataProvider canGetOrderRecipientFieldsDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\Configuration::getOrderRecipientFields
* @covers \D3\Linkmobility4OXID\Application\Model\Configuration::checkFieldExists
* @covers \D3\Linkmobility4OXID\Application\Model\Configuration::sanitizeKeys
*/
public function canGetOrderRecipientFields($config, $expected, $expectException)
{
/** @var Config|MockObject $configMock */
$configMock = $this->getMockBuilder(Config::class)
->onlyMethods(['getConfigParam'])
->getMock();
$configMock->method('getConfigParam')->willReturnCallback(
function () use ($config) {
$aArgs = func_get_args();
switch ($aArgs[0]) {
case Configuration::ORDER_RECFIELDS:
return $config;
}
$this->fail('Unknown variable '.$aArgs[0]);
}
);
/** @var Configuration|MockObject $sut */
$sut = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getConfig'])
->getMock();
$sut->method('getConfig')->willReturn($configMock);
if ($expectException) {
$this->expectException(InvalidArgumentException::class);
}
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'getOrderRecipientFields'
)
);
}
/**
* @return array[]
*/
public function canGetOrderRecipientFieldsDataProvider(): array
{
return [
'string fields' => ['oxbillfon', '', true],
'array fields exist' => [[' oxbillcountryid ' => ' oxbillfon ', ' oxdelcountryid ' => ' oxdelfon '], ['oxbillcountryid' => 'oxbillfon', 'oxdelcountryid' => 'oxdelfon'], false],
'array fields not exist'=> [[' d3custfield1 ' => ' oxbillfon ', ' oxdelcountryid ' => ' d3custfield2 '], [], false],
'empty number' => [[], [], false],
];
}
/**
* @test
* @param $config
* @param $expected
* @param $expectException
* @return void
* @throws ReflectionException
* @dataProvider canGetUserRecipientFieldsDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\Configuration::getUserRecipientFields
* @covers \D3\Linkmobility4OXID\Application\Model\Configuration::checkFieldExists
* @covers \D3\Linkmobility4OXID\Application\Model\Configuration::sanitizeKeys
*/
public function canGetUserRecipientFields($config, $expected, $expectException)
{
/** @var Config|MockObject $configMock */
$configMock = $this->getMockBuilder(Config::class)
->onlyMethods(['getConfigParam'])
->getMock();
$configMock->method('getConfigParam')->willReturnCallback(
function () use ($config) {
$aArgs = func_get_args();
switch ($aArgs[0]) {
case Configuration::USER_RECFIELDS:
return $config;
}
$this->fail('Unknown variable '.$aArgs[0]);
}
);
/** @var Configuration|MockObject $sut */
$sut = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getConfig'])
->getMock();
$sut->method('getConfig')->willReturn($configMock);
if ($expectException) {
$this->expectException(InvalidArgumentException::class);
}
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'getUserRecipientFields'
)
);
}
/**
* @return array[]
*/
public function canGetUserRecipientFieldsDataProvider(): array
{
return [
'string fields' => ['oxfon', '', true],
'array fields exist' => [[' oxfon ', ' oxmobfon '], ['oxfon', 'oxmobfon'], false],
'array fields not exist'=> [[' d3custfield1 ', ' d3custfield2 '], [], false],
'empty number' => [[], [], false],
];
}
/**
* @test
* @param $config
* @param $expected
* @return void
* @throws ReflectionException
* @dataProvider trueFalseDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\Configuration::sendOrderFinishedMessage
*/
public function canGetSendOrderFinishedMessage($config, $expected)
{
/** @var Config|MockObject $configMock */
$configMock = $this->getMockBuilder(Config::class)
->onlyMethods(['getConfigParam'])
->getMock();
$configMock->method('getConfigParam')->willReturnCallback(
function () use ($config) {
$aArgs = func_get_args();
switch ($aArgs[0]) {
case Configuration::SENDBY_ORDERED:
return $config;
}
$this->fail('Unknown variable '.$aArgs[0]);
}
);
/** @var Configuration|MockObject $sut */
$sut = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getConfig'])
->getMock();
$sut->method('getConfig')->willReturn($configMock);
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'sendOrderFinishedMessage'
)
);
}
/**
* @test
* @param $config
* @param $expected
* @return void
* @throws ReflectionException
* @dataProvider trueFalseDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\Configuration::sendOrderSendedNowMessage
*/
public function canGetSendOrderSendedNowMessage($config, $expected)
{
/** @var Config|MockObject $configMock */
$configMock = $this->getMockBuilder(Config::class)
->onlyMethods(['getConfigParam'])
->getMock();
$configMock->method('getConfigParam')->willReturnCallback(
function () use ($config) {
$aArgs = func_get_args();
switch ($aArgs[0]) {
case Configuration::SENDBY_SENDEDNOW:
return $config;
}
$this->fail('Unknown variable '.$aArgs[0]);
}
);
/** @var Configuration|MockObject $sut */
$sut = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getConfig'])
->getMock();
$sut->method('getConfig')->willReturn($configMock);
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'sendOrderSendedNowMessage'
)
);
}
/**
* @test
* @param $config
* @param $expected
* @return void
* @throws ReflectionException
* @dataProvider trueFalseDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\Configuration::sendOrderCanceledMessage
*/
public function canGetSendOrderCanceledMessage($config, $expected)
{
/** @var Config|MockObject $configMock */
$configMock = $this->getMockBuilder(Config::class)
->onlyMethods(['getConfigParam'])
->getMock();
$configMock->method('getConfigParam')->willReturnCallback(
function () use ($config) {
$aArgs = func_get_args();
switch ($aArgs[0]) {
case Configuration::SENDBY_CANCELED:
return $config;
}
$this->fail('Unknown variable '.$aArgs[0]);
}
);
/** @var Configuration|MockObject $sut */
$sut = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getConfig'])
->getMock();
$sut->method('getConfig')->willReturn($configMock);
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'sendOrderCanceledMessage'
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\Configuration::getConfig
*/
public function canGetConfig()
{
/** @var Configuration|MockObject $sut */
$sut = $this->getMockBuilder(Configuration::class)
->getMock();
$this->assertInstanceOf(
Config::class,
$this->callMethod(
$sut,
'getConfig'
)
);
}
/**
* @return array
*/
public function trueFalseDataProvider(): array
{
return [
'true value' => [true, true],
'false value' => [false, false],
'one value' => [1, true],
'zero value' => [0, false]
];
}
}

View File

@ -0,0 +1,48 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Application\Model\Exceptions;
use D3\Linkmobility4OXID\Application\Model\Exceptions\noRecipientFoundException;
use D3\Linkmobility4OXID\tests\unit\LMUnitTestCase;
use D3\TestingTools\Development\CanAccessRestricted;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
class noRecipientFoundExceptionTest extends LMUnitTestCase
{
use CanAccessRestricted;
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\Exceptions\noRecipientFoundException::__construct
*/
public function canConstruct()
{
/** @var noRecipientFoundException|MockObject $sut */
$sut = $this->getMockBuilder(noRecipientFoundException::class)
->getMock();
$this->assertRegExp(
'@.*NO.*RECIPIENT.*SET.*@',
$this->callMethod(
$sut,
'getMessage'
)
);
}
}

View File

@ -0,0 +1,57 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Application\Model\Exceptions;
use D3\Linkmobility4OXID\Application\Model\Exceptions\successfullySentException;
use D3\Linkmobility4OXID\tests\unit\LMUnitTestCase;
use D3\TestingTools\Development\CanAccessRestricted;
use OxidEsales\Eshop\Core\Language;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
class successfullySentExceptionTest extends LMUnitTestCase
{
use CanAccessRestricted;
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\Exceptions\successfullySentException::__construct
*/
public function canConstruct()
{
/** @var Language|MockObject $languageMock */
$languageMock = $this->getMockBuilder(Language::class)
->onlyMethods(['translateString'])
->getMock();
$languageMock->method('translateString')->willReturn('%1$s messages');
d3GetOxidDIC()->set('d3ox.linkmobility.'.Language::class, $languageMock);
/** @var successfullySentException|MockObject $sut */
$sut = $this->getMockBuilder(successfullySentException::class)
->setConstructorArgs([25, 10])
->getMock();
$this->assertSame(
'25 messages',
$this->callMethod(
$sut,
'getMessage'
)
);
}
}

View File

@ -0,0 +1,56 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Application\Model;
use D3\Linkmobility4OXID\Application\Model\Configuration;
use D3\Linkmobility4OXID\Application\Model\MessageClient;
use D3\Linkmobility4OXID\tests\unit\LMUnitTestCase;
use D3\LinkmobilityClient\Client;
use D3\TestingTools\Development\CanAccessRestricted;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
class MessageClientTest extends LMUnitTestCase
{
use CanAccessRestricted;
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageClient::getClient
*/
public function canGetClient()
{
/** @var Configuration|MockObject $configurationMock */
$configurationMock = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getApiToken'])
->getMock();
$configurationMock->method('getApiToken')->willReturn('apiTokenFixture');
d3GetOxidDIC()->set(Configuration::class, $configurationMock);
/** @var MessageClient $sut */
$sut = oxNew(MessageClient::class);
$this->assertInstanceOf(
Client::class,
$this->callMethod(
$sut,
'getClient'
)
);
}
}

View File

@ -0,0 +1,311 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Application\Model;
use D3\Linkmobility4OXID\Application\Model\Configuration;
use D3\Linkmobility4OXID\Application\Model\Exceptions\noRecipientFoundException;
use D3\Linkmobility4OXID\Application\Model\MessageSender;
use D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms;
use D3\Linkmobility4OXID\tests\unit\LMUnitTestCase;
use D3\LinkmobilityClient\LoggerHandler;
use D3\TestingTools\Development\CanAccessRestricted;
use Monolog\Logger;
use OxidEsales\Eshop\Application\Model\Order;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
class MessageSenderTest extends LMUnitTestCase
{
use CanAccessRestricted;
/**
* @test
*
* @param $actionConfigured
* @param $invocationCount
* @param $throwException
*
* @return void
* @throws ReflectionException
* @dataProvider canSendOrderFinishedMessageDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\MessageSender::sendOrderFinishedMessage
*/
public function canSendOrderFinishedMessage($actionConfigured, $invocationCount, $throwException)
{
/** @var Logger|MockObject $loggerMock */
$loggerMock = $this->getMockBuilder(Logger::class)
->onlyMethods(['debug'])
->disableOriginalConstructor()
->getMock();
$loggerMock->expects($this->exactly((int) $throwException))->method('debug');
/** @var LoggerHandler|MockObject $loggerHandlerMock */
$loggerHandlerMock = $this->getMockBuilder(LoggerHandler::class)
->onlyMethods(['getLogger'])
->getMock();
$loggerHandlerMock->method('getLogger')->willReturn($loggerMock);
d3GetOxidDIC()->set(LoggerHandler::class, $loggerHandlerMock);
/** @var Configuration|MockObject $configurationMock */
$configurationMock = $this->getMockBuilder(Configuration::class)
->onlyMethods(['sendOrderFinishedMessage'])
->getMock();
$configurationMock->method('sendOrderFinishedMessage')->willReturn($actionConfigured);
/** @var Order|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
/** @var MessageSender|MockObject $sut */
$sut = $this->getMockBuilder(MessageSender::class)
->onlyMethods(['getConfiguration', 'sendMessageByOrder'])
->getMock();
$sut->method('getConfiguration')->willReturn($configurationMock);
if ($throwException) {
$sut->expects($invocationCount)->method('sendMessageByOrder')
->willThrowException(oxNew(noRecipientFoundException::class));
} else {
$sut->expects($invocationCount)->method('sendMessageByOrder');
}
$this->callMethod(
$sut,
'sendOrderFinishedMessage',
[$orderMock, 'messageBody']
);
}
/**
* @test
*
* @param $actionConfigured
* @param $invocationCount
* @param $throwException
*
* @return void
* @throws ReflectionException
* @dataProvider canSendOrderFinishedMessageDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\MessageSender::sendSendedNowMessage
*/
public function canSendSendedNowMessage($actionConfigured, $invocationCount, $throwException)
{
/** @var Logger|MockObject $loggerMock */
$loggerMock = $this->getMockBuilder(Logger::class)
->onlyMethods(['debug'])
->disableOriginalConstructor()
->getMock();
$loggerMock->expects($this->exactly((int) $throwException))->method('debug');
/** @var LoggerHandler|MockObject $loggerHandlerMock */
$loggerHandlerMock = $this->getMockBuilder(LoggerHandler::class)
->onlyMethods(['getLogger'])
->getMock();
$loggerHandlerMock->method('getLogger')->willReturn($loggerMock);
d3GetOxidDIC()->set(LoggerHandler::class, $loggerHandlerMock);
/** @var Configuration|MockObject $configurationMock */
$configurationMock = $this->getMockBuilder(Configuration::class)
->onlyMethods(['sendOrderSendedNowMessage'])
->getMock();
$configurationMock->method('sendOrderSendedNowMessage')->willReturn($actionConfigured);
/** @var Order|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
/** @var MessageSender|MockObject $sut */
$sut = $this->getMockBuilder(MessageSender::class)
->onlyMethods(['getConfiguration', 'sendMessageByOrder'])
->getMock();
$sut->method('getConfiguration')->willReturn($configurationMock);
if ($throwException) {
$sut->expects($invocationCount)->method('sendMessageByOrder')
->willThrowException(oxNew(noRecipientFoundException::class));
} else {
$sut->expects($invocationCount)->method('sendMessageByOrder');
}
$this->callMethod(
$sut,
'sendSendedNowMessage',
[$orderMock, 'messageBody']
);
}
/**
* @test
*
* @param $actionConfigured
* @param $invocationCount
* @param $throwException
*
* @return void
* @throws ReflectionException
* @dataProvider canSendOrderFinishedMessageDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\MessageSender::sendCancelOrderMessage
*/
public function canSendCancelOrderMessage($actionConfigured, $invocationCount, $throwException)
{
/** @var Logger|MockObject $loggerMock */
$loggerMock = $this->getMockBuilder(Logger::class)
->onlyMethods(['debug'])
->disableOriginalConstructor()
->getMock();
$loggerMock->expects($this->exactly((int) $throwException))->method('debug');
/** @var LoggerHandler|MockObject $loggerHandlerMock */
$loggerHandlerMock = $this->getMockBuilder(LoggerHandler::class)
->onlyMethods(['getLogger'])
->getMock();
$loggerHandlerMock->method('getLogger')->willReturn($loggerMock);
d3GetOxidDIC()->set(LoggerHandler::class, $loggerHandlerMock);
/** @var Configuration|MockObject $configurationMock */
$configurationMock = $this->getMockBuilder(Configuration::class)
->onlyMethods(['sendOrderCanceledMessage'])
->getMock();
$configurationMock->method('sendOrderCanceledMessage')->willReturn($actionConfigured);
/** @var Order|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
/** @var MessageSender|MockObject $sut */
$sut = $this->getMockBuilder(MessageSender::class)
->onlyMethods(['getConfiguration', 'sendMessageByOrder'])
->getMock();
$sut->method('getConfiguration')->willReturn($configurationMock);
if ($throwException) {
$sut->expects($invocationCount)->method('sendMessageByOrder')
->willThrowException(oxNew(noRecipientFoundException::class));
} else {
$sut->expects($invocationCount)->method('sendMessageByOrder');
}
$this->callMethod(
$sut,
'sendCancelOrderMessage',
[$orderMock, 'messageBody']
);
}
/**
* @return array[]
*/
public function canSendOrderFinishedMessageDataProvider(): array
{
return [
'action configured, no exc' => [true, $this->once(), false],
'action configured, throw exc' => [true, $this->once(), true],
'action not configured' => [false, $this->never(), false],
];
}
/**
* @test
* @param $messageBody
* @param $invocationCount
* @return void
* @throws ReflectionException
* @dataProvider canSendMessageByOrderDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\MessageSender::sendMessageByOrder
*/
public function canSendMessageByOrder($messageBody, $invocationCount)
{
/** @var Sms|MockObject $smsMock */
$smsMock = $this->getMockBuilder(Sms::class)
->onlyMethods(['sendOrderMessage'])
->disableOriginalConstructor()
->getMock();
$smsMock->expects($invocationCount)->method('sendOrderMessage');
/** @var Order|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
/** @var MessageSender|MockObject $sut */
$sut = $this->getMockBuilder(MessageSender::class)
->onlyMethods(['getSms', 'getConfiguration'])
->getMock();
$sut->method('getSms')->willReturn($smsMock);
$this->callMethod(
$sut,
'sendMessageByOrder',
[$orderMock, $messageBody]
);
}
/**
* @return array
*/
public function canSendMessageByOrderDataProvider(): array
{
return [
'has message body' => ['body', $this->once()],
'spaced message body' => [' ', $this->never()],
'empty message body' => ['', $this->never()],
];
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageSender::getSms
*/
public function canGetSms()
{
/** @var MessageSender|MockObject $sut */
$sut = $this->getMockBuilder(MessageSender::class)
->getMock();
$this->assertInstanceOf(
Sms::class,
$this->callMethod(
$sut,
'getSms',
['messageFixture']
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageSender::getConfiguration
*/
public function canGetConfiguration()
{
/** @var MessageSender|MockObject $sut */
$sut = $this->getMockBuilder(MessageSender::class)
->onlyMethods(['sendMessageByOrder'])
->getMock();
$this->assertInstanceOf(
Configuration::class,
$this->callMethod(
$sut,
'getConfiguration'
)
);
}
}

View File

@ -0,0 +1,844 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Application\Model\MessageTypes;
use D3\Linkmobility4OXID\Application\Model\Configuration;
use D3\Linkmobility4OXID\Application\Model\MessageClient;
use D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms;
use D3\Linkmobility4OXID\Application\Model\OrderRecipients;
use D3\Linkmobility4OXID\Application\Model\RequestFactory;
use D3\Linkmobility4OXID\Application\Model\UserRecipients;
use D3\Linkmobility4OXID\tests\unit\LMUnitTestCase;
use D3\LinkmobilityClient\Client;
use D3\LinkmobilityClient\RecipientsList\RecipientsList;
use D3\LinkmobilityClient\SMS\BinaryRequest;
use D3\LinkmobilityClient\SMS\Response;
use D3\LinkmobilityClient\ValueObject\Recipient;
use D3\LinkmobilityClient\ValueObject\Sender;
use D3\TestingTools\Development\CanAccessRestricted;
use GuzzleHttp\Exception\ServerException;
use Monolog\Logger;
use OxidEsales\Eshop\Application\Model\Order;
use OxidEsales\Eshop\Application\Model\Remark;
use OxidEsales\Eshop\Application\Model\User;
use OxidEsales\Eshop\Core\UtilsView;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
use ReflectionException;
class SmsTest extends LMUnitTestCase
{
use CanAccessRestricted;
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::__construct
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::getMessage
*/
public function canConstruct()
{
/** @var Sms|MockObject $sut */
$sut = $this->getMockBuilder(Sms::class)
->disableOriginalConstructor()
->onlyMethods(['sanitizeMessage'])
->getMock();
$sut->expects($this->once())->method('sanitizeMessage')->willReturnArgument(0);
$this->callMethod(
$sut,
'__construct',
['messageFixture']
);
$this->assertSame(
'messageFixture',
$this->callMethod(
$sut,
'getMessage'
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::setRemark
*/
public function canSetRemark()
{
/** @var Remark|MockObject $remarkMock */
$remarkMock = $this->getMockBuilder(Remark::class)
->onlyMethods(['assign', 'save'])
->getMock();
$remarkMock->expects($this->atLeastOnce())->method('assign');
$remarkMock->expects($this->atLeastOnce())->method('save')->willReturn(true);
d3GetOxidDIC()->set('d3ox.linkmobility.'.Remark::class, $remarkMock);
/** @var Sms|MockObject $sut */
$sut = $this->getMockBuilder(Sms::class)
->setConstructorArgs(['messageFixture'])
->onlyMethods(['getTypeName'])
->getMock();
$sut->method('getTypeName')->willReturn('typeFixture');
$this->callMethod(
$sut,
'setRemark',
['userIdFixture', 'recipients', 'messageFixture']
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::getResponse
*/
public function canGetResponse()
{
/** @var Response|MockObject $responseMock */
$responseMock = $this->getMockBuilder(Response::class)
->disableOriginalConstructor()
->getMock();
/** @var Sms $sut */
$sut = oxNew(Sms::class, 'messageFixture');
$this->setValue(
$sut,
'response',
$responseMock
);
$this->assertSame(
$responseMock,
$this->callMethod(
$sut,
'getResponse'
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::setRecipients
*/
public function canSetRecipients()
{
/** @var RecipientsList|MockObject $recipientsListMock */
$recipientsListMock = $this->getMockBuilder(RecipientsList::class)
->disableOriginalConstructor()
->getMock();
/** @var Sms $sut */
$sut = oxNew(Sms::class, 'messageFixture');
$this->callMethod(
$sut,
'setRecipients',
[$recipientsListMock]
);
$this->assertSame(
$recipientsListMock,
$this->getValue(
$sut,
'recipients'
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::getRecipientsList
*/
public function canGetRecipientsList()
{
/** @var Recipient|MockObject $recipientsMock1 */
$recipientsMock1 = $this->getMockBuilder(Recipient::class)
->setConstructorArgs(['01512 3456788', 'DE'])
->onlyMethods(['getFormatted'])
->getMock();
/** @var Recipient|MockObject $recipientsMock1 */
$recipientsMock2 = $this->getMockBuilder(Recipient::class)
->setConstructorArgs(['01512 3456789', 'DE'])
->onlyMethods(['getFormatted'])
->getMock();
/** @var RecipientsList|MockObject $recipientsListMock */
$recipientsListMock = $this->getMockBuilder(RecipientsList::class)
->disableOriginalConstructor()
->onlyMethods(['clearRecipents'])
->getMock();
$recipientsListMock->add($recipientsMock1)->add($recipientsMock2);
/** @var Sms $sut */
$sut = oxNew(Sms::class, 'messageFixture');
$this->callMethod(
$sut,
'setRecipients',
[$recipientsListMock]
);
$this->assertSame(
'+4915123456788, +4915123456789',
$this->callMethod(
$sut,
'getRecipientsList'
)
);
}
/**
* @test
* @param $message
* @param $removeLineBreaks
* @param $removeMultiSpaces
* @param $expected
* @return void
* @throws ReflectionException
* @dataProvider canSanitizeMessageDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::sanitizeMessage
*/
public function canSanitizeMessage($message, $removeLineBreaks, $removeMultiSpaces, $expected)
{
/** @var Sms|MockObject $sut */
$sut = $this->getMockBuilder(Sms::class)
->disableOriginalConstructor()
->getMock();
$this->setValue(
$sut,
'removeLineBreaks',
$removeLineBreaks
);
$this->setValue(
$sut,
'removeMultipleSpaces',
$removeMultiSpaces
);
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'sanitizeMessage',
[$message]
)
);
}
/**
* @return array[]
*/
public function canSanitizeMessageDataProvider(): array
{
$message = " ab<br>cd ef\r\ngh ";
return [
'keep linebreaks, keep multispaces' => [$message, false, false, "abcd ef\r\ngh"],
'rem linebreaks, keep multispaces' => [$message, true, false, "abcd ef gh"],
'keep linebreaks, rem multispaces' => [$message, false, true, "abcd ef\r\ngh"],
'rem linebreaks, rem multispaces' => [$message, true, true, 'abcd ef gh'],
];
}
/**
* @test
* @param $sendReturn
* @param $setRemark
* @return void
* @throws ReflectionException
* @dataProvider canSendUserAccountMessageDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::sendUserAccountMessage
*/
public function canSendUserAccountMessage($sendReturn, $setRemark)
{
/** @var User|MockObject $userMock */
$userMock = $this->getMockBuilder(User::class)
->disableOriginalConstructor()
->onlyMethods(['getId'])
->getMock();
$userMock->method('getId')->willReturn('userIdFixture');
/** @var RecipientsList|MockObject $recipientsListMock */
$recipientsListMock = $this->getMockBuilder(RecipientsList::class)
->disableOriginalConstructor()
->getMock();
/** @var Sms|MockObject $sut */
$sut = $this->getMockBuilder(Sms::class)
->onlyMethods(['sendCustomRecipientMessage', 'getUserRecipientsList', 'setRemark',
'getRecipientsList', 'getMessage'])
->disableOriginalConstructor()
->getMock();
$sut->method('sendCustomRecipientMessage')->willReturn($sendReturn);
$sut->expects($setRemark ? $this->once() : $this->never())->method('setRemark');
$sut->method('getUserRecipientsList')->willReturn($recipientsListMock);
$sut->method('getRecipientsList')->willReturn('abc,def');
$sut->method('getMessage')->willReturn('messageFixture');
$this->assertSame(
$sendReturn,
$this->callMethod(
$sut,
'sendUserAccountMessage',
[$userMock]
)
);
}
/**
* @return array
*/
public function canSendUserAccountMessageDataProvider(): array
{
return [
'can send' => [true, true],
'cant send' => [false, false],
];
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::getUserRecipientsList
*/
public function canGetUserRecipientsList()
{
/** @var User|MockObject $userMock */
$userMock = $this->getMockBuilder(User::class)
->disableOriginalConstructor()
->getMock();
/** @var Recipient|MockObject $recipientMock */
$recipientMock = $this->getMockBuilder(Recipient::class)
->disableOriginalConstructor()
->getMock();
/** @var RecipientsList|MockObject $recipientsListMock */
$recipientsListMock = $this->getMockBuilder(RecipientsList::class)
->disableOriginalConstructor()
->onlyMethods(['add'])
->getMock();
$recipientsListMock->expects($this->once())->method('add')->willReturnSelf();
d3GetOxidDIC()->set(RecipientsList::class, $recipientsListMock);
$userRecipientsMock = $this->getMockBuilder(UserRecipients::class)
->disableOriginalConstructor()
->onlyMethods(['getSmsRecipient'])
->getMock();
$userRecipientsMock->method('getSmsRecipient')->willReturn($recipientMock);
d3GetOxidDIC()->set(UserRecipients::class, $userRecipientsMock);
/** @var MessageClient|MockObject $messageClientMock */
$messageClientMock = $this->getMockBuilder(MessageClient::class)
->getMock();
d3GetOxidDIC()->set(MessageClient::class, $messageClientMock);
/** @var Sms|MockObject $sut */
$sut = $this->getMockBuilder(Sms::class)
->disableOriginalConstructor()
->getMock();
$this->assertSame(
$recipientsListMock,
$this->callMethod(
$sut,
'getUserRecipientsList',
[$userMock]
)
);
}
/**
* @test
* @param $sendReturn
* @param $setRemark
* @return void
* @throws ReflectionException
* @dataProvider canSendUserAccountMessageDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::sendOrderMessage
*/
public function canSendOrderMessage($sendReturn, $setRemark)
{
/** @var User|MockObject $userMock */
$userMock = $this->getMockBuilder(User::class)
->disableOriginalConstructor()
->onlyMethods(['getId'])
->getMock();
$userMock->method('getId')->willReturn('userIdFixture');
/** @var Order|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->onlyMethods(['getId', 'getOrderUser'])
->getMock();
$orderMock->method('getId')->willReturn('userIdFixture');
$orderMock->method('getOrderUser')->willReturn($userMock);
/** @var RecipientsList|MockObject $recipientsListMock */
$recipientsListMock = $this->getMockBuilder(RecipientsList::class)
->disableOriginalConstructor()
->getMock();
/** @var Sms|MockObject $sut */
$sut = $this->getMockBuilder(Sms::class)
->onlyMethods(['sendCustomRecipientMessage', 'getOrderRecipientsList', 'setRemark',
'getRecipientsList', 'getMessage'])
->disableOriginalConstructor()
->getMock();
$sut->method('sendCustomRecipientMessage')->willReturn($sendReturn);
$sut->expects($setRemark ? $this->once() : $this->never())->method('setRemark');
$sut->method('getOrderRecipientsList')->willReturn($recipientsListMock);
$sut->method('getRecipientsList')->willReturn('abc,def');
$sut->method('getMessage')->willReturn('messageFixture');
$this->assertSame(
$sendReturn,
$this->callMethod(
$sut,
'sendOrderMessage',
[$orderMock]
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::getOrderRecipientsList
*/
public function canGetOrderRecipientsList()
{
/** @var Order|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
/** @var Recipient|MockObject $recipientMock */
$recipientMock = $this->getMockBuilder(Recipient::class)
->disableOriginalConstructor()
->getMock();
/** @var RecipientsList|MockObject $recipientsListMock */
$recipientsListMock = $this->getMockBuilder(RecipientsList::class)
->disableOriginalConstructor()
->onlyMethods(['add'])
->getMock();
$recipientsListMock->expects($this->once())->method('add')->willReturnSelf();
d3GetOxidDIC()->set(RecipientsList::class, $recipientsListMock);
/** @var MessageClient|MockObject $messageClientMock */
$messageClientMock = $this->getMockBuilder(MessageClient::class)
->getMock();
d3GetOxidDIC()->set(MessageClient::class, $messageClientMock);
/** @var Sms|MockObject $sut */
$sut = $this->getMockBuilder(Sms::class)
->disableOriginalConstructor()
->onlyMethods(['getOrderRecipient'])
->getMock();
$sut->method('getOrderRecipient')->willReturn($recipientMock);
$this->assertSame(
$recipientsListMock,
$this->callMethod(
$sut,
'getOrderRecipientsList',
[$orderMock]
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::getOrderRecipient
*/
public function canGetOrderRecipient()
{
/** @var Order|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
/** @var Recipient|MockObject $recipientMock */
$recipientMock = $this->getMockBuilder(Recipient::class)
->disableOriginalConstructor()
->getMock();
/** @var OrderRecipients|MockObject $orderRecipientsMock */
$orderRecipientsMock = $this->getMockBuilder(OrderRecipients::class)
->disableOriginalConstructor()
->onlyMethods(['getSmsRecipient'])
->getMock();
$orderRecipientsMock->method('getSmsRecipient')->willReturn($recipientMock);
d3GetOxidDIC()->set(OrderRecipients::class, $orderRecipientsMock);
/** @var Sms|MockObject $sut */
$sut = $this->getMockBuilder(Sms::class)
->disableOriginalConstructor()
->getMock();
$this->assertSame(
$recipientMock,
$this->callMethod(
$sut,
'getOrderRecipient',
[$orderMock]
)
);
}
/**
* @test
* @param $sendSuccessful
* @param $throwException
* @param $expected
* @return void
* @throws ReflectionException
* @dataProvider canSendCustomRecipientMessageDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::sendCustomRecipientMessage()
*/
public function canSendCustomRecipientMessage($sendSuccessful, $throwException, $expected)
{
/** @var RecipientsList|MockObject $recipientsListMock */
$recipientsListMock = $this->getMockBuilder(RecipientsList::class)
->disableOriginalConstructor()
->getMock();
/** @var Response|MockObject $smsResponseMock */
$smsResponseMock = $this->getMockBuilder(Response::class)
->onlyMethods(['isSuccessful'])
->disableOriginalConstructor()
->getMock();
$smsResponseMock->method('isSuccessful')->willReturn($sendSuccessful);
/** @var Logger|MockObject $loggerMock */
$loggerMock = $this->getMockBuilder(Logger::class)
->onlyMethods(['error'])
->disableOriginalConstructor()
->getMock();
$loggerMock->expects($this->exactly((int) $throwException))->method('error');
/** @var UtilsView|MockObject $utilsViewMock */
$utilsViewMock = $this->getMockBuilder(UtilsView::class)
->onlyMethods(['addErrorToDisplay'])
->getMock();
$utilsViewMock->expects($this->exactly((int) $throwException))->method('addErrorToDisplay');
d3GetOxidDIC()->set('d3ox.linkmobility.'.UtilsView::class, $utilsViewMock);
/** @var ServerException|MockObject $serverExceptionMock */
$serverExceptionMock = $this->getMockBuilder(ServerException::class)
->disableOriginalConstructor()
->getMock();
/** @var Sms|MockObject $sut */
$sut = $this->getMockBuilder(Sms::class)
->onlyMethods(['submitMessage', 'getLogger'])
->disableOriginalConstructor()
->getMock();
$sut->method('submitMessage')->will(
$throwException ?
$this->throwException($serverExceptionMock) :
$this->returnValue($smsResponseMock)
);
$sut->method('getLogger')->willReturn($loggerMock);
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'sendCustomRecipientMessage',
[$recipientsListMock]
)
);
}
/**
* @return array
*/
public function canSendCustomRecipientMessageDataProvider(): array
{
return [
'is successful' => [true, false, true],
'is not successful' => [false, false, false],
'no recipient' => [false, true, false],
];
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::getRequest()
*/
public function canGetRequest()
{
/** @var Sender|MockObject $senderMock */
$senderMock = $this->getMockBuilder(Sender::class)
->getMock();
/** @var Client|MockObject $clientMock */
$clientMock = $this->getMockBuilder(Client::class)
->disableOriginalConstructor()
->getMock();
/** @var Configuration|MockObject $configurationMock */
$configurationMock = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getSmsSenderNumber', 'getSmsSenderCountry'])
->getMock();
$configurationMock->method('getSmsSenderNumber')->willReturn('01512 3456789');
$configurationMock->method('getSmsSenderCountry')->willReturn('DE');
/** @var BinaryRequest|MockObject $binaryRequestMock */
$binaryRequestMock = $this->getMockBuilder(BinaryRequest::class)
->disableOriginalConstructor()
->getMock();
/** @var RequestFactory|MockObject $requestFactoryMock */
$requestFactoryMock = $this->getMockBuilder(RequestFactory::class)
->disableOriginalConstructor()
->onlyMethods(['getSmsRequest'])
->getMock();
$requestFactoryMock->method('getSmsRequest')->willReturn($binaryRequestMock);
/** @var Sms|MockObject $sut */
$sut = $this->getMockBuilder(Sms::class)
->onlyMethods(['getRequestFactory', 'getSender', 'getMessage'])
->disableOriginalConstructor()
->getMock();
$sut->method('getRequestFactory')->willReturn($requestFactoryMock);
$sut->method('getSender')->willReturn($senderMock);
$sut->method('getMessage')->willReturn('messageFixture');
$this->assertSame(
$binaryRequestMock,
$this->callMethod(
$sut,
'getRequest',
[$configurationMock, $clientMock]
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::getRequestFactory
*/
public function canGetRequestFactory()
{
/** @var Client|MockObject $clientMock */
$clientMock = $this->getMockBuilder(Client::class)
->disableOriginalConstructor()
->getMock();
/** @var Sms|MockObject $sut */
$sut = $this->getMockBuilder(Sms::class)
->disableOriginalConstructor()
->getMock();
$this->assertInstanceOf(
RequestFactory::class,
$this->callMethod(
$sut,
'getRequestFactory',
['messageFixture', $clientMock]
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::getSender
*/
public function canGetSender()
{
/** @var Sms|MockObject $sut */
$sut = $this->getMockBuilder(Sms::class)
->disableOriginalConstructor()
->getMock();
$this->assertInstanceOf(
Sender::class,
$this->callMethod(
$sut,
'getSender',
['01512 3456789', 'DE']
)
);
}
/**
* @test
* @param $submitSuccessful
* @return void
* @throws ReflectionException
* @dataProvider canSubmitMessageDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::submitMessage()
*/
public function canSubmitMessage($submitSuccessful)
{
/** @var Recipient|MockObject $recipientMock */
$recipientMock = $this->getMockBuilder(Recipient::class)
->disableOriginalConstructor()
->getMock();
/** @var RecipientsList|MockObject $recipientListMock */
$recipientListMock = $this->getMockBuilder(RecipientsList::class)
->onlyMethods(['getRecipientsList'])
->disableOriginalConstructor()
->getMock();
$recipientListMock->method('getRecipientsList')->willReturn([$recipientMock]);
/** @var RecipientsList|MockObject $requestRecipientListMock */
$requestRecipientListMock = $this->getMockBuilder(RecipientsList::class)
->disableOriginalConstructor()
->onlyMethods(['add'])
->getMock();
$requestRecipientListMock->expects($this->once())->method('add')->with(
$this->identicalTo($recipientMock)
);
/** @var BinaryRequest|MockObject $binaryRequestMock */
$binaryRequestMock = $this->getMockBuilder(BinaryRequest::class)
->onlyMethods(['getRecipientsList', 'getBody'])
->disableOriginalConstructor()
->getMock();
$binaryRequestMock->method('getRecipientsList')->willReturn($requestRecipientListMock);
$binaryRequestMock->method('getBody')->willReturn(['bodyFixture']);
/** @var Response|MockObject $smsResponseMock */
$smsResponseMock = $this->getMockBuilder(Response::class)
->disableOriginalConstructor()
->onlyMethods(['isSuccessful', 'getErrorMessage'])
->getMock();
$smsResponseMock->method('isSuccessful')->willReturn($submitSuccessful);
$smsResponseMock->method('getErrorMessage')->willReturn('errorMessageFixture');
/** @var Logger|MockObject $loggerMock */
$loggerMock = $this->getMockBuilder(Logger::class)
->onlyMethods(['warning'])
->disableOriginalConstructor()
->getMock();
$loggerMock->expects($this->exactly((int) !$submitSuccessful))->method('warning');
/** @var Client|MockObject $clientMock */
$clientMock = $this->getMockBuilder(Client::class)
->disableOriginalConstructor()
->onlyMethods(['request'])
->getMock();
$clientMock->method('request')->willReturn($smsResponseMock);
/** @var MessageClient|MockObject $messageClientMock */
$messageClientMock = $this->getMockBuilder(MessageClient::class)
->onlyMethods(['getClient'])
->getMock();
$messageClientMock->method('getClient')->willReturn($clientMock);
d3GetOxidDIC()->set(MessageClient::class, $messageClientMock);
/** @var Sms|MockObject $sut */
$sut = $this->getMockBuilder(Sms::class)
->disableOriginalConstructor()
->onlyMethods(['getRequest', 'getLogger'])
->getMock();
$sut->method('getRequest')->willReturn($binaryRequestMock);
$sut->method('getLogger')->willReturn($loggerMock);
$this->assertSame(
$smsResponseMock,
$this->callMethod(
$sut,
'submitMessage',
[$recipientListMock]
)
);
}
/**
* @return array
*/
public function canSubmitMessageDataProvider(): array
{
return [
'successful' => [true],
'not successful'=> [false]
];
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::getTypeName
*/
public function canGetTypeName()
{
/** @var Sms|MockObject $sut */
$sut = $this->getMockBuilder(Sms::class)
->disableOriginalConstructor()
->onlyMethods(['getMessage'])
->getMock();
$this->assertIsString(
$this->callMethod(
$sut,
'getTypeName'
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\MessageTypes\Sms::getLogger()
*/
public function canGetLogger()
{
/** @var Sms|MockObject $sut */
$sut = $this->getMockBuilder(Sms::class)
->disableOriginalConstructor()
->onlyMethods(['getMessage'])
->getMock();
$this->assertInstanceOf(
LoggerInterface::class,
$this->callMethod(
$sut,
'getLogger'
)
);
}
}

View File

@ -0,0 +1,261 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Application\Model;
use D3\Linkmobility4OXID\Application\Model\Configuration;
use D3\Linkmobility4OXID\Application\Model\Exceptions\noRecipientFoundException;
use D3\Linkmobility4OXID\Application\Model\OrderRecipients;
use D3\Linkmobility4OXID\tests\unit\LMUnitTestCase;
use D3\LinkmobilityClient\Exceptions\RecipientException;
use D3\LinkmobilityClient\ValueObject\Recipient;
use D3\TestingTools\Development\CanAccessRestricted;
use libphonenumber\NumberParseException;
use OxidEsales\Eshop\Application\Model\Country;
use OxidEsales\Eshop\Application\Model\Order;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
class OrderRecipientsTest extends LMUnitTestCase
{
use CanAccessRestricted;
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\OrderRecipients::__construct
*/
public function canConstruct()
{
/** @var Order|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
/** @var OrderRecipients|MockObject $sut */
$sut = $this->getMockBuilder(OrderRecipients::class)
->setConstructorArgs([$orderMock])
->getMock();
$this->assertSame(
$orderMock,
$this->getValue(
$sut,
'order'
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @dataProvider canGetSmsRecipientDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\OrderRecipients::getSmsRecipient
*/
public function canGetSmsRecipient($hasRecipient)
{
/** @var Recipient|MockObject $recipient1Mock */
$recipient1Mock = $this->getMockBuilder(Recipient::class)
->disableOriginalConstructor()
->getMock();
/** @var Recipient|MockObject $recipient2Mock */
$recipient2Mock = $this->getMockBuilder(Recipient::class)
->disableOriginalConstructor()
->getMock();
/** @var OrderRecipients|MockObject $sut */
$sut = $this->getMockBuilder(OrderRecipients::class)
->disableOriginalConstructor()
->onlyMethods(['getSmsRecipientFields', 'getSmsRecipientByField'])
->getMock();
$sut->method('getSmsRecipientFields')->willReturn(['pfield1' => 'cfield1', 'pfield2' => 'cfield2', 'pfield3' => 'cfield3']);
$sut->expects($this->exactly($hasRecipient ? 2 : 3))->method('getSmsRecipientByField')->willReturnOnConsecutiveCalls(
null,
$hasRecipient ? $recipient1Mock : null,
$hasRecipient ? $recipient2Mock : null
);
if (!$hasRecipient) {
$this->expectException(noRecipientFoundException::class);
}
$this->assertSame(
$recipient1Mock,
$this->callMethod(
$sut,
'getSmsRecipient'
)
);
}
/**
* @return array
*/
public function canGetSmsRecipientDataProvider(): array
{
return [
'has recipient' => [true],
'has no recipient' => [false],
];
}
/**
* @test
* @param $orderFieldValue
* @param $expected
* @param $thrownExc
* @return void
* @throws ReflectionException
* @dataProvider canGetSmsRecipientByFieldDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\OrderRecipients::getSmsRecipientByField
*/
public function canGetSmsRecipientByField($orderFieldValue, $expected, $thrownExc)
{
/** @var Recipient|MockObject $recipientMock */
$recipientMock = $this->getMockBuilder(Recipient::class)
->disableOriginalConstructor()
->getMock();
/** @var Country|MockObject $countryMock */
$countryMock = $this->getMockBuilder(Country::class)
->onlyMethods(['load', 'getFieldData'])
->getMock();
$countryMock->method('load')->will(
$thrownExc ?
$this->throwException(d3GetOxidDIC()->get($thrownExc)) :
$this->returnValue(true)
);
$countryMock->method('getFieldData')->willReturn('de');
d3GetOxidDIC()->set('d3ox.linkmobility.'.Country::class, $countryMock);
/** @var Order|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->onlyMethods(['getFieldData'])
->getMock();
$orderMock->method('getFieldData')->willReturnMap(
[
['phoneFieldName', $orderFieldValue],
['oxcountryid', 'country_de'],
]
);
/** @var OrderRecipients|MockObject $sut */
$sut = $this->getMockBuilder(OrderRecipients::class)
->onlyMethods(['getRecipient'])
->disableOriginalConstructor()
->getMock();
$sut->method('getRecipient')->willReturn($recipientMock);
$this->setValue(
$sut,
'order',
$orderMock
);
$this->assertSame(
$expected === 'recipientMock' ? $recipientMock : $expected,
$this->callMethod(
$sut,
'getSmsRecipientByField',
['phoneFieldName', 'countryIdFieldName']
)
);
}
/**
* @return array
*/
public function canGetSmsRecipientByFieldDataProvider(): array
{
return [
'has order field value no exc' => ['fieldContent', 'recipientMock', false],
'spaced order field value' => [' ', null, false],
'no order field value' => [null, null, false],
'has order field value recexc' => ['fieldContent', null, RecipientException::class],
'has order field value nmbexc' => ['fieldContent', null, NumberParseException::class],
];
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\OrderRecipients::getRecipient
*/
public function canGetRecipient()
{
/** @var OrderRecipients|MockObject $sut */
$sut = $this->getMockBuilder(OrderRecipients::class)
->disableOriginalConstructor()
->getMock();
$this->assertInstanceOf(
Recipient::class,
$this->callMethod(
$sut,
'getRecipient',
['01512 3456789', 'DE']
)
);
}
/**
* @test
* @param $configuredFields
* @param $expected
* @return void
* @throws ReflectionException
* @dataProvider canGetSmsRecipientFieldsDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\OrderRecipients::getSmsRecipientFields
*/
public function canGetSmsRecipientFields($configuredFields, $expected)
{
/** @var Configuration|MockObject $configurationMock */
$configurationMock = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getOrderRecipientFields'])
->getMock();
$configurationMock->method('getOrderRecipientFields')->willReturn($configuredFields);
d3GetOxidDIC()->set(Configuration::class, $configurationMock);
/** @var OrderRecipients|MockObject $sut */
$sut = $this->getMockBuilder(OrderRecipients::class)
->disableOriginalConstructor()
->onlyMethods(['__construct'])
->getMock();
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'getSmsRecipientFields'
)
);
}
/**
* @return array
*/
public function canGetSmsRecipientFieldsDataProvider(): array
{
return [
'fields configured' => [['pfield1' => 'cfield1', 'pfield2' => 'cfield2'], ['pfield1' => 'cfield1', 'pfield2' => 'cfield2']],
'fields not configured' => [[], ['oxdelfon' => 'oxdelcountryid', 'oxbillfon' => 'oxbillcountryid']],
];
}
}

View File

@ -0,0 +1,98 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Application\Model;
use D3\Linkmobility4OXID\Application\Model\Configuration;
use D3\Linkmobility4OXID\Application\Model\RequestFactory;
use D3\Linkmobility4OXID\tests\unit\LMUnitTestCase;
use D3\LinkmobilityClient\SMS\SmsRequestInterface;
use D3\LinkmobilityClient\SMS\TextRequest;
use D3\LinkmobilityClient\ValueObject\Sender;
use D3\TestingTools\Development\CanAccessRestricted;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
class RequestFactoryTest extends LMUnitTestCase
{
use CanAccessRestricted;
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\RequestFactory::getSmsRequest
*/
public function canGetSmsRequest()
{
/** @var Configuration|MockObject $configurationMock */
$configurationMock = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getTestMode', 'getSmsSenderNumber', 'getSmsSenderCountry'])
->getMock();
$configurationMock->expects($this->once())->method('getTestMode')->willReturn(true);
$configurationMock->expects($this->once())->method('getSmsSenderNumber')->willReturn('01512 3456789');
$configurationMock->expects($this->once())->method('getSmsSenderCountry')->willReturn('DE');
d3GetOxidDIC()->set(Configuration::class, $configurationMock);
/** @var Sender|MockObject $senderMock */
$senderMock = $this->getMockBuilder(Sender::class)
->disableOriginalConstructor()
->getMock();
/** @var TextRequest|MockObject $textRequestMock */
$textRequestMock = $this->getMockBuilder(TextRequest::class)
->disableOriginalConstructor()
->getMock();
/** @var RequestFactory|MockObject $sut */
$sut = $this->getMockBuilder(RequestFactory::class)
->disableOriginalConstructor()
->onlyMethods(['d3CallMockableFunction', 'getSender'])
->getMock();
$sut->method('d3CallMockableFunction')->willReturn($textRequestMock);
$sut->method('getSender')->willReturn($senderMock);
$this->assertInstanceOf(
SmsRequestInterface::class,
$this->callMethod(
$sut,
'getSmsRequest'
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\RequestFactory::getSender
*/
public function canGetSender()
{
/** @var RequestFactory|MockObject $sut */
$sut = $this->getMockBuilder(RequestFactory::class)
->disableOriginalConstructor()
->getMock();
$this->assertInstanceOf(
Sender::class,
$this->callMethod(
$sut,
'getSender',
['01512 3456789', 'DE']
)
);
}
}

View File

@ -0,0 +1,261 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Application\Model;
use D3\Linkmobility4OXID\Application\Model\Configuration;
use D3\Linkmobility4OXID\Application\Model\Exceptions\noRecipientFoundException;
use D3\Linkmobility4OXID\Application\Model\UserRecipients;
use D3\Linkmobility4OXID\tests\unit\LMUnitTestCase;
use D3\LinkmobilityClient\Exceptions\RecipientException;
use D3\LinkmobilityClient\ValueObject\Recipient;
use D3\TestingTools\Development\CanAccessRestricted;
use libphonenumber\NumberParseException;
use OxidEsales\Eshop\Application\Model\Country;
use OxidEsales\Eshop\Application\Model\User;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
class UserRecipientsTest extends LMUnitTestCase
{
use CanAccessRestricted;
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\UserRecipients::__construct
*/
public function canConstruct()
{
/** @var User|MockObject $userMock */
$userMock = $this->getMockBuilder(User::class)
->disableOriginalConstructor()
->getMock();
/** @var UserRecipients|MockObject $sut */
$sut = $this->getMockBuilder(UserRecipients::class)
->setConstructorArgs([$userMock])
->getMock();
$this->assertSame(
$userMock,
$this->getValue(
$sut,
'user'
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @dataProvider canGetSmsRecipientDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\UserRecipients::getSmsRecipient
*/
public function canGetSmsRecipient($hasRecipient)
{
/** @var Recipient|MockObject $recipient1Mock */
$recipient1Mock = $this->getMockBuilder(Recipient::class)
->disableOriginalConstructor()
->getMock();
/** @var Recipient|MockObject $recipient2Mock */
$recipient2Mock = $this->getMockBuilder(Recipient::class)
->disableOriginalConstructor()
->getMock();
/** @var UserRecipients|MockObject $sut */
$sut = $this->getMockBuilder(UserRecipients::class)
->disableOriginalConstructor()
->onlyMethods(['getSmsRecipientFields', 'getSmsRecipientByField'])
->getMock();
$sut->method('getSmsRecipientFields')->willReturn(['field1', 'field2', 'field3']);
$sut->expects($this->exactly($hasRecipient ? 2 : 3))->method('getSmsRecipientByField')->willReturnOnConsecutiveCalls(
null,
$hasRecipient ? $recipient1Mock : null,
$hasRecipient ? $recipient2Mock : null
);
if (!$hasRecipient) {
$this->expectException(noRecipientFoundException::class);
}
$this->assertSame(
$recipient1Mock,
$this->callMethod(
$sut,
'getSmsRecipient'
)
);
}
/**
* @return array
*/
public function canGetSmsRecipientDataProvider(): array
{
return [
'has recipient' => [true],
'has no recipient' => [false],
];
}
/**
* @test
* @param $userFieldValue
* @param $expected
* @param $thrownExc
* @return void
* @throws ReflectionException
* @dataProvider canGetSmsRecipientByFieldDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\UserRecipients::getSmsRecipientByField
*/
public function canGetSmsRecipientByField($userFieldValue, $expected, $thrownExc)
{
/** @var Recipient|MockObject $recipientMock */
$recipientMock = $this->getMockBuilder(Recipient::class)
->disableOriginalConstructor()
->getMock();
/** @var Country|MockObject $countryMock */
$countryMock = $this->getMockBuilder(Country::class)
->onlyMethods(['load', 'getFieldData'])
->getMock();
$countryMock->method('load')->will(
$thrownExc ?
$this->throwException(d3GetOxidDIC()->get($thrownExc)) :
$this->returnValue(true)
);
$countryMock->method('getFieldData')->willReturn('de');
d3GetOxidDIC()->set('d3ox.linkmobility.'.Country::class, $countryMock);
/** @var User|MockObject $userMock */
$userMock = $this->getMockBuilder(User::class)
->disableOriginalConstructor()
->onlyMethods(['getFieldData'])
->getMock();
$userMock->method('getFieldData')->willReturnMap(
[
['fieldName', $userFieldValue],
['oxcountryid', 'country_de'],
]
);
/** @var UserRecipients|MockObject $sut */
$sut = $this->getMockBuilder(UserRecipients::class)
->onlyMethods(['getRecipient'])
->disableOriginalConstructor()
->getMock();
$sut->method('getRecipient')->willReturn($recipientMock);
$this->setValue(
$sut,
'user',
$userMock
);
$this->assertSame(
$expected === 'recipientMock' ? $recipientMock : $expected,
$this->callMethod(
$sut,
'getSmsRecipientByField',
['fieldName']
)
);
}
/**
* @return array
*/
public function canGetSmsRecipientByFieldDataProvider(): array
{
return [
'has user field value no exc' => ['fieldContent', 'recipientMock', false],
'spaced user field value' => [' ', null, false],
'no user field value' => [null, null, false],
'has user field value recexc' => ['fieldContent', null, RecipientException::class],
'has user field value nmbexc' => ['fieldContent', null, NumberParseException::class],
];
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Application\Model\UserRecipients::getRecipient
*/
public function canGetRecipient()
{
/** @var UserRecipients|MockObject $sut */
$sut = $this->getMockBuilder(UserRecipients::class)
->disableOriginalConstructor()
->getMock();
$this->assertInstanceOf(
Recipient::class,
$this->callMethod(
$sut,
'getRecipient',
['01512 3456789', 'DE']
)
);
}
/**
* @test
* @param $configuredFields
* @param $expected
* @return void
* @throws ReflectionException
* @dataProvider canGetSmsRecipientFieldsDataProvider
* @covers \D3\Linkmobility4OXID\Application\Model\UserRecipients::getSmsRecipientFields
*/
public function canGetSmsRecipientFields($configuredFields, $expected)
{
/** @var Configuration|MockObject $configurationMock */
$configurationMock = $this->getMockBuilder(Configuration::class)
->onlyMethods(['getUserRecipientFields'])
->getMock();
$configurationMock->method('getUserRecipientFields')->willReturn($configuredFields);
d3GetOxidDIC()->set(Configuration::class, $configurationMock);
/** @var UserRecipients|MockObject $sut */
$sut = $this->getMockBuilder(UserRecipients::class)
->disableOriginalConstructor()
->onlyMethods(['__construct'])
->getMock();
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'getSmsRecipientFields'
)
);
}
/**
* @return array
*/
public function canGetSmsRecipientFieldsDataProvider(): array
{
return [
'fields configured' => [['field1', 'field2'], ['field1', 'field2']],
'fields not configured' => [[], ['oxmobfon', 'oxfon', 'oxprivfon']],
];
}
}

View File

@ -0,0 +1,60 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit;
use D3\DIContainerHandler\d3DicHandler;
use OxidEsales\TestingLibrary\UnitTestCase;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class LMUnitTestCase extends UnitTestCase
{
/**
* setup basic requirements
*/
public function setUp(): void
{
parent::setUp();
d3DicHandler::getUncompiledInstance();
}
public function tearDown(): void
{
parent::tearDown();
d3DicHandler::removeInstance();
}
/**
* @param $serviceName
* @param $serviceMock
*
* @return MockObject
*/
protected function getContainerMock($serviceName, $serviceMock): MockObject
{
$container = $this->getMockBuilder(ContainerInterface::class)
->onlyMethods(['get', 'has'])
->getMock();
$container->expects($this->any())
->method('get')
->with($this->equalTo($serviceName))
->will($this->returnValue($serviceMock));
return $container;
}
}

View File

@ -0,0 +1,83 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Modules\Application\Model;
use D3\Linkmobility4OXID\Modules\Application\Model\OrderModel;
use D3\Linkmobility4OXID\Modules\Core\EmailCore;
use D3\Linkmobility4OXID\tests\unit\LMUnitTestCase;
use D3\TestingTools\Development\CanAccessRestricted;
use OxidEsales\Eshop\Application\Model\Order;
use OxidEsales\Eshop\Core\Email;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
class OrderModelTest extends LMUnitTestCase
{
use CanAccessRestricted;
/**
* @test
* @param $stornoValue
* @param $invocationCount
* @return void
* @throws ReflectionException
* @dataProvider canCancelOrderDataProvider
* @covers \D3\Linkmobility4OXID\Modules\Application\Model\OrderModel::cancelOrder
*/
public function canCancelOrder($stornoValue, $invocationCount)
{
/** @var EmailCore|MockObject $EmailMock */
$EmailMock = $this->getMockBuilder(Email::class)
->onlyMethods(['d3SendCancelMessage'])
->getMock();
$EmailMock->expects($invocationCount)->method('d3SendCancelMessage');
d3GetOxidDIC()->set('d3ox.linkmobility.'.Email::class, $EmailMock);
/** @var OrderModel|MockObject $sut */
$sut = $this->getMockBuilder(Order::class)
->onlyMethods(['getFieldData', 'd3CallMockableFunction'])
->getMock();
$sut->method('getFieldData')->willReturnCallback(
function () use ($stornoValue) {
$aArgs = func_get_args();
switch ($aArgs[0]) {
case 'oxstorno':
return $stornoValue;
}
$this->fail('Unknown variable '.$aArgs[0]);
}
);
$sut->method('d3CallMockableFunction')->willReturn(true);
$this->callMethod(
$sut,
'cancelOrder'
);
}
/**
* @return array[]
*/
public function canCancelOrderDataProvider(): array
{
return [
'is canceled' => [true, $this->once()],
'not canceled' => [false, $this->never()],
];
}
}

View File

@ -0,0 +1,352 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Modules\Core;
use D3\Linkmobility4OXID\Application\Model\MessageSender;
use D3\Linkmobility4OXID\Modules\Application\Model\OrderModel;
use D3\Linkmobility4OXID\Modules\Core\EmailCore;
use D3\Linkmobility4OXID\tests\unit\LMUnitTestCase;
use D3\TestingTools\Development\CanAccessRestricted;
use OxidEsales\Eshop\Application\Model\Order;
use OxidEsales\Eshop\Core\Email;
use OxidEsales\EshopCommunity\Internal\Framework\Templating\TemplateRenderer;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
class EmailCoreTest extends LMUnitTestCase
{
use CanAccessRestricted;
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Modules\Core\EmailCore::sendOrderEmailToUser
*/
public function canSendOrderEmailToUser()
{
/** @var Order|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
/** @var EmailCore|MockObject $sut */
$sut = $this->getMockBuilder(Email::class)
->onlyMethods(['d3CallMockableFunction', 'd3SendOrderFinishedMessageToUser'])
->getMock();
$sut->method('d3CallMockableFunction')->willReturn('returnFixture');
$sut->expects($this->once())->method('d3SendOrderFinishedMessageToUser')->with(
$this->identicalTo($orderMock)
);
$this->assertSame(
'returnFixture',
$this->callMethod(
$sut,
'sendOrderEmailToUser',
[$orderMock]
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Modules\Core\EmailCore::sendSendedNowMail
*/
public function canSendSendedNowMail()
{
/** @var Order|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
/** @var EmailCore|MockObject $sut */
$sut = $this->getMockBuilder(Email::class)
->onlyMethods(['d3CallMockableFunction', 'd3SendedNowMessage'])
->getMock();
$sut->method('d3CallMockableFunction')->willReturn('returnFixture');
$sut->expects($this->once())->method('d3SendedNowMessage')->with(
$this->identicalTo($orderMock)
);
$this->assertSame(
'returnFixture',
$this->callMethod(
$sut,
'sendSendedNowMail',
[$orderMock]
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Modules\Core\EmailCore::d3SendOrderFinishedMessageToUser
*/
public function canSendOrderFinishedMessageToUser()
{
/** @var OrderModel|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
/** @var MessageSender|MockObject $messageSenderMock */
$messageSenderMock = $this->getMockBuilder(MessageSender::class)
->onlyMethods(['sendOrderFinishedMessage'])
->getMock();
$messageSenderMock->expects($this->once())->method('sendOrderFinishedMessage')->with(
$this->identicalTo($orderMock)
);
d3GetOxidDIC()->set(MessageSender::class, $messageSenderMock);
/** @var EmailCore|MockObject $sut */
$sut = $this->getMockBuilder(Email::class)
->onlyMethods(['d3GetOrderFinishedSmsMessageBody'])
->getMock();
$sut->method('d3GetOrderFinishedSmsMessageBody')->with(
$this->identicalTo($orderMock)
)->willReturn('smsMessageBodyFixture');
$this->callMethod(
$sut,
'd3SendOrderFinishedMessageToUser',
[$orderMock]
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Modules\Core\EmailCore::d3GetOrderFinishedSmsMessageBody
*/
public function canGetOrderFinishedSmsMessageBody()
{
/** @var Order|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
/** @var TemplateRenderer|MockObject $tplRendererMock */
$tplRendererMock = $this->getMockBuilder(TemplateRenderer::class)
->disableOriginalConstructor()
->onlyMethods(['renderTemplate'])
->getMock();
$tplRendererMock->method('renderTemplate')->willReturn('renderedFixture');
/** @var EmailCore|MockObject $sut */
$sut = $this->getMockBuilder(Email::class)
->onlyMethods(['d3GetTplRenderer', 'setViewData', 'getViewData'])
->getMock();
$sut->method('d3GetTplRenderer')->willReturn($tplRendererMock);
$sut->method('setViewData')->with(
$this->identicalTo('order'),
$this->identicalTo($orderMock)
);
$sut->method('getViewData')->willReturn([]);
$this->assertSame(
'renderedFixture',
$this->callMethod(
$sut,
'd3GetOrderFinishedSmsMessageBody',
[$orderMock]
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Modules\Core\EmailCore::d3SendedNowMessage
*/
public function canSendedNowMessage()
{
/** @var OrderModel|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
/** @var MessageSender|MockObject $messageSenderMock */
$messageSenderMock = $this->getMockBuilder(MessageSender::class)
->onlyMethods(['sendSendedNowMessage'])
->getMock();
$messageSenderMock->expects($this->once())->method('sendSendedNowMessage')->with(
$this->identicalTo($orderMock)
);
d3GetOxidDIC()->set(MessageSender::class, $messageSenderMock);
/** @var EmailCore|MockObject $sut */
$sut = $this->getMockBuilder(Email::class)
->onlyMethods(['d3GetSendedNowSmsMessageBody'])
->getMock();
$sut->method('d3GetSendedNowSmsMessageBody')->with(
$this->identicalTo($orderMock)
)->willReturn('smsMessageBodyFixture');
$this->callMethod(
$sut,
'd3SendedNowMessage',
[$orderMock]
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Modules\Core\EmailCore::d3GetSendedNowSmsMessageBody
*/
public function canGetSendedNowSmsMessageBody()
{
/** @var Order|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
/** @var TemplateRenderer|MockObject $tplRendererMock */
$tplRendererMock = $this->getMockBuilder(TemplateRenderer::class)
->disableOriginalConstructor()
->onlyMethods(['renderTemplate'])
->getMock();
$tplRendererMock->method('renderTemplate')->willReturn('renderedFixture');
/** @var EmailCore|MockObject $sut */
$sut = $this->getMockBuilder(Email::class)
->onlyMethods(['d3GetTplRenderer', 'setViewData', 'getViewData'])
->getMock();
$sut->method('d3GetTplRenderer')->willReturn($tplRendererMock);
$sut->method('setViewData')->with(
$this->identicalTo('order'),
$this->identicalTo($orderMock)
);
$sut->method('getViewData')->willReturn([]);
$this->assertSame(
'renderedFixture',
$this->callMethod(
$sut,
'd3GetSendedNowSmsMessageBody',
[$orderMock]
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Modules\Core\EmailCore::d3SendCancelMessage
*/
public function canSendCancelMessage()
{
/** @var OrderModel|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
/** @var MessageSender|MockObject $messageSenderMock */
$messageSenderMock = $this->getMockBuilder(MessageSender::class)
->onlyMethods(['sendCancelOrderMessage'])
->getMock();
$messageSenderMock->expects($this->once())->method('sendCancelOrderMessage')->with(
$this->identicalTo($orderMock)
);
d3GetOxidDIC()->set(MessageSender::class, $messageSenderMock);
/** @var EmailCore|MockObject $sut */
$sut = $this->getMockBuilder(Email::class)
->onlyMethods(['d3GetCancelOrderSmsMessageBody'])
->getMock();
$sut->method('d3GetCancelOrderSmsMessageBody')->with(
$this->identicalTo($orderMock)
)->willReturn('smsMessageBodyFixture');
$this->callMethod(
$sut,
'd3SendCancelMessage',
[$orderMock]
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Modules\Core\EmailCore::d3GetCancelOrderSmsMessageBody
*/
public function canGetCancelOrderSmsMessageBody()
{
/** @var Order|MockObject $orderMock */
$orderMock = $this->getMockBuilder(Order::class)
->disableOriginalConstructor()
->getMock();
/** @var TemplateRenderer|MockObject $tplRendererMock */
$tplRendererMock = $this->getMockBuilder(TemplateRenderer::class)
->disableOriginalConstructor()
->onlyMethods(['renderTemplate'])
->getMock();
$tplRendererMock->method('renderTemplate')->willReturn('renderedFixture');
/** @var EmailCore|MockObject $sut */
$sut = $this->getMockBuilder(Email::class)
->onlyMethods(['d3GetTplRenderer', 'setViewData', 'getViewData'])
->getMock();
$sut->method('d3GetTplRenderer')->willReturn($tplRendererMock);
$sut->method('setViewData')->with(
$this->identicalTo('order'),
$this->identicalTo($orderMock)
);
$sut->method('getViewData')->willReturn([]);
$this->assertSame(
'renderedFixture',
$this->callMethod(
$sut,
'd3GetCancelOrderSmsMessageBody',
[$orderMock]
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Modules\Core\EmailCore::d3GetTplRenderer
*/
public function canGetTplRenderer()
{
/** @var EmailCore|MockObject $sut */
$sut = $this->getMockBuilder(Email::class)
->disableOriginalConstructor()
->getMock();
$this->assertInstanceOf(
TemplateRenderer::class,
$this->callMethod(
$sut,
'd3GetTplRenderer'
)
);
}
}

View File

@ -0,0 +1,51 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Modules;
use D3\Linkmobility4OXID\Modules\LinkmobilityServices;
use D3\Linkmobility4OXID\tests\unit\LMUnitTestCase;
use D3\TestingTools\Development\CanAccessRestricted;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
class LinkMobilityServicesTest extends LMUnitTestCase
{
use CanAccessRestricted;
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Modules\LinkmobilityServices::__construct
*/
public function canConstruct()
{
/** @var LinkmobilityServices|MockObject $sut */
$sut = $this->getMockBuilder(LinkmobilityServices::class)
->disableOriginalConstructor()
->onlyMethods(['addYamlDefinitions', 'd3CallMockableFunction'])
->getMock();
$sut->expects($this->atLeastOnce())->method('addYamlDefinitions')->with(
$this->identicalTo('d3/linkmobility/Config/services.yaml')
);
$sut->method('d3CallMockableFunction')->willReturn(true);
$this->callMethod(
$sut,
'__construct'
);
}
}

View File

@ -0,0 +1,486 @@
<?php
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <support@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\Linkmobility4OXID\tests\unit\Setup;
use D3\Linkmobility4OXID\Setup\Actions;
use D3\Linkmobility4OXID\tests\unit\LMUnitTestCase;
use D3\LinkmobilityClient\LoggerHandler;
use D3\TestingTools\Development\CanAccessRestricted;
use Doctrine\DBAL\Query\Expression\ExpressionBuilder;
use Doctrine\DBAL\Query\QueryBuilder;
use Doctrine\DBAL\Statement;
use Monolog\Logger;
use OxidEsales\Eshop\Core\Config;
use OxidEsales\Eshop\Core\Database\Adapter\DatabaseInterface;
use OxidEsales\Eshop\Core\Database\Adapter\Doctrine\Database;
use OxidEsales\Eshop\Core\DbMetaDataHandler;
use OxidEsales\Eshop\Core\Exception\StandardException;
use OxidEsales\Eshop\Core\UtilsView;
use OxidEsales\EshopCommunity\Internal\Framework\Database\QueryBuilderFactory;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
use Symfony\Component\DependencyInjection\Container;
class ActionsTest extends LMUnitTestCase
{
use CanAccessRestricted;
/**
* @test
* @param $hasEnumValue
* @param $invocationCount
* @param $throwException
* @return void
* @throws ReflectionException
* @dataProvider canSetupDatabaseDataProvider
* @covers \D3\Linkmobility4OXID\Setup\Actions::setupDatabase
*/
public function canSetupDatabase($hasEnumValue, $invocationCount, $throwException)
{
/** @var Logger|MockObject $loggerMock */
$loggerMock = $this->getMockBuilder(Logger::class)
->onlyMethods(['error'])
->disableOriginalConstructor()
->getMock();
$loggerMock->expects($this->exactly((int) $throwException))->method('error');
d3GetOxidDIC()->get(LoggerHandler::class)->setLogger($loggerMock);
/** @var UtilsView|MockObject $utilsViewMock */
$utilsViewMock = $this->getMockBuilder(UtilsView::class)
->onlyMethods(['addErrorToDisplay'])
->getMock();
$utilsViewMock->expects($this->exactly((int) $throwException))->method('addErrorToDisplay');
d3GetOxidDIC()->set('d3ox.linkmobility.'.UtilsView::class, $utilsViewMock);
/** @var StandardException|MockObject $standardExceptionMock */
$standardExceptionMock = $this->getMockBuilder(StandardException::class)
->disableOriginalConstructor()
->getMock();
/** @var Actions|MockObject $sut */
$sut = $this->getMockBuilder(Actions::class)
->onlyMethods(['hasRemarkTypeEnumValue', 'addRemarkTypeEnumValue'])
->getMock();
$sut->method('hasRemarkTypeEnumValue')->will(
$throwException ?
$this->throwException($standardExceptionMock) :
$this->returnValue($hasEnumValue)
);
$sut->expects($invocationCount)->method('addRemarkTypeEnumValue');
$this->callMethod(
$sut,
'setupDatabase'
);
}
/**
* @return array[]
*/
public function canSetupDatabaseDataProvider(): array
{
return [
'has enum value' => [true, $this->never(), false],
'has no enum value' => [false, $this->once(), false],
'throws exception' => [false, $this->never(), true],
];
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Setup\Actions::regenerateViews
*/
public function canRegenerateViews()
{
/** @var DbMetaDataHandler|MockObject $dbMetaDataHandlerMock */
$dbMetaDataHandlerMock = $this->getMockBuilder(DbMetaDataHandler::class)
->onlyMethods(['updateViews'])
->getMock();
$dbMetaDataHandlerMock->expects($this->once())->method('updateViews');
d3GetOxidDIC()->set('d3ox.linkmobility.'.DbMetaDataHandler::class, $dbMetaDataHandlerMock);
/** @var Actions $sut */
$sut = d3GetOxidDIC()->get(Actions::class);
$this->callMethod(
$sut,
'regenerateViews'
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @dataProvider canHasRemarkTypeEnumValueDataProvider
* @covers \D3\Linkmobility4OXID\Setup\Actions::hasRemarkTypeEnumValue
*/
public function canHasRemarkTypeEnumValue($fieldType, $expectException, $expected)
{
/** @var Actions|MockObject $sut */
$sut = $this->getMockBuilder(Actions::class)
->onlyMethods(['getRemarkTypeFieldType'])
->getMock();
$sut->method('getRemarkTypeFieldType')->willReturn($fieldType);
if ($expectException) {
$this->expectException(StandardException::class);
}
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'hasRemarkTypeEnumValue'
)
);
}
/**
* @return array[]
*/
public function canHasRemarkTypeEnumValueDataProvider(): array
{
return [
'no enum' => ['varchar(25)', true, false],
'is enum, LM missing' => ['enum(foobar,barfoo)', false, false],
'is enum, LM exists' => ['enum(foobar,LINKMOB,barfoo)', false, true]
];
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Setup\Actions::getRemarkTypeFieldType()
*/
public function canGetRemarkTypeFieldType()
{
/** @var Statement|MockObject $resultStatementMock */
$resultStatementMock = $this->getMockBuilder(Statement::class)
->disableOriginalConstructor()
->onlyMethods(['fetchOne'])
->getMock();
$resultStatementMock->method('fetchOne')->willReturn('returnFixture');
$containerMock = $this->getQueryBuilderResultMock($resultStatementMock);
/** @var Actions|MockObject $sut */
$sut = $this->getMockBuilder(Actions::class)
->onlyMethods(['getContainer'])
->getMock();
$sut->method('getContainer')->willReturn($containerMock);
$this->assertSame(
'returnFixture',
$this->callMethod(
$sut,
'getRemarkTypeFieldType'
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Setup\Actions::addRemarkTypeEnumValue()
*/
public function acnAddRemarkTypeEnumValue()
{
/** @var Database|MockObject $databaseMock */
$databaseMock = $this->getMockBuilder(Database::class)
->onlyMethods(['execute', 'quoteIdentifier', 'quoteArray', 'quote'])
->getMock();
$databaseMock->expects($this->once())->method('execute')->willReturn(1);
$databaseMock->method('quoteIdentifier')->willReturn('foo');
$databaseMock->method('quoteArray')->willReturn('foo');
$databaseMock->method('quote')->willReturn('foo');
/** @var Actions|MockObject $sut */
$sut = $this->getMockBuilder(Actions::class)
->onlyMethods(['getUniqueFieldTypes', 'getDb'])
->getMock();
$sut->method('getUniqueFieldTypes')->willReturn(['foobar', 'LINKMOB', 'barfoo']);
$sut->method('getDb')->willReturn($databaseMock);
$this->callMethod(
$sut,
'addRemarkTypeEnumValue'
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Setup\Actions::getUniqueFieldTypes()
*/
public function canGetUniqueFieldTypes()
{
/** @var Actions|MockObject $sut */
$sut = $this->getMockBuilder(Actions::class)
->onlyMethods(['getRemarkTypeFieldType'])
->getMock();
$sut->method('getRemarkTypeFieldType')->willReturn("enum('val1', 'val2')");
$this->assertSame(
[
'val1',
'val2',
'LINKMOB'
],
$this->callMethod(
$sut,
'getUniqueFieldTypes'
)
);
}
/**
* @test
* @param $missing
* @return void
* @throws ReflectionException
* @dataProvider canCheckCmsItemsDataProvider
* @covers \D3\Linkmobility4OXID\Setup\Actions::checkCmsItems
*/
public function canCheckCmsItems($missing)
{
/** @var Actions|MockObject $sut */
$sut = $this->getMockBuilder(Actions::class)
->onlyMethods(['cmsMissing', 'addCms1Item', 'addCms2Item', 'addCms3Item'])
->getMock();
$sut->expects($this->exactly(3))->method('cmsMissing')->willReturn($missing);
$sut->expects($this->exactly((int) $missing))->method('addCms1Item');
$sut->expects($this->exactly((int) $missing))->method('addCms2Item');
$sut->expects($this->exactly((int) $missing))->method('addCms3Item');
$this->callMethod(
$sut,
'checkCmsItems'
);
}
/**
* @return array
*/
public function canCheckCmsItemsDataProvider(): array
{
return [
'CMS missing' => [true],
'CMS exists' => [false],
];
}
/**
* @test
* @return void
* @throws ReflectionException
* @dataProvider canCmsMissingDataProvider
* @covers \D3\Linkmobility4OXID\Setup\Actions::cmsMissing
*/
public function canCmsMissing($itemCount, $expected)
{
/** @var Statement|MockObject $resultStatementMock */
$resultStatementMock = $this->getMockBuilder(Statement::class)
->disableOriginalConstructor()
->onlyMethods(['fetchOne'])
->getMock();
$resultStatementMock->expects($this->once())->method('fetchOne')->willReturn($itemCount);
$containerMock = $this->getQueryBuilderResultMock($resultStatementMock);
/** @var Actions|MockObject $sut */
$sut = $this->getMockBuilder(Actions::class)
->onlyMethods(['getContainer'])
->getMock();
$sut->method('getContainer')->willReturn($containerMock);
$this->assertSame(
$expected,
$this->callMethod(
$sut,
'cmsMissing',
['checkIdent']
)
);
}
/**
* @return array[]
*/
public function canCmsMissingDataProvider(): array
{
return [
'found one' => [1, false],
'found none' => [0, true]
];
}
/**
* @test
* @param $method
* @return void
* @throws ReflectionException
* @dataProvider canAddCmsItemDataProvider
* @covers \D3\Linkmobility4OXID\Setup\Actions::addCms1Item
* @covers \D3\Linkmobility4OXID\Setup\Actions::addCms2Item
* @covers \D3\Linkmobility4OXID\Setup\Actions::addCms3Item
*/
public function canAddCmsItem($method)
{
/** @var QueryBuilder|MockObject $queryBuilderMock */
$queryBuilderMock = $this->getMockBuilder(QueryBuilder::class)
->disableOriginalConstructor()
->onlyMethods(['execute', 'expr'])
->getMock();
$queryBuilderMock->expects($this->once())->method('execute');
/** @var QueryBuilderFactory|MockObject $queryBuilderFactoryMock */
$queryBuilderFactoryMock = $this->getMockBuilder(QueryBuilderFactory::class)
->disableOriginalConstructor()
->onlyMethods(['create'])
->getMock();
$queryBuilderFactoryMock->method('create')->willReturn($queryBuilderMock);
/** @var Container|MockObject $containerMock */
$containerMock = $this->getMockBuilder(Container::class)
->onlyMethods(['get'])
->getMock();
$containerMock->method('get')->willReturn($queryBuilderFactoryMock);
/** @var Actions|MockObject $sut */
$sut = $this->getMockBuilder(Actions::class)
->onlyMethods(['getContainer'])
->getMock();
$sut->method('getContainer')->willReturn($containerMock);
$this->callMethod(
$sut,
$method
);
}
/**
* @return string[]
*/
public function canAddCmsItemDataProvider(): array
{
return [
['addCms1Item'],
['addCms2Item'],
['addCms3Item'],
];
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Setup\Actions::getContainer()
*/
public function canGetContainer()
{
/** @var Actions $sut */
$sut = oxNew(Actions::class);
$this->assertInstanceOf(
Container::class,
$this->callMethod(
$sut,
'getContainer'
)
);
}
/**
* @param MockObject $resultStatementMock
* @return MockObject|Container
*/
protected function getQueryBuilderResultMock(MockObject $resultStatementMock)
{
/** @var ExpressionBuilder|MockObject $expressionBuilderMock */
$expressionBuilderMock = $this->getMockBuilder(ExpressionBuilder::class)
->disableOriginalConstructor()
->getMock();
/** @var QueryBuilder|MockObject $queryBuilderMock */
$queryBuilderMock = $this->getMockBuilder(QueryBuilder::class)
->disableOriginalConstructor()
->onlyMethods(['execute', 'expr'])
->getMock();
$queryBuilderMock->method('execute')->willReturn($resultStatementMock);
$queryBuilderMock->method('expr')->willReturn($expressionBuilderMock);
/** @var QueryBuilderFactory|MockObject $queryBuilderFactoryMock */
$queryBuilderFactoryMock = $this->getMockBuilder(QueryBuilderFactory::class)
->disableOriginalConstructor()
->onlyMethods(['create'])
->getMock();
$queryBuilderFactoryMock->method('create')->willReturn($queryBuilderMock);
/** @var Container|MockObject $containerMock */
$containerMock = $this->getMockBuilder(Container::class)
->onlyMethods(['get'])
->getMock();
$containerMock->method('get')->willReturn($queryBuilderFactoryMock);
return $containerMock;
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Setup\Actions::getDb
*/
public function canGetDb()
{
/** @var Actions $sut */
$sut = oxNew(Actions::class);
$this->assertInstanceOf(
DatabaseInterface::class,
$this->callMethod(
$sut,
'getDb'
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\Linkmobility4OXID\Setup\Actions::getConfig
*/
public function canGetConfig()
{
/** @var Actions $sut */
$sut = oxNew(Actions::class);
$this->assertInstanceOf(
Config::class,
$this->callMethod(
$sut,
'getConfig'
)
);
}
}