diff --git a/app/code/Magento/Authorizenet/Model/Authorizenet.php b/app/code/Magento/Authorizenet/Model/Authorizenet.php
index b35e4f4c39911df89d553ef98ad77eba768ccf3c..4ad08d89cc495556bd4b5b794417fb7185817d92 100644
--- a/app/code/Magento/Authorizenet/Model/Authorizenet.php
+++ b/app/code/Magento/Authorizenet/Model/Authorizenet.php
@@ -6,6 +6,7 @@
 namespace Magento\Authorizenet\Model;
 
 use Magento\Authorizenet\Model\TransactionService;
+use Magento\Framework\HTTP\ZendClientFactory;
 
 /**
  * @SuppressWarnings(PHPMD.TooManyFields)
@@ -97,6 +98,11 @@ abstract class Authorizenet extends \Magento\Payment\Model\Method\Cc
      */
     protected $_debugReplacePrivateDataKeys = ['merchantAuthentication', 'x_login'];
 
+    /**
+     * @var \Magento\Framework\HTTP\ZendClientFactory
+     */
+    protected $httpClientFactory;
+
     /**
      * @param \Magento\Framework\Model\Context $context
      * @param \Magento\Framework\Registry $registry
@@ -111,6 +117,7 @@ abstract class Authorizenet extends \Magento\Payment\Model\Method\Cc
      * @param \Magento\Authorizenet\Model\Request\Factory $requestFactory
      * @param \Magento\Authorizenet\Model\Response\Factory $responseFactory
      * @param \Magento\Authorizenet\Model\TransactionService $transactionService
+     * @param \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory
      * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource
      * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection
      * @param array $data
@@ -130,6 +137,7 @@ abstract class Authorizenet extends \Magento\Payment\Model\Method\Cc
         \Magento\Authorizenet\Model\Request\Factory $requestFactory,
         \Magento\Authorizenet\Model\Response\Factory $responseFactory,
         TransactionService $transactionService,
+        ZendClientFactory $httpClientFactory,
         \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
         \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
         array $data = []
@@ -138,6 +146,7 @@ abstract class Authorizenet extends \Magento\Payment\Model\Method\Cc
         $this->requestFactory = $requestFactory;
         $this->responseFactory = $responseFactory;
         $this->transactionService = $transactionService;
+        $this->httpClientFactory = $httpClientFactory;
 
         parent::__construct(
             $context,
@@ -370,7 +379,8 @@ abstract class Authorizenet extends \Magento\Payment\Model\Method\Cc
     protected function postRequest(\Magento\Authorizenet\Model\Request $request)
     {
         $result = $this->responseFactory->create();
-        $client = new \Magento\Framework\HTTP\ZendClient();
+        /** @var \Magento\Framework\HTTP\ZendClient $client */
+        $client = $this->httpClientFactory->create();
         $url = $this->getConfigData('cgi_url') ?: self::CGI_URL;
         $debugData = ['url' => $url, 'request' => $request->getData()];
         $client->setUri($url);
diff --git a/app/code/Magento/Authorizenet/Model/Directpost.php b/app/code/Magento/Authorizenet/Model/Directpost.php
index bbfcd0f7d6e128fb7d0e5d0740223ef42282c469..68fd630f21f4593740fed6288e3821b87677d7db 100644
--- a/app/code/Magento/Authorizenet/Model/Directpost.php
+++ b/app/code/Magento/Authorizenet/Model/Directpost.php
@@ -6,6 +6,7 @@
 namespace Magento\Authorizenet\Model;
 
 use Magento\Authorizenet\Model\TransactionService;
+use Magento\Framework\HTTP\ZendClientFactory;
 use Magento\Payment\Model\Method\ConfigInterface;
 use Magento\Payment\Model\Method\TransparentInterface;
 use Magento\Sales\Model\Order\Email\Sender\OrderSender;
@@ -132,6 +133,7 @@ class Directpost extends \Magento\Authorizenet\Model\Authorizenet implements Tra
      * @param Directpost\Request\Factory $requestFactory
      * @param Directpost\Response\Factory $responseFactory
      * @param \Magento\Authorizenet\Model\TransactionService $transactionService
+     * @param \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory
      * @param \Magento\Sales\Model\OrderFactory $orderFactory
      * @param \Magento\Store\Model\StoreManagerInterface $storeManager
      * @param \Magento\Quote\Model\QuoteRepository $quoteRepository
@@ -156,6 +158,7 @@ class Directpost extends \Magento\Authorizenet\Model\Authorizenet implements Tra
         \Magento\Authorizenet\Model\Directpost\Request\Factory $requestFactory,
         \Magento\Authorizenet\Model\Directpost\Response\Factory $responseFactory,
         TransactionService $transactionService,
+        ZendClientFactory $httpClientFactory,
         \Magento\Sales\Model\OrderFactory $orderFactory,
         \Magento\Store\Model\StoreManagerInterface $storeManager,
         \Magento\Quote\Model\QuoteRepository $quoteRepository,
@@ -187,6 +190,7 @@ class Directpost extends \Magento\Authorizenet\Model\Authorizenet implements Tra
             $requestFactory,
             $responseFactory,
             $transactionService,
+            $httpClientFactory,
             $resource,
             $resourceCollection,
             $data
@@ -404,9 +408,7 @@ class Directpost extends \Magento\Authorizenet\Model\Authorizenet implements Tra
                     if ($result->getXTransId() != $payment->getParentTransactionId()) {
                         $payment->setTransactionId($result->getXTransId());
                     }
-                    $shouldCloseCaptureTransaction = $payment->getOrder()->canCreditmemo() ? 0 : 1;
-                    $payment->setIsTransactionClosed(1)
-                        ->setShouldCloseParentTransaction($shouldCloseCaptureTransaction)
+                    $payment->setIsTransactionClosed(true)
                         ->setTransactionAdditionalInfo(self::REAL_TRANSACTION_ID_KEY, $result->getXTransId());
                     return $this;
                 }
diff --git a/app/code/Magento/Authorizenet/Test/Unit/Model/DirectpostTest.php b/app/code/Magento/Authorizenet/Test/Unit/Model/DirectpostTest.php
index 3247ed2cb9329f86e0efda4e07aeae938515f05b..3726d4e5108ae84b6076a8e39b4e8b628620a7f9 100644
--- a/app/code/Magento/Authorizenet/Test/Unit/Model/DirectpostTest.php
+++ b/app/code/Magento/Authorizenet/Test/Unit/Model/DirectpostTest.php
@@ -9,13 +9,21 @@ use Magento\Framework\Simplexml\Element;
 use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper;
 use Magento\Authorizenet\Model\Directpost;
 use Magento\Authorizenet\Model\TransactionService;
+use Magento\Authorizenet\Model\Request;
+use Magento\Authorizenet\Model\Directpost\Request\Factory;
+use Magento\Sales\Model\Order;
 use Magento\Sales\Model\Order\Payment\Transaction\Repository as TransactionRepository;
 
 /**
  * Class DirectpostTest
+ * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  */
 class DirectpostTest extends \PHPUnit_Framework_TestCase
 {
+    const TOTAL_AMOUNT = 100.02;
+    const INVOICE_NUM = '00000001';
+    const TRANSACTION_ID = '41a23x34fd124';
+
     /**
      * @var \Magento\Authorizenet\Model\Directpost
      */
@@ -56,6 +64,16 @@ class DirectpostTest extends \PHPUnit_Framework_TestCase
      */
     protected $transactionServiceMock;
 
+    /**
+     * @var \Magento\Framework\HTTP\ZendClient|\PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $httpClientMock;
+
+    /**
+     * @var \Magento\Authorizenet\Model\Directpost\Request\Factory|\PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $requestFactory;
+
     protected function setUp()
     {
         $this->scopeConfigMock = $this->getMockBuilder('Magento\Framework\App\Config\ScopeConfigInterface')
@@ -64,7 +82,8 @@ class DirectpostTest extends \PHPUnit_Framework_TestCase
             ->disableOriginalConstructor()
             ->setMethods([
                 'getOrder', 'getId', 'setAdditionalInformation', 'getAdditionalInformation',
-                'setIsTransactionDenied', 'setIsTransactionClosed'
+                'setIsTransactionDenied', 'setIsTransactionClosed', 'decrypt', 'getCcLast4',
+                'getParentTransactionId', 'getPoNumber'
             ])
             ->getMock();
         $this->dataHelperMock = $this->getMockBuilder('Magento\Authorizenet\Helper\Data')
@@ -85,15 +104,20 @@ class DirectpostTest extends \PHPUnit_Framework_TestCase
             ->setMethods(['getTransactionDetails'])
             ->getMock();
 
+        $this->requestFactory = $this->getRequestFactoryMock();
+        $httpClientFactoryMock = $this->getHttpClientFactoryMock();
+
         $helper = new ObjectManagerHelper($this);
         $this->directpost = $helper->getObject(
             'Magento\Authorizenet\Model\Directpost',
             [
                 'scopeConfig' => $this->scopeConfigMock,
                 'dataHelper' => $this->dataHelperMock,
+                'requestFactory' => $this->requestFactory,
                 'responseFactory' => $this->responseFactoryMock,
                 'transactionRepository' => $this->transactionRepositoryMock,
-                'transactionService' => $this->transactionServiceMock
+                'transactionService' => $this->transactionServiceMock,
+                'httpClientFactory' => $httpClientFactoryMock
             ]
         );
     }
@@ -376,7 +400,7 @@ class DirectpostTest extends \PHPUnit_Framework_TestCase
     }
 
     /**
-     * @covers \Magento\Authorizenet\Model\Directpost::fetchTransactionInfo
+     * @covers       \Magento\Authorizenet\Model\Directpost::fetchTransactionInfo
      *
      * @param $transactionId
      * @param $resultStatus
@@ -440,6 +464,72 @@ class DirectpostTest extends \PHPUnit_Framework_TestCase
         $this->directpost->fetchTransactionInfo($this->paymentMock, $transactionId);
     }
 
+    /**
+     * @covers \Magento\Authorizenet\Model\Directpost::refund()
+     * @return void
+     */
+    public function testSuccessRefund()
+    {
+        $card = 1111;
+
+        $this->paymentMock->expects(static::exactly(2))
+            ->method('getCcLast4')
+            ->willReturn($card);
+        $this->paymentMock->expects(static::once())
+            ->method('decrypt')
+            ->willReturn($card);
+        $this->paymentMock->expects(static::exactly(3))
+            ->method('getParentTransactionId')
+            ->willReturn(self::TRANSACTION_ID . '-capture');
+        $this->paymentMock->expects(static::once())
+            ->method('getPoNumber')
+            ->willReturn(self::INVOICE_NUM);
+        $this->paymentMock->expects(static::once())
+            ->method('setIsTransactionClosed')
+            ->with(true)
+            ->willReturnSelf();
+
+        $orderMock = $this->getOrderMock();
+
+        $this->paymentMock->expects(static::exactly(2))
+            ->method('getOrder')
+            ->willReturn($orderMock);
+
+        $transactionMock = $this->getMockBuilder(Order\Payment\Transaction::class)
+            ->disableOriginalConstructor()
+            ->setMethods(['getAdditionalInformation'])
+            ->getMock();
+        $transactionMock->expects(static::once())
+            ->method('getAdditionalInformation')
+            ->with(Directpost::REAL_TRANSACTION_ID_KEY)
+            ->willReturn(self::TRANSACTION_ID);
+
+        $this->transactionRepositoryMock->expects(static::once())
+            ->method('getByTransactionId')
+            ->willReturn($transactionMock);
+
+        $response = $this->getRefundResponseBody(
+            Directpost::RESPONSE_CODE_APPROVED,
+            Directpost::RESPONSE_REASON_CODE_APPROVED,
+            'Successful'
+        );
+        $this->httpClientMock->expects(static::once())
+            ->method('getBody')
+            ->willReturn($response);
+
+        $this->responseMock->expects(static::once())
+            ->method('getXResponseCode')
+            ->willReturn(Directpost::RESPONSE_CODE_APPROVED);
+        $this->responseMock->expects(static::once())
+            ->method('getXResponseReasonCode')
+            ->willReturn(Directpost::RESPONSE_REASON_CODE_APPROVED);
+
+        $this->dataHelperMock->expects(static::never())
+            ->method('wrapGatewayError');
+
+        $this->directpost->refund($this->paymentMock, self::TOTAL_AMOUNT);
+    }
+
     /**
      * Get data for tests
      * @return array
@@ -468,14 +558,48 @@ class DirectpostTest extends \PHPUnit_Framework_TestCase
         $this->responseMock = $this->getMockBuilder('Magento\Authorizenet\Model\Directpost\Response')
             ->setMethods(
                 [
-                    'setData', 'isValidHash', 'getXTransId',
-                    'getXResponseCode', 'getXResponseReasonText',
-                    'getXAmount'
+                    'isValidHash',
+                    'getXTransId', 'getXResponseCode', 'getXResponseReasonCode', 'getXResponseReasonText', 'getXAmount',
+                    'setXResponseCode', 'setXResponseReasonCode', 'setXAvsCode', 'setXResponseReasonText',
+                    'setXTransId', 'setXInvoiceNum', 'setXAmount', 'setXMethod', 'setXType', 'setData',
+                    'setXAccountNumber',
+                    '__wakeup'
                 ]
             )
             ->disableOriginalConstructor()
             ->getMock();
 
+        $this->responseMock->expects(static::any())
+            ->method('setXResponseCode')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXResponseReasonCode')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXResponseReasonText')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXAvsCode')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXTransId')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXInvoiceNum')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXAmount')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXMethod')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setXType')
+            ->willReturnSelf();
+        $this->responseMock->expects(static::any())
+            ->method('setData')
+            ->willReturnSelf();
+
         $this->responseFactoryMock->expects($this->any())
             ->method('create')
             ->willReturn($this->responseMock);
@@ -530,4 +654,105 @@ class DirectpostTest extends \PHPUnit_Framework_TestCase
         libxml_use_internal_errors(false);
         return $document;
     }
+
+    /**
+     * Get mock for authorize.net request factory
+     * @return \PHPUnit_Framework_MockObject_MockBuilder
+     */
+    private function getRequestFactoryMock()
+    {
+        $requestFactory = $this->getMockBuilder(Factory::class)
+            ->disableOriginalConstructor()
+            ->setMethods(['create'])
+            ->getMock();
+        $request = $this->getMockBuilder(Request::class)
+            ->disableOriginalConstructor()
+            ->setMethods(['__wakeup'])
+            ->getMock();
+        $requestFactory->expects(static::any())
+            ->method('create')
+            ->willReturn($request);
+        return $requestFactory;
+    }
+
+    /**
+     * Get mock for order
+     * @return \PHPUnit_Framework_MockObject_MockObject
+     */
+    private function getOrderMock()
+    {
+        $orderMock = $this->getMockBuilder(Order::class)
+            ->disableOriginalConstructor()
+            ->setMethods([
+                'getId', 'getIncrementId', 'getStoreId', 'getBillingAddress', 'getShippingAddress',
+                'getBaseCurrencyCode', 'getBaseTaxAmount', '__wakeup'
+            ])
+            ->getMock();
+
+        $orderMock->expects(static::once())
+            ->method('getId')
+            ->willReturn(1);
+
+        $orderMock->expects(static::exactly(2))
+            ->method('getIncrementId')
+            ->willReturn(self::INVOICE_NUM);
+
+        $orderMock->expects(static::once())
+            ->method('getStoreId')
+            ->willReturn(1);
+
+        $orderMock->expects(static::once())
+            ->method('getBaseCurrencyCode')
+            ->willReturn('USD');
+        return $orderMock;
+    }
+
+    /**
+     * Create and return mock for http client factory
+     * @return \PHPUnit_Framework_MockObject_MockObject
+     */
+    private function getHttpClientFactoryMock()
+    {
+        $this->httpClientMock = $this->getMockBuilder(\Magento\Framework\HTTP\ZendClient::class)
+            ->disableOriginalConstructor()
+            ->setMethods(['request', 'getBody', '__wakeup'])
+            ->getMock();
+
+        $this->httpClientMock->expects(static::any())
+            ->method('request')
+            ->willReturnSelf();
+
+        $httpClientFactoryMock = $this->getMockBuilder(\Magento\Framework\HTTP\ZendClientFactory::class)
+            ->disableOriginalConstructor()
+            ->setMethods(['create'])
+            ->getMock();
+
+        $httpClientFactoryMock->expects(static::any())
+            ->method('create')
+            ->willReturn($this->httpClientMock);
+        return $httpClientFactoryMock;
+    }
+
+    /**
+     * Get mocked response for refund transaction
+     * @param $code
+     * @param $reasonCode
+     * @param $reasonText
+     * @return string
+     */
+    private function getRefundResponseBody($code, $reasonCode, $reasonText)
+    {
+        $result = array_fill(0, 50, '');
+        $result[0] = $code; // XResponseCode
+        $result[2] = $reasonCode; // XResponseReasonCode
+        $result[3] = $reasonText; // XResponseReasonText
+        $result[6] = self::TRANSACTION_ID; // XTransId
+        $result[7] = self::INVOICE_NUM; // XInvoiceNum
+        $result[9] = self::TOTAL_AMOUNT; // XAmount
+        $result[10] = Directpost::REQUEST_METHOD_CC; // XMethod
+        $result[11] = Directpost::REQUEST_TYPE_CREDIT; // XType
+        $result[37] = md5(self::TRANSACTION_ID); // x_MD5_Hash
+        $result[50] = '48329483921'; // setXAccountNumber
+        return implode(Directpost::RESPONSE_DELIM_CHAR, $result);
+    }
 }
diff --git a/app/code/Magento/Authorizenet/view/adminhtml/templates/directpost/info.phtml b/app/code/Magento/Authorizenet/view/adminhtml/templates/directpost/info.phtml
index 6c02076b5a7dbe55d9a81b7114599221c6c9f14e..9251ad16e7258cfb7938591fe66c9a1a2d353f50 100644
--- a/app/code/Magento/Authorizenet/view/adminhtml/templates/directpost/info.phtml
+++ b/app/code/Magento/Authorizenet/view/adminhtml/templates/directpost/info.phtml
@@ -9,7 +9,7 @@
  * @var \Magento\Authorizenet\Block\Transparent\Iframe $block
  * @see \Magento\Authorizenet\Block\Transparent\Iframe
  */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 $method = $block->getMethod();
 $controller = $block->escapeHtml($block->getRequest()->getControllerName());
 $orderUrl = $block->escapeUrl($this->helper('Magento\Authorizenet\Helper\Backend\Data')->getPlaceOrderAdminUrl());
@@ -20,12 +20,12 @@ $ccExpYear = $block->getInfoData('cc_exp_year');
 <!-- IFRAME for request to our server -->
 <iframe id="order-directpost-iframe" allowtransparency="true" frameborder="0" name="iframeSubmitOrder"
         style="display:none;width:100%;background-color:transparent"
-        src="<?php /* @noEscape */ echo $block->getViewFileUrl('blank.html'); ?>">
+        src="<?php echo $block->escapeUrl($block->getViewFileUrl('blank.html')); ?>">
 </iframe>
 <!-- IFRAME for request to Authorize.net -->
 <iframe id="directpost-iframe" allowtransparency="true" frameborder="0"  name="iframeDirectPost"
         style="display:none;width:100%;background-color:transparent"
-        src="<?php /* @noEscape */ echo $block->getViewFileUrl('blank.html'); ?>">
+        src="<?php echo $block->escapeUrl($block->getViewFileUrl('blank.html')); ?>">
 </iframe>
 <fieldset class="admin__fieldset payment-method" id="payment_form_<?php /* @noEscape */ echo $code; ?>"
           style="display:none;">
@@ -124,9 +124,9 @@ $ccExpYear = $block->getInfoData('cc_exp_year');
             '<?php /* @noEscape */ echo $controller; ?>',
             '<?php /* @noEscape */ echo $orderUrl; ?>',
             '<?php echo $block->escapeUrl($method->getCgiUrl()); ?>',
-            '<?php /* @noEscape */ echo $block->getUrl('*/*/save', [
+            '<?php echo $block->escapeUrl($block->getUrl('*/*/save', [
                 '_secure' => $block->getRequest()->isSecure()
-            ]);?>');
+            ]));?>');
 
         <?php if (!$block->isAjaxRequest()): ?>
             });
diff --git a/app/code/Magento/Backend/Console/Command/AbstractCacheTypeManageCommand.php b/app/code/Magento/Backend/Console/Command/AbstractCacheTypeManageCommand.php
index 5974798f74be4355cff4926d0bd4e65b48f583f9..56970004795e1b93758432657da8bf4db3e06af8 100644
--- a/app/code/Magento/Backend/Console/Command/AbstractCacheTypeManageCommand.php
+++ b/app/code/Magento/Backend/Console/Command/AbstractCacheTypeManageCommand.php
@@ -6,11 +6,28 @@
 
 namespace Magento\Backend\Console\Command;
 
+use Magento\Framework\Event\ManagerInterface as EventManagerInterface;
 use Symfony\Component\Console\Input\InputInterface;
 use Symfony\Component\Console\Output\OutputInterface;
+use Magento\Framework\App\Cache\Manager;
 
 abstract class AbstractCacheTypeManageCommand extends AbstractCacheManageCommand
 {
+    /** @var EventManagerInterface */
+    protected $eventManager;
+
+    /**
+     * @param Manager $cacheManager
+     * @param EventManagerInterface $eventManager
+     */
+    public function __construct(
+        Manager $cacheManager,
+        EventManagerInterface $eventManager
+    ) {
+        $this->eventManager = $eventManager;
+        parent::__construct($cacheManager);
+    }
+
     /**
      * Perform a cache management action on cache types
      *
diff --git a/app/code/Magento/Backend/Console/Command/CacheCleanCommand.php b/app/code/Magento/Backend/Console/Command/CacheCleanCommand.php
index ab57f0ff7b578611ee3a64402650aa07ba52219e..49aeb17839e2ae54fd39c86865c8b2e4e36b2941 100644
--- a/app/code/Magento/Backend/Console/Command/CacheCleanCommand.php
+++ b/app/code/Magento/Backend/Console/Command/CacheCleanCommand.php
@@ -29,6 +29,7 @@ class CacheCleanCommand extends AbstractCacheTypeManageCommand
      */
     protected function performAction(array $cacheTypes)
     {
+        $this->eventManager->dispatch('adminhtml_cache_flush_system');
         $this->cacheManager->clean($cacheTypes);
     }
 
diff --git a/app/code/Magento/Backend/Console/Command/CacheFlushCommand.php b/app/code/Magento/Backend/Console/Command/CacheFlushCommand.php
index c847204de9043e84ded25607e890273441ec0e4e..7572fb21cba6dc3e8fb6a7d785ed3d7bbf32e97d 100644
--- a/app/code/Magento/Backend/Console/Command/CacheFlushCommand.php
+++ b/app/code/Magento/Backend/Console/Command/CacheFlushCommand.php
@@ -29,6 +29,7 @@ class CacheFlushCommand extends AbstractCacheTypeManageCommand
      */
     protected function performAction(array $cacheTypes)
     {
+        $this->eventManager->dispatch('adminhtml_cache_flush_all');
         $this->cacheManager->flush($cacheTypes);
     }
 
diff --git a/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheCommandTest.php b/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheCommandTest.php
index 33bce6388fb71d5a8765c86e2c078916858b1741..b7ecddf4d23610b94cee2519c597a907cb4effe5 100644
--- a/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheCommandTest.php
+++ b/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheCommandTest.php
@@ -13,7 +13,7 @@ abstract class AbstractCacheCommandTest extends \PHPUnit_Framework_TestCase
     /**
      * @var \Magento\Framework\App\Cache\Manager|\PHPUnit_Framework_MockObject_MockObject
      */
-    protected $cacheManager;
+    protected $cacheManagerMock;
 
     /**
      * @var AbstractCacheManageCommand
@@ -22,7 +22,7 @@ abstract class AbstractCacheCommandTest extends \PHPUnit_Framework_TestCase
 
     public function setUp()
     {
-        $this->cacheManager = $this->getMock('Magento\Framework\App\Cache\Manager', [], [], '', false);
+        $this->cacheManagerMock = $this->getMock('Magento\Framework\App\Cache\Manager', [], [], '', false);
     }
 
     /**
diff --git a/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheManageCommandTest.php b/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheManageCommandTest.php
index 53ed624db47685ea3b72ed92b8b466dbeca363bb..97d1f57ad1c1f67eb2af82640bc3e81f679c9199 100644
--- a/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheManageCommandTest.php
+++ b/app/code/Magento/Backend/Test/Unit/Console/Command/AbstractCacheManageCommandTest.php
@@ -10,6 +10,20 @@ use Symfony\Component\Console\Tester\CommandTester;
 
 abstract class AbstractCacheManageCommandTest extends AbstractCacheCommandTest
 {
+    /** @var  string */
+    protected $cacheEventName;
+
+    /** @var  \Magento\Framework\Event\ManagerInterface | \PHPUnit_Framework_MockObject_MockObject */
+    protected $eventManagerMock;
+
+    public function setUp()
+    {
+        $this->eventManagerMock = $this->getMockBuilder('\Magento\Framework\Event\ManagerInterface')
+            ->disableOriginalConstructor()
+            ->getMock();
+        parent::setUp();
+    }
+
     /**
      * @return array
      */
@@ -35,7 +49,7 @@ abstract class AbstractCacheManageCommandTest extends AbstractCacheCommandTest
      */
     public function testExecuteInvalidCacheType()
     {
-        $this->cacheManager->expects($this->once())->method('getAvailableTypes')->willReturn(['A', 'B', 'C']);
+        $this->cacheManagerMock->expects($this->once())->method('getAvailableTypes')->willReturn(['A', 'B', 'C']);
         $param = ['types' => ['A', 'D']];
         $commandTester = new CommandTester($this->command);
         $commandTester->execute($param);
diff --git a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheCleanCommandTest.php b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheCleanCommandTest.php
index a51fa92c1addf7dfca4f654a6d5e72079cc9d3ca..fe812c1a93daa190f555e189f9fc95aa26471b05 100644
--- a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheCleanCommandTest.php
+++ b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheCleanCommandTest.php
@@ -13,8 +13,9 @@ class CacheCleanCommandTest extends AbstractCacheManageCommandTest
 {
     public function setUp()
     {
+        $this->cacheEventName = 'adminhtml_cache_flush_system';
         parent::setUp();
-        $this->command = new CacheCleanCommand($this->cacheManager);
+        $this->command = new CacheCleanCommand($this->cacheManagerMock, $this->eventManagerMock);
     }
 
     /**
@@ -25,8 +26,9 @@ class CacheCleanCommandTest extends AbstractCacheManageCommandTest
      */
     public function testExecute($param, $types, $output)
     {
-        $this->cacheManager->expects($this->once())->method('getAvailableTypes')->willReturn(['A', 'B', 'C']);
-        $this->cacheManager->expects($this->once())->method('clean')->with($types);
+        $this->cacheManagerMock->expects($this->once())->method('getAvailableTypes')->willReturn(['A', 'B', 'C']);
+        $this->cacheManagerMock->expects($this->once())->method('clean')->with($types);
+        $this->eventManagerMock->expects($this->once())->method('dispatch')->with($this->cacheEventName);
 
         $commandTester = new CommandTester($this->command);
         $commandTester->execute($param);
diff --git a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheDisableCommandTest.php b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheDisableCommandTest.php
index 1eb4cffd23fd64cda13e2cc49c7ac4dd557dc374..4446b1b992e03b44bb3602adbab2c16cda301106 100644
--- a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheDisableCommandTest.php
+++ b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheDisableCommandTest.php
@@ -14,7 +14,7 @@ class CacheDisableCommandTest extends AbstractCacheSetCommandTest
     public function setUp()
     {
         parent::setUp();
-        $this->command = new CacheDisableCommand($this->cacheManager);
+        $this->command = new CacheDisableCommand($this->cacheManagerMock);
     }
 
     /**
@@ -26,8 +26,13 @@ class CacheDisableCommandTest extends AbstractCacheSetCommandTest
      */
     public function testExecute($param, $enable, $result, $output)
     {
-        $this->cacheManager->expects($this->once())->method('getAvailableTypes')->willReturn(['A', 'B', 'C']);
-        $this->cacheManager->expects($this->once())->method('setEnabled')->with($enable, false)->willReturn($result);
+        $this->cacheManagerMock->expects($this->once())
+            ->method('getAvailableTypes')
+            ->willReturn(['A', 'B', 'C']);
+        $this->cacheManagerMock->expects($this->once())
+            ->method('setEnabled')
+            ->with($enable, false)
+            ->willReturn($result);
 
         $commandTester = new CommandTester($this->command);
         $commandTester->execute($param);
diff --git a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheEnableCommandTest.php b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheEnableCommandTest.php
index e20978e81e7d759e23e18f1fc1bdd5277cebed8a..e44b71d06f9fdc9a624959b50a32521c2db479eb 100644
--- a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheEnableCommandTest.php
+++ b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheEnableCommandTest.php
@@ -14,7 +14,7 @@ class CacheEnableCommandTest extends AbstractCacheSetCommandTest
     public function setUp()
     {
         parent::setUp();
-        $this->command = new CacheEnableCommand($this->cacheManager);
+        $this->command = new CacheEnableCommand($this->cacheManagerMock);
     }
 
     /**
@@ -26,9 +26,15 @@ class CacheEnableCommandTest extends AbstractCacheSetCommandTest
      */
     public function testExecute($param, $enable, $result, $output)
     {
-        $this->cacheManager->expects($this->once())->method('getAvailableTypes')->willReturn(['A', 'B', 'C']);
-        $this->cacheManager->expects($this->once())->method('setEnabled')->with($enable, true)->willReturn($result);
-        $this->cacheManager->expects($result === [] ? $this->never() : $this->once())->method('clean')->with($enable);
+        $this->cacheManagerMock->expects($this->once())->method('getAvailableTypes')->willReturn(['A', 'B', 'C']);
+        $this->cacheManagerMock->expects($this->once())
+            ->method('setEnabled')
+            ->with($enable, true)
+            ->willReturn($result);
+        $cleanInvocationCount = $result === [] ? 0 : 1;
+        $this->cacheManagerMock->expects($this->exactly($cleanInvocationCount))
+            ->method('clean')
+            ->with($enable);
 
         $commandTester = new CommandTester($this->command);
         $commandTester->execute($param);
diff --git a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheFlushCommandTest.php b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheFlushCommandTest.php
index 53032fe55ae049267f802b85b3e6127a02def5d7..07828c6627d5d440e9c10fcd28716ed7b280c067 100644
--- a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheFlushCommandTest.php
+++ b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheFlushCommandTest.php
@@ -13,8 +13,9 @@ class CacheFlushCommandTest extends AbstractCacheManageCommandTest
 {
     public function setUp()
     {
+        $this->cacheEventName = 'adminhtml_cache_flush_all';
         parent::setUp();
-        $this->command = new CacheFlushCommand($this->cacheManager);
+        $this->command = new CacheFlushCommand($this->cacheManagerMock, $this->eventManagerMock);
     }
 
     /**
@@ -25,8 +26,9 @@ class CacheFlushCommandTest extends AbstractCacheManageCommandTest
      */
     public function testExecute($param, $types, $output)
     {
-        $this->cacheManager->expects($this->once())->method('getAvailableTypes')->willReturn(['A', 'B', 'C']);
-        $this->cacheManager->expects($this->once())->method('flush')->with($types);
+        $this->cacheManagerMock->expects($this->once())->method('getAvailableTypes')->willReturn(['A', 'B', 'C']);
+        $this->cacheManagerMock->expects($this->once())->method('flush')->with($types);
+        $this->eventManagerMock->expects($this->once())->method('dispatch')->with($this->cacheEventName);
 
         $commandTester = new CommandTester($this->command);
         $commandTester->execute($param);
diff --git a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheStatusCommandTest.php b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheStatusCommandTest.php
index 4c792a4548dd1833d33334c6005ea4b2953f52e3..a8ee48491fbb7523f23cdc3d230092f86a967293 100644
--- a/app/code/Magento/Backend/Test/Unit/Console/Command/CacheStatusCommandTest.php
+++ b/app/code/Magento/Backend/Test/Unit/Console/Command/CacheStatusCommandTest.php
@@ -14,13 +14,13 @@ class CacheStatusCommandTest extends AbstractCacheCommandTest
     public function setUp()
     {
         parent::setUp();
-        $this->command = new CacheStatusCommand($this->cacheManager);
+        $this->command = new CacheStatusCommand($this->cacheManagerMock);
     }
 
     public function testExecute()
     {
         $cacheTypes = ['A' => 0, 'B' => 1, 'C' => 1];
-        $this->cacheManager->expects($this->once())->method('getStatus')->willReturn($cacheTypes);
+        $this->cacheManagerMock->expects($this->once())->method('getStatus')->willReturn($cacheTypes);
         $commandTester = new CommandTester($this->command);
         $commandTester->execute([]);
 
diff --git a/app/code/Magento/Braintree/Model/PaymentMethod.php b/app/code/Magento/Braintree/Model/PaymentMethod.php
index 45171956e87bcf8832723f7b7dffeb90ea5f1f79..da5ff0d88e29aaf2bf417fa332cf57659672fe04 100644
--- a/app/code/Magento/Braintree/Model/PaymentMethod.php
+++ b/app/code/Magento/Braintree/Model/PaymentMethod.php
@@ -604,7 +604,7 @@ class PaymentMethod extends \Magento\Payment\Model\Method\Cc
                     if ($result->success) {
                         $payment->setIsTransactionClosed(false)
                             ->setShouldCloseParentTransaction(false);
-                        if ($this->isFinalCapture($payment->getParentId(), $amount)) {
+                        if ($payment->isCaptureFinal($amount)) {
                             $payment->setShouldCloseParentTransaction(true);
                         }
                     } else {
@@ -657,7 +657,6 @@ class PaymentMethod extends \Magento\Payment\Model\Method\Cc
                 : $this->braintreeTransaction->refund($transactionId, $amount);
             $this->_debug($this->_convertObjToArray($result));
             if ($result->success) {
-                $payment->setTransactionId($transactionId . '-' . Transaction::TYPE_REFUND);
                 $payment->setIsTransactionClosed(true);
             } else {
                 throw new LocalizedException($this->errorHelper->parseBraintreeError($result));
@@ -905,7 +904,7 @@ class PaymentMethod extends \Magento\Payment\Model\Method\Cc
             ->setAdditionalInformation($this->getExtraTransactionInformation($result->transaction))
             ->setAmount($amount)
             ->setShouldCloseParentTransaction(false);
-        if ($this->isFinalCapture($payment->getParentId(), $amount)) {
+        if ($payment->isCaptureFinal($amount)) {
             $payment->setShouldCloseParentTransaction(true);
         }
         if (isset($result->transaction->creditCard['token']) && $result->transaction->creditCard['token']) {
@@ -964,21 +963,4 @@ class PaymentMethod extends \Magento\Payment\Model\Method\Cc
     {
         return json_decode(json_encode($data), true);
     }
-
-    /**
-     * Checks whether the capture is final
-     *
-     * @param string $orderId
-     * @param string $amount
-     * @return bool
-     */
-    protected function isFinalCapture($orderId, $amount)
-    {
-        if (!empty($orderId)) {
-            $order = $this->orderRepository->get($orderId);
-            return (float)$order->getTotalDue() === (float) $amount;
-        }
-
-        return false;
-    }
 }
diff --git a/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethodTest.php b/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethodTest.php
index e20af765062e3b3b0713c5732d5b67f8f3c279f3..749c2cf390f36359a4364027e9612a76ed810f89 100644
--- a/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethodTest.php
+++ b/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethodTest.php
@@ -32,6 +32,7 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
     const LNAME = 'Doe';
     const AUTH_TRAN_ID = 'r4z34j';
     const AUTH_AMOUNT = 5.76;
+    const TOTAL_AMOUNT = 10.02;
     const AUTH_CC_LAST_4 = '0004';
     const CUSTOMER_ID = '221b3649effb4bb1b62fc940691bd18c';
 
@@ -325,11 +326,8 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
      * @param $ccType
      * @param null $ccToken
      */
-    protected function setupInfoInstance(
-        $countryId,
-        $ccType,
-        $ccToken = null
-    ) {
+    protected function setupInfoInstance($countryId, $ccType, $ccToken = null)
+    {
         $quoteObj = new \Magento\Framework\DataObject(
             [
                 'billing_address' => new \Magento\Framework\DataObject(
@@ -501,6 +499,7 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
                     'getCustomerEmail',
                     'getCustomerId',
                     'getStoreId',
+                    'getTotalDue'
                 ]
             )->getMock();
 
@@ -522,18 +521,25 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
         $orderMock->expects($this->any())
             ->method('getStoreId')
             ->willReturn($storeId);
+        $orderMock->expects(static::any())
+            ->method('getTotalDue')
+            ->willReturn(self::TOTAL_AMOUNT);
+
+        $this->orderRepository->expects(static::any())
+            ->method('get')
+            ->willReturn($orderMock);
+
         return $orderMock;
     }
+
     /**
      * @param \Magento\Framework\DataObject $paymentObject
      * @param int $storeId
      * @return array
      * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
      */
-    protected function setupPaymentObject(
-        \Magento\Framework\DataObject $paymentObject,
-        $storeId
-    ) {
+    protected function setupPaymentObject(\Magento\Framework\DataObject $paymentObject, $storeId)
+    {
         $customerId = '12';
         $customerEmail = 'abc@example.com';
         $company = 'NA';
@@ -564,13 +570,9 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
             'address_type' => 'billing',
         ];
 
-        $billingAddress = new \Magento\Framework\DataObject(
-            $addressData
-        );
+        $billingAddress = new \Magento\Framework\DataObject($addressData);
         $addressData['address_type'] = 'shipping';
-        $shippingAddress = new \Magento\Framework\DataObject(
-            $addressData
-        );
+        $shippingAddress = new \Magento\Framework\DataObject($addressData);
 
         $order = $this->setupOrderMock(
             $billingAddress,
@@ -606,26 +608,26 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
             ->willReturn($regionMock);
 
         $braintreeAddressData = [
-            'firstName'         => self::FNAME,
-            'lastName'          => self::LNAME,
-            'company'           => $company,
-            'streetAddress'     => $street,
-            'extendedAddress'   => $street2,
-            'locality'          => $city,
-            'region'            => $regionCode,
-            'postalCode'        => $postcode,
+            'firstName' => self::FNAME,
+            'lastName' => self::LNAME,
+            'company' => $company,
+            'streetAddress' => $street,
+            'extendedAddress' => $street2,
+            'locality' => $city,
+            'region' => $regionCode,
+            'postalCode' => $postcode,
             'countryCodeAlpha2' => $countryId,
         ];
         return [
-            'channel'   => self::CHANNEL,
-            'orderId'   => $orderId,
-            'customer'  => [
+            'channel' => self::CHANNEL,
+            'orderId' => $orderId,
+            'customer' => [
                 'firstName' => self::FNAME,
-                'lastName'  => self::LNAME,
-                'company'   => $company,
-                'phone'     => $phone,
-                'fax'       => $fax,
-                'email'     => $customerEmail,
+                'lastName' => self::LNAME,
+                'company' => $company,
+                'phone' => $phone,
+                'fax' => $fax,
+                'email' => $customerEmail,
             ],
             'billing' => $braintreeAddressData,
             'shipping' => $braintreeAddressData,
@@ -765,8 +767,11 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
     ) {
         $storeId = 3;
         $amount = self::AUTH_AMOUNT;
-        $paymentObject = $this->objectManagerHelper->getObject('Magento\Sales\Model\Order\Payment');
-
+        $currencyMock = $this->getPriceCurrencyMock();
+        /** @var \Magento\Sales\Model\Order\Payment $paymentObject */
+        $paymentObject = $this->objectManagerHelper->getObject('Magento\Sales\Model\Order\Payment', [
+            'priceCurrency' => $currencyMock
+        ]);
 
         $expectedRequestAttribs = $this->setupAuthorizeRequest(
             $configData,
@@ -798,14 +803,6 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
         }
 
         $paymentObject->setParentId('1');
-        $order = $this->getMockBuilder('Magento\Sales\Api\Data\OrderInterface')
-            ->getMockForAbstractClass();
-        $order->expects($this->once())
-            ->method('getTotalDue')
-            ->willReturn(10.02);
-        $this->orderRepository->expects($this->once())
-            ->method('get')
-            ->willReturn($order);
 
         $this->assertEquals($this->model, $this->model->authorize($paymentObject, $amount));
         foreach ($expectedPaymentFields as $key => $value) {
@@ -1598,13 +1595,8 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
      * @expectedException \Magento\Framework\Exception\LocalizedException
      * @expectedExceptionMessage error
      */
-    public function testAuthorizeError(
-        array $configData,
-        $vault,
-        $registry,
-        $existingCustomer,
-        array $paymentInfo
-    ) {
+    public function testAuthorizeError(array $configData, $vault, $registry, $existingCustomer, array $paymentInfo)
+    {
         $storeId = 3;
         $amount = self::AUTH_AMOUNT;
         $paymentObject = $this->objectManagerHelper->getObject('Magento\Sales\Model\Order\Payment');
@@ -1649,13 +1641,8 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
      * @expectedException \Magento\Framework\Exception\LocalizedException
      * @expectedExceptionMessage Please try again later
      */
-    public function testAuthorizeException(
-        array $configData,
-        $vault,
-        $registry,
-        $existingCustomer,
-        array $paymentInfo
-    ) {
+    public function testAuthorizeException(array $configData, $vault, $registry, $existingCustomer, array $paymentInfo)
+    {
         $storeId = 3;
         $amount = self::AUTH_AMOUNT;
         $paymentObject = $this->objectManagerHelper->getObject('Magento\Sales\Model\Order\Payment');
@@ -1716,10 +1703,8 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
      * @param int $numberOfTransactions
      * @return $this
      */
-    protected function setupSalesTransaction(
-        $paymentId,
-        $numberOfTransactions
-    ) {
+    protected function setupSalesTransaction($paymentId, $numberOfTransactions)
+    {
         $transactionCollectionMock = $this->getMockBuilder(
             'Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\Collection'
         )->disableOriginalConstructor()
@@ -1741,12 +1726,24 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
         return $this;
     }
 
-    protected function setupPaymentObjectForCapture(
-        $paymentId
-    ) {
+    protected function setupPaymentObjectForCapture($paymentId)
+    {
+        $order = $this->getMockBuilder('Magento\Sales\Api\Data\OrderInterface')
+            ->getMockForAbstractClass();
+        $order->expects(static::any())
+            ->method('getTotalDue')
+            ->willReturn(self::TOTAL_AMOUNT);
+        $this->orderRepository->expects(static::any())
+            ->method('get')
+            ->willReturn($order);
+
+        $currencyMock = $this->getPriceCurrencyMock();
+
         $paymentObject = $this->objectManagerHelper->getObject(
             'Magento\Sales\Model\Order\Payment',
             [
+                'priceCurrency' => $currencyMock,
+                'orderRepository' => $this->orderRepository,
                 'data' => [
                     'id' => $paymentId,
                     'cc_trans_id' => self::AUTH_TRAN_ID,
@@ -1756,6 +1753,11 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
 
         return $paymentObject;
     }
+
+    /**
+     * @covers \Magento\Braintree\Model\PaymentMethod::capture()
+     * @throws LocalizedException
+     */
     public function testCaptureSuccess()
     {
         $amount = self::AUTH_AMOUNT;
@@ -1774,20 +1776,40 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
             ->method('critical');
 
         $paymentObject->setParentId('1');
-        $order = $this->getMockBuilder('Magento\Sales\Api\Data\OrderInterface')
-            ->getMockForAbstractClass();
-        $order->expects($this->once())
-            ->method('getTotalDue')
-            ->willReturn(10.02);
-        $this->orderRepository->expects($this->once())
-            ->method('get')
-            ->willReturn($order);
 
         $this->model->capture($paymentObject, $amount);
         $this->assertEquals(0, $paymentObject->getIsTransactionClosed());
         $this->assertFalse($paymentObject->getShouldCloseParentTransaction());
     }
 
+    /**
+     * @covers \Magento\Braintree\Model\PaymentMethod::capture()
+     * @return void
+     */
+    public function testCaptureSuccessAuthTransactionClosed()
+    {
+        $paymentId = 31232;
+        /** @var \Magento\Sales\Model\Order\Payment $payment */
+        $payment = $this->setupPaymentObjectForCapture($paymentId);
+        $this->setupSalesTransaction($paymentId, 0); //no existing capture transaction
+
+        $result = $this->setupSuccessResponse([]);
+        $this->braintreeTransactionMock->expects(static::once())
+            ->method('submitForSettlement')
+            ->with(self::AUTH_TRAN_ID, self::TOTAL_AMOUNT)
+            ->willReturn($result);
+
+        $this->psrLoggerMock->expects(static::never())
+            ->method('critical');
+
+        $payment->setParentId(1);
+        $this->model->capture($payment, self::TOTAL_AMOUNT);
+
+        static::assertFalse($payment->getIsTransactionClosed());
+        static::assertTrue($payment->getShouldCloseParentTransaction());
+
+    }
+
     /**
      * @expectedException \Magento\Framework\Exception\LocalizedException
      * @expectedExceptionMessage There was an error capturing the transaction: error.
@@ -1820,10 +1842,8 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
         $this->model->capture($paymentObject, $amount);
     }
 
-    protected function setupAuthTransaction(
-        $paymentId,
-        $authTransaction
-    ) {
+    protected function setupAuthTransaction($paymentId, $authTransaction)
+    {
         $authTransactionCollectionMock = $this->getMockBuilder(
             'Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\Collection'
         )->disableOriginalConstructor()
@@ -1926,14 +1946,6 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
             ->willReturn($result);
 
         $paymentObject->setParentId('1');
-        $order = $this->getMockBuilder('Magento\Sales\Api\Data\OrderInterface')
-            ->getMockForAbstractClass();
-        $order->expects($this->once())
-            ->method('getTotalDue')
-            ->willReturn(10.02);
-        $this->orderRepository->expects($this->once())
-            ->method('get')
-            ->willReturn($order);
 
         $this->model->capture($paymentObject, $amount);
         $this->assertEquals(0, $paymentObject->getIsTransactionClosed());
@@ -2115,17 +2127,10 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
                         'submitForSettlement' => true,
                     ],
                 ]
-            )->willReturn($resultSuccess);
+            )
+            ->willReturn($resultSuccess);
 
         $paymentObject->setParentId('1');
-        $order = $this->getMockBuilder('Magento\Sales\Api\Data\OrderInterface')
-            ->getMockForAbstractClass();
-        $order->expects($this->once())
-            ->method('getTotalDue')
-            ->willReturn(10.02);
-        $this->orderRepository->expects($this->once())
-            ->method('get')
-            ->willReturn($order);
 
         $this->model->capture($paymentObject, $amount);
         $this->assertEquals(PaymentMethod::STATUS_APPROVED, $paymentObject->getStatus());
@@ -2192,9 +2197,8 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
     //End: test capture
 
     //Start: test refund
-    protected function setupPaymentObjectForRefund(
-        $refundTransactionId
-    ) {
+    protected function setupPaymentObjectForRefund($refundTransactionId)
+    {
         $paymentObject = $this->objectManagerHelper->getObject(
             'Magento\Sales\Model\Order\Payment',
             [
@@ -2379,7 +2383,6 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
 
         $this->model->refund($paymentObject, $amount);
         $this->assertEquals(1, $paymentObject->getIsTransactionClosed());
-        $this->assertEquals($refundTransactionId . '-' .Transaction::TYPE_REFUND, $paymentObject->getTransactionId());
     }
 
     /**
@@ -2461,9 +2464,8 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
             ->willReturnArgument(0);
     }
 
-    protected function setupPaymentObjectForVoid(
-        $orderId
-    ) {
+    protected function setupPaymentObjectForVoid($orderId)
+    {
         $paymentObject = $this->objectManagerHelper->getObject(
             'Magento\Sales\Model\Order\Payment'
         );
@@ -2666,4 +2668,22 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase
             ->willReturn($orderMock);
         $this->assertEquals(false, $this->model->canVoid());
     }
+
+    /**
+     * @return \Magento\Directory\Model\PriceCurrency|\PHPUnit_Framework_MockObject_MockObject
+     */
+    protected function getPriceCurrencyMock()
+    {
+        $currencyMock = $this->getMockBuilder('\Magento\Directory\Model\PriceCurrency')
+            ->disableOriginalConstructor()
+            ->setMethods(['round'])
+            ->getMock();
+        $currencyMock->expects(static::any())
+            ->method('round')
+            ->willReturnMap([
+                [self::TOTAL_AMOUNT, round(self::TOTAL_AMOUNT, 2)],
+                [self::AUTH_AMOUNT, round(self::AUTH_AMOUNT, 2)]
+            ]);
+        return $currencyMock;
+    }
 }
diff --git a/app/code/Magento/Braintree/view/adminhtml/templates/form.phtml b/app/code/Magento/Braintree/view/adminhtml/templates/form.phtml
index 5610e082e1715e36dcecc8f7cc241bf1aeee2798..508313a25527a942d6c55cea7fd64873528e91a6 100644
--- a/app/code/Magento/Braintree/view/adminhtml/templates/form.phtml
+++ b/app/code/Magento/Braintree/view/adminhtml/templates/form.phtml
@@ -7,7 +7,7 @@
 // @codingStandardsIgnoreFile
 
 /** @var \Magento\Braintree\Block\Form $block */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 $storedCards = $this->helper('\Magento\Braintree\Helper\Createorder')->getLoggedInCustomerCards();
 $useVault = $block->useVault();
 $useCvv = $block->useCvv();
diff --git a/app/code/Magento/Braintree/view/frontend/templates/PayPal/shortcut.phtml b/app/code/Magento/Braintree/view/frontend/templates/PayPal/shortcut.phtml
index 267a6fede0644551bf2e45c5027bf2aebc9effe4..6edb66bd04c8f1c5858104007035a9b83c14fad9 100644
--- a/app/code/Magento/Braintree/view/frontend/templates/PayPal/shortcut.phtml
+++ b/app/code/Magento/Braintree/view/frontend/templates/PayPal/shortcut.phtml
@@ -42,7 +42,7 @@ $config = [
      class="paypal checkout <?php echo $block->escapeHtml($block->getShowOrPosition()) ?> paypal-logo"
     >
     <fieldset class="fieldset paypal items">
-        <div id="<?php /* @noEscape */ echo $containerId ?>"
+        <div id="<?php echo $block->escapeHtml($containerId); ?>"
              data-mage-init='<?php /* @noEscape */ echo json_encode($config); ?>'></div>
     </fieldset>
 </div>
diff --git a/app/code/Magento/Braintree/view/frontend/templates/creditcard/edit.phtml b/app/code/Magento/Braintree/view/frontend/templates/creditcard/edit.phtml
index 6fcac2eae9c411929472c7b79ef1038836646183..44dc85b5404a1b51b2b3e508cbaa6b575788215e 100644
--- a/app/code/Magento/Braintree/view/frontend/templates/creditcard/edit.phtml
+++ b/app/code/Magento/Braintree/view/frontend/templates/creditcard/edit.phtml
@@ -164,7 +164,7 @@ $serializedFormData = $this->helper('Magento\Framework\Json\Helper\Data')->jsonE
                                 class="year required-entry"
                                 data-validate="{required:true}">
                                 <?php foreach ($block->getCcYears() as $k => $v): ?>
-                                    <option value="<?php /* @noEscape */ echo $k ? $k : ''; ?>"
+                                    <option value="<?php /* @noEscape */ echo $k ? $block->escapeHtml($k) : ''; ?>"
                                         <?php if ($k == $defaultExpYear): ?> selected="selected"<?php endif; ?>>
                                         <?php echo $block->escapeHtml($v); ?>
                                     </option>
diff --git a/app/code/Magento/Braintree/view/frontend/templates/form.phtml b/app/code/Magento/Braintree/view/frontend/templates/form.phtml
index 459a61568cff7fa67f19d3146b1a2f7e0fb5ff5d..41029526cc388a58d93dc9c8ef119d99a1ccafd4 100644
--- a/app/code/Magento/Braintree/view/frontend/templates/form.phtml
+++ b/app/code/Magento/Braintree/view/frontend/templates/form.phtml
@@ -7,7 +7,7 @@
 // @codingStandardsIgnoreFile
 
 /** @var \Magento\Braintree\Block\Form $block */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 $loggedIn = $block->isCustomerLoggedIn();
 $storedCards = $block->getStoredCards();
 $useVault = $loggedIn && $block->useVault() && count($storedCards);
diff --git a/app/code/Magento/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php b/app/code/Magento/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php
index b07b6e82bdc4d04f71bc4c8a46ac686f82bf2332..fb92f2bc3fffd09f5ac54eca2a2fb65e77bd913b 100644
--- a/app/code/Magento/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php
+++ b/app/code/Magento/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php
@@ -463,4 +463,13 @@ class Links extends \Magento\Backend\Block\Template
     {
         return $this->_storeManager->getStore($storeId)->getBaseCurrencyCode();
     }
+
+    /**
+     * @param null|string|bool|int|\Magento\Store\Model\Store $storeId $storeId
+     * @return string
+     */
+    public function getBaseCurrencySymbol($storeId)
+    {
+        return $this->_storeManager->getStore($storeId)->getBaseCurrency()->getCurrencySymbol();
+    }
 }
diff --git a/app/code/Magento/Downloadable/view/adminhtml/templates/product/edit/downloadable/links.phtml b/app/code/Magento/Downloadable/view/adminhtml/templates/product/edit/downloadable/links.phtml
index d5c4b6dca86ea769bc9bb04fe98309bffcccd0e5..cf43aa7d3f4f62de46a4d86395648c671a654c2a 100644
--- a/app/code/Magento/Downloadable/view/adminhtml/templates/product/edit/downloadable/links.phtml
+++ b/app/code/Magento/Downloadable/view/adminhtml/templates/product/edit/downloadable/links.phtml
@@ -107,8 +107,10 @@ require([
             '</td>'+
             <?php if ($block->getCanReadPrice() !== false) : ?>
                 '<td class="col-price">'+
-                    '<input type="text" id="downloadable_link_<%- data.id %>_price_value" class="input-text admin__control-text validate-number link-prices<?php if ($block->getCanEditPrice() === false) : ?> disabled<?php endif; ?>" name="downloadable[link][<%- data.id %>][price]" value="<%- data.price %>"<?php if ($block->getCanEditPrice() === false) : ?> disabled="disabled"<?php endif; ?> /> ' +
-                    '<div class="note">[<?php /* @escapeNotVerified */ echo $block->getBaseCurrencyCode($_product->getStoreId()) ?>]</div>' +
+                    '<div class="admin__control-addon">' +
+                        '<input type="text" id="downloadable_link_<%- data.id %>_price_value" class="input-text admin__control-text validate-number link-prices<?php if ($block->getCanEditPrice() === false) : ?> disabled<?php endif; ?>" name="downloadable[link][<%- data.id %>][price]" value="<%- data.price %>"<?php if ($block->getCanEditPrice() === false) : ?> disabled="disabled"<?php endif; ?> /> ' +
+                        '<label class="admin__addon-prefix"><span><?php echo $block->escapeHtml($block->getBaseCurrencySymbol($_product->getStoreId())) ?></span></label>' +
+                    '</div>' +
                     <?php if ($_product->getStoreId() && $block->getIsPriceWebsiteScope()) : ?>
                         '<div class="admin__field admin__field-option">'+
                             '<input type="checkbox" id="downloadable_link_<%- data.id %>_price" name="downloadable[link][<%- data.id %>][use_default_price]" value="1"<?php if ($block->getCanEditPrice() === false) : ?> disabled="disabled"<?php endif; ?> class="admin__control-checkbox" />'+
diff --git a/app/code/Magento/Multishipping/view/frontend/templates/checkout/success.phtml b/app/code/Magento/Multishipping/view/frontend/templates/checkout/success.phtml
index dc0c669468da9a1aaae43fc83bfa32cc22776044..21b83793d7d27f94ea511f1e7a6cde2ab0a8384f 100644
--- a/app/code/Magento/Multishipping/view/frontend/templates/checkout/success.phtml
+++ b/app/code/Magento/Multishipping/view/frontend/templates/checkout/success.phtml
@@ -8,16 +8,16 @@
 
 ?>
 <div class="multicheckout success">
-    <h2 class="subtitle"><?php /* @noEscape */ echo __('Thank you for your purchase!') ?></h2>
-    <p><?php /* @escapeNotVerified */ echo __('Thanks for your order. We\'ll email you order details and tracking information.') ?></p>
+    <h2 class="subtitle"><?php echo $block->escapeHtml(__('Thank you for your purchase!')) ?></h2>
+    <p><?php echo $block->escapeHtml(__('Thanks for your order. We\'ll email you order details and tracking information.')) ?></p>
     <?php if ($_orderIds = $block->getOrderIds()): ?>
     <p class="order-number">
         <?php $flag = false ?>
         <span>
             <?php if (count($_orderIds) > 1): ?>
-                <?php /* @noEscape */ echo __('Your order numbers are: ') ?>
+                <?php echo $block->escapeHtml(__('Your order numbers are: ')) ?>
             <?php else : ?>
-                <?php /* @noEscape */ echo __('Your order number is: ') ?>
+                <?php echo $block->escapeHtml(__('Your order number is: ')) ?>
             <?php endif; ?>
         </span>
         <?php foreach ($_orderIds as $orderId => $incrementId): ?><?php if ($flag): ?><?php echo ', ' ?><?php endif; ?><?php $flag = true ?><a href="<?php /* @escapeNotVerified */ echo $block->getViewOrderUrl($orderId) ?>"><?php /* @escapeNotVerified */ echo $incrementId ?></a><?php endforeach; ?>
@@ -25,6 +25,6 @@
     <?php endif; ?>
     <?php echo $block->getChildHtml() ?>
     <div class="actions">
-        <a class="action continue" title="<?php /* @noEscape */ echo __('Continue Shopping') ?>" href="<?php /* @escapeNotVerified */ echo $block->getContinueUrl() ?>"><span><?php /* @noEscape */ echo __('Continue Shopping') ?></span></a>
+        <a class="action continue" title="<?php echo $block->escapeHtml(__('Continue Shopping')) ?>" href="<?php /* @escapeNotVerified */ echo $block->getContinueUrl() ?>"><span><?php echo $block->escapeHtml(__('Continue Shopping')) ?></span></a>
     </div>
 </div>
diff --git a/app/code/Magento/PageCache/Model/Cache/Server.php b/app/code/Magento/PageCache/Model/Cache/Server.php
index fc52e41e3b23428142c147c8a13556005ca72e12..2e2f3a87fb8c07a7eb33c9b61f4ef421992e6c49 100644
--- a/app/code/Magento/PageCache/Model/Cache/Server.php
+++ b/app/code/Magento/PageCache/Model/Cache/Server.php
@@ -60,7 +60,7 @@ class Server
             $httpHost = $this->request->getHttpHost();
             $servers[] = $httpHost ?
                 UriFactory::factory('')->setHost($httpHost)->setPort(self::DEFAULT_PORT)->setScheme('http') :
-                UriFactory::factory($this->urlBuilder->getUrl('*'))
+                UriFactory::factory($this->urlBuilder->getUrl('*', ['_nosid' => true])) // Don't use SID in building URL
                     ->setScheme('http')
                     ->setPath(null)
                     ->setQuery(null);
diff --git a/app/code/Magento/PageCache/Test/Unit/Model/Cache/ServerTest.php b/app/code/Magento/PageCache/Test/Unit/Model/Cache/ServerTest.php
index 38cc49be2ff4839736af9bd27d18752a585e8aee..f18c5e04468da59169ae6b3b5642d428b7113667 100644
--- a/app/code/Magento/PageCache/Test/Unit/Model/Cache/ServerTest.php
+++ b/app/code/Magento/PageCache/Test/Unit/Model/Cache/ServerTest.php
@@ -64,7 +64,7 @@ class ServerTest extends \PHPUnit_Framework_TestCase
             ->willReturn($httpHost);
         $this->urlBuilderMock->expects($this->exactly($getUrlCallCtr))
             ->method('getUrl')
-            ->with('*')
+            ->with('*', ['_nosid' => true])
             ->willReturn($url);
 
         $uris = [];
diff --git a/app/code/Magento/Payment/view/adminhtml/templates/form/cc.phtml b/app/code/Magento/Payment/view/adminhtml/templates/form/cc.phtml
index ab38d3752a679f68d8a0371d087c126268707a99..f1109afb7974ef65ee42d01d18162dc121c428ab 100644
--- a/app/code/Magento/Payment/view/adminhtml/templates/form/cc.phtml
+++ b/app/code/Magento/Payment/view/adminhtml/templates/form/cc.phtml
@@ -8,7 +8,7 @@
 /**
  * @var \Magento\Payment\Block\Adminhtml\Transparent\Form $block
  */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 $ccType = $block->getInfoData('cc_type');
 $ccExpMonth = $block->getInfoData('cc_exp_month');
 $ccExpYear = $block->getInfoData('cc_exp_year');
diff --git a/app/code/Magento/Payment/view/adminhtml/templates/transparent/form.phtml b/app/code/Magento/Payment/view/adminhtml/templates/transparent/form.phtml
index 1bb248e6fd5662bced43e2f7ee9d4c5a942a1f69..0d28d33caea9cadcfce22c7fb68e2da557c7935b 100644
--- a/app/code/Magento/Payment/view/adminhtml/templates/transparent/form.phtml
+++ b/app/code/Magento/Payment/view/adminhtml/templates/transparent/form.phtml
@@ -7,7 +7,7 @@
 // @codingStandardsIgnoreFile
 
 /** @var \Magento\Payment\Block\Transparent\Form $block */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 $ccType = $block->getInfoData('cc_type');
 $ccExpYear = $block->getInfoData('cc_exp_year');
 $ccExpMonth = $block->getInfoData('cc_exp_month');
@@ -29,7 +29,7 @@ $ccExpMonth = $block->getInfoData('cc_exp_month');
         "controller":"<?php echo $block->escapeHtml($block->getRequest()->getControllerName()); ?>",
         "gateway":"<?php /* @noEscape */ echo $code; ?>",
         "dateDelim":"<?php echo $block->escapeHtml($block->getDateDelim()); ?>",
-        "cardFieldsMap":<?php /* @noEscape */ echo $block->getCardFieldsMap(); ?>,
+        "cardFieldsMap":<?php echo $block->escapeHtml($block->getCardFieldsMap()); ?>,
         "orderSaveUrl":"<?php echo $block->escapeUrl($block->getOrderUrl()); ?>",
         "cgiUrl":"<?php echo $block->escapeUrl($block->getCgiUrl()); ?>",
         "expireYearLength":"<?php echo $block->escapeHtml($block->getMethodConfigData('cc_year_length')); ?>",
@@ -102,7 +102,7 @@ $ccExpMonth = $block->getInfoData('cc_exp_month');
                     data-container="<?php /* @noEscape */ echo $code; ?>-cc-year" data-validate='{required:true}'>
                 <?php foreach ($block->getCcYears() as $k => $v): ?>
                     <option
-                        value="<?php /* @noEscape */ echo $k ? $k : '' ?>"
+                        value="<?php /* @noEscape */ echo $k ? $block->escapeHtml($k) : '' ?>"
                         <?php if ($k == $ccExpYear): ?> selected="selected"<?php endif ?>>
                         <?php echo $block->escapeHtml($v); ?>
                     </option>
diff --git a/app/code/Magento/Payment/view/adminhtml/templates/transparent/info.phtml b/app/code/Magento/Payment/view/adminhtml/templates/transparent/info.phtml
index 8deddb094d1799a1f1459a6be34e7fdbf5a054f0..8b20f64b5a60109508916e2a2ed2b07d36fa586f 100644
--- a/app/code/Magento/Payment/view/adminhtml/templates/transparent/info.phtml
+++ b/app/code/Magento/Payment/view/adminhtml/templates/transparent/info.phtml
@@ -11,6 +11,6 @@
  * @see \Magento\Payment\Block\Transparent\Info
  */
 ?>
-<fieldset id="payment_form_<?php /* @noEscape */ echo $block->getMethodCode(); ?>" style="display:none" class="fieldset items redirect">
+<fieldset id="payment_form_<?php echo $block->escapeHtml($block->getMethodCode()); ?>" style="display:none" class="fieldset items redirect">
     <div><?php echo $block->escapeHtml(__('We\'ll ask for your payment details before you place an order.')); ?></div>
 </fieldset>
diff --git a/app/code/Magento/Payment/view/frontend/templates/form/cc.phtml b/app/code/Magento/Payment/view/frontend/templates/form/cc.phtml
index 05d8d3c02c82cdfc54c16a9d77a6863422e7ecbd..a02de6dbaff84f73d2f9d7fa48dcc23c2b482f1d 100644
--- a/app/code/Magento/Payment/view/frontend/templates/form/cc.phtml
+++ b/app/code/Magento/Payment/view/frontend/templates/form/cc.phtml
@@ -8,7 +8,7 @@
 /**
  * @var \Magento\Payment\Block\Transparent\Form $block
  */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 $ccType = $block->getInfoData('cc_type');
 $ccExpMonth = $block->getInfoData('cc_exp_month');
 $ccExpYear = $block->getInfoData('cc_exp_year');
diff --git a/app/code/Magento/Payment/view/frontend/templates/transparent/form.phtml b/app/code/Magento/Payment/view/frontend/templates/transparent/form.phtml
index 64ea503996cd280d8b29dc154b4dc20e9e47f69d..a589900d6233ae186fbef507484d2334a64c1db6 100644
--- a/app/code/Magento/Payment/view/frontend/templates/transparent/form.phtml
+++ b/app/code/Magento/Payment/view/frontend/templates/transparent/form.phtml
@@ -7,7 +7,7 @@
 // @codingStandardsIgnoreFile
 
 /** @var \Magento\Payment\Block\Transparent\Form $block */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 $ccExpMonth = $block->getInfoData('cc_exp_month');
 $ccExpYear = $block->getInfoData('cc_exp_year');
 $ccType = $block->getInfoData('cc_type');
@@ -20,7 +20,7 @@ $content = '<img src=\"' . $block->getViewFileUrl('Magento_Checkout::cvv.png') .
 <iframe width="0" height="0" id="<?php /* @noescape */ echo $code; ?>-transparent-iframe"
         data-container="<?php /* @noEscape */ echo $code; ?>-transparent-iframe" allowtransparency="true"
         frameborder="0"  name="iframeTransparent" style="display:none;width:100%;background-color:transparent"
-        src="<?php /* @noEscape */ echo $block->getViewFileUrl('blank.html') ?>"></iframe>
+        src="<?php echo $block->escapeUrl($block->getViewFileUrl('blank.html')) ?>"></iframe>
 <form class="form" id="co-transparent-form" action="#" method="post" data-mage-init='{
     "transparent":{
         "controller":"<?php echo $block->escapeHtml($block->getRequest()->getControllerName()); ?>",
@@ -28,7 +28,7 @@ $content = '<img src=\"' . $block->getViewFileUrl('Magento_Checkout::cvv.png') .
         "orderSaveUrl":"<?php echo $block->escapeUrl($block->getOrderUrl()); ?>",
         "cgiUrl":"<?php echo $block->escapeUrl($block->getCgiUrl()); ?>",
         "dateDelim":"<?php echo $block->escapeHtml($block->getDateDelim()); ?>",
-        "cardFieldsMap":<?php /* @noEscape */ echo $block->getCardFieldsMap(); ?>,
+        "cardFieldsMap":<?php echo $block->escapeHtml($block->getCardFieldsMap()); ?>,
         "nativeAction":"<?php echo $block->escapeUrl($block->getUrl('checkout/onepage/saveOrder', ['_secure' => $block->getRequest()->isSecure()])); ?>"
     }, "validation":[]}'>
     <fieldset class="fieldset ccard <?php /* @noEscape */ echo $code; ?>" id="payment_form_<?php /* @noEscape */ echo $code; ?>">
diff --git a/app/code/Magento/Payment/view/frontend/templates/transparent/iframe.phtml b/app/code/Magento/Payment/view/frontend/templates/transparent/iframe.phtml
index b191981585af62dde6804c9dbfc44a3b0258e1b5..fc9624bde1016edc28d53a7bc282ca36ca64625f 100644
--- a/app/code/Magento/Payment/view/frontend/templates/transparent/iframe.phtml
+++ b/app/code/Magento/Payment/view/frontend/templates/transparent/iframe.phtml
@@ -33,7 +33,7 @@ $params = $block->getParams();
                     'Magento_Checkout/js/action/place-order'
                 ],
                 function(quote, placeOrderAction) {
-                    placeOrderAction(quote.paymentMethod(), true);
+                    placeOrderAction({"method": quote.paymentMethod().method}, true);
                 }
             );
         <?php endif; ?>
diff --git a/app/code/Magento/Payment/view/frontend/templates/transparent/info.phtml b/app/code/Magento/Payment/view/frontend/templates/transparent/info.phtml
index c3ce1e5dbb7029ed65db079fcbf0230839373a3b..84cd69f6e4f698ff8731f76c5367e1b8244e0dae 100644
--- a/app/code/Magento/Payment/view/frontend/templates/transparent/info.phtml
+++ b/app/code/Magento/Payment/view/frontend/templates/transparent/info.phtml
@@ -11,7 +11,7 @@
  * @see \Magento\Payment\Block\Transparent\Info
  */
 ?>
-<fieldset id="payment_form_<?php /* @noEscape */ echo $block->getMethodCode(); ?>" style="display:none" class="fieldset items redirect">
+<fieldset id="payment_form_<?php echo $block->escapeHtml($block->getMethodCode()); ?>" style="display:none" class="fieldset items redirect">
     <div>
         <?php echo $block->escapeHtml(__('We\'ll ask for your payment details before you place an order.')); ?>
     </div>
diff --git a/app/code/Magento/Paypal/Model/Config/Rules/Converter.php b/app/code/Magento/Paypal/Model/Config/Rules/Converter.php
index a636188baf1cf571ea572625e6de6dec367b640e..5528f79b385758a89b1c4c1fad3d2fa90e92b08e 100644
--- a/app/code/Magento/Paypal/Model/Config/Rules/Converter.php
+++ b/app/code/Magento/Paypal/Model/Config/Rules/Converter.php
@@ -58,8 +58,8 @@ class Converter implements ConverterInterface
     protected function createEvents(\DOMElement $node)
     {
         $result = [];
-        /** @var \DOMElement $child */
         foreach ($node->childNodes as $child) {
+            /** @var \DOMElement $child */
             if ($this->hasNodeElement($child)) {
                 $result[$child->getAttribute('name')] = [
                     'value' => $child->getAttribute('value'),
@@ -80,8 +80,8 @@ class Converter implements ConverterInterface
     protected function createPredicate(\DOMElement $node)
     {
         $result = [];
-        /** @var \DOMElement $child */
         foreach ($node->childNodes as $child) {
+            /** @var \DOMElement $child */
             if ($this->hasNodeElement($child)) {
                 $result = [
                     'name' => $child->getAttribute('name'),
@@ -105,33 +105,18 @@ class Converter implements ConverterInterface
     {
         $result = [];
         foreach ($node->childNodes as $child) {
+            /** @var \DOMElement $child */
             if ($this->hasNodeElement($child)) {
-                $result = array_merge($result, $this->createRule($child));
+                $result[$child->getAttribute('type')][] = [
+                    'event' => $child->getAttribute('event'),
+                    'argument' => $this->createArgument($child),
+                ];
             }
         }
 
         return [$node->getAttribute('target') => $result];
     }
 
-    /**
-     * Creating rules
-     *
-     * @param \DOMElement $node
-     * @return array
-     */
-    protected function createRule(\DOMElement $node)
-    {
-        $result = [];
-        $type = $node->getAttribute('type');
-        /** @var \DOMElement $node */
-        $result[$type] = [
-            'event' => $node->getAttribute('event'),
-        ];
-        $result[$type]['argument'] = $this->createArgument($node);
-
-        return $result;
-    }
-
     /**
      * Create argument
      *
@@ -141,8 +126,8 @@ class Converter implements ConverterInterface
     protected function createArgument(\DOMElement $node)
     {
         $result = [];
-        /** @var \DOMElement $child */
         foreach ($node->childNodes as $child) {
+            /** @var \DOMElement $child */
             if ($this->hasNodeElement($child)) {
                 $result[$child->getAttribute('name')] = $child->textContent;
             }
diff --git a/app/code/Magento/Paypal/Model/Payflowpro.php b/app/code/Magento/Paypal/Model/Payflowpro.php
index 6efc7e7cca4ed1735aeeaaacc8deee09aaf18eb1..894c0792a99e4ab689f5c40aed6b0d29c0d334a5 100644
--- a/app/code/Magento/Paypal/Model/Payflowpro.php
+++ b/app/code/Magento/Paypal/Model/Payflowpro.php
@@ -500,8 +500,7 @@ class Payflowpro extends \Magento\Payment\Model\Method\Cc implements GatewayInte
         $this->processErrors($response);
 
         if ($response->getResultCode() == self::RESPONSE_CODE_APPROVED) {
-            $payment->setTransactionId($response->getPnref())->setIsTransactionClosed(1);
-            $payment->setShouldCloseParentTransaction(!$payment->getCreditmemo()->getInvoice()->canRefund());
+            $payment->setTransactionId($response->getPnref())->setIsTransactionClosed(true);
         }
         return $this;
     }
diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConverterTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConverterTest.php
index eb62d570481bde11725647a1ab54858c4ca96dcf..ffd2f141e0a0d7da9bc3f642e581e754d3324d6e 100644
--- a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConverterTest.php
+++ b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConverterTest.php
@@ -78,22 +78,27 @@ class ConverterTest extends \PHPUnit_Framework_TestCase
                         'relations' => [
                             'payment_test_1' => [
                                 'test' => [
-                                    'event' => 'event0',
-                                    'argument' => [],
+                                    [
+                                        'event' => 'event0',
+                                        'argument' => [],
+                                    ]
                                 ],
                             ],
                             'payment_test_2' => [
                                 'test' => [
-                                    'event' => 'event1',
-                                    'argument' => [
-                                    ],
+                                    [
+                                        'event' => 'event1',
+                                        'argument' => [],
+                                    ]
                                 ],
                                 'test-two' => [
-                                    'event' => 'event1',
-                                    'argument' => [
-                                        'argument1' => 'argument1',
-                                        'argument2' => 'argument2',
-                                    ],
+                                    [
+                                        'event' => 'event1',
+                                        'argument' => [
+                                            'argument1' => 'argument1',
+                                            'argument2' => 'argument2',
+                                        ],
+                                    ]
                                 ],
                             ],
                         ],
@@ -122,21 +127,34 @@ class ConverterTest extends \PHPUnit_Framework_TestCase
                         'relations' => [
                             'payment_test_1' => [
                                 'test' => [
-                                    'event' => 'event0',
-                                    'argument' => [],
+                                    [
+                                        'event' => 'event0',
+                                        'argument' => [],
+                                    ]
                                 ],
                             ],
                             'payment_test_2' => [
                                 'test' => [
-                                    'event' => 'event1',
-                                    'argument' => [],
+                                    [
+                                        'event' => 'event1',
+                                        'argument' => [],
+                                    ]
                                 ],
                                 'test-two' => [
-                                    'event' => 'event1',
-                                    'argument' => [
-                                        'argument1' => 'argument1',
-                                        'argument2' => 'argument2',
+                                    [
+                                        'event' => 'event1',
+                                        'argument' => [
+                                            'argument1' => 'argument1',
+                                            'argument2' => 'argument2',
+                                        ],
                                     ],
+                                    [
+                                        'event' => 'event2',
+                                        'argument' => [
+                                            'argument1' => 'argument1',
+                                            'argument2' => 'argument2',
+                                        ],
+                                    ]
                                 ],
                             ],
                         ],
diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConvertibleContent/rules.xml b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConvertibleContent/rules.xml
index 297d3c8e620a06480da9c009f1cfc59ae81d746f..4b4c6833d92c92399d29fae6e687472d24cbedfb 100644
--- a/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConvertibleContent/rules.xml
+++ b/app/code/Magento/Paypal/Test/Unit/Model/Config/Rules/ConvertibleContent/rules.xml
@@ -52,6 +52,10 @@
                 <argument name="argument1">argument1</argument>
                 <argument name="argument2">argument2</argument>
             </rule>
+            <rule type="test-two" event="event2">
+                <argument name="argument1">argument1</argument>
+                <argument name="argument2">argument2</argument>
+            </rule>
         </relation>
     </payment>
 </rules>
diff --git a/app/code/Magento/Paypal/Test/Unit/Model/PayflowproTest.php b/app/code/Magento/Paypal/Test/Unit/Model/PayflowproTest.php
index 215680852225b7b3ed5b4507a223fda725b821b5..c6250a24903ee0e71b30669e762a44c00a3eb06c 100644
--- a/app/code/Magento/Paypal/Test/Unit/Model/PayflowproTest.php
+++ b/app/code/Magento/Paypal/Test/Unit/Model/PayflowproTest.php
@@ -175,7 +175,6 @@ class PayflowproTest extends \PHPUnit_Framework_TestCase
         $this->payflowpro->fetchTransactionInfo($payment, 'AD49G8N825');
     }
 
-
     /**
      * @param $response
      * @dataProvider setTransStatusDataProvider
@@ -323,6 +322,22 @@ class PayflowproTest extends \PHPUnit_Framework_TestCase
         ];
     }
 
+    /**
+     * @covers \Magento\Paypal\Model\Payflowpro::refund()
+     */
+    public function testRefund()
+    {
+        /** @var \Magento\Sales\Model\Order\Payment $paymentMock */
+        $paymentMock = $this->getPaymentMock();
+
+        $response = $this->execGatewayRequest();
+
+        $amount = 213.04;
+        $this->payflowpro->refund($paymentMock, $amount);
+        static::assertEquals($response['pnref'], $paymentMock->getTransactionId());
+        static::assertTrue($paymentMock->getIsTransactionClosed());
+    }
+
     /**
      * Create mock object for store model
      * @return void
@@ -399,16 +414,16 @@ class PayflowproTest extends \PHPUnit_Framework_TestCase
             'year' => 18,
             'cvv' => 123
         ];
-        $paymentMock->expects(static::once())
+        $paymentMock->expects(static::any())
             ->method('getCcNumber')
             ->willReturn($cardData['number']);
-        $paymentMock->expects(static::once())
+        $paymentMock->expects(static::any())
             ->method('getCcExpMonth')
             ->willReturn($cardData['month']);
-        $paymentMock->expects(static::once())
+        $paymentMock->expects(static::any())
             ->method('getCcExpYear')
             ->willReturn($cardData['year']);
-        $paymentMock->expects(static::once())
+        $paymentMock->expects(static::any())
             ->method('getCcCid')
             ->willReturn($cardData['cvv']);
         return $paymentMock;
diff --git a/app/code/Magento/Paypal/etc/adminhtml/rules/payment_us.xml b/app/code/Magento/Paypal/etc/adminhtml/rules/payment_us.xml
index c187130b357b85e975b93c17f457b30c78bd5f0f..4b5acbe6e073e8259ff3a3b4364c7c5c7ef70fac 100644
--- a/app/code/Magento/Paypal/etc/adminhtml/rules/payment_us.xml
+++ b/app/code/Magento/Paypal/etc/adminhtml/rules/payment_us.xml
@@ -329,7 +329,10 @@
                 <argument name="wpp_usuk">wpp_usuk</argument>
                 <argument name="paypal_payflowpro_with_express_checkout">paypal_payflowpro_with_express_checkout</argument>
             </rule>
+
             <rule type="payflow/bml/disable-conditional-express" event="deactivate-express"/>
+            <rule type="payflow/bml/disable-conditional-express" event=":load"/>
+
             <rule type="payflow/bml/enable" event="activate-express"/>
             <rule type="payflow/express/lock-conditional" event=":load"/>
             <rule type="payflow/bml/lock-conditional" event=":load"/>
diff --git a/app/code/Magento/Paypal/view/adminhtml/templates/billing/agreement/form.phtml b/app/code/Magento/Paypal/view/adminhtml/templates/billing/agreement/form.phtml
index 0d933a861b54182146e34358253ac033072f4c28..e1f6c1ac9655bcaa39a0e78efcf0023c1564b6ae 100644
--- a/app/code/Magento/Paypal/view/adminhtml/templates/billing/agreement/form.phtml
+++ b/app/code/Magento/Paypal/view/adminhtml/templates/billing/agreement/form.phtml
@@ -7,7 +7,7 @@
 // @codingStandardsIgnoreFile
 /** @var \Magento\Paypal\Block\Adminhtml\Billing\Agreement\View\Form $block */
 ?>
-<?php $code = $block->getMethodCode() ?>
+<?php $code = $block->escapeHtml($block->getMethodCode()) ?>
 <fieldset class="form-list" id="payment_form_<?php /* @noEscape */ echo $code; ?>" style="display:none;">
     <div class="admin__field _required">
         <label for="<?php /* @noEscape */ echo $code; ?>_ba_agreement_id" class="admin__field-label">
diff --git a/app/code/Magento/Paypal/view/adminhtml/templates/payment/form/billing/agreement.phtml b/app/code/Magento/Paypal/view/adminhtml/templates/payment/form/billing/agreement.phtml
index d3a6bab129806819191d864a6dde2c60c952703f..66c2184c31012317eaa1cd704b3a3ba3ec0f5385 100644
--- a/app/code/Magento/Paypal/view/adminhtml/templates/payment/form/billing/agreement.phtml
+++ b/app/code/Magento/Paypal/view/adminhtml/templates/payment/form/billing/agreement.phtml
@@ -7,7 +7,7 @@
 // @codingStandardsIgnoreFile
 /* @var $block \Magento\Paypal\Block\Payment\Form\Billing\Agreement */
 ?>
-<?php $code = $block->getMethodCode() ?>
+<?php $code = $block->escapeHtml($block->getMethodCode()) ?>
 <fieldset class="admin__fieldset payment-method form-list"
           id="payment_form_<?php /* @noEscape */ echo $code; ?>" style="display:none;">
     <div class="admin__field _required">
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/predicate/confirm.js b/app/code/Magento/Paypal/view/adminhtml/web/js/predicate/confirm.js
index ea426368243185bc14ed8fded1b77387366dddb3..278b101c9c696aabe05c1c62a28d426ce399acaf 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/predicate/confirm.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/predicate/confirm.js
@@ -2,25 +2,28 @@
  * Copyright © 2015 Magento. All rights reserved.
  * See COPYING.txt for license details.
  */
-define([], function () {
-    "use strict";
+define(['underscore'], function (_) {
+    'use strict';
+
     return function (solution, message, argument) {
         var isConfirm = false;
 
         _.every(argument, function (name) {
-            if (solution.solutionsElements[name]
-                && solution.solutionsElements[name].find(solution.enableButton).val() == 1
+            if (solution.solutionsElements[name] &&
+                solution.solutionsElements[name].find(solution.enableButton).val() == 1
             ) {
                 isConfirm = true;
+
                 return !isConfirm;
             }
+
             return !isConfirm;
         }, this);
 
         if (isConfirm) {
             return confirm(message);
-        } else {
-            return true;
         }
+
+        return true;
     };
 });
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rule.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rule.js
index b565aa2d66d6b46c2165650567b06fe440291b4e..c1c12344cc54c15ededbd2bb0b80184b09be19fd 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rule.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rule.js
@@ -3,18 +3,24 @@
  * See COPYING.txt for license details.
  */
 define([
-    "uiClass",
-    "underscore"
-], function (Class, _) {
-    "use strict";
+    'uiClass'
+], function (Class) {
+    'use strict';
+
     return Class.extend({
+
         /**
          * Constructor
+         *
+         * @param {Object} config
+         * @returns {exports.initialize}
          */
         initialize: function (config) {
             this.initConfig(config);
+
             return this;
         },
+
         /**
          * To apply the rule
          */
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/conflict.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/conflict.js
index 4d94f6a2a9ff63cdb9195b4bbdaf012f98ec4cf7..54b263be6421dcdd7534f811c7ef80a02be12e99 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/conflict.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/conflict.js
@@ -2,32 +2,42 @@
  * Copyright © 2015 Magento. All rights reserved.
  * See COPYING.txt for license details.
  */
-(function() {
+(function () {
+    'use strict';
+
     var executed = false;
+
     define([
-        'Magento_Ui/js/modal/alert'
-    ], function (alert) {
-        "use strict";
+        'Magento_Ui/js/modal/alert',
+        'underscore'
+    ], function (alert, _) {
+
         return function ($target, $owner, data) {
-            if ($owner.find(data.enableButton).val() == 1) {
-                var isDisabled = true;
 
+            var isDisabled = true,
+                newLine = String.fromCharCode(10, 13);
+
+            if ($owner.find(data.enableButton).val() === '1') {
                 _.every(data.argument, function (name) {
-                    if (data.solutionsElements[name]
-                        && data.solutionsElements[name].find(data.enableButton).val() == 1
+                    if (data.solutionsElements[name] &&
+                        data.solutionsElements[name].find(data.enableButton).val() === '1'
                     ) {
                         isDisabled = false;
+
                         return isDisabled;
                     }
+
                     return isDisabled;
                 }, this);
 
                 if (!isDisabled && !executed) {
                     executed = true;
                     alert({
-                        content: "The following error(s) occured:\n\r"
-                                +"Some PayPal solutions conflict.\n\r"
-                                +"Please re-enable the previously enabled payment solutions."
+                        content: 'The following error(s) occurred:' +
+                        newLine +
+                        'Some PayPal solutions conflict.' +
+                        newLine +
+                        'Please re-enable the previously enabled payment solutions.'
                     });
                 }
             }
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/disable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/disable.js
index a5cc52ed96bc2b145d06a638cef1be7135ce920b..54e355580394b5437fb79b6d2ecc6e20be54e184 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/disable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/disable.js
@@ -5,7 +5,8 @@
 define([
     'Magento_Paypal/js/rules/simple/disable'
 ], function (disable) {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         disable($target, $owner, data);
         $target.find(data.enableButton).change();
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional-express.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional-express.js
index 8fccdd054558b3e289fd79ec88c52fbb32dac7ce..e3d95340b8bfe534f1da36452b36dcc63bc2e4db 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional-express.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional-express.js
@@ -5,9 +5,10 @@
 define([
     'Magento_Paypal/js/rules/payflow/bml/disable'
 ], function (disable) {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
-        if ($target.find(data.enableExpress).val() == "0") {
+        if ($target.find(data.enableExpress).val() === '0') {
             disable($target, $owner, data);
         }
     };
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional.js
index 2c5ae4265342b266e9fe76d9b60994482e371a0e..20182ef0205f4135e853b77b3c937d17f59c66bc 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable-conditional.js
@@ -5,9 +5,10 @@
 define([
     'Magento_Paypal/js/rules/payflow/bml/disable'
 ], function (disable) {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
-        if ($target.find(data.enableButton).val() == "0") {
+        if ($target.find(data.enableButton).val() === '0') {
             disable($target, $owner, data);
         }
     };
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable.js
index 873eea979583c30b3fdc10906b968b1c7a1fba00..01d241a0e36197981029a2cfa63eaf1399193967 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/disable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find('label[for="' + $target.find(data.enableBml).attr('id') + '"]').removeClass('enabled');
         $target.find(data.enableBml + ' option[value="0"]').prop('selected', true);
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable-conditional.js
index f5d796397c705af56a476831d3710ff0c66f504b..9770d463f45fc676eeda339a9d7849368822f93f 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable-conditional.js
@@ -2,18 +2,21 @@
  * Copyright © 2015 Magento. All rights reserved.
  * See COPYING.txt for license details.
  */
-define([], function () {
-    "use strict";
+define(['underscore'], function (_) {
+    'use strict';
+
     return function ($target, $owner, data) {
         var isDisabled = true;
 
         _.every(data.argument, function (name) {
-            if (data.solutionsElements[name]
-                && data.solutionsElements[name].find(data.enableButton).val() == 1
+            if (data.solutionsElements[name] &&
+                data.solutionsElements[name].find(data.enableButton).val() === '1'
             ) {
                 isDisabled = false;
+
                 return isDisabled;
             }
+
             return isDisabled;
         }, this);
 
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable.js
index e7710d80cf07fc84a6ee9769ee8bb4388c155921..3ddfc3b0f60446334670836e98fffcf2cdac2dd4 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/enable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find(data.enableBml).prop('disabled', false);
         $target.find(data.enableBml + ' option[value="1"]').prop('selected', true);
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/lock-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/lock-conditional.js
index 09007924b0b4bb53f90f968717766af6e5ba9d74..607c56984e7dc6f4047a20a55b8a262442bd69ba 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/lock-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/bml/lock-conditional.js
@@ -3,9 +3,10 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
-        if ($target.find(data.enableButton).val() == "0") {
+        if ($target.find(data.enableButton).val() === '0') {
             $target.find(data.enableBml).prop('disabled', true);
         }
     };
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable-conditional.js
index f37306731b8857896fcade130783a5de86ccbe20..94b178c071642e09b80771094946ba7522541815 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable-conditional.js
@@ -5,9 +5,10 @@
 define([
     'Magento_Paypal/js/rules/payflow/express/disable'
 ], function (disableExpress) {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
-        if ($target.find(data.enableButton).val() == "0") {
+        if ($target.find(data.enableButton).val() === '0') {
             disableExpress($target, $owner, data);
             $target.find(data.enableExpress).change();
         }
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable.js
index 4d8b6fa3ca39918293381d36e23d1314304f1439..77649695f3c11394c98f95d7e50bd57d4857971a 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/disable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find('label[for="' + $target.find(data.enableExpress).attr('id') + '"]').removeClass('enabled');
         $target.find(data.enableExpress + ' option[value="0"]').prop('selected', true);
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable-conditional.js
index cc76875080a4ee00e98e93c56b182982bd06e233..ea9fc5f2d0ccbe6741615fed4bb9cd5cb0c85b74 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable-conditional.js
@@ -2,18 +2,21 @@
  * Copyright © 2015 Magento. All rights reserved.
  * See COPYING.txt for license details.
  */
-define([], function () {
-    "use strict";
+define(['underscore'], function (_) {
+    'use strict';
+
     return function ($target, $owner, data) {
         var isDisabled = true;
 
         _.every(data.argument, function (name) {
-            if (data.solutionsElements[name]
-                && data.solutionsElements[name].find(data.enableButton).val() == 1
+            if (data.solutionsElements[name] &&
+                data.solutionsElements[name].find(data.enableButton).val() === '1'
             ) {
                 isDisabled = false;
+
                 return isDisabled;
             }
+
             return isDisabled;
         }, this);
 
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable.js
index 456b4a6ac78ddd8bc591653a45aaf247303f1d2a..6dc1a0a49cfba72168b9e0d69b067b9dab2fa380 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/enable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find(data.enableExpress).prop('disabled', false);
         $target.find(data.enableExpress + ' option[value="1"]').prop('selected', true);
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/lock-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/lock-conditional.js
index 476af3b58366a86ffef757addeb4230a4f0436de..c07a0b5cf713e2b7c65bda537e331e47980f6e37 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/lock-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/payflow/express/lock-conditional.js
@@ -3,9 +3,10 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
-        if ($target.find(data.enableButton).val() == "0") {
+        if ($target.find(data.enableButton).val() === '0') {
             $target.find(data.enableExpress).prop('disabled', true);
         }
     };
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable-conditional.js
index ed327a4678fbc1db79bc1250cee0557aa06f9e5f..d4b8d4100e56d5e9e5e2ffc134ae79e6a5445859 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable-conditional.js
@@ -5,9 +5,10 @@
 define([
     'Magento_Paypal/js/rules/paypal/bml/disable'
 ], function (disable) {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
-        if ($target.find(data.enableButton).val() == "0") {
+        if ($target.find(data.enableButton).val() === '0') {
             disable($target, $owner, data);
         }
     };
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable.js
index 124c325c445dce34969c7e02a4ad89455daedbcf..c6ef93d332fb64b102a4ec2ba30370e5cc61d384 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/disable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find('label[for="' + $target.find(data.enableBmlPayPal).attr('id') + '"]').removeClass('enabled');
         $target.find(data.enableBmlPayPal + ' option[value="0"]').prop('selected', true);
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/enable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/enable.js
index 1beb826bf39a003926868e7b420537a03686da50..90f7561734f14f34d21e126ba7df9d2d9926dadc 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/enable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/bml/enable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find(data.enableBmlPayPal).prop('disabled', false);
         $target.find(data.enableBmlPayPal + ' option[value="1"]').prop('selected', true);
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/disable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/disable.js
index 8421803de67a2e84fc1030fcb60ab6909547b814..25e7b611a24692ed05b544bb8bcf8e80b05862b3 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/disable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/disable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find(data.enableButton + ' option[value="0"]').prop('selected', true);
         $target.find('label.enabled').removeClass('enabled');
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration-conditional.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration-conditional.js
index bd2c2f62a29f5b20a08910fdf3e2504c584bfdff..55a82e3cc19322136dec33e5b6c14e41ec0525f8 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration-conditional.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration-conditional.js
@@ -3,19 +3,23 @@
  * See COPYING.txt for license details.
  */
 define([
-    'Magento_Paypal/js/rules/paypal/express/lock-configuration'
-], function (lockConfiguration) {
-    "use strict";
+    'Magento_Paypal/js/rules/paypal/express/lock-configuration',
+    'underscore'
+], function (lockConfiguration, _) {
+    'use strict';
+
     return function ($target, $owner, data) {
         var isDisabled = true;
 
         _.every(data.argument, function (name) {
-            if (data.solutionsElements[name]
-                && data.solutionsElements[name].find(data.enableButton).val() == 1
+            if (data.solutionsElements[name] &&
+                data.solutionsElements[name].find(data.enableButton).val() === '1'
             ) {
                 isDisabled = false;
+
                 return isDisabled;
             }
+
             return isDisabled;
         }, this);
 
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration.js
index e549bda0adf3db7d2a8e8f0f626a72097f96530c..351f799b57b28a3739d23f37cb46bc0afaedafe8 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/lock-configuration.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find(data.buttonConfiguration).addClass('disabled')
             .attr('disabled', 'disabled');
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/mark-disable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/mark-disable.js
index 6bcf9a559b39a05e5d9a76ef35afb8e2b029d81a..7943c843b13cde484d9d0baf1149110ac4885754 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/mark-disable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/mark-disable.js
@@ -3,19 +3,23 @@
  * See COPYING.txt for license details.
  */
 define([
-    'Magento_Paypal/js/rules/simple/disable'
-], function (disable) {
-    "use strict";
+    'Magento_Paypal/js/rules/simple/disable',
+    'underscore'
+], function (disable, _) {
+    'use strict';
+
     return function ($target, $owner, data) {
         var isDisabled = true;
 
         _.every(data.argument, function (name) {
-            if (data.solutionsElements[name]
-                && data.solutionsElements[name].find(data.enableButton).val() == 1
+            if (data.solutionsElements[name] &&
+                data.solutionsElements[name].find(data.enableButton).val() === '1'
             ) {
                 isDisabled = false;
+
                 return isDisabled;
             }
+
             return isDisabled;
         }, this);
 
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/unlock-configuration.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/unlock-configuration.js
index 413a8bf08b1d013bfc0c1b0d7f4d49beb25b2997..fda160c6d94f4babe5257180db769a37aa667537 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/unlock-configuration.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/paypal/express/unlock-configuration.js
@@ -2,18 +2,21 @@
  * Copyright © 2015 Magento. All rights reserved.
  * See COPYING.txt for license details.
  */
-define([], function () {
-    "use strict";
+define(['underscore'], function (_) {
+    'use strict';
+
     return function ($target, $owner, data) {
         var isUnlock = true;
 
         _.every(data.argument, function (name) {
-            if (data.solutionsElements[name]
-                && data.solutionsElements[name].find(data.enableButton).val() == 1
+            if (data.solutionsElements[name] &&
+                data.solutionsElements[name].find(data.enableButton).val() === '1'
             ) {
                 isUnlock = false;
+
                 return isUnlock;
             }
+
             return isUnlock;
         }, this);
 
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/disable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/disable.js
index 4b7c4234dd3ede12113f544c9f3c76a3cd72ed41..7531d4fae1aaab06dc14f3ffd611b7bc63508e53 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/disable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/disable.js
@@ -3,7 +3,8 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
+    'use strict';
+
     return function ($target, $owner, data) {
         $target.find(data.enableButton + ' option[value="0"]').prop('selected', true);
         $target.find('label.enabled').removeClass('enabled');
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/mark-enable.js b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/mark-enable.js
index b686f1be7c949c484de9f9dc416611c4459fcb2b..1dec21bb5b4931c2109fe2c3ab4adec651c06c3d 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/mark-enable.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/rules/simple/mark-enable.js
@@ -3,8 +3,9 @@
  * See COPYING.txt for license details.
  */
 define([], function () {
-    "use strict";
-    return function ($target, $owner, data) {
+    'use strict';
+
+    return function ($target) {
         $target.find('.section-config').addClass('enabled');
     };
 });
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/solution.js b/app/code/Magento/Paypal/view/adminhtml/web/js/solution.js
index 787d9e066cdbe0234bb434f57d39919d00639181..4f8de68474d7a53dc3af22f5c73c12e4ce28ef98 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/solution.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/solution.js
@@ -3,39 +3,47 @@
  * See COPYING.txt for license details.
  */
 define([
-    "jquery",
-    "uiClass",
-    "Magento_Paypal/js/rule",
-    "mageUtils",
-    "underscore"
+    'jquery',
+    'uiClass',
+    'Magento_Paypal/js/rule',
+    'mageUtils',
+    'underscore'
 ], function ($, Class, Rule, utils, _) {
-    "use strict";
+    'use strict';
+
     return Class.extend({
         defaults: {
+
             /**
              * The event corresponding to the state change
              */
             systemEvent: 'change',
+
             /**
              * The rules applied after the page is loaded
              */
             afterLoadRules: [],
+
             /**
              * An attribute of the element responsible for the activation of the payment method (data attribute)
              */
             enableButton:   '[data-enable="payment"]',
+
             /**
              * An attribute of the element responsible for the activation of the Payflow Express (data attribute)
              */
             enableExpress:  '[data-enable="express"]',
+
             /**
              * An attribute of the element responsible for the activation of the Payflow Bml (data attribute)
              */
             enableBml:      '[data-enable="bml"]',
+
             /**
              * An attribute of the element responsible for the activation of the PayPal Bml (data attribute)
              */
             enableBmlPayPal:      '[data-enable="bml-api"]',
+
             /**
              * Templates element selectors
              */
@@ -43,100 +51,149 @@ define([
                 elementSelector: 'div.section-config tr[id$="${ $.identifier }"]:first'
             }
         },
+
         /**
          * Constructor
+         *
+         * @param {Object} config
+         * @param {String} identifier
+         * @returns {exports.initialize}
          */
         initialize: function (config, identifier) {
             this.initConfig(config);
             this.$self = this.createElement(identifier);
+
             return this;
         },
+
         /**
          * Initialization events
+         *
+         * @returns {exports.initEvents}
          */
         initEvents: function () {
             _.each(this.config.events, function (elementEvents, selector) {
+
                 var solution = this,
                     selectorButton = solution.$self.find(selector),
                     $self = solution.$self,
                     events = elementEvents;
-                selectorButton.on(solution.systemEvent, function (event) {
+
+                selectorButton.on(solution.systemEvent, function () {
                     _.each(events, function (elementEvent, name) {
+
                         var predicate = elementEvent.predicate,
-                            result = true;
+                            result = true,
+
+                            /**
+                             * @param {Function} functionPredicate
+                             */
+                            predicateCallback = function (functionPredicate) {
+                                result = functionPredicate(solution, predicate.message, predicate.argument);
+
+                                if (result) {
+                                    $self.trigger(name);
+                                } else {
+                                    $self.trigger(predicate.event);
+                                }
+                            };
+
                         if (solution.getValue($(this)) === elementEvent.value) {
                             if (predicate.name) {
                                 require([
                                     'Magento_Paypal/js/predicate/' + predicate.name
-                                ], function (functionPredicate) {
-                                    result = functionPredicate(solution, predicate.message, predicate.argument);
-                                    if (result) {
-                                        $self.trigger(name);
-                                    } else {
-                                        $self.trigger(predicate.event);
-                                    }
-                                });
+                                ], predicateCallback);
                             } else {
                                 $self.trigger(name);
                             }
-                            }
+                        }
                     }, this);
-                    });
+                });
             }, this);
+
             return this;
         },
 
+        /**
+         * @param {Object} $element
+         * @returns {*}
+         */
         getValue: function ($element) {
             if ($element.is(':checkbox')) {
                 return $element.prop('checked') ? '1' : '0';
             }
+
             return $element.val();
         },
+
         /**
          * Adding event listeners
+         *
+         * @returns {exports.addListeners}
          */
         addListeners: function () {
+
             _.each(this.config.relations, function (rules, targetName) {
+
                 var $target = this.createElement(targetName);
-                _.each(rules, function (rule, name) {
-                    var handler = new Rule({
-                        name :name,
-                        $target: $target,
-                        $owner: this.$self,
-                        data: {
-                            buttonConfiguration: this.buttonConfiguration,
-                            enableButton: this.enableButton,
-                            enableExpress: this.enableExpress,
-                            enableBml: this.enableBml,
-                            enableBmlPayPal: this.enableBmlPayPal,
-                            solutionsElements: this.solutionsElements,
-                            argument: rule.argument
+
+                _.each(rules, function (instances, instanceName) {
+
+                    _.each(instances, function (instance) {
+                        var handler = new Rule({
+                            name: instanceName,
+                            $target: $target,
+                            $owner: this.$self,
+                            data: {
+                                buttonConfiguration: this.buttonConfiguration,
+                                enableButton: this.enableButton,
+                                enableExpress: this.enableExpress,
+                                enableBml: this.enableBml,
+                                enableBmlPayPal: this.enableBmlPayPal,
+                                solutionsElements: this.solutionsElements,
+                                argument: instance.argument
+                            }
+                        });
+
+                        if (instance.event === ':load') {
+                            this.afterLoadRules.push(handler);
+
+                            return;
                         }
-                    });
-                    if (rule.event === ':load') {
-                        this.afterLoadRules.push(handler);
-                        return;
-                    }
-                    this.$self.on(rule.event, _.bind(handler.apply, handler));
+
+                        this.$self.on(instance.event, _.bind(handler.apply, handler));
+                    }, this);
                 }, this);
             }, this);
+
             return this;
         },
+
         /**
          * Create a jQuery element according to selector
+         *
+         * @param {String} identifier
+         * @returns {*}
          */
         createElement: function (identifier) {
-            if (':self' === identifier) {
+            if (identifier === ':self') {
                 return this.$self;
             }
-            var selector = utils.template(this.templates.elementSelector, {identifier: identifier});
-            return $(selector);
+
+            return $(utils.template(this.templates.elementSelector, {
+                'identifier': identifier
+            }));
         },
+
         /**
          * Assign solutions elements
+         *
+         * @param {Object} elements
+         * @returns {exports.setSolutionsElements}
          */
         setSolutionsElements: function (elements) {
             this.solutionsElements = elements;
+
             return this;
         }
     });
diff --git a/app/code/Magento/Paypal/view/adminhtml/web/js/solutions.js b/app/code/Magento/Paypal/view/adminhtml/web/js/solutions.js
index b1e124aca387a556069a776721a90d0c529db62a..f92a531e91414da86c78fcc564d8accf96a32191 100644
--- a/app/code/Magento/Paypal/view/adminhtml/web/js/solutions.js
+++ b/app/code/Magento/Paypal/view/adminhtml/web/js/solutions.js
@@ -3,47 +3,64 @@
  * See COPYING.txt for license details.
  */
 define([
-    "jquery",
-    "uiClass",
-    "Magento_Paypal/js/solution",
-    "underscore"
+    'jquery',
+    'uiClass',
+    'Magento_Paypal/js/solution',
+    'underscore'
 ], function ($, Class, Solution, _) {
-    "use strict";
+    'use strict';
+
     return Class.extend({
         defaults: {
+
             /**
              * Initialized solutions
              */
             solutions: {},
+
             /**
              * The elements of created solutions
              */
             solutionsElements: {},
+
             /**
              * The selector element responsible for configuration of payment method (CSS class)
              */
             buttonConfiguration: '.button.action-configure'
         },
+
         /**
          * Constructor
+         *
+         * @param {Object} config
+         * @returns {exports.initialize}
          */
         initialize: function (config) {
             this.initConfig(config)
                 .initSolutions();
+
             return this;
         },
+
         /**
          * Initialization and configuration solutions
+         *
+         * @returns {exports.initSolutions}
          */
         initSolutions: function () {
             _.each(this.config.solutions, this.addSolution, this);
             this.initializeSolutions()
                 .wipeButtonsConfiguration();
             _.each(this.solutions, this.applicationRules);
+
             return this;
         },
+
         /**
          * The creation and addition of the solution according to the configuration
+         *
+         * @param {Object} solution
+         * @param {String} identifier
          */
         addSolution: function (solution, identifier) {
             this.solutions[identifier] = new Solution({
@@ -52,6 +69,7 @@ define([
             }, identifier);
             this.solutionsElements[identifier] = this.solutions[identifier].$self;
         },
+
         /**
          * Wiping buttons configuration of the payment method
          */
@@ -59,16 +77,22 @@ define([
             $(this.buttonConfiguration).removeClass('disabled')
                 .removeAttr('disabled');
         },
+
         /**
          * Application of the rules
+         *
+         * @param {Object} solution
          */
         applicationRules: function (solution) {
             _.each(solution.afterLoadRules, function (rule) {
                 rule.apply();
             });
         },
+
         /**
          * Initialize solutions
+         *
+         * @returns {exports.initializeSolutions}
          */
         initializeSolutions: function () {
             _.each(this.solutions, function (solution) {
@@ -76,6 +100,7 @@ define([
                     .initEvents()
                     .addListeners();
             }, this);
+
             return this;
         }
     });
diff --git a/app/code/Magento/Paypal/view/frontend/templates/express/review.phtml b/app/code/Magento/Paypal/view/frontend/templates/express/review.phtml
index 892e8771da7dce8e89e43717a2cf0fbfd5f626da..9146130881cabf5d0bd40352950db4b897b58b4a 100644
--- a/app/code/Magento/Paypal/view/frontend/templates/express/review.phtml
+++ b/app/code/Magento/Paypal/view/frontend/templates/express/review.phtml
@@ -84,7 +84,7 @@
                     </strong>
                     <div class="box-content">
                         <address>
-                            <?php /* @noEscape */ echo $block->renderAddress($block->getShippingAddress()); ?>
+                            <?php echo $block->escapeHtml($block->renderAddress($block->getShippingAddress())); ?>
                         </address>
                     </div>
                     <?php if ($block->getCanEditShippingAddress()): ?>
diff --git a/app/code/Magento/Paypal/view/frontend/templates/express/shortcut.phtml b/app/code/Magento/Paypal/view/frontend/templates/express/shortcut.phtml
index fa9afa80e5fa8abd356ed6ccfe3d54e80e3638a4..5858917ed8964d3c56b696e78d787f33f411819b 100644
--- a/app/code/Magento/Paypal/view/frontend/templates/express/shortcut.phtml
+++ b/app/code/Magento/Paypal/view/frontend/templates/express/shortcut.phtml
@@ -43,9 +43,7 @@ if ($block->getConfirmationUrl() || $block->getIsInCatalogProduct()) {
     {
         ".paypal-logo.<?php /* @noEscape */ echo $shortcutHtmlId; ?>": {
             "paypalCheckout": {
-                "confirmMessage": "<?php /* @noEscape */ echo $block->escapeJsQuote(
-                        $block->getConfirmationMessage()
-                    ); ?>",
+                "confirmMessage": "<?php /* @noEscape */ echo $block->escapeJsQuote($block->getConfirmationMessage()); ?>",
                 "confirmUrl": "<?php /* @noEscape */ echo !empty($confirmationUrl) ? $confirmationUrl : false; ?>",
                 "isCatalogProduct": "<?php /* @noEscape */ echo !empty($isInCatalogProduct) ?
                         (bool)$isInCatalogProduct : false;
diff --git a/app/code/Magento/Paypal/view/frontend/templates/hss/info.phtml b/app/code/Magento/Paypal/view/frontend/templates/hss/info.phtml
index 69bf40f9314e3efe35056fa5b0b1bc1915f61c33..c29f82418f83748e61f17632a13f6c891276bf38 100644
--- a/app/code/Magento/Paypal/view/frontend/templates/hss/info.phtml
+++ b/app/code/Magento/Paypal/view/frontend/templates/hss/info.phtml
@@ -11,7 +11,8 @@
  * @see \Magento\Paypal\Block\Payflow\Link\Info
  */
 ?>
-<div id="payment_form_<?php /* @noEscape */ echo $block->getMethodCode(); ?>" style="display:none" class="hss items">
+<div id="payment_form_<?php echo $block->escapeHtml($block->getMethodCode()); ?>"
+     style="display:none" class="hss items">
     <?php echo $block->escapeHtml(__(
         'You will be required to enter your payment details after you place an order.'
     )); ?>
diff --git a/app/code/Magento/Paypal/view/frontend/templates/payflowadvanced/info.phtml b/app/code/Magento/Paypal/view/frontend/templates/payflowadvanced/info.phtml
index a11a3786c2c2d9f40e13dddb8b5546c6d546016c..252622af0f40880c76412aa4a06e29d066275e05 100644
--- a/app/code/Magento/Paypal/view/frontend/templates/payflowadvanced/info.phtml
+++ b/app/code/Magento/Paypal/view/frontend/templates/payflowadvanced/info.phtml
@@ -9,7 +9,7 @@
  * @var \Magento\Paypal\Block\Payflow\Advanced\Form $block
  */
 ?>
-<fieldset id="payment_form_<?php /* @noEscape */ echo $block->getMethodCode(); ?>" style="display:none"
+<fieldset id="payment_form_<?php echo $block->escapeHtml($block->getMethodCode()); ?>" style="display:none"
           class="fieldset payflowadvanced items redirect">
     <div>
         <?php echo $block->escapeHtml(__('You will be required to enter your payment details after you place an order.')); ?>
diff --git a/app/code/Magento/Paypal/view/frontend/templates/payflowlink/info.phtml b/app/code/Magento/Paypal/view/frontend/templates/payflowlink/info.phtml
index 629141539e2aacd9865c42e85ec04396fc77a999..7296aaabccf4ea15d86f1be1ef07fcf62950b08d 100644
--- a/app/code/Magento/Paypal/view/frontend/templates/payflowlink/info.phtml
+++ b/app/code/Magento/Paypal/view/frontend/templates/payflowlink/info.phtml
@@ -8,7 +8,7 @@
  * @var \Magento\Paypal\Block\Payflow\Link\Form $block
  */
 ?>
-<div class="payflowlink items" id="payment_form_<?php /* @noEscape */ echo $block->getMethodCode(); ?>"
+<div class="payflowlink items" id="payment_form_<?php echo $block->escapeHtml($block->getMethodCode()); ?>"
      style="display:none">
     <?php echo $block->escapeHtml(__('You will be required to enter your payment details after you place an order.'));?>
 </div>
diff --git a/app/code/Magento/Paypal/view/frontend/templates/payment/form/billing/agreement.phtml b/app/code/Magento/Paypal/view/frontend/templates/payment/form/billing/agreement.phtml
index 834a623d65b3f0b59a37ae59e2cab5e67e3e0695..7eb9423ce3be47a5d0528d786e59d898e0eb5aa3 100644
--- a/app/code/Magento/Paypal/view/frontend/templates/payment/form/billing/agreement.phtml
+++ b/app/code/Magento/Paypal/view/frontend/templates/payment/form/billing/agreement.phtml
@@ -8,7 +8,7 @@
 /**
  * @var \Magento\Paypal\Block\Payment\Form\Billing\Agreement $block
  */
-$code = $block->getMethodCode();
+$code = $block->escapeHtml($block->getMethodCode());
 ?>
 <div class="field items required" id="payment_form_<?php /* @noEscape */ echo $code; ?>" style="display:none;">
     <label for="<?php /* @noEscape */ echo $code; ?>_ba_agreement_id" class="label">
diff --git a/app/code/Magento/Paypal/view/frontend/templates/payment/redirect.phtml b/app/code/Magento/Paypal/view/frontend/templates/payment/redirect.phtml
index 5397d9aba46151905be8f46ee6da030f2567c5eb..b10e2f975964f649791f9c5788d57b76819beb17 100644
--- a/app/code/Magento/Paypal/view/frontend/templates/payment/redirect.phtml
+++ b/app/code/Magento/Paypal/view/frontend/templates/payment/redirect.phtml
@@ -12,7 +12,7 @@
 $code = $block->escapeHtml($block->getBillingAgreementCode());
 ?>
 <fieldset class="fieldset paypal items redirect" style="display:none;"
-          id="payment_form_<?php /* @noEscape */ echo $block->getMethodCode(); ?>">
+          id="payment_form_<?php echo $block->escapeHtml($block->getMethodCode()); ?>">
     <div><?php echo $block->escapeHtml($block->getRedirectMessage()); ?></div>
     <?php  ?>
     <?php if ($code): ?>
diff --git a/app/code/Magento/Sales/Model/Order/Payment.php b/app/code/Magento/Sales/Model/Order/Payment.php
index 690bde68d5c575ece27f56d68165d1ccf31bc7d5..83cf0853fdab41721a8bde05cdfc46426fc6cd94 100644
--- a/app/code/Magento/Sales/Model/Order/Payment.php
+++ b/app/code/Magento/Sales/Model/Order/Payment.php
@@ -629,7 +629,7 @@ class Payment extends Info implements OrderPaymentInterface
                     $this->getOrder()->getId()
                 );
                 if ($captureTxn) {
-                    $this->setParentTransactionId($captureTxn->getTxnId());
+                    $this->setTransactionIdsForRefund($captureTxn);
                 }
                 $this->setShouldCloseParentTransaction(true);
                 // TODO: implement multiple refunds per capture
@@ -638,10 +638,7 @@ class Payment extends Info implements OrderPaymentInterface
                         $this->getOrder()->getStoreId()
                     );
                     $this->setRefundTransactionId($invoice->getTransactionId());
-                    $gateway->refund(
-                        $this,
-                        $baseAmountToRefund
-                    );
+                    $gateway->refund($this, $baseAmountToRefund);
 
                     $creditmemo->setTransactionId($this->getLastTransId());
                 } catch (\Magento\Framework\Exception\LocalizedException $e) {
@@ -1263,16 +1260,8 @@ class Payment extends Info implements OrderPaymentInterface
      */
     public function isCaptureFinal($amountToCapture)
     {
-        $amountPaid = $this->formatAmount($this->getBaseAmountPaid(), true);
-        $amountToCapture = $this->formatAmount($amountToCapture, true);
-        $orderGrandTotal = $this->formatAmount($this->getOrder()->getBaseGrandTotal(), true);
-        if ($orderGrandTotal == $amountPaid + $amountToCapture) {
-            if (false !== $this->getShouldCloseParentTransaction()) {
-                $this->setShouldCloseParentTransaction(true);
-            }
-            return true;
-        }
-        return false;
+        $total = $this->getOrder()->getTotalDue();
+        return $this->formatAmount($total, true) == $this->formatAmount($amountToCapture, true);
     }
 
     /**
@@ -2414,5 +2403,24 @@ class Payment extends Info implements OrderPaymentInterface
         return (bool)$this->getData('should_close_parent_transaction');
     }
 
+    /**
+     * Set payment parent transaction id and current transaction id if it not set
+     * @param Transaction $transaction
+     * @return void
+     */
+    private function setTransactionIdsForRefund(Transaction $transaction)
+    {
+        if (!$this->getTransactionId()) {
+            $this->setTransactionId(
+                $this->transactionManager->generateTransactionId(
+                    $this,
+                    Transaction::TYPE_REFUND,
+                    $transaction
+                )
+            );
+        }
+        $this->setParentTransactionId($transaction->getTxnId());
+    }
+
     //@codeCoverageIgnoreEnd
 }
diff --git a/app/code/Magento/Sales/Model/Order/Payment/Operations/CaptureOperation.php b/app/code/Magento/Sales/Model/Order/Payment/Operations/CaptureOperation.php
index 590422b153130b34b55dddb6f1777fd206ec4149..3bb13ccca2bf88b3d99cce521f59e7e0b6fb2126 100644
--- a/app/code/Magento/Sales/Model/Order/Payment/Operations/CaptureOperation.php
+++ b/app/code/Magento/Sales/Model/Order/Payment/Operations/CaptureOperation.php
@@ -37,13 +37,6 @@ class CaptureOperation extends AbstractOperation
         $amountToCapture = $payment->formatAmount($invoice->getBaseGrandTotal());
         $order = $payment->getOrder();
 
-        // prepare parent transaction and its amount
-        $paidWorkaround = 0;
-        if (!$invoice->wasPayCalled()) {
-            $paidWorkaround = (double)$amountToCapture;
-        }
-        $payment->isCaptureFinal($paidWorkaround);
-
         $payment->setTransactionId(
             $this->transactionManager->generateTransactionId(
                 $payment,
@@ -72,38 +65,48 @@ class CaptureOperation extends AbstractOperation
             );
         }
 
-        if (!$invoice->getIsPaid()) {
-            // attempt to capture: this can trigger "is_transaction_pending"
-            $method = $payment->getMethodInstance();
-            $method->setStore(
-                $order->getStoreId()
+        if ($invoice->getIsPaid()) {
+            throw new \Magento\Framework\Exception\LocalizedException(
+                __('The transaction "%1" cannot be captured yet.', $invoice->getTransactionId())
             );
-            //TODO replace for sale usage
-            $method->capture($payment, $amountToCapture);
+        }
+
+        // attempt to capture: this can trigger "is_transaction_pending"
+        $method = $payment->getMethodInstance();
+        $method->setStore(
+            $order->getStoreId()
+        );
+        //TODO replace for sale usage
+        $method->capture($payment, $amountToCapture);
 
-            $transactionBuilder = $this->transactionBuilder->setPayment($payment);
-            $transactionBuilder->setOrder($order);
-            $transactionBuilder->setFailSafe(true);
-            $transactionBuilder->setTransactionId($payment->getTransactionId());
-            $transactionBuilder->setAdditionalInformation($payment->getTransactionAdditionalInfo());
-            $transactionBuilder->setSalesDocument($invoice);
-            $transaction = $transactionBuilder->build(Transaction::TYPE_CAPTURE);
+        // prepare parent transaction and its amount
+        $paidWorkaround = 0;
+        if (!$invoice->wasPayCalled()) {
+            $paidWorkaround = (double)$amountToCapture;
+        }
+        if ($payment->isCaptureFinal($paidWorkaround)) {
+            $payment->setShouldCloseParentTransaction(true);
+        }
 
-            $message = $this->stateCommand->execute($payment, $amountToCapture, $order);
-            if ($payment->getIsTransactionPending()) {
-                $invoice->setIsPaid(false);
-            } else {
-                $invoice->setIsPaid(true);
-                $this->updateTotals($payment, ['base_amount_paid_online' => $amountToCapture]);
-            }
-            $message = $payment->prependMessage($message);
-            $payment->addTransactionCommentsToOrder($transaction, $message);
-            $invoice->setTransactionId($payment->getLastTransId());
+        $transactionBuilder = $this->transactionBuilder->setPayment($payment);
+        $transactionBuilder->setOrder($order);
+        $transactionBuilder->setFailSafe(true);
+        $transactionBuilder->setTransactionId($payment->getTransactionId());
+        $transactionBuilder->setAdditionalInformation($payment->getTransactionAdditionalInfo());
+        $transactionBuilder->setSalesDocument($invoice);
+        $transaction = $transactionBuilder->build(Transaction::TYPE_CAPTURE);
 
-            return $payment;
+        $message = $this->stateCommand->execute($payment, $amountToCapture, $order);
+        if ($payment->getIsTransactionPending()) {
+            $invoice->setIsPaid(false);
+        } else {
+            $invoice->setIsPaid(true);
+            $this->updateTotals($payment, ['base_amount_paid_online' => $amountToCapture]);
         }
-        throw new \Magento\Framework\Exception\LocalizedException(
-            __('The transaction "%1" cannot be captured yet.', $invoice->getTransactionId())
-        );
+        $message = $payment->prependMessage($message);
+        $payment->addTransactionCommentsToOrder($transaction, $message);
+        $invoice->setTransactionId($payment->getLastTransId());
+
+        return $payment;
     }
 }
diff --git a/app/code/Magento/Sales/Model/Order/Payment/Operations/RegisterCaptureNotificationOperation.php b/app/code/Magento/Sales/Model/Order/Payment/Operations/RegisterCaptureNotificationOperation.php
index 7c5e892ce035878f1ae41ee5c55d89c0bab8056c..8b7759b79a680079aadee62d56279e59a267cc2d 100644
--- a/app/code/Magento/Sales/Model/Order/Payment/Operations/RegisterCaptureNotificationOperation.php
+++ b/app/code/Magento/Sales/Model/Order/Payment/Operations/RegisterCaptureNotificationOperation.php
@@ -44,6 +44,7 @@ class RegisterCaptureNotificationOperation extends AbstractOperation
                 $invoice->setOrder($order);
                 $order->addRelatedObject($invoice);
                 $payment->setCreatedInvoice($invoice);
+                $payment->setShouldCloseParentTransaction(true);
             } else {
                 $payment->setIsFraudDetected(!$skipFraudDetection);
                 $this->updateTotals($payment, ['base_amount_paid_online' => $amount]);
diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentTest.php
index 29757fc570f2380410376d09d3ca137062ffad9d..b56c83e38d724a1783f82744e4c53d69846e42d8 100644
--- a/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentTest.php
+++ b/app/code/Magento/Sales/Test/Unit/Model/Order/PaymentTest.php
@@ -17,6 +17,8 @@ use Magento\Sales\Model\Order\Payment\Transaction;
  */
 class PaymentTest extends \PHPUnit_Framework_TestCase
 {
+    const TRANSACTION_ID = 'ewr34fM49V0';
+
     private $mockContext;
     /**
      * @var Payment
@@ -166,6 +168,7 @@ class PaymentTest extends \PHPUnit_Framework_TestCase
                     'order',
                     'isInitializeNeeded',
                     'initialize',
+                    'refund'
                 ]
             )
             ->getMock();
@@ -258,7 +261,10 @@ class PaymentTest extends \PHPUnit_Framework_TestCase
                 'register',
                 'addComment',
                 'save',
-                'getGrandTotal'
+                'getGrandTotal',
+                'getBaseGrandTotal',
+                'getDoTransaction',
+                'getInvoice'
             ],
             [],
             '',
@@ -268,7 +274,7 @@ class PaymentTest extends \PHPUnit_Framework_TestCase
         $this->payment = $this->initPayment();
         $this->payment->setMethod('any');
         $this->payment->setOrder($this->orderMock);
-        $this->transactionId = 100;
+        $this->transactionId = self::TRANSACTION_ID;
     }
 
     protected function tearDown()
@@ -825,13 +831,13 @@ class PaymentTest extends \PHPUnit_Framework_TestCase
      */
     protected function mockInvoice($transactionId, $countCall = 1)
     {
-        $this->invoiceMock->expects($this->once())
+        $this->invoiceMock->expects(static::any())
             ->method('getTransactionId')
             ->willReturn($transactionId);
-        $this->invoiceMock->expects($this->once())
+        $this->invoiceMock->expects(static::any())
             ->method('load')
             ->with($transactionId);
-        $this->invoiceMock->expects($this->once())
+        $this->invoiceMock->expects(static::any())
             ->method('getId')
             ->willReturn($transactionId);
         $this->orderMock->expects($this->exactly($countCall))
@@ -1314,7 +1320,8 @@ class PaymentTest extends \PHPUnit_Framework_TestCase
      */
     public function testRegisterRefundNotification()
     {
-        $message = 'Registered notification about refunded amount of . Transaction ID: "100-refund"';
+        $message = 'Registered notification about refunded amount of . Transaction ID: "' .
+            self::TRANSACTION_ID . '-refund"';
         $amount = 50;
         $grandTotalCreditMemo = 50;
         $invoiceBaseGrandTotal = 50;
@@ -1429,6 +1436,73 @@ class PaymentTest extends \PHPUnit_Framework_TestCase
         $this->assertEquals($canRefund, $this->payment->canRefund());
     }
 
+    /**
+     * @covers \Magento\Sales\Model\Order\Payment::refund()
+     */
+    public function testRefund()
+    {
+        $amount = 204.04;
+        $this->creditMemoMock->expects(static::once())
+            ->method('getBaseGrandTotal')
+            ->willReturn($amount);
+        $this->creditMemoMock->expects(static::once())
+            ->method('getGrandTotal')
+            ->willReturn($amount);
+        $this->creditMemoMock->expects(static::once())
+            ->method('getDoTransaction')
+            ->willReturn(true);
+
+        $this->paymentMethodMock->expects(static::once())
+            ->method('canRefund')
+            ->willReturn(true);
+
+        $this->mockInvoice(self::TRANSACTION_ID, 0);
+        $this->creditMemoMock->expects(static::once())
+            ->method('getInvoice')
+            ->willReturn($this->invoiceMock);
+
+        $captureTranId = self::TRANSACTION_ID . '-' . Transaction::TYPE_CAPTURE;
+        $captureTransaction = $this->getMockBuilder(Transaction::class)
+            ->disableOriginalConstructor()
+            ->setMethods(['getTxnId'])
+            ->getMock();
+
+        $refundTranId = $captureTranId . '-' . Transaction::TYPE_REFUND;
+        $this->transactionManagerMock->expects(static::once())
+            ->method('generateTransactionId')
+            ->willReturn($refundTranId);
+        $captureTransaction->expects(static::once())
+            ->method('getTxnId')
+            ->willReturn($captureTranId);
+        $this->transactionRepositoryMock->expects(static::once())
+            ->method('getByTransactionId')
+            ->willReturn($captureTransaction);
+
+        $this->paymentMethodMock->expects(static::once())
+            ->method('refund')
+            ->with($this->payment, $amount);
+
+        $isOnline = true;
+        $this->getTransactionBuilderMock([], $isOnline, Transaction::TYPE_REFUND, $refundTranId);
+
+        $this->currencyMock->expects(static::once())
+            ->method('formatTxt')
+            ->willReturn($amount);
+        $this->orderMock->expects(static::once())
+            ->method('getBaseCurrency')
+            ->willReturn($this->currencyMock);
+
+        $status = 'status';
+        $message = 'We refunded ' . $amount . ' online. Transaction ID: "' . $refundTranId . '"';
+        $this->mockGetDefaultStatus(Order::STATE_PROCESSING, $status);
+        $this->assertOrderUpdated(Order::STATE_PROCESSING, $status, $message);
+
+        static::assertSame($this->payment, $this->payment->refund($this->creditMemoMock));
+        static::assertEquals($amount, $this->payment->getData('amount_refunded'));
+        static::assertEquals($amount, $this->payment->getData('base_amount_refunded_online'));
+        static::assertEquals($amount, $this->payment->getData('base_amount_refunded'));
+    }
+
     public function boolProvider()
     {
         return [
@@ -1437,6 +1511,36 @@ class PaymentTest extends \PHPUnit_Framework_TestCase
         ];
     }
 
+    /**
+     * @covers \Magento\Sales\Model\Order\Payment::isCaptureFinal()
+     * @return void
+     */
+    public function testIsCaptureFinal()
+    {
+        $amount = 23.02;
+        $partialAmount = 12.00;
+
+        $this->orderMock->expects(static::exactly(2))
+            ->method('getTotalDue')
+            ->willReturn($amount);
+
+        static::assertFalse($this->payment->isCaptureFinal($partialAmount));
+        static::assertTrue($this->payment->isCaptureFinal($amount));
+    }
+
+    /**
+     * @covers \Magento\Sales\Model\Order\Payment::getShouldCloseParentTransaction()
+     * @return void
+     */
+    public function testGetShouldCloseParentTransaction()
+    {
+        $this->payment->setShouldCloseParentTransaction(1);
+        static::assertTrue($this->payment->getShouldCloseParentTransaction());
+
+        $this->payment->setShouldCloseParentTransaction(0);
+        static::assertFalse($this->payment->getShouldCloseParentTransaction());
+    }
+
     protected function initPayment()
     {
         return (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this))->getObject(
diff --git a/app/code/Magento/Ups/view/adminhtml/templates/system/shipping/carrier_config.phtml b/app/code/Magento/Ups/view/adminhtml/templates/system/shipping/carrier_config.phtml
index c3ca415c7c2869ffad51232487b894c7599a2f9f..7cffb845b9387b55dbb5d51eb89e8d332ee9b3bb 100644
--- a/app/code/Magento/Ups/view/adminhtml/templates/system/shipping/carrier_config.phtml
+++ b/app/code/Magento/Ups/view/adminhtml/templates/system/shipping/carrier_config.phtml
@@ -20,19 +20,19 @@ if (!$storeCode && $websiteCode) {
     /** @var $web \Magento\Store\Model\Website */
     $web = $block->getWebsiteModel()->load($websiteCode);
     $storedAllowedMethods = explode(',', $web->getConfig('carriers/ups/allowed_methods'));
-    $storedOriginShipment = $web->getConfig('carriers/ups/origin_shipment');
-    $storedFreeShipment   = $web->getConfig('carriers/ups/free_method');
-    $storedUpsType        = $web->getConfig('carriers/ups/type');
+    $storedOriginShipment = $block->escapeHtml($web->getConfig('carriers/ups/origin_shipment'));
+    $storedFreeShipment   = $block->escapeHtml($web->getConfig('carriers/ups/free_method'));
+    $storedUpsType        = $block->escapeHtml($web->getConfig('carriers/ups/type'));
 } elseif ($storeCode) {
     $storedAllowedMethods = explode(',', $block->getConfig('carriers/ups/allowed_methods', $storeCode));
-    $storedOriginShipment = $block->getConfig('carriers/ups/origin_shipment', $storeCode);
-    $storedFreeShipment   = $block->getConfig('carriers/ups/free_method', $storeCode);
-    $storedUpsType        = $block->getConfig('carriers/ups/type', $storeCode);
+    $storedOriginShipment = $block->escapeHtml($block->getConfig('carriers/ups/origin_shipment', $storeCode));
+    $storedFreeShipment   = $block->escapeHtml($block->getConfig('carriers/ups/free_method', $storeCode));
+    $storedUpsType        = $block->escapeHtml($block->getConfig('carriers/ups/type', $storeCode));
 } else {
     $storedAllowedMethods = explode(',', $block->getConfig('carriers/ups/allowed_methods'));
-    $storedOriginShipment = $block->getConfig('carriers/ups/origin_shipment');
-    $storedFreeShipment   = $block->getConfig('carriers/ups/free_method');
-    $storedUpsType        = $block->getConfig('carriers/ups/type');
+    $storedOriginShipment = $block->escapeHtml($block->getConfig('carriers/ups/origin_shipment'));
+    $storedFreeShipment   = $block->escapeHtml($block->getConfig('carriers/ups/free_method'));
+    $storedUpsType        = $block->escapeHtml($block->getConfig('carriers/ups/type'));
 }
 ?>
 <script>
diff --git a/dev/tests/integration/testsuite/Magento/Framework/Code/GeneratorTest.php b/dev/tests/integration/testsuite/Magento/Framework/Code/GeneratorTest.php
index e31201caf943440ce75a00725b65c79cde471c29..81fcb128903e1059ea0190b5b6d63b137c448d9d 100644
--- a/dev/tests/integration/testsuite/Magento/Framework/Code/GeneratorTest.php
+++ b/dev/tests/integration/testsuite/Magento/Framework/Code/GeneratorTest.php
@@ -95,7 +95,9 @@ class GeneratorTest extends \PHPUnit_Framework_TestCase
         // This test is only valid if the factory created the object if Autoloader did not pick it up automatically
         if (\Magento\Framework\Code\Generator::GENERATION_SUCCESS == $generatorResult) {
             $content = $this->_clearDocBlock(
-                file_get_contents($this->_ioObject->getResultFileName(self::CLASS_NAME_WITH_NAMESPACE . 'Factory'))
+                file_get_contents(
+                    $this->_ioObject->generateResultFileName(self::CLASS_NAME_WITH_NAMESPACE . 'Factory')
+                )
             );
             $expectedContent = $this->_clearDocBlock(
                 file_get_contents(__DIR__ . '/_expected/SourceClassWithNamespaceFactory.php.sample')
@@ -120,7 +122,7 @@ class GeneratorTest extends \PHPUnit_Framework_TestCase
         // This test is only valid if the factory created the object if Autoloader did not pick it up automatically
         if (\Magento\Framework\Code\Generator::GENERATION_SUCCESS == $generatorResult) {
             $content = $this->_clearDocBlock(
-                file_get_contents($this->_ioObject->getResultFileName(self::CLASS_NAME_WITH_NAMESPACE . '\Proxy'))
+                file_get_contents($this->_ioObject->generateResultFileName(self::CLASS_NAME_WITH_NAMESPACE . '\Proxy'))
             );
             $expectedContent = $this->_clearDocBlock(
                 file_get_contents(__DIR__ . '/_expected/SourceClassWithNamespaceProxy.php.sample')
@@ -142,7 +144,7 @@ class GeneratorTest extends \PHPUnit_Framework_TestCase
         if (\Magento\Framework\Code\Generator::GENERATION_SUCCESS == $generatorResult) {
             $content = $this->_clearDocBlock(
                 file_get_contents(
-                    $this->_ioObject->getResultFileName(self::CLASS_NAME_WITH_NAMESPACE . '\Interceptor')
+                    $this->_ioObject->generateResultFileName(self::CLASS_NAME_WITH_NAMESPACE . '\Interceptor')
                 )
             );
             $expectedContent = $this->_clearDocBlock(
diff --git a/dev/tests/integration/testsuite/Magento/Paypal/_files/ipn.php b/dev/tests/integration/testsuite/Magento/Paypal/_files/ipn.php
index 5c27950d64f00760345068372d780397163c04f0..3949117079b68d8ecc8a93bcd86dac4a886b87ce 100644
--- a/dev/tests/integration/testsuite/Magento/Paypal/_files/ipn.php
+++ b/dev/tests/integration/testsuite/Magento/Paypal/_files/ipn.php
@@ -8,6 +8,7 @@ return [
     'mc_gross' => '100.00',
     'invoice' => '100000001',
     'payment_status' => 'Completed',
+    'auth_status' => 'Completed',
     'mc_currency' => 'USD',
     'receiver_email' => 'merchant_2012050718_biz@example.com'
 ];
diff --git a/dev/tests/integration/testsuite/Magento/Paypal/_files/order_express.php b/dev/tests/integration/testsuite/Magento/Paypal/_files/order_express.php
index cc659a62b1eb2361855aa61bfeb812ff92966c2d..9fbab06028d7988f983157325c5f8e64fdb38eec 100644
--- a/dev/tests/integration/testsuite/Magento/Paypal/_files/order_express.php
+++ b/dev/tests/integration/testsuite/Magento/Paypal/_files/order_express.php
@@ -18,30 +18,21 @@ $shippingAddress->setId(null)->setAddressType('shipping');
 $payment = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\Sales\Model\Order\Payment');
 $payment->setMethod(\Magento\Paypal\Model\Config::METHOD_WPP_EXPRESS);
 
-$order = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\Sales\Model\Order');
-$order
-    ->setCustomerEmail('co@co.co')
-    ->setIncrementId(
-    '100000001'
-)->setSubtotal(
-    100
-)->setBaseSubtotal(
-    100
-)->setBaseGrandTotal(
-    100
-)->setBaseCurrencyCode(
-    'USD'
-)->setCustomerIsGuest(
-    true
-)->setStoreId(
-    1
-)->setEmailSent(
-    1
-)->setBillingAddress(
-    $billingAddress
-)->setShippingAddress(
-    $shippingAddress
-)->setPayment(
-    $payment
-);
+$amount = 100;
+
+/** @var \Magento\Sales\Model\Order $order */
+$order = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(Magento\Sales\Model\Order::class);
+$order->setCustomerEmail('co@co.co')
+    ->setIncrementId('100000001')
+    ->setSubtotal($amount)
+    ->setBaseSubtotal($amount)
+    ->setBaseGrandTotal($amount)
+    ->setGrandTotal($amount)
+    ->setBaseCurrencyCode('USD')
+    ->setCustomerIsGuest(true)
+    ->setStoreId(1)
+    ->setEmailSent(true)
+    ->setBillingAddress($billingAddress)
+    ->setShippingAddress($shippingAddress)
+    ->setPayment($payment);
 $order->save();
diff --git a/dev/tests/integration/testsuite/Magento/Setup/Console/Command/I18nCollectPhrasesCommandTest.php b/dev/tests/integration/testsuite/Magento/Setup/Console/Command/I18nCollectPhrasesCommandTest.php
index 924853df6bc0c75cb219ec88afb42317c33d4f1d..2d5e9026ceefe6e4853e08e3e3859b681e6ab6ea 100644
--- a/dev/tests/integration/testsuite/Magento/Setup/Console/Command/I18nCollectPhrasesCommandTest.php
+++ b/dev/tests/integration/testsuite/Magento/Setup/Console/Command/I18nCollectPhrasesCommandTest.php
@@ -46,17 +46,19 @@ class I18nCollectPhrasesCommandTest extends \PHPUnit_Framework_TestCase
 
     public function testExecuteCsvOutput()
     {
-        $outputPath = BP . '/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/output/output.csv';
+        $outputPath = BP . '/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/output/phrases.csv';
         $this->tester->execute(
             [
-                'directory' => BP . '/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/',
+                'directory' => BP . '/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/phrases/',
                 '--output' => $outputPath,
             ]
         );
 
         $handle = fopen($outputPath, 'r');
         $output = fread($handle, filesize($outputPath));
-        $expected = '"Hello world","Hello world"' . PHP_EOL . '"Foo bar","Foo bar"' . PHP_EOL;
+        $expected = file_get_contents(
+            BP . '/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/expectedPhrases.csv'
+        );
         $this->assertEquals($expected, $output);
         unlink($outputPath);
     }
diff --git a/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/Magento/TestModule/Phrases.php b/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/Magento/TestModule/Phrases.php
deleted file mode 100644
index d55885ff96f2b8da7acce4f97c505fa2a6b8aa76..0000000000000000000000000000000000000000
--- a/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/Magento/TestModule/Phrases.php
+++ /dev/null
@@ -1,7 +0,0 @@
-<?php
-/**
- * Copyright © 2015 Magento. All rights reserved.
- * See COPYING.txt for license details.
- */
-$a = __("Hello world");
-$b = __("Foo bar");
diff --git a/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/expectedPhrases.csv b/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/expectedPhrases.csv
new file mode 100644
index 0000000000000000000000000000000000000000..43c331ecb48d6faa3e12d04eccb53d992779e907
--- /dev/null
+++ b/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/expectedPhrases.csv
@@ -0,0 +1,19 @@
+"simple text","simple text"
+"simple text with 1 string literal placeholder %1","simple text with 1 string literal placeholder %1"
+"simple text with 1 variable placeholder %1","simple text with 1 variable placeholder %1"
+"simple text with multiple placeholders %1 %2","simple text with multiple placeholders %1 %2"
+"first part second part","first part second part"
+"first part second part third part","first part second part third part"
+"first part second part with one string literal placeholder %1","first part second part with one string literal placeholder %1"
+"first part of concat second part with one variable placeholder %1","first part of concat second part with one variable placeholder %1"
+"first part of concat second part with two placeholders %1, %2","first part of concat second part with two placeholders %1, %2"
+"first part of concat second part third part with one placeholder %1","first part of concat second part third part with one placeholder %1"
+"first part of concat second part third part with two placeholders %1, %2","first part of concat second part third part with two placeholders %1, %2"
+"string with escaped 'single quotes'","string with escaped 'single quotes'"
+"string with placeholder in escaped single quotes '%1'","string with placeholder in escaped single quotes '%1'"
+"string with ""double quotes""","string with ""double quotes"""
+"string with placeholder in double quotes ""%1""","string with placeholder in double quotes ""%1"""
+"string with 'single quotes'","string with 'single quotes'"
+"string with placeholder in single quotes '%1'","string with placeholder in single quotes '%1'"
+"string with escaped ""double quotes""","string with escaped ""double quotes"""
+"string with placeholder in escaped double quotes ""%1""","string with placeholder in escaped double quotes ""%1"""
diff --git a/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/phrases/TestPhrases.php b/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/phrases/TestPhrases.php
new file mode 100644
index 0000000000000000000000000000000000000000..f3306a521add5a671e626d3cd49c19c9a6640c5f
--- /dev/null
+++ b/dev/tests/integration/testsuite/Magento/Setup/Console/Command/_files/phrases/TestPhrases.php
@@ -0,0 +1,87 @@
+<?php
+/***
+ * Copyright © 2015 Magento. All rights reserved.
+ * See COPYING.txt for license details.
+ */
+
+// @codingStandardsIgnoreFile
+
+use Magento\Framework\Phrase;
+
+/**
+ * @SuppressWarnings(PHPMD)
+ */
+class TestPhrases
+{
+    public function awesomeFunction()
+    {
+        $str1 = 'str1';
+        $str2 = 'str2';
+
+        // Simple
+        $simpleCases = [
+            new Phrase('simple text'),
+            new Phrase('simple text with 1 string literal placeholder %1', 'arg'),
+            new Phrase('simple text with 1 variable placeholder %1', $str1),
+            new Phrase('simple text with multiple placeholders %1 %2', $str1, $str2),
+        ];
+
+        // Phrase objects
+        $phraseObjects = [
+            // Single concatenation
+            new Phrase('first part' . ' second part'),
+            new Phrase('first part' . ' second part' . ' third part'),
+
+            // Multiple concatenation
+            new Phrase('first part' . ' second part with one string literal placeholder %1', 'arg'),
+            new Phrase('first part of concat' . ' second part with one variable placeholder %1', $str1),
+            new Phrase('first part of concat' . ' second part with two placeholders %1, %2', $str1, $str2),
+            new Phrase('first part of concat' . ' second part' . ' third part with one placeholder %1', 'arg'),
+            new Phrase('first part of concat' . ' second part' . ' third part with two placeholders %1, %2', $str1, $str2),
+
+            // Escaped quotes
+            new Phrase('string with escaped \'single quotes\''),
+            new Phrase('string with placeholder in escaped single quotes \'%1\'', 'arg'),
+            new Phrase('string with "double quotes"'),
+            new Phrase('string with placeholder in double quotes "%1"', 'arg'),
+        ];
+
+        $singleQuoteTranslateFunctions = [
+            // Single concatenation
+            __('first part' . ' second part'),
+            __('first part' . ' second part' . ' third part'),
+
+            // Multiple concatenation
+            __('first part' . ' second part with one string literal placeholder %1', 'arg'),
+            __('first part of concat' . ' second part with one variable placeholder %1', $str1),
+            __('first part of concat' . ' second part with two placeholders %1, %2', $str1, $str2),
+            __('first part of concat' . ' second part' . ' third part with one placeholder %1', 'arg'),
+            __('first part of concat' . ' second part' . ' third part with two placeholders %1, %2', $str1, $str2),
+
+            // Escaped quotes
+            __('string with escaped \'single quotes\''),
+            __('string with placeholder in escaped single quotes \'%1\'', 'arg'),
+            __('string with "double quotes"'),
+            __('string with placeholder in double quotes "%1"', 'arg'),
+        ];
+
+        $doubleQuoteTranslateFunctions = [
+            // Single concatenation
+            __("first part" . " second part"),
+            __("first part" . " second part" . " third part"),
+
+            // Multiple concatenation
+            __("first part" . " second part with one string literal placeholder %1", "arg"),
+            __("first part of concat" . " second part with one variable placeholder %1", $str1),
+            __("first part of concat" . " second part with two placeholders %1, %2", $str1, $str2),
+            __("first part of concat" . " second part" . " third part with one placeholder %1", "arg"),
+            __("first part of concat" . " second part" . " third part with two placeholders %1, %2", $str1, $str2),
+
+            // Escaped quotes
+            __("string with 'single quotes'"),
+            __("string with placeholder in single quotes '%1'", "arg"),
+            __("string with escaped \"double quotes\""),
+            __("string with placeholder in escaped double quotes \"%1\"", "arg"),
+        ];
+    }
+}
diff --git a/lib/internal/Magento/Framework/Api/Test/Unit/Code/Generator/EntityChildTestAbstract.php b/lib/internal/Magento/Framework/Api/Test/Unit/Code/Generator/EntityChildTestAbstract.php
index acbc463380d5292bab9de0851a1328ef4cebe3d3..5ea51a6d56024ca4645bcd6d5bbda4c691b65580 100644
--- a/lib/internal/Magento/Framework/Api/Test/Unit/Code/Generator/EntityChildTestAbstract.php
+++ b/lib/internal/Magento/Framework/Api/Test/Unit/Code/Generator/EntityChildTestAbstract.php
@@ -109,7 +109,7 @@ abstract class EntityChildTestAbstract extends \PHPUnit_Framework_TestCase
 
         //Mocking generation
         $this->ioObjectMock->expects($this->any())
-            ->method('getResultFileName')
+            ->method('generateResultFileName')
             ->with($this->getResultClassName())
             ->willReturn($resultFileName);
         $this->ioObjectMock->expects($this->once())
diff --git a/lib/internal/Magento/Framework/Api/Test/Unit/Code/Generator/GenerateMapperTest.php b/lib/internal/Magento/Framework/Api/Test/Unit/Code/Generator/GenerateMapperTest.php
index a78b00f1ceebd60559f0a786342f965d83703b47..bdc11e49ddd360a0dfd281122ae7fef5b503a5c5 100644
--- a/lib/internal/Magento/Framework/Api/Test/Unit/Code/Generator/GenerateMapperTest.php
+++ b/lib/internal/Magento/Framework/Api/Test/Unit/Code/Generator/GenerateMapperTest.php
@@ -51,7 +51,7 @@ class GenerateMapperTest extends \PHPUnit_Framework_TestCase
         );
         $sampleMapperCode = file_get_contents(__DIR__ . '/_files/SampleMapper.txt');
         $this->ioObjectMock->expects($this->once())
-            ->method('getResultFileName')
+            ->method('generateResultFileName')
             ->with('\Magento\Framework\Api\Code\Generator\SampleMapper')
             ->will($this->returnValue('SampleMapper.php'));
         $this->ioObjectMock->expects($this->once())
diff --git a/lib/internal/Magento/Framework/Api/Test/Unit/Code/Generator/GenerateSearchResultsTest.php b/lib/internal/Magento/Framework/Api/Test/Unit/Code/Generator/GenerateSearchResultsTest.php
index 7ee5ff3acff604ad716f27d0886f6ac06c58fc33..1f7609b0e923ceff66ebb81d41786276b79d3700 100644
--- a/lib/internal/Magento/Framework/Api/Test/Unit/Code/Generator/GenerateSearchResultsTest.php
+++ b/lib/internal/Magento/Framework/Api/Test/Unit/Code/Generator/GenerateSearchResultsTest.php
@@ -52,7 +52,7 @@ class GenerateSearchResultsTest extends \PHPUnit_Framework_TestCase
         );
         $sampleSearchResultBuilderCode = file_get_contents(__DIR__ . '/_files/SampleSearchResults.txt');
         $this->ioObjectMock->expects($this->once())
-            ->method('getResultFileName')
+            ->method('generateResultFileName')
             ->with('\Magento\Framework\Api\Code\Generator\SampleSearchResults')
             ->will($this->returnValue('SampleSearchResults.php'));
         $this->ioObjectMock->expects($this->once())
diff --git a/lib/internal/Magento/Framework/Code/Generator.php b/lib/internal/Magento/Framework/Code/Generator.php
index edd02f6c2049282b6af2fa7f3b8e7d2559492857..2a572346e6a60bf2cb149a12f9c2a53d00e0b11d 100644
--- a/lib/internal/Magento/Framework/Code/Generator.php
+++ b/lib/internal/Magento/Framework/Code/Generator.php
@@ -104,25 +104,13 @@ class Generator
                     new \Magento\Framework\Phrase(implode(' ', $errors))
                 );
             }
-            $this->tryToIncludeFile($file, $className);
+            if (!$this->definedClasses->isClassLoadableFromMemory($className)) {
+                $this->_ioObject->includeFile($file);
+            }
             return self::GENERATION_SUCCESS;
         }
     }
 
-    /**
-     * Include file only if the class is not already defined in memory
-     *
-     * @param string $fileName
-     * @param string $className
-     * @return void
-     */
-    public function tryToIncludeFile($fileName, $className)
-    {
-        if (!$this->definedClasses->isClassLoadableFromMemory($className)) {
-            include $fileName;
-        }
-    }
-
     /**
      * Create entity generator
      *
@@ -203,6 +191,16 @@ class Generator
         if (!$resultEntityType || !$sourceClassName) {
             return self::GENERATION_ERROR;
         } else if ($this->definedClasses->isClassLoadableFromDisc($resultClass)) {
+            $generatedFileName = $this->_ioObject->generateResultFileName($resultClass);
+            /**
+             * Must handle two edge cases: a competing process has generated the class and written it to disc already,
+             * or the class exists in committed code, despite matching pattern to be generated.
+             */
+            if ($this->_ioObject->fileExists($generatedFileName)
+                && !$this->definedClasses->isClassLoadableFromMemory($resultClass)
+            ) {
+                $this->_ioObject->includeFile($generatedFileName);
+            }
             return self::GENERATION_SKIP;
         } else if (!isset($this->_generatedEntities[$resultEntityType])) {
             throw new \InvalidArgumentException('Unknown generation entity.');
diff --git a/lib/internal/Magento/Framework/Code/Generator/EntityAbstract.php b/lib/internal/Magento/Framework/Code/Generator/EntityAbstract.php
index fee367f49ca8046d5088bdbda5167bbcab90f82f..aed8424282e8b3e7cfb5c292227752af728fd1c9 100644
--- a/lib/internal/Magento/Framework/Code/Generator/EntityAbstract.php
+++ b/lib/internal/Magento/Framework/Code/Generator/EntityAbstract.php
@@ -97,7 +97,7 @@ abstract class EntityAbstract
             if ($this->_validateData()) {
                 $sourceCode = $this->_generateCode();
                 if ($sourceCode) {
-                    $fileName = $this->_ioObject->getResultFileName($this->_getResultClassName());
+                    $fileName = $this->_ioObject->generateResultFileName($this->_getResultClassName());
                     $this->_ioObject->writeResultFile($fileName, $sourceCode);
                     return $fileName;
                 } else {
@@ -252,9 +252,6 @@ abstract class EntityAbstract
         if (!$this->definedClasses->isClassLoadable($sourceClassName)) {
             $this->_addError('Source class ' . $sourceClassName . ' doesn\'t exist.');
             return false;
-        } elseif ($this->definedClasses->isClassLoadableFromDisc($resultClassName)) {
-            $this->_addError('Result class ' . $resultClassName . ' already exists.');
-            return false;
         } elseif (
             /**
              * If makeResultFileDirectory only fails because the file is already created,
diff --git a/lib/internal/Magento/Framework/Code/Generator/Io.php b/lib/internal/Magento/Framework/Code/Generator/Io.php
index eb6cabeebf911acce56eeba33e087d8e731f15a4..365482c797c4ac937ede669be5e9246ca0d7d792 100644
--- a/lib/internal/Magento/Framework/Code/Generator/Io.php
+++ b/lib/internal/Magento/Framework/Code/Generator/Io.php
@@ -61,7 +61,7 @@ class Io
      */
     public function getResultFileDirectory($className)
     {
-        $fileName = $this->getResultFileName($className);
+        $fileName = $this->generateResultFileName($className);
         $pathParts = explode('/', $fileName);
         unset($pathParts[count($pathParts) - 1]);
 
@@ -72,7 +72,7 @@ class Io
      * @param string $className
      * @return string
      */
-    public function getResultFileName($className)
+    public function generateResultFileName($className)
     {
         return $this->_generationDirectory . ltrim(str_replace(['\\', '_'], '/', $className), '/') . '.php';
     }
@@ -98,7 +98,7 @@ class Io
         try {
             $success = $this->filesystemDriver->rename($tmpFile, $fileName);
         } catch (FileSystemException $e) {
-            if (!file_exists($fileName)) {
+            if (!$this->fileExists($fileName)) {
                 throw $e;
             } else {
                 /**
@@ -146,6 +146,18 @@ class Io
         return $this->filesystemDriver->isExists($fileName);
     }
 
+    /**
+     * Wrapper for include
+     *
+     * @param string $fileName
+     * @return mixed
+     * @codeCoverageIgnore
+     */
+    public function includeFile($fileName)
+    {
+        return include $fileName;
+    }
+
     /**
      * @param string $directory
      * @return bool
diff --git a/lib/internal/Magento/Framework/Code/Test/Unit/Generator/EntityAbstractTest.php b/lib/internal/Magento/Framework/Code/Test/Unit/Generator/EntityAbstractTest.php
index cf74e8a67f1573a8eb9ce202c35014f9ca6e263b..c10467f7cdf4bce65b4687cb90b9a700080a1ad7 100644
--- a/lib/internal/Magento/Framework/Code/Test/Unit/Generator/EntityAbstractTest.php
+++ b/lib/internal/Magento/Framework/Code/Test/Unit/Generator/EntityAbstractTest.php
@@ -103,39 +103,33 @@ class EntityAbstractTest extends \PHPUnit_Framework_TestCase
     {
         return [
             'no_source_class' => [
-                '$errors' => ['Source class ' . self::SOURCE_CLASS . ' doesn\'t exist.'],
-                '$validationSuccess' => false,
-                '$sourceClassExists' => false,
-            ],
-            'result_class_exists' => [
-                '$errors' => ['Result class ' . self::RESULT_CLASS . ' already exists.'],
-                '$validationSuccess' => false,
-                '$sourceClassExists' => true,
-                '$resultClassExists' => true,
+                'errors' => ['Source class ' . self::SOURCE_CLASS . ' doesn\'t exist.'],
+                'validationSuccess' => false,
+                'sourceClassExists' => false,
             ],
             'cant_create_result_directory' => [
-                '$errors' => ['Can\'t create directory ' . self::RESULT_DIRECTORY . '.'],
-                '$validationSuccess' => false,
-                '$sourceClassExists' => true,
-                '$resultClassExists' => false,
-                '$makeResultDirSuccess' => false,
+                'errors' => ['Can\'t create directory ' . self::RESULT_DIRECTORY . '.'],
+                'validationSuccess' => false,
+                'sourceClassExists' => true,
+                'resultClassExists' => false,
+                'makeResultDirSuccess' => false,
             ],
             'result_file_exists' => [
-                '$errors' => [],
-                '$validationSuccess' => true,
-                '$sourceClassExists' => true,
-                '$resultClassExists' => false,
-                '$makeResultDirSuccess' => false,
-                '$resultFileExists' => true,
+                'errors' => [],
+                'validationSuccess' => true,
+                'sourceClassExists' => true,
+                'resultClassExists' => false,
+                'makeResultDirSuccess' => false,
+                'resultFileExists' => true,
             ],
             'generate_no_data' => [
-                '$errors' => ['Can\'t generate source code.'],
-                '$validationSuccess' => true,
-                '$sourceClassExists' => true,
-                '$resultClassExists' => false,
-                '$makeResultDirSuccess' => true,
-                '$resultFileExists' => true,
-                '$willWriteCode' => false,
+                'errors' => ['Can\'t generate source code.'],
+                'validationSuccess' => true,
+                'sourceClassExists' => true,
+                'resultClassExists' => false,
+                'makeResultDirSuccess' => true,
+                'resultFileExists' => true,
+                'willWriteCode' => false,
             ],
             'generate_ok' => []
         ];
@@ -292,7 +286,7 @@ class EntityAbstractTest extends \PHPUnit_Framework_TestCase
         if ($willWriteCode) {
             $ioObject->expects($this->once())->method('writeResultFile')->with(self::RESULT_FILE, self::RESULT_CODE);
         }
-        $ioObject->expects($this->any())->method('getResultFileName')->willReturn(self::RESULT_FILE);
+        $ioObject->expects($this->any())->method('generateResultFileName')->willReturn(self::RESULT_FILE);
 
         return [
             'source_class' => $mocks['source_class'],
diff --git a/lib/internal/Magento/Framework/Code/Test/Unit/Generator/IoTest.php b/lib/internal/Magento/Framework/Code/Test/Unit/Generator/IoTest.php
index bd3a34bc4710363c71d0bbd892364ff6e06714cb..33b12746656a63722623aea045b237712ea6c75f 100644
--- a/lib/internal/Magento/Framework/Code/Test/Unit/Generator/IoTest.php
+++ b/lib/internal/Magento/Framework/Code/Test/Unit/Generator/IoTest.php
@@ -5,6 +5,10 @@
  */
 namespace Magento\Framework\Code\Test\Unit\Generator;
 
+use Magento\Framework\Component\ComponentRegistrar;
+use Magento\Framework\Exception\FileSystemException;
+use Magento\Framework\Phrase;
+
 class IoTest extends \PHPUnit_Framework_TestCase
 {
     /**#@+
@@ -16,8 +20,6 @@ class IoTest extends \PHPUnit_Framework_TestCase
 
     const CLASS_FILE_NAME = 'class/file/name';
 
-    const FILE_NAME = 'test_file';
-
     const FILE_CONTENT = "content";
 
     /**#@-*/
@@ -29,16 +31,18 @@ class IoTest extends \PHPUnit_Framework_TestCase
      */
     protected $_generationDirectory;
 
-    /**
-     * @var \Magento\Framework\Code\Generator\Io
-     */
+    /** @var \Magento\Framework\Code\Generator\Io */
     protected $_object;
 
-    /**
-     * @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject
-     */
+    /** @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject */
     protected $_filesystemDriverMock;
 
+    /** @var string */
+    protected $existingFile = '/Magento/Class/Exists.php';
+
+    /** @var string */
+    protected $nonExistingFile = '/Magento/Class/Does/Not/Exists.php';
+
     protected function setUp()
     {
         $this->_generationDirectory = rtrim(self::GENERATION_DIRECTORY, '/') . '/';
@@ -68,26 +72,68 @@ class IoTest extends \PHPUnit_Framework_TestCase
     public function testGetResultFileName()
     {
         $expectedFileName = self::GENERATION_DIRECTORY . '/class/name.php';
-        $this->assertEquals($expectedFileName, $this->_object->getResultFileName(self::CLASS_NAME));
+        $this->assertEquals($expectedFileName, $this->_object->generateResultFileName(self::CLASS_NAME));
     }
 
-    public function testWriteResultFile()
+    /**
+     * @dataProvider testWriteResultFileAlreadyExistsDataProvider
+     */
+    public function testWriteResultFileAlreadyExists($resultFileName, $fileExists, $exceptionDuringRename, $success)
     {
         $this->_filesystemDriverMock->expects($this->once())
             ->method('filePutContents')
             ->with(
-                $this->stringContains(self::FILE_NAME),
+                $this->stringContains($resultFileName),
                 "<?php\n" . self::FILE_CONTENT
             )->willReturn(true);
+        $isExistsInvocationCount = $exceptionDuringRename ? 1 : 0;
+        $this->_filesystemDriverMock->expects($this->exactly($isExistsInvocationCount))
+            ->method('isExists')
+            ->willReturn($fileExists);
+
+        if (!$exceptionDuringRename) {
+            $renameMockEvent = $this->returnValue(true);
+        } else if ($fileExists) {
+            $renameMockEvent = $this->throwException(new FileSystemException(new Phrase('File already exists')));
+        } else {
+            $exceptionMessage = 'Some error renaming file';
+            $renameMockEvent = $this->throwException(new FileSystemException(new Phrase($exceptionMessage)));
+            $this->setExpectedException('\Magento\Framework\Exception\FileSystemException', $exceptionMessage);
+        }
 
         $this->_filesystemDriverMock->expects($this->once())
             ->method('rename')
             ->with(
-                $this->stringContains(self::FILE_NAME),
-                self::FILE_NAME
-            )->willReturn(true);
+                $this->stringContains($resultFileName),
+                $resultFileName
+            )->will($renameMockEvent); //Throw exception or return true
 
-        $this->assertTrue($this->_object->writeResultFile(self::FILE_NAME, self::FILE_CONTENT));
+        $this->assertSame($success, $this->_object->writeResultFile($resultFileName, self::FILE_CONTENT));
+    }
+
+    public function testWriteResultFileAlreadyExistsDataProvider()
+    {
+        return [
+            'Writing file succeeds: writeResultFile succeeds' => [
+                'resultFileName' => $this->nonExistingFile,
+                'fileExists' => false,
+                'exceptionDuringRename' => false,
+                'success' => true
+
+            ],
+            'Writing file fails because class already exists on disc: writeResultFile succeeds' => [
+                'resultFileName' => $this->existingFile,
+                'fileExists' => true,
+                'exceptionDuringRename' => true,
+                'success' => true
+            ],
+            'Error renaming file, btu class does not exist on disc: writeResultFile throws exception and fails' => [
+                'resultFileName' => $this->nonExistingFile,
+                'fileExists' => false,
+                'exceptionDuringRename' => true,
+                'success' => false
+            ]
+        ];
     }
 
     public function testMakeGenerationDirectoryWritable()
@@ -136,18 +182,31 @@ class IoTest extends \PHPUnit_Framework_TestCase
         $this->assertEquals($this->_generationDirectory, $this->_object->getGenerationDirectory());
     }
 
-    public function testFileExists()
+    /**
+     * @dataProvider fileExistsDataProvider
+     * @param $fileName
+     * @param $exists
+     */
+    public function testFileExists($fileName, $exists)
     {
         $this->_filesystemDriverMock->expects(
             $this->once()
         )->method(
             'isExists'
         )->with(
-            $this->equalTo(self::FILE_NAME)
+            $this->equalTo($fileName)
         )->will(
-            $this->returnValue(false)
+            $this->returnValue($exists)
         );
 
-        $this->assertFalse($this->_object->fileExists(self::FILE_NAME));
+        $this->assertSame($exists, $this->_object->fileExists($fileName));
+    }
+
+    public function fileExistsDataProvider()
+    {
+        return [
+            ['fileName' => $this->existingFile, 'exists' => true],
+            ['fileName' => $this->nonExistingFile, 'exists' => false]
+        ];
     }
 }
diff --git a/lib/internal/Magento/Framework/Code/Test/Unit/GeneratorTest.php b/lib/internal/Magento/Framework/Code/Test/Unit/GeneratorTest.php
index 88a043753daa73776e941541651e7cc3b237e555..c289ba47967435ded674df11cc9af595e280909e 100644
--- a/lib/internal/Magento/Framework/Code/Test/Unit/GeneratorTest.php
+++ b/lib/internal/Magento/Framework/Code/Test/Unit/GeneratorTest.php
@@ -8,6 +8,10 @@
 
 namespace Magento\Framework\Code\Test\Unit;
 
+use Magento\Framework\Code\Generator;
+use Magento\Framework\Code\Generator\DefinedClasses;
+use Magento\Framework\Code\Generator\Io;
+
 class GeneratorTest extends \PHPUnit_Framework_TestCase
 {
     /**
@@ -27,34 +31,41 @@ class GeneratorTest extends \PHPUnit_Framework_TestCase
     ];
 
     /**
-     * Model under test
+     * System under test
      *
      * @var \Magento\Framework\Code\Generator
      */
     protected $model;
 
-    /**
-     * @var \PHPUnit_Framework_MockObject_MockObject|Generator\Io
-     */
+    /** @var \PHPUnit_Framework_MockObject_MockObject|Io */
     protected $ioObjectMock;
 
+    /** @var \Magento\Framework\Code\Generator\DefinedClasses | \PHPUnit_Framework_MockObject_MockObject */
+    protected $definedClassesMock;
+
     protected function setUp()
     {
+        $this->definedClassesMock = $this->getMock('\Magento\Framework\Code\Generator\DefinedClasses');
         $this->ioObjectMock = $this->getMockBuilder('\Magento\Framework\Code\Generator\Io')
             ->disableOriginalConstructor()
             ->getMock();
-    }
-
-    protected function tearDown()
-    {
-        unset($this->model);
+        $this->model = $this->buildModel(
+            $this->ioObjectMock,
+            [
+                'factory' => '\Magento\Framework\ObjectManager\Code\Generator\Factory',
+                'proxy' => '\Magento\Framework\ObjectManager\Code\Generator\Proxy',
+                'interceptor' => '\Magento\Framework\Interception\Code\Generator\Interceptor'
+            ],
+            $this->definedClassesMock
+        );
     }
 
     public function testGetGeneratedEntities()
     {
-        $this->model = new \Magento\Framework\Code\Generator(
+        $this->model = $this->buildModel(
             $this->ioObjectMock,
-            ['factory', 'proxy', 'interceptor']
+            ['factory', 'proxy', 'interceptor'],
+            $this->definedClassesMock
         );
         $this->assertEquals(array_values($this->expectedEntities), $this->model->getGeneratedEntities());
     }
@@ -65,14 +76,6 @@ class GeneratorTest extends \PHPUnit_Framework_TestCase
      */
     public function testGenerateClass($className, $entityType)
     {
-        $this->model = new \Magento\Framework\Code\Generator(
-            $this->ioObjectMock,
-            [
-                'factory' => '\Magento\Framework\ObjectManager\Code\Generator\Factory',
-                'proxy' => '\Magento\Framework\ObjectManager\Code\Generator\Proxy',
-                'interceptor' => '\Magento\Framework\Interception\Code\Generator\Interceptor'
-            ]
-        );
         $objectManagerMock = $this->getMock('Magento\Framework\ObjectManagerInterface');
         $fullClassName = $className . $entityType;
         $entityGeneratorMock = $this->getMockBuilder('\Magento\Framework\Code\Generator\EntityAbstract')
@@ -83,35 +86,8 @@ class GeneratorTest extends \PHPUnit_Framework_TestCase
         $this->model->generateClass($fullClassName);
     }
 
-    /**
-     * @dataProvider generateValidClassDataProvider
-     */
-    public function testGenerateClassWithExistName($className, $entityType)
-    {
-        $definedClassesMock = $this->getMock('Magento\Framework\Code\Generator\DefinedClasses');
-        $definedClassesMock->expects($this->any())
-            ->method('isClassLoadableFromDisc')
-            ->willReturn(true);
-        $this->model = new \Magento\Framework\Code\Generator(
-            $this->ioObjectMock,
-            [
-                'factory' => '\Magento\Framework\ObjectManager\Code\Generator\Factory',
-                'proxy' => '\Magento\Framework\ObjectManager\Code\Generator\Proxy',
-                'interceptor' => '\Magento\Framework\Interception\Code\Generator\Interceptor'
-            ],
-            $definedClassesMock
-        );
-
-        $this->assertEquals(
-            \Magento\Framework\Code\Generator::GENERATION_SKIP,
-            $this->model->generateClass($className . $entityType)
-        );
-    }
-
     public function testGenerateClassWithWrongName()
     {
-        $this->model = new \Magento\Framework\Code\Generator($this->ioObjectMock);
-
         $this->assertEquals(
             \Magento\Framework\Code\Generator::GENERATION_ERROR,
             $this->model->generateClass(self::SOURCE_CLASS)
@@ -123,15 +99,6 @@ class GeneratorTest extends \PHPUnit_Framework_TestCase
      */
     public function testGenerateClassWithError()
     {
-        $this->model = new \Magento\Framework\Code\Generator(
-            $this->ioObjectMock,
-            [
-                'factory' => '\Magento\Framework\ObjectManager\Code\Generator\Factory',
-                'proxy' => '\Magento\Framework\ObjectManager\Code\Generator\Proxy',
-                'interceptor' => '\Magento\Framework\Interception\Code\Generator\Interceptor'
-            ]
-        );
-
         $expectedEntities = array_values($this->expectedEntities);
         $resultClassName = self::SOURCE_CLASS . ucfirst(array_shift($expectedEntities));
         $objectManagerMock = $this->getMock('Magento\Framework\ObjectManagerInterface');
@@ -143,6 +110,32 @@ class GeneratorTest extends \PHPUnit_Framework_TestCase
         $this->model->generateClass($resultClassName);
     }
 
+    /**
+     * @dataProvider trueFalseDataProvider
+     */
+    public function testGenerateClassWithExistName($fileExists)
+    {
+        $this->definedClassesMock->expects($this->any())
+            ->method('isClassLoadableFromDisc')
+            ->willReturn(true);
+
+        $resultClassFileName = '/Magento/Path/To/Class.php';
+        $this->ioObjectMock->expects($this->once())->method('generateResultFileName')->willReturn($resultClassFileName);
+        $this->ioObjectMock->expects($this->once())->method('fileExists')->willReturn($fileExists);
+        $includeFileInvokeCount = $fileExists ? 1 : 0;
+        $this->ioObjectMock->expects($this->exactly($includeFileInvokeCount))->method('includeFile');
+
+        $this->assertEquals(
+            \Magento\Framework\Code\Generator::GENERATION_SKIP,
+            $this->model->generateClass('Magento\GeneratedClass\Factory')
+        );
+    }
+
+    public function trueFalseDataProvider()
+    {
+        return [[true], [false]];
+    }
+
     /**
      * Data provider for generate class tests
      *
@@ -160,4 +153,17 @@ class GeneratorTest extends \PHPUnit_Framework_TestCase
         }
         return $data;
     }
+
+    /**
+     * Build SUT object
+     *
+     * @param Io $ioObject
+     * @param array $generatedEntities
+     * @param DefinedClasses $definedClasses
+     * @return Generator
+     */
+    private function buildModel(Io $ioObject, array $generatedEntities, DefinedClasses $definedClasses)
+    {
+        return new Generator($ioObject, $generatedEntities, $definedClasses);
+    }
 }
diff --git a/lib/internal/Magento/Framework/Interception/Test/Unit/Code/Generator/InterceptorTest.php b/lib/internal/Magento/Framework/Interception/Test/Unit/Code/Generator/InterceptorTest.php
index 78f5759d9fa77707de1e1c1bb1cf39b5c4596fdc..97f1ff1b368d56130f72c8c61790f6e8e2a42f20 100644
--- a/lib/internal/Magento/Framework/Interception/Test/Unit/Code/Generator/InterceptorTest.php
+++ b/lib/internal/Magento/Framework/Interception/Test/Unit/Code/Generator/InterceptorTest.php
@@ -56,7 +56,7 @@ class InterceptorTest extends \PHPUnit_Framework_TestCase
         $this->classGeneratorMock->expects($this->once())->method('generate')
             ->will($this->returnValue('source code example'));
         $model->expects($this->once())->method('_validateData')->will($this->returnValue(true));
-        $this->ioObjectMock->expects($this->any())->method('getResultFileName')->with('Exception_Interceptor');
+        $this->ioObjectMock->expects($this->any())->method('generateResultFileName')->with('Exception_Interceptor');
         $this->assertEquals('', $model->generate());
     }
 }
diff --git a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/ConverterTest.php b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/ConverterTest.php
index 10bafa24672ad8ed72d942d6de81262d8f2434e8..8578107b4cf70fffe960aa52b2b9d11e9bf07070 100644
--- a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/ConverterTest.php
+++ b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/ConverterTest.php
@@ -105,7 +105,7 @@ class ConverterTest extends \PHPUnit_Framework_TestCase
 
         //Mocking generation
         $this->ioObjectMock->expects($this->any())
-            ->method('getResultFileName')
+            ->method('generateResultFileName')
             ->with(self::RESULT_CLASS_NAME)
             ->will($this->returnValue($resultFileName));
         $this->ioObjectMock->expects($this->once())
diff --git a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/FactoryTest.php b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/FactoryTest.php
index 80d63e0133df7c7f29651628d1e4285bd1748880..3a477ec43a52c4b6a56fcc4235554fdd8585288e 100644
--- a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/FactoryTest.php
+++ b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/FactoryTest.php
@@ -34,7 +34,7 @@ class FactoryTest extends \PHPUnit_Framework_TestCase
             ]
         );
 
-        $this->ioObjectMock->expects($this->once())->method('getResultFileName')
+        $this->ioObjectMock->expects($this->once())->method('generateResultFileName')
             ->with('\Magento\Framework\ObjectManager\Code\Generator\SampleFactory')
             ->will($this->returnValue('sample_file.php'));
         $factoryCode = file_get_contents(__DIR__ . '/_files/SampleFactory.txt');
diff --git a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/GenerateRepositoryTest.php b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/GenerateRepositoryTest.php
index a2744ca17becda4478dff35173d9982b33ba2ae3..27cea41af83218ebb2810b1763e897ab1d1710c7 100644
--- a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/GenerateRepositoryTest.php
+++ b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/GenerateRepositoryTest.php
@@ -54,7 +54,7 @@ class GenerateRepositoryTest extends \PHPUnit_Framework_TestCase
         );
 
         $this->ioObjectMock->expects($this->once())
-            ->method('getResultFileName')
+            ->method('generateResultFileName')
             ->with('\Magento\Framework\ObjectManager\Code\Generator\SampleRepository')
             ->willReturn('SampleRepository.php');
 
diff --git a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/ProxyTest.php b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/ProxyTest.php
index 4fb66556991ccaec70b2e361094db556448a3e23..7eb9795742d1f7ce96b369e8c057e7d15b1d540e 100644
--- a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/ProxyTest.php
+++ b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Code/Generator/ProxyTest.php
@@ -34,7 +34,7 @@ class ProxyTest extends \PHPUnit_Framework_TestCase
         );
         $sampleProxyCode = file_get_contents(__DIR__ . '/_files/SampleProxy.txt');
 
-        $this->ioObjectMock->expects($this->once())->method('getResultFileName')
+        $this->ioObjectMock->expects($this->once())->method('generateResultFileName')
             ->with('\Magento\Framework\ObjectManager\Code\Generator\Sample_Proxy')
             ->will($this->returnValue('sample_file.php'));
         $this->ioObjectMock->expects($this->once())->method('writeResultFile')
diff --git a/lib/internal/Magento/Framework/TestFramework/Unit/Autoloader/ExtensionGeneratorAutoloader.php b/lib/internal/Magento/Framework/TestFramework/Unit/Autoloader/ExtensionGeneratorAutoloader.php
index 9f14464d01c877ddbb5c8e097c5d5646d1922e3e..4382d23df89eeac89e54fddbaba8df862dcc6262 100644
--- a/lib/internal/Magento/Framework/TestFramework/Unit/Autoloader/ExtensionGeneratorAutoloader.php
+++ b/lib/internal/Magento/Framework/TestFramework/Unit/Autoloader/ExtensionGeneratorAutoloader.php
@@ -41,7 +41,7 @@ class ExtensionGeneratorAutoloader
                 return false;
             }
 
-            $resultFileName = $this->generatorIo->getResultFileName($className);
+            $resultFileName = $this->generatorIo->generateResultFileName($className);
 
             if (!$this->generatorIo->fileExists($resultFileName)) {
                 $this->generatorIo->makeResultFileDirectory($className);
diff --git a/lib/internal/Magento/Framework/View/Asset/PreProcessor/AlternativeSource.php b/lib/internal/Magento/Framework/View/Asset/PreProcessor/AlternativeSource.php
index d727bd9fa40598dba7c3cf65330c8da88155d361..95fe57227895b643dd4bbbbdc8596699fb692918 100644
--- a/lib/internal/Magento/Framework/View/Asset/PreProcessor/AlternativeSource.php
+++ b/lib/internal/Magento/Framework/View/Asset/PreProcessor/AlternativeSource.php
@@ -96,7 +96,7 @@ class AlternativeSource implements AlternativeSourceInterface
         }
 
         try {
-            $this->lockerProcess->lockProcess($this->lockName . sprintf('%x', crc32($path . $content)));
+            $this->lockerProcess->lockProcess($this->lockName);
 
             $module = $chain->getAsset()->getModule();
 
diff --git a/setup/src/Magento/Setup/Module/I18n/Parser/Adapter/Php/Tokenizer/PhraseCollector.php b/setup/src/Magento/Setup/Module/I18n/Parser/Adapter/Php/Tokenizer/PhraseCollector.php
index ee7ecd15e0c5fdc8ed9f24c2eb4a3092dffe0371..96f7c84fd7e7a611579f13e153d37f0cd1b87af9 100644
--- a/setup/src/Magento/Setup/Module/I18n/Parser/Adapter/Php/Tokenizer/PhraseCollector.php
+++ b/setup/src/Magento/Setup/Module/I18n/Parser/Adapter/Php/Tokenizer/PhraseCollector.php
@@ -139,7 +139,7 @@ class PhraseCollector
         if ($phraseTokens) {
             /** @var \Magento\Setup\Module\I18n\Parser\Adapter\Php\Tokenizer\Token $phraseToken */
             foreach ($phraseTokens as $phraseToken) {
-                if ($phraseToken->isConstantEncapsedString()) {
+                if ($phraseToken->isConstantEncapsedString() || $phraseToken->isConcatenateOperator()) {
                     $phrase[] = $phraseToken->getValue();
                 }
             }
diff --git a/setup/src/Magento/Setup/Module/I18n/Parser/Adapter/Php/Tokenizer/Token.php b/setup/src/Magento/Setup/Module/I18n/Parser/Adapter/Php/Tokenizer/Token.php
index a36b8b1e885307150ba4ef9d95ccd8381bfd2137..0477da1bcd3ce5f490c19c7e058e35d89b92f0f2 100644
--- a/setup/src/Magento/Setup/Module/I18n/Parser/Adapter/Php/Tokenizer/Token.php
+++ b/setup/src/Magento/Setup/Module/I18n/Parser/Adapter/Php/Tokenizer/Token.php
@@ -166,6 +166,14 @@ class Token
         return $this->getValue() == ';';
     }
 
+    /**
+     * @return bool
+     */
+    public function isConcatenateOperator()
+    {
+        return $this->getValue() == '.';
+    }
+
     /**
      * Is namespace separator
      *
diff --git a/setup/src/Magento/Setup/Test/Unit/Module/I18n/Parser/Adapter/Php/Tokenizer/PhraseCollectorTest.php b/setup/src/Magento/Setup/Test/Unit/Module/I18n/Parser/Adapter/Php/Tokenizer/PhraseCollectorTest.php
index 954bcc013ade66bfdd3c10c10597fe205f6f5e58..b4f7d60a1ca113b43c289ed4cc57e0bfc471a2b7 100644
--- a/setup/src/Magento/Setup/Test/Unit/Module/I18n/Parser/Adapter/Php/Tokenizer/PhraseCollectorTest.php
+++ b/setup/src/Magento/Setup/Test/Unit/Module/I18n/Parser/Adapter/Php/Tokenizer/PhraseCollectorTest.php
@@ -204,4 +204,23 @@ class PhraseCollectorTest extends \PHPUnit_Framework_TestCase
             ->willReturn($line);
         return $token;
     }
+
+    public function testCollectPhrases()
+    {
+        $firstPart = "'first part'";
+        $firstPartToken = new Token(\T_CONSTANT_ENCAPSED_STRING, $firstPart);
+        $concatenationToken = new Token('.', '.');
+        $secondPart = "' second part'";
+        $secondPartToken = new Token(\T_CONSTANT_ENCAPSED_STRING, $secondPart);
+        $phraseTokens = [$firstPartToken, $concatenationToken, $secondPartToken];
+        $phraseString = "'first part' . ' second part'";
+
+        $reflectionMethod = new \ReflectionMethod(
+            '\Magento\Setup\Module\I18n\Parser\Adapter\Php\Tokenizer\PhraseCollector',
+            '_collectPhrase'
+        );
+
+        $reflectionMethod->setAccessible(true);
+        $this->assertSame($phraseString, $reflectionMethod->invoke($this->phraseCollector, $phraseTokens));
+    }
 }
diff --git a/setup/src/Magento/Setup/Test/Unit/Module/I18n/Parser/Adapter/Php/Tokenizer/TokenTest.php b/setup/src/Magento/Setup/Test/Unit/Module/I18n/Parser/Adapter/Php/Tokenizer/TokenTest.php
index 26bcea7516dd2495526e0b75202c3082591a77c6..c29edab1c442d5d96398424fd00be82251c223af 100644
--- a/setup/src/Magento/Setup/Test/Unit/Module/I18n/Parser/Adapter/Php/Tokenizer/TokenTest.php
+++ b/setup/src/Magento/Setup/Test/Unit/Module/I18n/Parser/Adapter/Php/Tokenizer/TokenTest.php
@@ -118,4 +118,16 @@ class TokenTest extends \PHPUnit_Framework_TestCase
             ]
         );
     }
+
+    public function testIsConcatenateOperatorTrue()
+    {
+        $token = new \Magento\Setup\Module\I18n\Parser\Adapter\Php\Tokenizer\Token('.', '.');
+        $this->assertTrue($token->isConcatenateOperator());
+    }
+
+    public function testIsConcatenateOperatorFalse()
+    {
+        $token = new \Magento\Setup\Module\I18n\Parser\Adapter\Php\Tokenizer\Token(',', ',');
+        $this->assertFalse($token->isConcatenateOperator());
+    }
 }