Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add optional configuration for maximum comment length #3

Merged
merged 4 commits into from
Jul 7, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Model/OrderCommentConfigProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace Bold\OrderComment\Model;

use Magento\Checkout\Model\ConfigProviderInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;

class OrderCommentConfigProvider implements ConfigProviderInterface
{
const CONFIG_MAX_LENGTH = 'sales/ordercomments/max_length';

/**
* @var ScopeConfigInterface
*/
private $scopeConfig;

public function __construct(ScopeConfigInterface $scopeConfig)
{
$this->scopeConfig = $scopeConfig;
}

public function getConfig()
{
return [
'max_length' => (int) $this->scopeConfig->getValue(self::CONFIG_MAX_LENGTH),
];
}

}
25 changes: 24 additions & 1 deletion Model/OrderCommentManagement.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
namespace Bold\OrderComment\Model;

use Bold\OrderComment\Model\Data\OrderComment;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\ValidatorException;

class OrderCommentManagement implements \Bold\OrderComment\Api\OrderCommentManagementInterface
{
Expand All @@ -14,14 +16,21 @@ class OrderCommentManagement implements \Bold\OrderComment\Api\OrderCommentManag
*/
protected $quoteRepository;

/**
* @var ScopeConfigInterface
*/
protected $scopeConfig;

/**
*
* @param \Magento\Quote\Api\CartRepositoryInterface $quoteRepository Quote repository.
*/
public function __construct(
\Magento\Quote\Api\CartRepositoryInterface $quoteRepository
\Magento\Quote\Api\CartRepositoryInterface $quoteRepository,
ScopeConfigInterface $scopeConfig
) {
$this->quoteRepository = $quoteRepository;
$this->scopeConfig = $scopeConfig;
}

/**
Expand All @@ -41,6 +50,8 @@ public function saveOrderComment(
}
$comment = $orderComment->getComment();

$this->validateComment($comment);

try {
$quote->setData(OrderComment::COMMENT_FIELD_NAME, strip_tags($comment));
$this->quoteRepository->save($quote);
Expand All @@ -50,4 +61,16 @@ public function saveOrderComment(

return $comment;
}

/**
* @param string $comment
* @throws ValidatorException
*/
protected function validateComment($comment)
{
$maxLength = $this->scopeConfig->getValue(OrderCommentConfigProvider::CONFIG_MAX_LENGTH);
if ($maxLength && (mb_strlen($comment) > $maxLength)) {
throw new ValidatorException(__('Comment is too long'));
}
}
}
122 changes: 74 additions & 48 deletions Test/Unit/Model/OrderCommentManagementTest.php
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
<?php
namespace Bold\OrderComment\Test\Unit\Model;

use Bold\OrderComment\Api\Data\OrderCommentInterface;
use Bold\OrderComment\Model\Data\OrderComment;
use Bold\OrderComment\Model\OrderCommentConfigProvider;
use Bold\OrderComment\Model\OrderCommentManagement;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Model\Quote;
use Magento\Quote\Model\QuoteRepository;

class OrderCommentManagementTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
* @var \PHPUnit_Framework_MockObject_MockObject|QuoteRepository
*/
protected $quoteRepositoryMock;

/**
* @var \PHPUnit_Framework_MockObject_MockObject
* @var \PHPUnit_Framework_MockObject_MockObject|Quote
*/
protected $quoteMock;

Expand All @@ -21,12 +27,17 @@ class OrderCommentManagementTest extends \PHPUnit_Framework_TestCase
*/
protected $testObject;

/**
* @var \PHPUnit_Framework_MockObject_MockObject|ScopeConfigInterface
*/
protected $configMock;

public function setUp()
{
$this->quoteRepositoryMock = $this->getMock('\Magento\Quote\Api\CartRepositoryInterface');
$this->quoteRepositoryMock = $this->getMock(CartRepositoryInterface::class);

$this->quoteMock = $this->getMock(
'\Magento\Quote\Model\Quote',
Quote::class,
[
'getItemsCount',
'save',
Expand All @@ -36,8 +47,11 @@ public function setUp()
'',
false
);
$this->configMock = $this->getMockForAbstractClass(
ScopeConfigInterface::class
);

$this->testObject = new OrderCommentManagement($this->quoteRepositoryMock);
$this->testObject = new OrderCommentManagement($this->quoteRepositoryMock, $this->configMock);
}

/**
Expand All @@ -46,16 +60,8 @@ public function setUp()
*/
public function testSaveCommentWithEmptyCart()
{
$cartId = 123;

$this->quoteRepositoryMock->expects($this->once())
->method('getActive')->with($cartId)->will($this->returnValue($this->quoteMock));
$this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue(0));

$orderCommentMock = $this->getMockBuilder('\Bold\OrderComment\Model\Data\OrderComment')
->disableOriginalConstructor();

$this->testObject->saveOrderComment($cartId, $orderCommentMock->getMock());
$this->setupQuoteRepositoryMockQueries(123, 0);
$this->testObject->saveOrderComment(123, $this->mockOrderComment());
}

/**
Expand All @@ -65,10 +71,9 @@ public function testSaveCommentWithEmptyCart()
public function testSaveCommentWhenCouldNotSaveQuote()
{
$cartId = 123;
$cartItemCount = 12;

$this->quoteRepositoryMock->expects($this->once())
->method('getActive')->with($cartId)->will($this->returnValue($this->quoteMock));
$this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue(12));
$this->setupQuoteRepositoryMockQueries($cartId, $cartItemCount);

$exceptionMessage = 'The order comment could not be saved';
$exception = new \Magento\Framework\Exception\CouldNotSaveException(__($exceptionMessage));
Expand All @@ -77,64 +82,85 @@ public function testSaveCommentWhenCouldNotSaveQuote()
->with($this->quoteMock)
->willThrowException($exception);

$orderCommentMock = $this->getMockBuilder('\Bold\OrderComment\Model\Data\OrderComment')
->disableOriginalConstructor()
->getMock();

$this->testObject->saveOrderComment($cartId, $orderCommentMock);
$this->testObject->saveOrderComment($cartId, $this->mockOrderComment());
}

/**
* @expectedException \Magento\Framework\Exception\ValidatorException
* @expectedExceptionMessage Comment is too long
*/
public function testSaveCommentThatIsTooLong()
{
$cartId = 123;
$cartItemCount = 12;
$comment = '123456789';
$this->configMock
->method('getValue')
->with(OrderCommentConfigProvider::CONFIG_MAX_LENGTH)
->willReturn(8);

$this->setupQuoteRepositoryMockQueries($cartId, $cartItemCount);
$this->quoteRepositoryMock->expects($this->never())
->method('save');

$this->testObject->saveOrderComment($cartId, $this->mockOrderComment($comment));
}

public function testSaveComment()
{
$cartId = 123;
$comment = 'test comment';
$cartItemCount = 12;

$this->quoteRepositoryMock->expects($this->once())
->method('getActive')->with($cartId)->will($this->returnValue($this->quoteMock));
$this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue(12));

$this->setupQuoteRepositoryMockQueries($cartId, $cartItemCount);
$this->quoteRepositoryMock->expects($this->once())
->method('save')
->with($this->quoteMock)
->will($this->returnSelf());

$orderCommentMock = $this->getMockBuilder('\Bold\OrderComment\Model\Data\OrderComment')
->disableOriginalConstructor()
->getMock();

$orderCommentMock->expects($this->once())
->method('getComment')
->willReturn($comment);

$this->testObject->saveOrderComment($cartId, $orderCommentMock);
$this->testObject->saveOrderComment($cartId, $this->mockOrderComment($comment));

$this->assertEquals($comment, $this->quoteMock->getData(OrderComment::COMMENT_FIELD_NAME));
}

public function testSaveCommentWithTags()
{
$cartId = 123;
$cartItemCount = 12;
$comment = 'test comment<script>alert("abcd");</script><?php die("qwerty")?>';

$this->quoteRepositoryMock->expects($this->once())
->method('getActive')->with($cartId)->will($this->returnValue($this->quoteMock));
$this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue(12));

$this->setupQuoteRepositoryMockQueries($cartId, $cartItemCount);
$this->quoteRepositoryMock->expects($this->once())
->method('save')
->with($this->quoteMock)
->will($this->returnSelf());

$orderCommentMock = $this->getMockBuilder('\Bold\OrderComment\Model\Data\OrderComment')
->disableOriginalConstructor()
->getMock();
$this->testObject->saveOrderComment($cartId, $this->mockOrderComment($comment));

$orderCommentMock->expects($this->once())
->method('getComment')
->willReturn($comment);
$this->assertEquals(strip_tags($comment), $this->quoteMock->getData(OrderComment::COMMENT_FIELD_NAME));
}

$this->testObject->saveOrderComment($cartId, $orderCommentMock);
private function setupQuoteRepositoryMockQueries(int $cartId, int $cartItemCount)
{
$this->quoteRepositoryMock->expects($this->once())
->method('getActive')->with($cartId)->will($this->returnValue($this->quoteMock));
$this->quoteMock->expects($this->once())->method('getItemsCount')->will($this->returnValue($cartItemCount));
}

$this->assertEquals(strip_tags($comment), $this->quoteMock->getData(OrderComment::COMMENT_FIELD_NAME));
/**
* @return \PHPUnit_Framework_MockObject_MockObject|OrderCommentInterface
*/
private function mockOrderComment(string $comment = null): \PHPUnit_Framework_MockObject_MockObject
{
$orderCommentMock = $this->getMockBuilder(OrderComment::class)
->disableOriginalConstructor()
->getMock();

if ($comment !== null) {
$orderCommentMock->expects($this->once())
->method('getComment')
->willReturn($comment);
}
return $orderCommentMock;
}
}
14 changes: 14 additions & 0 deletions etc/adminhtml/system.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<section id="sales">
<group id="ordercomments" translate="label" type="text" sortOrder="110" showInDefault="1" showInWebsite="1" showInStore="0">
<label>Order Comment</label>
<field id="max_length" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
<label>Maximum length in characters</label>
<comment>Leave emtpy for no limit</comment>
</field>
</group>
</section>
</system>
</config>
10 changes: 10 additions & 0 deletions etc/frontend/di.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Checkout\Model\CompositeConfigProvider">
<arguments>
<argument name="configProviders" xsi:type="array">
<item name="ordercomments_config_provider" xsi:type="object">Bold\OrderComment\Model\OrderCommentConfigProvider</item>
</argument>
</arguments>
</type>
</config>
5 changes: 5 additions & 0 deletions view/frontend/web/css/source/_module.less
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
._error {
.order-comment-form__characters {
color: @checkout-field-validation__border-color;
}
}
22 changes: 18 additions & 4 deletions view/frontend/web/js/model/checkout/order-comment-validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ define(
'Magento_Checkout/js/model/quote',
'Magento_Checkout/js/model/url-builder',
'mage/url',
'Magento_Checkout/js/model/error-processor'
'Magento_Checkout/js/model/error-processor',
'Magento_Ui/js/model/messageList',
'mage/translate'
],
function ($, customer, quote, urlBuilder, urlFormatter, errorProcessor) {
function ($, customer, quote, urlBuilder, urlFormatter, errorProcessor, messageContainer, __) {
'use strict';

return {
Expand All @@ -21,9 +23,15 @@ define(
var isCustomer = customer.isLoggedIn();
var form = $('.payment-method input[name="payment[method]"]:checked').parents('.payment-method').find('form.order-comment-form');

var comment = form.find('.input-text.order-comment').val();
if (this.hasMaxLength() && comment.length > this.getMaxLength()) {
messageContainer.addErrorMessage({ message: __("Comment is too long") });
return false;
}

var quoteId = quote.getQuoteId();
var url;

var url;
if (isCustomer) {
url = urlBuilder.createUrl('/carts/mine/set-order-comment', {})
} else {
Expand All @@ -33,7 +41,7 @@ define(
var payload = {
cartId: quoteId,
orderComment: {
comment: form.find('.input-text.order-comment').val()
comment: comment
}
};

Expand Down Expand Up @@ -62,6 +70,12 @@ define(
);

return result;
},
hasMaxLength: function() {
return window.checkoutConfig.max_length > 0;
},
getMaxLength: function () {
return window.checkoutConfig.max_length;
}
};
}
Expand Down
Loading