diff --git a/app/code/Magento/Authorizenet/Controller/Directpost/Payment/Redirect.php b/app/code/Magento/Authorizenet/Controller/Directpost/Payment/Redirect.php index f2ca4aec50d7a..8745737a19bd6 100644 --- a/app/code/Magento/Authorizenet/Controller/Directpost/Payment/Redirect.php +++ b/app/code/Magento/Authorizenet/Controller/Directpost/Payment/Redirect.php @@ -8,18 +8,12 @@ use Magento\Framework\App\ObjectManager; use Magento\Payment\Block\Transparent\Iframe; -use Magento\Framework\Escaper; /** * Class Redirect */ class Redirect extends \Magento\Authorizenet\Controller\Directpost\Payment { - /** - * @var Escaper - */ - private $escaper; - /** * Retrieve params and put javascript into iframe * @@ -29,7 +23,7 @@ public function execute() { $helper = $this->dataFactory->create('frontend'); - $redirectParams = $this->filterData($this->getRequest()->getParams()); + $redirectParams = $this->getRequest()->getParams(); $params = []; if (!empty($redirectParams['success']) && isset($redirectParams['x_invoice_num']) @@ -38,9 +32,11 @@ public function execute() $this->_getDirectPostSession()->unsetData('quote_id'); $params['redirect_parent'] = $helper->getSuccessOrderUrl([]); } + if (!empty($redirectParams['error_msg'])) { $cancelOrder = empty($redirectParams['x_invoice_num']); $this->_returnCustomerQuote($cancelOrder, $redirectParams['error_msg']); + $params['error_msg'] = $redirectParams['error_msg']; } if (isset($redirectParams['controller_action_name']) @@ -50,34 +46,8 @@ public function execute() unset($params['redirect_parent']); } - $this->_coreRegistry->register(Iframe::REGISTRY_KEY, array_merge($params, $redirectParams)); + $this->_coreRegistry->register(Iframe::REGISTRY_KEY, $params); $this->_view->addPageLayoutHandles(); $this->_view->loadLayout(false)->renderLayout(); } - - /** - * Escape xss in request data - * @param array $data - * @return array - */ - private function filterData(array $data) - { - $self = $this; - array_walk($data, function (&$item) use ($self) { - $item = $self->getEscaper()->escapeXssInUrl($item); - }); - return $data; - } - - /** - * Get Escaper instance - * @return Escaper - */ - private function getEscaper() - { - if (!$this->escaper) { - $this->escaper = ObjectManager::getInstance()->get(Escaper::class); - } - return $this->escaper; - } } diff --git a/app/code/Magento/Authorizenet/Test/Unit/Controller/Directpost/Payment/RedirectTest.php b/app/code/Magento/Authorizenet/Test/Unit/Controller/Directpost/Payment/RedirectTest.php index 809e0ac98f884..d11a7b8df3521 100644 --- a/app/code/Magento/Authorizenet/Test/Unit/Controller/Directpost/Payment/RedirectTest.php +++ b/app/code/Magento/Authorizenet/Test/Unit/Controller/Directpost/Payment/RedirectTest.php @@ -8,7 +8,6 @@ use Magento\Authorizenet\Controller\Directpost\Payment\Redirect; use Magento\Framework\App\RequestInterface; use Magento\Framework\App\ViewInterface; -use Magento\Framework\Escaper; use Magento\Framework\Registry; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Payment\Block\Transparent\Iframe; @@ -34,11 +33,6 @@ class RedirectTest extends \PHPUnit_Framework_TestCase */ private $coreRegistry; - /** - * @var Escaper|MockObject - */ - private $escaper; - /** * @var Redirect */ @@ -57,21 +51,11 @@ protected function setUp() ->setMethods(['register']) ->getMock(); - $this->escaper = static::getMockBuilder(Escaper::class) - ->disableOriginalConstructor() - ->setMethods(['escapeXssInUrl']) - ->getMock(); - $this->controller = $objectManager->getObject(Redirect::class, [ 'request' => $this->request, 'view' => $this->view, 'coreRegistry' => $this->coreRegistry ]); - - $refClass = new \ReflectionClass(Redirect::class); - $refProperty = $refClass->getProperty('escaper'); - $refProperty->setAccessible(true); - $refProperty->setValue($this->controller, $this->escaper); } /** @@ -87,14 +71,9 @@ public function testExecute() ->method('getParams') ->willReturn($params); - $this->escaper->expects(static::once()) - ->method('escapeXssInUrl') - ->with($url) - ->willReturn($url); - $this->coreRegistry->expects(static::once()) ->method('register') - ->with(Iframe::REGISTRY_KEY, $params); + ->with(Iframe::REGISTRY_KEY, []); $this->view->expects(static::once()) ->method('addPageLayoutHandles'); diff --git a/app/code/Magento/Backend/App/BackendAppList.php b/app/code/Magento/Backend/App/BackendAppList.php index 224ce9893100c..afb812b823488 100644 --- a/app/code/Magento/Backend/App/BackendAppList.php +++ b/app/code/Magento/Backend/App/BackendAppList.php @@ -44,6 +44,7 @@ public function getCurrentApp() if ($appName && isset($this->backendApps[$appName])) { return $this->backendApps[$appName]; } + return null; } /** diff --git a/app/code/Magento/Braintree/Model/PaymentMethod.php b/app/code/Magento/Braintree/Model/PaymentMethod.php index 0665d9d5e65a7..3f85a3d79b563 100644 --- a/app/code/Magento/Braintree/Model/PaymentMethod.php +++ b/app/code/Magento/Braintree/Model/PaymentMethod.php @@ -10,6 +10,7 @@ use \Braintree_Exception; use \Braintree_Transaction; use \Braintree_Result_Successful; +use Magento\Framework\DataObject; use Magento\Framework\Exception\LocalizedException; use Magento\Sales\Model\Order\Payment\Transaction; use Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\CollectionFactory as TransactionCollectionFactory; @@ -254,15 +255,29 @@ public function __construct( */ public function assignData(\Magento\Framework\DataObject $data) { - parent::assignData($data); + $additionalData = $data->getAdditionalData(); + + if (!is_array($data->getAdditionalData())) { + return $this; + } + $additionalData = new DataObject($additionalData); + $infoInstance = $this->getInfoInstance(); if ($this->getConfigData('fraudprotection') > 0) { - $infoInstance->setAdditionalInformation('device_data', $data->getData('device_data')); + $infoInstance->setAdditionalInformation('device_data', $additionalData->getData('device_data')); } - $infoInstance->setAdditionalInformation('cc_last4', $data->getData('cc_last4')); - $infoInstance->setAdditionalInformation('cc_token', $data->getCcToken()); - $infoInstance->setAdditionalInformation('payment_method_nonce', $data->getPaymentMethodNonce()); - $infoInstance->setAdditionalInformation('store_in_vault', $data->getStoreInVault()); + + $infoInstance->setAdditionalInformation('cc_last4', $additionalData->getData('cc_last4')); + $infoInstance->setAdditionalInformation('cc_token', $additionalData->getData('cc_token')); + $infoInstance->setAdditionalInformation( + 'payment_method_nonce', + $additionalData->getData('payment_method_nonce') + ); + + $infoInstance->setCcLast4($additionalData->getData('cc_last4')); + $infoInstance->setCcType($additionalData->getData('cc_type')); + $infoInstance->setCcExpMonth($additionalData->getData('cc_exp_month')); + $infoInstance->setCcExpYear($additionalData->getData('cc_exp_year')); return $this; } diff --git a/app/code/Magento/Braintree/Model/PaymentMethod/PayPal.php b/app/code/Magento/Braintree/Model/PaymentMethod/PayPal.php index 901950ac81cc5..edca711216d10 100644 --- a/app/code/Magento/Braintree/Model/PaymentMethod/PayPal.php +++ b/app/code/Magento/Braintree/Model/PaymentMethod/PayPal.php @@ -10,6 +10,7 @@ use \Braintree_Exception; use \Braintree_Transaction; use \Braintree_Result_Successful; +use Magento\Framework\DataObject; use Magento\Framework\Exception\LocalizedException; use Magento\Braintree\Model\PaymentMethod; use Magento\Payment\Model\InfoInterface; @@ -152,8 +153,18 @@ public function getConfigData($field, $storeId = null) */ public function assignData(\Magento\Framework\DataObject $data) { + $additionalData = $data->getAdditionalData(); + + if (!is_array($data->getAdditionalData())) { + return $this; + } + $additionalData = new DataObject($additionalData); + $infoInstance = $this->getInfoInstance(); - $infoInstance->setAdditionalInformation('payment_method_nonce', $data->getPaymentMethodNonce()); + $infoInstance->setAdditionalInformation( + 'payment_method_nonce', + $additionalData->getData('payment_method_nonce') + ); return $this; } diff --git a/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethod/PayPalTest.php b/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethod/PayPalTest.php index 8803d24a0f310..f21631fd7088d 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethod/PayPalTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethod/PayPalTest.php @@ -230,10 +230,12 @@ public function testAssignData() $paymentMethodNonce = 'nonce'; $storeInVault = true; $data = [ - 'cc_last4' => $ccLast4, - 'cc_token' => $ccToken, - 'payment_method_nonce' => $paymentMethodNonce, - 'store_in_vault' => $storeInVault, + 'additional_data' => [ + 'cc_last4' => $ccLast4, + 'cc_token' => $ccToken, + 'payment_method_nonce' => $paymentMethodNonce, + 'store_in_vault' => $storeInVault + ] ]; $data = new \Magento\Framework\DataObject($data); $this->model->setInfoInstance($this->infoInstanceMock); diff --git a/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethodTest.php b/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethodTest.php index 32e65e001e5f2..29e45a4016bca 100644 --- a/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethodTest.php +++ b/app/code/Magento/Braintree/Test/Unit/Model/PaymentMethodTest.php @@ -8,6 +8,8 @@ use Magento\Braintree\Model\PaymentMethod; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Payment\Model\InfoInterface; +use Magento\Quote\Model\Quote\Payment; use Magento\Sales\Model\Order\Payment\Transaction; use \Magento\Sales\Model\ResourceModel\Order\Payment\Transaction\CollectionFactory as TransactionCollectionFactory; use Magento\Framework\Exception\LocalizedException; @@ -62,7 +64,7 @@ class PaymentMethodTest extends \PHPUnit_Framework_TestCase protected $registryMock; /** - * @var \Magento\Payment\Model\InfoInterface|\PHPUnit_Framework_MockObject_MockObject + * @var Payment|\PHPUnit_Framework_MockObject_MockObject */ protected $infoInstanceMock; @@ -200,29 +202,25 @@ protected function setUp() 'orderRepository' => $this->orderRepository ] ); - $this->infoInstanceMock = $this->getMockForAbstractClass( - '\Magento\Payment\Model\InfoInterface', - [], - '', - false, - false, - false, - [ - 'setCcType', - 'setCcOwner', - 'setCcLast4', - 'setCcNumber', - 'setCcCid', - 'setCcExpMonth', - 'setCcExpYear', - 'setCcSsIssue', - 'setCcSsStartMonth', - 'setCcSsStartYear', - 'getOrder', - 'getQuote', - 'getCcType', - ] - ); + $this->infoInstanceMock = $this->getMockBuilder(InfoInterface::class) + ->disableOriginalConstructor() + ->setMethods( + [ + 'setCcType', + 'setCcOwner', + 'setCcLast4', + 'setCcNumber', + 'setCcCid', + 'setCcExpMonth', + 'setCcExpYear', + 'setCcSsIssue', + 'setCcSsStartMonth', + 'setCcSsStartYear', + 'getOrder', + 'getQuote', + 'getCcType' + ] + )->getMockForAbstractClass(); $this->productMetaDataMock->expects($this->any()) ->method('getEdition') ->willReturn('Community Edition'); @@ -234,7 +232,6 @@ protected function setUp() public function testAssignData() { $ccType = 'VI'; - $ccOwner = 'John Doe'; $ccExpMonth = '10'; $ccExpYear = '2020'; @@ -244,15 +241,16 @@ public function testAssignData() $storeInVault = true; $deviceData = 'mobile'; $data = [ - 'cc_type' => $ccType, - 'cc_owner' => $ccOwner, - 'cc_exp_month' => $ccExpMonth, - 'cc_exp_year' => $ccExpYear, - 'cc_last4' => $ccLast4, - 'cc_token' => $ccToken, - 'payment_method_nonce' => $paymentMethodNonce, - 'store_in_vault' => $storeInVault, - 'device_data' => $deviceData, + 'additional_data' => [ + 'cc_type' => $ccType, + 'cc_exp_month' => $ccExpMonth, + 'cc_exp_year' => $ccExpYear, + 'cc_last4' => $ccLast4, + 'cc_token' => $ccToken, + 'payment_method_nonce' => $paymentMethodNonce, + 'store_in_vault' => $storeInVault, + 'device_data' => $deviceData + ] ]; $data = new \Magento\Framework\DataObject($data); $this->model->setInfoInstance($this->infoInstanceMock); @@ -265,21 +263,9 @@ public function testAssignData() ->method('setCcType') ->with($ccType) ->willReturnSelf(); - $this->infoInstanceMock->expects($this->once()) - ->method('setCcOwner') - ->with($ccOwner) - ->willReturnSelf(); $this->infoInstanceMock->expects($this->once()) ->method('setCcLast4') - ->with(false) - ->willReturnSelf(); - $this->infoInstanceMock->expects($this->once()) - ->method('setCcNumber') - ->with(null) - ->willReturnSelf(); - $this->infoInstanceMock->expects($this->once()) - ->method('setCcCid') - ->with(null) + ->with($ccLast4) ->willReturnSelf(); $this->infoInstanceMock->expects($this->once()) ->method('setCcExpMonth') @@ -289,34 +275,19 @@ public function testAssignData() ->method('setCcExpYear') ->with($ccExpYear) ->willReturnSelf(); - $this->infoInstanceMock->expects($this->once()) - ->method('setCcSsIssue') - ->with(null) - ->willReturnSelf(); - $this->infoInstanceMock->expects($this->once()) - ->method('setCcSsStartMonth') - ->with(null) - ->willReturnSelf(); - $this->infoInstanceMock->expects($this->once()) - ->method('setCcSsStartYear') - ->with(null) - ->willReturnSelf(); - $this->infoInstanceMock->expects($this->at(10)) + $this->infoInstanceMock->expects($this->atLeastOnce()) ->method('setAdditionalInformation') - ->with('device_data', $deviceData); - $this->infoInstanceMock->expects($this->at(11)) - ->method('setAdditionalInformation') - ->with('cc_last4', $ccLast4); - $this->infoInstanceMock->expects($this->at(12)) - ->method('setAdditionalInformation') - ->with('cc_token', $ccToken); - $this->infoInstanceMock->expects($this->at(13)) - ->method('setAdditionalInformation') - ->with('payment_method_nonce', $paymentMethodNonce); - $this->infoInstanceMock->expects($this->at(14)) - ->method('setAdditionalInformation') - ->with('store_in_vault', $storeInVault); + ->willReturnMap( + [ + ['device_data', $deviceData], + ['cc_last4', $ccLast4], + ['cc_token', $ccToken], + ['payment_method_nonce', $paymentMethodNonce], + ['store_in_vault', $storeInVault] + ] + ); + $this->model->assignData($data); } diff --git a/app/code/Magento/Integration/Model/Oauth/Consumer.php b/app/code/Magento/Integration/Model/Oauth/Consumer.php index 4382196665e3c..c0bf015705100 100644 --- a/app/code/Magento/Integration/Model/Oauth/Consumer.php +++ b/app/code/Magento/Integration/Model/Oauth/Consumer.php @@ -43,6 +43,11 @@ class Consumer extends \Magento\Framework\Model\AbstractModel implements Consume */ protected $dataHelper; + /** + * @var \Magento\Framework\Stdlib\DateTime\DateTime + */ + private $_dateHelper; + /** * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry @@ -80,6 +85,22 @@ protected function _construct() $this->_init('Magento\Integration\Model\ResourceModel\Oauth\Consumer'); } + /** + * The getter function to get the new DateTime dependency + * + * @return \Magento\Framework\Stdlib\DateTime\DateTime + * + * @deprecated + */ + private function getDateHelper() + { + if ($this->_dateHelper === null) { + $this->_dateHelper = \Magento\Framework\App\ObjectManager::getInstance() + ->get(\Magento\Framework\Stdlib\DateTime\DateTime::class); + } + return $this->_dateHelper; + } + /** * BeforeSave actions * @@ -176,6 +197,8 @@ public function getCreatedAt() public function isValidForTokenExchange() { $expiry = $this->dataHelper->getConsumerExpirationPeriod(); - return $expiry > $this->getResource()->getTimeInSecondsSinceCreation($this->getId()); + $currentTimestamp = $this->getDateHelper()->gmtTimestamp(); + $updatedTimestamp = $this->getDateHelper()->gmtTimestamp($this->getUpdatedAt()); + return $expiry > ($currentTimestamp - $updatedTimestamp); } } diff --git a/app/code/Magento/Integration/Model/OauthService.php b/app/code/Magento/Integration/Model/OauthService.php index 9ce2df70a547b..2e09f872f0164 100644 --- a/app/code/Magento/Integration/Model/OauthService.php +++ b/app/code/Magento/Integration/Model/OauthService.php @@ -61,6 +61,11 @@ class OauthService implements \Magento\Integration\Api\OauthServiceInterface */ protected $_tokenProvider; + /** + * @var \Magento\Framework\Stdlib\DateTime\DateTime + */ + private $_dateHelper; + /** * Initialize dependencies. * @@ -93,6 +98,22 @@ public function __construct( $this->_tokenProvider = $tokenProvider; } + /** + * The getter function to get the new DateTime dependency + * + * @return \Magento\Framework\Stdlib\DateTime\DateTime + * + * @deprecated + */ + private function getDateHelper() + { + if ($this->_dateHelper === null) { + $this->_dateHelper = \Magento\Framework\App\ObjectManager::getInstance() + ->get(\Magento\Framework\Stdlib\DateTime\DateTime::class); + } + return $this->_dateHelper; + } + /** * {@inheritdoc} */ @@ -193,6 +214,8 @@ public function postToConsumer($consumerId, $endpointUrl) { try { $consumer = $this->_consumerFactory->create()->load($consumerId); + $consumer->setUpdatedAt($this->getDateHelper()->gmtDate()); + $consumer->save(); if (!$consumer->getId()) { throw new \Magento\Framework\Oauth\Exception( __('A consumer with ID %1 does not exist', $consumerId) diff --git a/app/code/Magento/Integration/Model/ResourceModel/Oauth/Consumer.php b/app/code/Magento/Integration/Model/ResourceModel/Oauth/Consumer.php index 2fcd1910b1bcc..7a610b43e6ec6 100644 --- a/app/code/Magento/Integration/Model/ResourceModel/Oauth/Consumer.php +++ b/app/code/Magento/Integration/Model/ResourceModel/Oauth/Consumer.php @@ -45,6 +45,8 @@ public function _afterDelete(\Magento\Framework\Model\AbstractModel $object) /** * Compute time in seconds since consumer was created. * + * @deprecated + * * @param int $consumerId - The consumer id * @return int - time lapsed in seconds */ diff --git a/app/code/Magento/Integration/Test/Unit/Helper/Oauth/ConsumerTest.php b/app/code/Magento/Integration/Test/Unit/Helper/Oauth/ConsumerTest.php index 5fdb6ce861e61..89bb5d943b898 100644 --- a/app/code/Magento/Integration/Test/Unit/Helper/Oauth/ConsumerTest.php +++ b/app/code/Magento/Integration/Test/Unit/Helper/Oauth/ConsumerTest.php @@ -5,6 +5,11 @@ */ namespace Magento\Integration\Test\Unit\Helper\Oauth; +/** + * Test for \Magento\Integration\Model\Oauth\Consumer + * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ class ConsumerTest extends \PHPUnit_Framework_TestCase { /** @var \Magento\Store\Model\StoreManagerInterface */ @@ -152,6 +157,16 @@ public function testPostToConsumer() )->will( $this->returnSelf() ); + + $dateHelperMock = $this->getMockBuilder('Magento\Framework\Stdlib\DateTime\DateTime') + ->disableOriginalConstructor() + ->getMock(); + $dateHelperMock->expects($this->any())->method('gmtDate'); + + $dateHelper = new \ReflectionProperty('Magento\Integration\Model\OauthService', '_dateHelper'); + $dateHelper->setAccessible(true); + $dateHelper->setValue($this->_oauthService, $dateHelperMock); + $this->_consumerMock->expects($this->once())->method('getId')->will($this->returnValue($consumerId)); $this->_consumerMock->expects($this->once())->method('getData')->will($this->returnValue($consumerData)); $this->_httpClientMock->expects( diff --git a/app/code/Magento/Integration/Test/Unit/Model/Oauth/ConsumerTest.php b/app/code/Magento/Integration/Test/Unit/Model/Oauth/ConsumerTest.php index 328eb1ebe7568..2a8875658a202 100644 --- a/app/code/Magento/Integration/Test/Unit/Model/Oauth/ConsumerTest.php +++ b/app/code/Magento/Integration/Test/Unit/Model/Oauth/ConsumerTest.php @@ -110,7 +110,7 @@ public function setUp() $this->resourceMock = $this->getMock( 'Magento\Integration\Model\ResourceModel\Oauth\Consumer', - ['getTimeInSecondsSinceCreation', 'getIdFieldName', 'selectByCompositeKey', 'deleteOldEntries'], + ['getIdFieldName', 'selectByCompositeKey', 'deleteOldEntries'], [], '', false, @@ -215,21 +215,33 @@ public function testValidateInvalidConsumerSecret() public function testGetConsumerExpirationPeriodValid() { - $this->resourceMock->expects($this->once()) - ->method('getTimeInSecondsSinceCreation') - ->will($this->returnValue(30)); + $dateHelperMock = $this->getMockBuilder('Magento\Framework\Stdlib\DateTime\DateTime') + ->disableOriginalConstructor() + ->getMock(); + $dateHelperMock->expects($this->at(0))->method('gmtTimestamp')->willReturn(time()); + $dateHelperMock->expects($this->at(1))->method('gmtTimestamp')->willReturn(time() - 100); - $this->consumerModel->setCreatedAt(time()); + $dateHelper = new \ReflectionProperty('Magento\Integration\Model\Oauth\Consumer', '_dateHelper'); + $dateHelper->setAccessible(true); + $dateHelper->setValue($this->consumerModel, $dateHelperMock); + + $this->consumerModel->setUpdatedAt(time()); $this->assertTrue($this->consumerModel->isValidForTokenExchange()); } public function testGetConsumerExpirationPeriodExpired() { - $this->resourceMock->expects($this->once()) - ->method('getTimeInSecondsSinceCreation') - ->will($this->returnValue(400)); + $dateHelperMock = $this->getMockBuilder('Magento\Framework\Stdlib\DateTime\DateTime') + ->disableOriginalConstructor() + ->getMock(); + $dateHelperMock->expects($this->at(0))->method('gmtTimestamp')->willReturn(time()); + $dateHelperMock->expects($this->at(1))->method('gmtTimestamp')->willReturn(time() - 1000); + + $dateHelper = new \ReflectionProperty('Magento\Integration\Model\Oauth\Consumer', '_dateHelper'); + $dateHelper->setAccessible(true); + $dateHelper->setValue($this->consumerModel, $dateHelperMock); - $this->consumerModel->setCreatedAt(time()); + $this->consumerModel->setUpdatedAt(time()); $this->assertFalse($this->consumerModel->isValidForTokenExchange()); } } diff --git a/app/code/Magento/OfflinePayments/Model/Purchaseorder.php b/app/code/Magento/OfflinePayments/Model/Purchaseorder.php index b209af925a9db..52eee8df4ba78 100644 --- a/app/code/Magento/OfflinePayments/Model/Purchaseorder.php +++ b/app/code/Magento/OfflinePayments/Model/Purchaseorder.php @@ -47,10 +47,6 @@ class Purchaseorder extends \Magento\Payment\Model\Method\AbstractMethod */ public function assignData(\Magento\Framework\DataObject $data) { - if (!$data instanceof \Magento\Framework\DataObject) { - $data = new \Magento\Framework\DataObject($data); - } - $this->getInfoInstance()->setPoNumber($data->getPoNumber()); return $this; } diff --git a/app/code/Magento/Payment/Model/Info.php b/app/code/Magento/Payment/Model/Info.php index ea5927974fce9..fc25416c27074 100644 --- a/app/code/Magento/Payment/Model/Info.php +++ b/app/code/Magento/Payment/Model/Info.php @@ -217,9 +217,6 @@ protected function _initAdditionalInformation() { $additionalInfo = $this->_getData('additional_information'); if (empty($this->_additionalInformation) && $additionalInfo) { - if (!is_array($additionalInfo)) { - $additionalInfo = unserialize($additionalInfo); - } $this->_additionalInformation = $additionalInfo; } } diff --git a/app/code/Magento/Payment/Model/Method/AbstractMethod.php b/app/code/Magento/Payment/Model/Method/AbstractMethod.php index 12bc561b1a3c7..fec399be6fbc0 100644 --- a/app/code/Magento/Payment/Model/Method/AbstractMethod.php +++ b/app/code/Magento/Payment/Model/Method/AbstractMethod.php @@ -20,6 +20,7 @@ * @SuppressWarnings(PHPMD.ExcessivePublicCount) * @SuppressWarnings(PHPMD.TooManyFields) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * @deprecated */ abstract class AbstractMethod extends \Magento\Framework\Model\AbstractExtensibleModel implements MethodInterface, @@ -765,14 +766,10 @@ public function getConfigData($field, $storeId = null) * @return $this * @throws \Magento\Framework\Exception\LocalizedException * @api + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function assignData(\Magento\Framework\DataObject $data) { - if (is_array($data)) { - $this->getInfoInstance()->addData($data); - } elseif ($data instanceof \Magento\Framework\DataObject) { - $this->getInfoInstance()->addData($data->getData()); - } return $this; } diff --git a/app/code/Magento/Payment/Model/Method/Adapter.php b/app/code/Magento/Payment/Model/Method/Adapter.php index 1421c6a399324..2a6e4f8fd219d 100644 --- a/app/code/Magento/Payment/Model/Method/Adapter.php +++ b/app/code/Magento/Payment/Model/Method/Adapter.php @@ -611,8 +611,7 @@ public function assignData(\Magento\Framework\DataObject $data) 'data' => $data ] ); - - $this->getInfoInstance()->addData($data->getData()); + return $this; } diff --git a/app/code/Magento/Payment/Test/Unit/Model/InfoTest.php b/app/code/Magento/Payment/Test/Unit/Model/InfoTest.php index 22ebf692706b3..72a6e3eda5507 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/InfoTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/InfoTest.php @@ -90,7 +90,6 @@ public function ccKeysDataProvider() ]; } - public function testGetMethodInstanceWithRealMethod() { $method = 'real_method'; @@ -108,7 +107,6 @@ public function testGetMethodInstanceWithRealMethod() $this->info->getMethodInstance(); } - public function testGetMethodInstanceWithUnrealMethod() { $method = 'unreal_method'; @@ -131,7 +129,6 @@ public function testGetMethodInstanceWithUnrealMethod() $this->info->getMethodInstance(); } - /** * @expectedException \Magento\Framework\Exception\LocalizedException * @expectedExceptionMessage The payment method you requested is not available. @@ -141,8 +138,7 @@ public function testGetMethodInstanceWithNoMethod() $this->info->setData('method', false); $this->info->getMethodInstance(); } - - + public function testGetMethodInstanceRequestedMethod() { $code = 'real_method'; @@ -251,9 +247,9 @@ public function testHasAdditionalInformation() public function testInitAdditionalInformationWithUnserialize() { - $data = serialize(['key1' => 'data1', 'key2' => 'data2']); + $data = ['key1' => 'data1', 'key2' => 'data2']; $this->info->setData('additional_information', $data); - $this->assertEquals(unserialize($data), $this->info->getAdditionalInformation()); + $this->assertEquals($data, $this->info->getAdditionalInformation()); } } diff --git a/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethodTest.php b/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethodTest.php index 1504aff5308f8..c2ec5857230ab 100644 --- a/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethodTest.php +++ b/app/code/Magento/Payment/Test/Unit/Model/Method/AbstractMethodTest.php @@ -5,6 +5,9 @@ */ namespace Magento\Payment\Test\Unit\Model\Method; +use Magento\Framework\DataObject; +use Magento\Payment\Model\InfoInterface; +use Magento\Payment\Observer\AbstractDataAssignObserver; use Magento\Store\Model\ScopeInterface; use Magento\Payment\Test\Unit\Model\Method\AbstractMethod\Stub; @@ -65,7 +68,7 @@ protected function setUp() $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->payment = $helper->getObject( - 'Magento\Payment\Test\Unit\Model\Method\AbstractMethod\Stub', + Stub::class, [ 'scopeConfig' => $this->scopeConfigMock, 'context' => $contextMock, diff --git a/app/code/Magento/Paypal/Model/Express.php b/app/code/Magento/Paypal/Model/Express.php index 2464ef48498ce..9c0129e3116c6 100644 --- a/app/code/Magento/Paypal/Model/Express.php +++ b/app/code/Magento/Paypal/Model/Express.php @@ -8,6 +8,7 @@ use Magento\Paypal\Model\Api\Nvp; use Magento\Paypal\Model\Api\ProcessableException as ApiProcessableException; use Magento\Paypal\Model\Express\Checkout as ExpressCheckout; +use Magento\Quote\Api\Data\PaymentInterface; use Magento\Sales\Api\Data\OrderPaymentInterface; use Magento\Sales\Model\Order\Payment; use Magento\Sales\Model\Order\Payment\Transaction; @@ -666,14 +667,24 @@ public function getApi() */ public function assignData(\Magento\Framework\DataObject $data) { - $result = parent::assignData($data); - $key = ExpressCheckout::PAYMENT_INFO_TRANSPORT_BILLING_AGREEMENT; - if (is_array($data)) { - $this->getInfoInstance()->setAdditionalInformation($key, isset($data[$key]) ? $data[$key] : null); - } elseif ($data instanceof \Magento\Framework\DataObject) { - $this->getInfoInstance()->setAdditionalInformation($key, $data->getData($key)); + parent::assignData($data); + + $additionalData = $data->getData(PaymentInterface::KEY_ADDITIONAL_DATA); + + if ( + !is_array($additionalData) + || !isset($additionalData[ExpressCheckout::PAYMENT_INFO_TRANSPORT_BILLING_AGREEMENT]) + ) { + return $this; } - return $result; + + $this->getInfoInstance() + ->setAdditionalInformation( + ExpressCheckout::PAYMENT_INFO_TRANSPORT_BILLING_AGREEMENT, + $additionalData[ExpressCheckout::PAYMENT_INFO_TRANSPORT_BILLING_AGREEMENT] + ); + + return $this; } /** diff --git a/app/code/Magento/Paypal/Model/Payment/Method/Billing/AbstractAgreement.php b/app/code/Magento/Paypal/Model/Payment/Method/Billing/AbstractAgreement.php index f6f6154012a77..c4c103e4c3800 100644 --- a/app/code/Magento/Paypal/Model/Payment/Method/Billing/AbstractAgreement.php +++ b/app/code/Magento/Paypal/Model/Payment/Method/Billing/AbstractAgreement.php @@ -5,6 +5,9 @@ */ namespace Magento\Paypal\Model\Payment\Method\Billing; +use Magento\Paypal\Model\Billing\Agreement; +use Magento\Quote\Api\Data\PaymentInterface; + /** * Billing Agreement Payment Method Abstract model * @@ -110,29 +113,29 @@ public function isAvailable(\Magento\Quote\Api\Data\CartInterface $quote = null) */ public function assignData(\Magento\Framework\DataObject $data) { - $result = parent::assignData($data); - - $key = self::TRANSPORT_BILLING_AGREEMENT_ID; - $id = false; - if (is_array($data) && isset($data[$key])) { - $id = $data[$key]; - } elseif ($data instanceof \Magento\Framework\DataObject && $data->getData($key)) { - $id = $data->getData($key); + parent::assignData($data); + + $additionalData = $data->getData(PaymentInterface::KEY_ADDITIONAL_DATA); + if (!is_array($additionalData) || !isset($additionalData[self::TRANSPORT_BILLING_AGREEMENT_ID])) { + return $this; } - if ($id) { - $info = $this->getInfoInstance(); - $ba = $this->_agreementFactory->create()->load($id); - if ($ba->getId() && $ba->getCustomerId() == $info->getQuote()->getCustomerId()) { - $info->setAdditionalInformation( - $key, - $id - )->setAdditionalInformation( - self::PAYMENT_INFO_REFERENCE_ID, - $ba->getReferenceId() - ); - } + + $id = $additionalData[self::TRANSPORT_BILLING_AGREEMENT_ID]; + if (!$id || !is_numeric($id)) { + return $this; } - return $result; + + $info = $this->getInfoInstance(); + /** @var Agreement $ba */ + $ba = $this->_agreementFactory->create(); + $ba->load($id); + + if ($ba->getId() && $ba->getCustomerId() == $info->getQuote()->getCustomerId()) { + $info->setAdditionalInformation(self::TRANSPORT_BILLING_AGREEMENT_ID, $id); + $info->setAdditionalInformation(self::PAYMENT_INFO_REFERENCE_ID, $ba->getReferenceId()); + } + + return $this; } /** diff --git a/app/code/Magento/Paypal/Test/Unit/Model/ExpressTest.php b/app/code/Magento/Paypal/Test/Unit/Model/ExpressTest.php index 288b01bd05d39..41d053c638dc4 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/ExpressTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/ExpressTest.php @@ -5,7 +5,13 @@ */ namespace Magento\Paypal\Test\Unit\Model; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Payment\Model\InfoInterface; +use Magento\Payment\Observer\AbstractDataAssignObserver; use Magento\Paypal\Model\Api\ProcessableException as ApiProcessableException; +use Magento\Paypal\Model\Express; +use Magento\Quote\Api\Data\PaymentInterface; class ExpressTest extends \PHPUnit_Framework_TestCase { @@ -54,6 +60,11 @@ class ExpressTest extends \PHPUnit_Framework_TestCase */ protected $transactionBuilder; + /** + * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $eventManagerMock; + protected function setUp() { $this->_checkoutSession = $this->getMock( @@ -78,24 +89,28 @@ protected function setUp() false ); $this->_pro = $this->getMock( - 'Magento\Paypal\Model\ProFactory', - ['create', 'setMethod', 'getApi', 'importPaymentInfo', 'resetApi'], + 'Magento\Paypal\Model\Pro', + ['setMethod', 'getApi', 'importPaymentInfo', 'resetApi'], [], '', false ); - $this->_pro->expects($this->any())->method('create')->will($this->returnSelf()); + $this->eventManagerMock = $this->getMockBuilder(ManagerInterface::class) + ->setMethods(['dispatch']) + ->getMockForAbstractClass(); + + $this->_pro->expects($this->any())->method('getApi')->will($this->returnValue($this->_nvp)); $this->_helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); } public function testSetApiProcessableErrors() { $this->_nvp->expects($this->once())->method('setProcessableErrors')->with($this->errorCodes); - $this->_pro->expects($this->any())->method('getApi')->will($this->returnValue($this->_nvp)); + $this->_model = $this->_helper->getObject( 'Magento\Paypal\Model\Express', [ - 'proFactory' => $this->_pro, + 'data' => [$this->_pro], 'checkoutSession' => $this->_checkoutSession, 'transactionBuilder' => $this->transactionBuilder ] @@ -109,7 +124,7 @@ public function testOrder() $this->_nvp->expects($this->any())->method('setCurrencyCode')->will($this->returnSelf()); $this->_nvp->expects($this->any())->method('setTransactionId')->will($this->returnSelf()); $this->_nvp->expects($this->any())->method('callDoAuthorization')->will($this->returnSelf()); - $this->_pro->expects($this->any())->method('getApi')->will($this->returnValue($this->_nvp)); + $this->_checkoutSession->expects($this->once())->method('getPaypalTransactionData')->will( $this->returnValue([]) ); @@ -147,11 +162,46 @@ public function testOrder() $this->_model = $this->_helper->getObject( 'Magento\Paypal\Model\Express', [ - 'proFactory' => $this->_pro, + 'data' => [$this->_pro], 'checkoutSession' => $this->_checkoutSession, 'transactionBuilder' => $this->transactionBuilder ] ); $this->assertEquals($this->_model, $this->_model->order($paymentModel, 12.3)); } + + public function testAssignData() + { + $transportValue = 'something'; + + $data = new DataObject( + [ + PaymentInterface::KEY_ADDITIONAL_DATA => [ + Express\Checkout::PAYMENT_INFO_TRANSPORT_BILLING_AGREEMENT => $transportValue + ] + ] + ); + + $this->_model = $this->_helper->getObject( + 'Magento\Paypal\Model\Express', + [ + 'data' => [$this->_pro], + 'checkoutSession' => $this->_checkoutSession, + 'transactionBuilder' => $this->transactionBuilder, + 'eventDispatcher' => $this->eventManagerMock, + ] + ); + + $paymentInfo = $this->getMock(InfoInterface::class); + $this->_model->setInfoInstance($paymentInfo); + + $paymentInfo->expects(static::once()) + ->method('setAdditionalInformation') + ->with( + Express\Checkout::PAYMENT_INFO_TRANSPORT_BILLING_AGREEMENT, + $transportValue + ); + + $this->_model->assignData($data); + } } diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Payment/Method/Billing/AbstractAgreementStub.php b/app/code/Magento/Paypal/Test/Unit/Model/Payment/Method/Billing/AbstractAgreementStub.php new file mode 100644 index 0000000000000..e92339a382592 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Unit/Model/Payment/Method/Billing/AbstractAgreementStub.php @@ -0,0 +1,31 @@ +agreementFactory = $this->getMockBuilder('Magento\Paypal\Model\Billing\AgreementFactory') + ->disableOriginalConstructor() + ->setMethods(['create']) + ->getMock(); + $this->payment = $helper->getObject( + AbstractAgreementStub::class, + [ + 'agreementFactory' => $this->agreementFactory + ] + ); + } + public function testAssignData() + { + $baId = '1678235'; + $customerId = 67; + $referenceId = '1234124'; + + $data = new DataObject( + [ + PaymentInterface::KEY_ADDITIONAL_DATA => [ + AbstractAgreement::TRANSPORT_BILLING_AGREEMENT_ID => $baId + ] + ] + ); + + $paymentInfo = $this->getMockBuilder(Payment::class) + ->disableOriginalConstructor() + ->getMock(); + $quote = $this->getMockBuilder(Quote::class) + ->disableOriginalConstructor() + ->setMethods(['__wakeup', 'getCustomerId']) + ->getMock(); + + $this->payment->setInfoInstance($paymentInfo); + + $agreementModel = $this->getMockBuilder(Agreement::class) + ->disableOriginalConstructor() + ->setMethods(['__wakeup', 'load', 'getCustomerId', 'getId', 'getReferenceId']) + ->getMock(); + + $this->agreementFactory->expects(static::once()) + ->method('create') + ->willReturn($agreementModel); + + $paymentInfo->expects(static::once()) + ->method('getQuote') + ->willReturn($quote); + + $agreementModel->expects(static::once()) + ->method('load') + ->with($baId); + $agreementModel->expects(static::once()) + ->method('getId') + ->willReturn($baId); + $agreementModel->expects(static::atLeastOnce()) + ->method('getCustomerId') + ->willReturn($customerId); + $agreementModel->expects(static::atLeastOnce()) + ->method('getReferenceId') + ->willReturn($referenceId); + + $quote->expects(static::once()) + ->method('getCustomerId') + ->willReturn($customerId); + + $paymentInfo->expects(static::exactly(2)) + ->method('setAdditionalInformation') + ->willReturnMap( + [ + AbstractAgreement::TRANSPORT_BILLING_AGREEMENT_ID, $baId, + AbstractAgreement::PAYMENT_INFO_REFERENCE_ID, $referenceId + ] + ); + $this->payment->assignData($data); + } +} diff --git a/app/code/Magento/Quote/Model/PaymentMethodManagement.php b/app/code/Magento/Quote/Model/PaymentMethodManagement.php index 63d3fc166467e..6bff056cd034a 100644 --- a/app/code/Magento/Quote/Model/PaymentMethodManagement.php +++ b/app/code/Magento/Quote/Model/PaymentMethodManagement.php @@ -61,10 +61,6 @@ public function set($cartId, \Magento\Quote\Api\Data\PaymentInterface $method) $payment = $quote->getPayment(); $data = $method->getData(); - if (isset($data['additional_data'])) { - $data = array_merge($data, (array)$data['additional_data']); - unset($data['additional_data']); - } $payment->importData($data); if ($quote->isVirtual()) { diff --git a/app/code/Magento/Quote/Model/Quote/Payment.php b/app/code/Magento/Quote/Model/Quote/Payment.php index 0efdf0620e66a..b6c9da379aa3b 100644 --- a/app/code/Magento/Quote/Model/Quote/Payment.php +++ b/app/code/Magento/Quote/Model/Quote/Payment.php @@ -5,6 +5,8 @@ */ namespace Magento\Quote\Model\Quote; +use Magento\Quote\Api\Data\PaymentInterface; + /** * Quote payment information * @@ -143,6 +145,7 @@ public function getQuote() */ public function importData(array $data) { + $data = $this->convertPaymentData($data); $data = new \Magento\Framework\DataObject($data); $this->_eventManager->dispatch( $this->_eventPrefix . '_import_data_before', @@ -174,6 +177,37 @@ public function importData(array $data) return $this; } + /** + * Converts request to payment data + * + * @param array $rawData + * @return array + */ + private function convertPaymentData(array $rawData) + { + $paymentData = [ + PaymentInterface::KEY_METHOD => null, + PaymentInterface::KEY_PO_NUMBER => null, + PaymentInterface::KEY_ADDITIONAL_DATA => [], + 'checks' => [] + ]; + + foreach (array_keys($rawData) as $requestKey) { + if (!array_key_exists($requestKey, $paymentData)) { + $paymentData[PaymentInterface::KEY_ADDITIONAL_DATA][$requestKey] = $rawData[$requestKey]; + } elseif ($requestKey === PaymentInterface::KEY_ADDITIONAL_DATA) { + $paymentData[PaymentInterface::KEY_ADDITIONAL_DATA] = array_merge( + $paymentData[PaymentInterface::KEY_ADDITIONAL_DATA], + (array) $rawData[$requestKey] + ); + } else { + $paymentData[$requestKey] = $rawData[$requestKey]; + } + } + + return $paymentData; + } + /** * Prepare object for save * @@ -223,7 +257,7 @@ public function getOrderPlaceRedirectUrl() public function getMethodInstance() { $method = parent::getMethodInstance(); - $method->setStore($this->getQuote()->getStore()->getStoreId()); + $method->setStore($this->getQuote()->getStoreId()); return $method; } diff --git a/app/code/Magento/Quote/Model/QuoteManagement.php b/app/code/Magento/Quote/Model/QuoteManagement.php index 2e640d7dca255..dcec33d999e32 100644 --- a/app/code/Magento/Quote/Model/QuoteManagement.php +++ b/app/code/Magento/Quote/Model/QuoteManagement.php @@ -21,6 +21,8 @@ use Magento\Sales\Api\OrderManagementInterface as OrderManagement; use Magento\Store\Model\StoreManagerInterface; use Magento\Quote\Model\Quote\Address; +use Magento\Framework\App\ObjectManager; +use Magento\Quote\Model\QuoteIdMaskFactory; /** * Class QuoteManagement @@ -130,6 +132,11 @@ class QuoteManagement implements \Magento\Quote\Api\CartManagementInterface */ protected $quoteFactory; + /** + * @var QuoteIdMaskFactory + */ + private $quoteIdMaskFactory; + /** * @param EventManager $eventManager * @param QuoteValidator $quoteValidator @@ -262,6 +269,12 @@ public function assignCustomer($cartId, $customerId, $storeId) $quote->setCustomer($customer); $quote->setCustomerIsGuest(0); + $quoteIdMaskFactory = $this->getQuoteIdMaskFactory(); + /** @var \Magento\Quote\Model\QuoteIdMask $quoteIdMask */ + $quoteIdMask = $quoteIdMaskFactory->create()->load($cartId, 'quote_id'); + if ($quoteIdMask->getId()) { + $quoteIdMask->delete(); + } $this->quoteRepository->save($quote); return true; @@ -547,4 +560,16 @@ protected function _prepareCustomerQuote($quote) $shipping->setIsDefaultBilling(true); } } + + /** + * @return QuoteIdMaskFactory + * @deprecated + */ + private function getQuoteIdMaskFactory() + { + if (!$this->quoteIdMaskFactory) { + $this->quoteIdMaskFactory = ObjectManager::getInstance()->get(QuoteIdMaskFactory::class); + } + return $this->quoteIdMaskFactory; + } } diff --git a/app/code/Magento/Quote/Test/Unit/Model/PaymentMethodManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/PaymentMethodManagementTest.php index d4bea1326812f..60d7618413676 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/PaymentMethodManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/PaymentMethodManagementTest.php @@ -16,6 +16,7 @@ class PaymentMethodManagementTest extends \PHPUnit_Framework_TestCase * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ protected $objectManager; + /** * @var \PHPUnit_Framework_MockObject_MockObject */ @@ -111,7 +112,7 @@ public function testSetVirtualProduct() $cartId = 100; $paymentId = 200; $methodDataWithAdditionalData = ['method' => 'data', 'additional_data' => ['additional' => 'value']]; - $methodData = ['method' => 'data', 'additional' => 'value']; + $methodData = $methodDataWithAdditionalData; $paymentMethod = 'checkmo'; $quoteMock = $this->getMock( diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/PaymentTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/PaymentTest.php index 53d95bda04ed3..849f45764abdc 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/PaymentTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/PaymentTest.php @@ -5,6 +5,13 @@ */ namespace Magento\Quote\Test\Unit\Model\Quote; +use Magento\Framework\DataObject; +use Magento\Framework\Event\ManagerInterface; +use Magento\Payment\Model\Checks\Composite; +use Magento\Payment\Model\Checks\SpecificationFactory; +use Magento\Payment\Model\MethodInterface; +use Magento\Quote\Api\Data\PaymentInterface; +use Magento\Quote\Model\Quote; use \Magento\Quote\Model\Quote\Payment; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; @@ -16,11 +23,31 @@ class PaymentTest extends \PHPUnit_Framework_TestCase */ private $model; + /** + * @var \PHPUnit_Framework_MockObject_MockObject|SpecificationFactory + */ + private $specificationFactory; + + /** + * @var \PHPUnit_Framework_MockObject_MockObject|ManagerInterface + */ + private $eventManager; + protected function setUp() { $objectManager = new ObjectManager($this); + $this->specificationFactory = $this->getMockBuilder( + SpecificationFactory::class + )->disableOriginalConstructor() + ->getMock(); + $this->eventManager = $this->getMock(ManagerInterface::class); + $this->model = $objectManager->getObject( - '\Magento\Quote\Model\Quote\Payment' + Payment::class, + [ + 'methodSpecificationFactory' => $this->specificationFactory, + 'eventDispatcher' => $this->eventManager + ] ); } @@ -32,7 +59,7 @@ protected function setUp() public function testGetCcExpYearReturnsValidValue($databaseValue, $expectedValue) { $this->model->setData('cc_exp_year', $databaseValue); - $this->assertEquals($expectedValue, $this->model->getCcExpYear()); + static::assertEquals($expectedValue, $this->model->getCcExpYear()); } /** @@ -47,4 +74,141 @@ public function yearValueDataProvider() [1939, 1939], ]; } + + /** + * @param array $data + * @param array $convertedData + * @param array $dataToAssign + * @param array $checks + * @dataProvider importDataPositiveCheckDataProvider + */ + public function testImportDataPositiveCheck( + array $data, + array $convertedData, + array $dataToAssign, + array $checks + ) { + $quoteId = 1; + $storeId = 1; + + $paymentMethod = $this->getMock(MethodInterface::class); + $quote = $this->getMockBuilder(Quote::class) + ->disableOriginalConstructor() + ->getMock(); + $methodSpecification = $this->getMockBuilder(Composite::class) + ->disableOriginalConstructor() + ->getMock(); + + $quote->expects(static::once()) + ->method('getId') + ->willReturn($quoteId); + + $this->model->setQuote($quote); + $this->model->setMethodInstance($paymentMethod); + $this->eventManager->expects(static::once()) + ->method('dispatch') + ->with( + 'sales_quote_payment_import_data_before', + [ + 'payment' => $this->model, + 'input' => new DataObject($convertedData) + ] + ); + $quote->expects(static::once()) + ->method('getStoreId') + ->willReturn($storeId); + + $quote->expects(static::once()) + ->method('collectTotals'); + + $this->specificationFactory->expects(static::once()) + ->method('create') + ->with($checks) + ->willReturn($methodSpecification); + + $paymentMethod->expects(static::once()) + ->method('isAvailable') + ->with($quote) + ->willReturn(true); + $methodSpecification->expects(static::once()) + ->method('isApplicable') + ->with($paymentMethod, $quote) + ->willReturn(true); + + $paymentMethod->expects(static::once()) + ->method('assignData') + ->with(new DataObject($dataToAssign)); + $paymentMethod->expects(static::once()) + ->method('validate'); + + $this->model->importData($data); + } + + /** + * @return array + */ + public function importDataPositiveCheckDataProvider() + { + return [ + [ + [ + PaymentInterface::KEY_METHOD => 'payment_method_code', + 'cc_number' => '1111', + 'cc_type' => 'VI', + 'cc_owner' => 'John Doe' + ], + [ + PaymentInterface::KEY_METHOD => 'payment_method_code', + PaymentInterface::KEY_PO_NUMBER => null, + PaymentInterface::KEY_ADDITIONAL_DATA => [ + 'cc_number' => '1111', + 'cc_type' => 'VI', + 'cc_owner' => 'John Doe' + ], + 'checks' => [] + ], + [ + PaymentInterface::KEY_METHOD => 'payment_method_code', + PaymentInterface::KEY_PO_NUMBER => null, + PaymentInterface::KEY_ADDITIONAL_DATA => [ + 'cc_number' => '1111', + 'cc_type' => 'VI', + 'cc_owner' => 'John Doe' + ], + 'checks' => [] + ], + [] + ], + [ + [ + PaymentInterface::KEY_METHOD => 'payment_method_code', + 'cc_number' => '1111', + 'cc_type' => 'VI', + 'cc_owner' => 'John Doe', + 'checks' => ['check_code1', 'check_code2'] + ], + [ + PaymentInterface::KEY_METHOD => 'payment_method_code', + PaymentInterface::KEY_PO_NUMBER => null, + PaymentInterface::KEY_ADDITIONAL_DATA => [ + 'cc_number' => '1111', + 'cc_type' => 'VI', + 'cc_owner' => 'John Doe' + ], + 'checks' => ['check_code1', 'check_code2'] + ], + [ + PaymentInterface::KEY_METHOD => 'payment_method_code', + PaymentInterface::KEY_PO_NUMBER => null, + PaymentInterface::KEY_ADDITIONAL_DATA => [ + 'cc_number' => '1111', + 'cc_type' => 'VI', + 'cc_owner' => 'John Doe' + ], + 'checks' => ['check_code1', 'check_code2'] + ], + ['check_code1', 'check_code2'] + ] + ]; + } } diff --git a/app/code/Magento/Quote/Test/Unit/Model/QuoteManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/QuoteManagementTest.php index cd2a56b3b9d7b..13fc99773f37a 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/QuoteManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/QuoteManagementTest.php @@ -126,6 +126,11 @@ class QuoteManagementTest extends \PHPUnit_Framework_TestCase */ protected $quoteFactoryMock; + /** + * @var \PHPUnit_Framework_MockObject_MockObject + */ + private $quoteIdMock; + /** * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ @@ -238,7 +243,6 @@ protected function setUp() ); $this->quoteFactoryMock = $this->getMock('\Magento\Quote\Model\QuoteFactory', ['create'], [], '', false); - $this->model = $objectManager->getObject( '\Magento\Quote\Model\QuoteManagement', [ @@ -264,6 +268,12 @@ protected function setUp() 'quoteFactory' => $this->quoteFactoryMock ] ); + + // Set the new dependency + $this->quoteIdMock = $this->getMock('Magento\Quote\Model\QuoteIdMask', [], [], '', false); + $quoteIdFactoryMock = $this->getMock(\Magento\Quote\Model\QuoteIdMaskFactory::class, ['create'], [], '', false); + $this->setPropertyValue($this->model, 'quoteIdMaskFactory', $quoteIdFactoryMock); + } public function testCreateEmptyCartAnonymous() @@ -508,6 +518,13 @@ public function testAssignCustomer() $customerId = 455; $storeId = 5; + $this->getPropertyValue($this->model, 'quoteIdMaskFactory') + ->expects($this->once()) + ->method('create') + ->willReturn($this->quoteIdMock); + $this->quoteIdMock->expects($this->once())->method('load')->with($cartId, 'quote_id')->willReturnSelf(); + $this->quoteIdMock->expects($this->once())->method('getId')->willReturn(10); + $this->quoteIdMock->expects($this->once())->method('delete'); $quoteMock = $this->getMock( '\Magento\Quote\Model\Quote', ['getCustomerId', 'setCustomer', 'setCustomerIsGuest'], @@ -979,4 +996,37 @@ public function testGetCartForCustomer() ->willReturn($cartMock); $this->assertEquals($cartMock, $this->model->getCartForCustomer($customerId)); } + + /** + * Get any object property value. + * + * @param $object + * @param $property + * @return mixed + */ + protected function getPropertyValue($object, $property) + { + $reflection = new \ReflectionClass(get_class($object)); + $reflectionProperty = $reflection->getProperty($property); + $reflectionProperty->setAccessible(true); + + return $reflectionProperty->getValue($object); + } + + /** + * Set object property value. + * + * @param $object + * @param $property + * @param $value + */ + protected function setPropertyValue(&$object, $property, $value) + { + $reflection = new \ReflectionClass(get_class($object)); + $reflectionProperty = $reflection->getProperty($property); + $reflectionProperty->setAccessible(true); + $reflectionProperty->setValue($object, $value); + + return $object; + } } diff --git a/app/code/Magento/Sales/Model/Order/Payment/Info.php b/app/code/Magento/Sales/Model/Order/Payment/Info.php index 58592f3d04d6b..b8947ba741b7f 100644 --- a/app/code/Magento/Sales/Model/Order/Payment/Info.php +++ b/app/code/Magento/Sales/Model/Order/Payment/Info.php @@ -223,9 +223,6 @@ protected function initAdditionalInformation() { $additionalInfo = $this->getData('additional_information'); if (empty($this->additionalInformation) && $additionalInfo) { - if (!is_array($additionalInfo)) { - $additionalInfo = unserialize($additionalInfo); - } $this->additionalInformation = $additionalInfo; } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/InfoTest.php b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/InfoTest.php index f47806866aef6..3516aef705982 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/InfoTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Order/Payment/InfoTest.php @@ -89,8 +89,7 @@ public function ccKeysDataProvider() ['cc_cid', 'cc_cid_enc'] ]; } - - + public function testGetMethodInstanceWithRealMethod() { $method = 'real_method'; @@ -108,7 +107,6 @@ public function testGetMethodInstanceWithRealMethod() $this->info->getMethodInstance(); } - public function testGetMethodInstanceWithUnrealMethod() { $method = 'unreal_method'; @@ -131,7 +129,6 @@ public function testGetMethodInstanceWithUnrealMethod() $this->info->getMethodInstance(); } - /** * @expectedException \Magento\Framework\Exception\LocalizedException * @expectedExceptionMessage The payment method you requested is not available. @@ -253,9 +250,9 @@ public function testHasAdditionalInformation() public function testInitAdditionalInformationWithUnserialize() { - $data = serialize(['key1' => 'data1', 'key2' => 'data2']); + $data = ['key1' => 'data1', 'key2' => 'data2']; $this->info->setData('additional_information', $data); - $this->assertEquals(unserialize($data), $this->info->getAdditionalInformation()); + $this->assertEquals($data, $this->info->getAdditionalInformation()); } } diff --git a/app/code/Magento/Webapi/Controller/Soap/Request/Handler.php b/app/code/Magento/Webapi/Controller/Soap/Request/Handler.php index 48585ee3d846b..078ef04540b5c 100644 --- a/app/code/Magento/Webapi/Controller/Soap/Request/Handler.php +++ b/app/code/Magento/Webapi/Controller/Soap/Request/Handler.php @@ -107,10 +107,10 @@ public function __call($operation, $arguments) throw new WebapiException(__("Operation allowed only in HTTPS")); } - $isAllowed = false; + $isAllowed = true; foreach ($serviceMethodInfo[ServiceMetadata::KEY_ACL_RESOURCES] as $resource) { - if ($this->_authorization->isAllowed($resource)) { - $isAllowed = true; + if (!$this->_authorization->isAllowed($resource)) { + $isAllowed = false; break; } } diff --git a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartManagementTest.php b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartManagementTest.php index c67470fd69ae5..a201724eaaa68 100644 --- a/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartManagementTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Quote/Api/GuestCartManagementTest.php @@ -70,9 +70,9 @@ public function testAssignCustomer() $quote = $this->objectManager->create('Magento\Quote\Model\Quote')->load('test01', 'reserved_order_id'); $cartId = $quote->getId(); /** @var \Magento\Quote\Model\QuoteIdMask $quoteIdMask */ - $quoteIdMask = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() - ->create('Magento\Quote\Model\QuoteIdMaskFactory') - ->create(); + $quoteIdMaskFactory = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() + ->create('Magento\Quote\Model\QuoteIdMaskFactory'); + $quoteIdMask = $quoteIdMaskFactory->create(); $quoteIdMask->load($cartId, 'quote_id'); //Use masked cart Id $cartId = $quoteIdMask->getMaskedId(); @@ -110,6 +110,7 @@ public function testAssignCustomer() $this->assertEquals($customer->getId(), $quote->getCustomerId()); $this->assertEquals($customer->getFirstname(), $quote->getCustomerFirstname()); $this->assertEquals($customer->getLastname(), $quote->getCustomerLastname()); + $this->assertNull($quoteIdMaskFactory->create()->load($cartId, 'masked_id')->getId()); } /** diff --git a/dev/tests/api-functional/testsuite/Magento/Webapi/Authentication/RestTest.php b/dev/tests/api-functional/testsuite/Magento/Webapi/Authentication/RestTest.php index d4295866c8e8e..9394d9383d23c 100644 --- a/dev/tests/api-functional/testsuite/Magento/Webapi/Authentication/RestTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Webapi/Authentication/RestTest.php @@ -90,6 +90,8 @@ public function testGetRequestToken() public function testGetRequestTokenExpiredConsumer() { $this::consumerFixture('2012-01-01 00:00:00'); + $this::$_consumer->setUpdatedAt('2012-01-01 00:00:00'); + $this::$_consumer->save(); /** @var $oAuthClient \Magento\TestFramework\Authentication\Rest\OauthClient */ $oAuthClient = $this->_getOauthClient(self::$_consumerKey, self::$_consumerSecret); $oAuthClient->requestRequestToken(); diff --git a/dev/tests/integration/testsuite/Magento/Paypal/Model/Payment/Method/Billing/AbstractAgreementTest.php b/dev/tests/integration/testsuite/Magento/Paypal/Model/Payment/Method/Billing/AbstractAgreementTest.php index 25405d261abdb..e05b3f6cdefe5 100644 --- a/dev/tests/integration/testsuite/Magento/Paypal/Model/Payment/Method/Billing/AbstractAgreementTest.php +++ b/dev/tests/integration/testsuite/Magento/Paypal/Model/Payment/Method/Billing/AbstractAgreementTest.php @@ -6,6 +6,8 @@ namespace Magento\Paypal\Model\Payment\Method\Billing; +use Magento\Quote\Api\Data\PaymentInterface; + class AbstractAgreementTest extends \PHPUnit_Framework_TestCase { /** @var \Magento\Paypal\Model\Method\Agreement */ @@ -60,7 +62,9 @@ public function testAssignData() )->getFirstItem(); $data = new \Magento\Framework\DataObject( [ - AbstractAgreement::TRANSPORT_BILLING_AGREEMENT_ID => $billingAgreement->getId() + PaymentInterface::KEY_ADDITIONAL_DATA => [ + AbstractAgreement::TRANSPORT_BILLING_AGREEMENT_ID => $billingAgreement->getId() + ] ] ); $this->_model->assignData($data); diff --git a/dev/tests/integration/testsuite/Magento/Setup/Controller/ComponentGridTest.php b/dev/tests/integration/testsuite/Magento/Setup/Controller/ComponentGridTest.php index ae8ddc94dcbed..c49957cbe8c3d 100644 --- a/dev/tests/integration/testsuite/Magento/Setup/Controller/ComponentGridTest.php +++ b/dev/tests/integration/testsuite/Magento/Setup/Controller/ComponentGridTest.php @@ -15,73 +15,13 @@ use Magento\Framework\Stdlib\DateTime\TimezoneInterface; use Magento\Setup\Model\MarketplaceManager; +/** + * @deprecated + * + * @link setup/src/Magento/Setup/Test/Unit/Controller/ComponentGridTest.php + */ class ComponentGridTest extends \PHPUnit_Framework_TestCase { - /** - * @var ComposerInformation|\PHPUnit_Framework_MockObject_MockObject - */ - private $composerInformationMock; - - /** - * @var UpdatePackagesCache|\PHPUnit_Framework_MockObject_MockObject - */ - private $updatePackagesCacheMock; - - /** - * @var TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject - * - */ - private $timezoneMock; - - /** - * @var FullModuleList|\PHPUnit_Framework_MockObject_MockObject - */ - private $fullModuleListMock; - - /** - * @var ModuleList|\PHPUnit_Framework_MockObject_MockObject - */ - private $enabledModuleListMock; - - /** - * @var PackageInfoFactory|\PHPUnit_Framework_MockObject_MockObject - */ - private $packageInfoFactoryMock; - - /** - * Module package info - * - * @var PackageInfo - */ - private $packageInfo; - - /** - * Controller - * - * @var ComponentGrid - */ - private $controller; - - /** - * @var MarketplaceManager - */ - private $marketplaceManagerMock; - - /** - * @var array - */ - private $componentData = []; - - /** - * @var array - */ - private $lastSyncData = []; - - /** - * @var array - */ - private $convertedLastSyncDate = []; - /**#@+ * Canned formatted date and time to return from mock */ @@ -91,179 +31,17 @@ class ComponentGridTest extends \PHPUnit_Framework_TestCase public function setUp() { - $this->convertedLastSyncDate = [ - 'lastSyncDate' => [ - 'date' => self::FORMATTED_DATE, - 'time' => self::FORMATTED_TIME, - ], - ]; - - $this->lastSyncData = [ - "lastSyncDate" => "1447271496", - "packages" => [ - 'magento/sample-module-one' => [ - 'name' => 'magento/sample-module-one', - 'type' => 'magento2-module', - 'version' => '1.0.0' - ] - ], - 'countOfInstall' => 0, - 'countOfUpdate' => 1 - ]; - $this->componentData = [ - 'magento/sample-module-one' => [ - 'name' => 'magento/sample-module-one', - 'type' => 'magento2-module', - 'version' => '1.0.0' - ] - ]; - $allComponentData = [ - 'magento/sample-module-two' => [ - 'name' => 'magento/sample-module-two', - 'type' => 'magento2-module', - 'version' => '1.0.0' - ] - ]; - $allComponentData = array_merge($allComponentData, $this->componentData); - $this->composerInformationMock = $this->getMock( - 'Magento\Framework\Composer\ComposerInformation', - [], - [], - '', - false - ); - $objectManagerProvider = $this->getMock('Magento\Setup\Model\ObjectManagerProvider', [], [], '', false); - $objectManager = $this->getMock('Magento\Framework\ObjectManagerInterface', [], [], '', false); - $objectManagerProvider->expects($this->once()) - ->method('get') - ->willReturn($objectManager); - $this->packageInfoFactoryMock = $this - ->getMock('Magento\Framework\Module\PackageInfoFactory', [], [], '', false); - $this->enabledModuleListMock = $this->getMock('Magento\Framework\Module\ModuleList', [], [], '', false); - $this->enabledModuleListMock->expects($this->any())->method('has')->willReturn(true); - $this->fullModuleListMock = $this->getMock('Magento\Framework\Module\FullModuleList', [], [], '', false); - $this->fullModuleListMock->expects($this->any())->method('getNames')->willReturn($allComponentData); - $this->timezoneMock = $this->getMock('Magento\Framework\Stdlib\DateTime\TimezoneInterface', [], [], '', false); - $objectManager->expects($this->exactly(4)) - ->method('get') - ->willReturnMap([ - ['Magento\Framework\Module\PackageInfoFactory', $this->packageInfoFactoryMock], - ['Magento\Framework\Module\FullModuleList', $this->fullModuleListMock], - ['Magento\Framework\Module\ModuleList', $this->enabledModuleListMock], - ['Magento\Framework\Stdlib\DateTime\TimezoneInterface', $this->timezoneMock] - ]); - $this->packageInfo = $this->getMock('Magento\Framework\Module\PackageInfo', [], [], '', false); - $this->updatePackagesCacheMock = $this->getMock('Magento\Setup\Model\UpdatePackagesCache', [], [], '', false); - $this->marketplaceManagerMock = $this->getMock('Magento\Setup\Model\MarketplaceManager', [], [], '', false); - $this->packageInfoFactoryMock->expects($this->once())->method('create')->willReturn($this->packageInfo); - $this->controller = new ComponentGrid( - $this->composerInformationMock, - $objectManagerProvider, - $this->updatePackagesCacheMock, - $this->marketplaceManagerMock - ); } public function testIndexAction() { - $viewModel = $this->controller->indexAction(); - $this->assertInstanceOf('Zend\View\Model\ViewModel', $viewModel); - $this->assertTrue($viewModel->terminate()); } public function testComponentsAction() { - $this->fullModuleListMock->expects($this->once()) - ->method('getNames') - ->willReturn(['magento/sample-module1']); - $this->packageInfo->expects($this->once()) - ->method('getModuleName') - ->willReturn('Sample_Module'); - $this->packageInfo->expects($this->exactly(2)) - ->method('getPackageName') - ->willReturn($this->componentData['magento/sample-module-one']['name']); - $this->packageInfo->expects($this->exactly(2)) - ->method('getVersion') - ->willReturn($this->componentData['magento/sample-module-one']['version']); - $this->enabledModuleListMock->expects($this->once()) - ->method('has') - ->willReturn(true); - $this->composerInformationMock->expects($this->once()) - ->method('getInstalledMagentoPackages') - ->willReturn($this->componentData); - $this->composerInformationMock->expects($this->once()) - ->method('isPackageInComposerJson') - ->willReturn(true); - $this->updatePackagesCacheMock->expects($this->once()) - ->method('getPackagesForUpdate') - ->willReturn($this->lastSyncData); - $this->setupTimezoneMock(); - $jsonModel = $this->controller->componentsAction(); - $this->assertInstanceOf('Zend\View\Model\JsonModel', $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertTrue($variables['success']); - $expected = [[ - 'name' => 'magento/sample-module-one', - 'type' => 'magento2-module', - 'version' => '1.0.0', - 'update' => false, - 'uninstall' => true, - 'vendor' => 'magento', - 'moduleName' => 'Sample_Module', - 'enable' => true, - 'disable' => false - ]]; - $this->assertEquals($expected, $variables['components']); - $this->assertArrayHasKey('total', $variables); - $this->assertEquals(1, $variables['total']); - $expectedLastSyncData = array_replace($this->lastSyncData, $this->convertedLastSyncDate); - $this->assertEquals($expectedLastSyncData, $variables['lastSyncData']); } public function testSyncAction() { - $this->updatePackagesCacheMock->expects($this->once()) - ->method('syncPackagesForUpdate'); - $this->updatePackagesCacheMock->expects($this->once()) - ->method('getPackagesForUpdate') - ->willReturn($this->lastSyncData); - $this->setupTimezoneMock(); - $jsonModel = $this->controller->syncAction(); - $this->assertInstanceOf('Zend\View\Model\JsonModel', $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertTrue($variables['success']); - $expectedLastSyncData = array_replace($this->lastSyncData, $this->convertedLastSyncDate); - $this->assertEquals($expectedLastSyncData, $variables['lastSyncData']); - } - - /** - * Prepare the timezone mock to expect calls and return formatted date and time - * - * @return none - */ - private function setupTimezoneMock() - { - $this->timezoneMock->expects($this->at(0)) - ->method('formatDateTime') - ->with( - $this->isInstanceOf('\DateTime'), - \IntlDateFormatter::MEDIUM, - \IntlDateFormatter::NONE, - null, - null, - null - )->willReturn(self::FORMATTED_DATE); - $this->timezoneMock->expects($this->at(1)) - ->method('formatDateTime') - ->with( - $this->isInstanceOf('\DateTime'), - \IntlDateFormatter::NONE, - \IntlDateFormatter::MEDIUM, - null, - null, - null - )->willReturn(self::FORMATTED_TIME); } } diff --git a/dev/tests/integration/testsuite/Magento/Setup/Model/UpdatePackagesCacheTest.php b/dev/tests/integration/testsuite/Magento/Setup/Model/UpdatePackagesCacheTest.php index c3f2a9c94af9a..29dcb3b10cda2 100644 --- a/dev/tests/integration/testsuite/Magento/Setup/Model/UpdatePackagesCacheTest.php +++ b/dev/tests/integration/testsuite/Magento/Setup/Model/UpdatePackagesCacheTest.php @@ -9,7 +9,6 @@ use Magento\TestFramework\Helper\Bootstrap; use Magento\Framework\Composer\ComposerJsonFinder; use Magento\Framework\Composer\MagentoComposerApplicationFactory; -use Magento\Setup\Model\UpdatePackagesCache; /** * Tests Magento\Framework\ComposerInformation @@ -81,12 +80,6 @@ public function testGetPackagesForUpdate() $this->setupDirectory('testSkeleton'); - $objectManagerProvider = $this->getMock('Magento\Setup\Model\ObjectManagerProvider', [], [], '', false); - $objectManagerProvider - ->expects($this->any()) - ->method('get') - ->willReturn($this->objectManager); - /** @var UpdatePackagesCache $updatePackagesCache|\PHPUnit_Framework_MockObject_MockObject */ $updatePackagesCache = $this->getMock('Magento\Setup\Model\UpdatePackagesCache', [], [], '', false); diff --git a/lib/internal/Magento/Framework/Model/ResourceModel/AbstractResource.php b/lib/internal/Magento/Framework/Model/ResourceModel/AbstractResource.php index 3d6fa336f0295..e344f27d567f4 100644 --- a/lib/internal/Magento/Framework/Model/ResourceModel/AbstractResource.php +++ b/lib/internal/Magento/Framework/Model/ResourceModel/AbstractResource.php @@ -3,11 +3,10 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - namespace Magento\Framework\Model\ResourceModel; +use Magento\Framework\DataObject; + /** * Abstract resource model */ @@ -38,7 +37,6 @@ public function __construct() */ abstract protected function _construct(); - /** * Get connection * @@ -119,26 +117,19 @@ public function rollBack() /** * Serialize specified field in an object * - * @param \Magento\Framework\DataObject $object + * @param DataObject $object * @param string $field * @param mixed $defaultValue * @param bool $unsetEmpty * @return $this */ - protected function _serializeField(\Magento\Framework\DataObject $object, $field, $defaultValue = null, $unsetEmpty = false) + protected function _serializeField(DataObject $object, $field, $defaultValue = null, $unsetEmpty = false) { $value = $object->getData($field); - if (empty($value)) { - if ($unsetEmpty) { - $object->unsetData($field); - } else { - if (is_object($defaultValue) || is_array($defaultValue)) { - $defaultValue = serialize($defaultValue); - } - $object->setData($field, $defaultValue); - } - } elseif (is_array($value) || is_object($value)) { - $object->setData($field, serialize($value)); + if (empty($value) && $unsetEmpty) { + $object->unsetData($field); + } else { + $object->setData($field, serialize($value ?: $defaultValue)); } return $this; @@ -152,24 +143,30 @@ protected function _serializeField(\Magento\Framework\DataObject $object, $field * @param mixed $defaultValue * @return void */ - protected function _unserializeField(\Magento\Framework\DataObject $object, $field, $defaultValue = null) + protected function _unserializeField(DataObject $object, $field, $defaultValue = null) { $value = $object->getData($field); + + if ($value) { + $unserializedValue = @unserialize($value); + $value = $unserializedValue !== false || $value === 'b:0;' ? $unserializedValue : $value; + } + if (empty($value)) { $object->setData($field, $defaultValue); - } elseif (!is_array($value) && !is_object($value)) { - $object->setData($field, unserialize($value)); + } else { + $object->setData($field, $value); } } /** * Prepare data for passed table * - * @param \Magento\Framework\DataObject $object + * @param DataObject $object * @param string $table * @return array */ - protected function _prepareDataForTable(\Magento\Framework\DataObject $object, $table) + protected function _prepareDataForTable(DataObject $object, $table) { $data = []; $fields = $this->getConnection()->describeTable($table); diff --git a/lib/internal/Magento/Framework/Model/Test/Unit/ResourceModel/AbstractResourceStub.php b/lib/internal/Magento/Framework/Model/Test/Unit/ResourceModel/AbstractResourceStub.php new file mode 100644 index 0000000000000..13370114aa7ae --- /dev/null +++ b/lib/internal/Magento/Framework/Model/Test/Unit/ResourceModel/AbstractResourceStub.php @@ -0,0 +1,54 @@ +_serializeField($dataObject, $field, $defaultValue, $unsetEmpty); + + static::assertEquals($expectation, $dataObject->getDataByKey($field)); + } + + /** + * @return array + */ + public function serializableFieldsDataProvider() + { + $dataObject = new DataObject( + [ + 'object' => new \stdClass(), + 'array' => ['a', 'b', 'c'], + 'string' => 'i am string', + 'int' => 969, + 'serialized_object' => 'O:8:"stdClass":0:{}', + 'empty_value' => '', + 'empty_value_with_default' => '' + ] + ); + + return [ + [[$dataObject, 'object', null, false], serialize($dataObject->getDataByKey('object'))], + [[$dataObject, 'array', null, false], serialize($dataObject->getDataByKey('array'))], + [[$dataObject, 'string', null, false], serialize($dataObject->getDataByKey('string'))], + [[$dataObject, 'int', null, false], serialize($dataObject->getDataByKey('int'))], + [ + [$dataObject, 'serialized_object', null, false], + serialize($dataObject->getDataByKey('serialized_object')) + ], + [[$dataObject, 'empty_value', null, true], null], + [[$dataObject, 'empty_value_with_default', new \stdClass(), false], 'O:8:"stdClass":0:{}'], + ]; + } + + /** + * @param array $arguments + * @param mixed $expectation + * @dataProvider unserializableFieldsDataProvider + */ + public function testUnserializeFields(array $arguments, $expectation) + { + /** @var DataObject $dataObject */ + list($dataObject, $field, $defaultValue) = $arguments; + + $abstractResource = new AbstractResourceStub(); + + $abstractResource->_unserializeField($dataObject, $field, $defaultValue); + + static::assertEquals($expectation, $dataObject->getDataByKey($field)); + } + + /** + * @return array + */ + public function unserializableFieldsDataProvider() + { + $dataObject = new DataObject( + [ + 'object' => serialize(new \stdClass()), + 'array' => serialize(['a', 'b', 'c']), + 'string' => serialize('i am string'), + 'int' => serialize(969), + 'serialized_object' => serialize('O:8:"stdClass":0:{}'), + 'empty_value_with_default' => serialize(''), + 'not_serialized_string' => 'i am string', + 'serialized_boolean_false' => serialize(false) + ] + ); + + $defaultValue = new \stdClass(); + + return [ + [[$dataObject, 'object', null], unserialize($dataObject->getDataByKey('object'))], + [[$dataObject, 'array', null], unserialize($dataObject->getDataByKey('array'))], + [[$dataObject, 'string', null], unserialize($dataObject->getDataByKey('string'))], + [[$dataObject, 'int', null], unserialize($dataObject->getDataByKey('int'))], + [[$dataObject, 'serialized_object', null], unserialize($dataObject->getDataByKey('serialized_object'))], + [[$dataObject, 'empty_value_with_default', $defaultValue], $defaultValue], + [[$dataObject, 'not_serialized_string', null], 'i am string'], + [[$dataObject, 'serialized_boolean_false', null], false] + ]; + } +} diff --git a/lib/internal/Magento/Framework/ObjectManager/ObjectManager.php b/lib/internal/Magento/Framework/ObjectManager/ObjectManager.php index 057de7d037356..1eb1dcd227cf7 100644 --- a/lib/internal/Magento/Framework/ObjectManager/ObjectManager.php +++ b/lib/internal/Magento/Framework/ObjectManager/ObjectManager.php @@ -27,7 +27,7 @@ class ObjectManager implements \Magento\Framework\ObjectManagerInterface protected $_sharedInstances = []; /** - * @var Config\Config + * @var ConfigInterface */ protected $_config; diff --git a/setup/src/Magento/Setup/Console/Command/AbstractModuleCommand.php b/setup/src/Magento/Setup/Console/Command/AbstractModuleCommand.php index 41034aa34909d..9a06568e1385f 100644 --- a/setup/src/Magento/Setup/Console/Command/AbstractModuleCommand.php +++ b/setup/src/Magento/Setup/Console/Command/AbstractModuleCommand.php @@ -84,14 +84,18 @@ protected function cleanup(InputInterface $input, OutputInterface $output) /** @var \Magento\Framework\App\State\CleanupFiles $cleanupFiles */ $cleanupFiles = $this->objectManager->get('Magento\Framework\App\State\CleanupFiles'); $cleanupFiles->clearCodeGeneratedClasses(); - $output->writeln('Generated classes cleared successfully. Please re-run Magento compile command'); + $output->writeln( + "Generated classes cleared successfully. Please run the 'setup:di:compile' command to " + . 'generate classes.' + ); if ($input->getOption(self::INPUT_KEY_CLEAR_STATIC_CONTENT)) { $cleanupFiles->clearMaterializedViewFiles(); $output->writeln('Generated static view files cleared successfully.'); } else { $output->writeln( - 'Info: Some modules might require static view files to be cleared. Use the optional --' . - self::INPUT_KEY_CLEAR_STATIC_CONTENT . ' option to clear them.' + "Info: Some modules might require static view files to be cleared. To do this, run '" + . $this->getName() . "' with the --" . self::INPUT_KEY_CLEAR_STATIC_CONTENT + . ' option to clear them.' ); } } diff --git a/setup/src/Magento/Setup/Console/Command/AbstractModuleManageCommand.php b/setup/src/Magento/Setup/Console/Command/AbstractModuleManageCommand.php index 143632420a226..e207f114a69eb 100644 --- a/setup/src/Magento/Setup/Console/Command/AbstractModuleManageCommand.php +++ b/setup/src/Magento/Setup/Console/Command/AbstractModuleManageCommand.php @@ -6,8 +6,10 @@ namespace Magento\Setup\Console\Command; use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; +use Symfony\Component\Console\Input\InputOption; +use Magento\Framework\App\DeploymentConfig; +use Magento\Framework\Module\Status; abstract class AbstractModuleManageCommand extends AbstractModuleCommand { @@ -17,6 +19,11 @@ abstract class AbstractModuleManageCommand extends AbstractModuleCommand const INPUT_KEY_ALL = 'all'; const INPUT_KEY_FORCE = 'force'; + /** + * @var DeploymentConfig + */ + protected $deploymentConfig; + /** * {@inheritdoc} */ @@ -64,12 +71,8 @@ protected function execute(InputInterface $input, OutputInterface $output) $output->writeln(implode(PHP_EOL, $messages)); return; } - /** - * @var \Magento\Framework\Module\Status $status - */ - $status = $this->objectManager->get('Magento\Framework\Module\Status'); try { - $modulesToChange = $status->getModulesToChange($isEnable, $modules); + $modulesToChange = $this->getStatus()->getModulesToChange($isEnable, $modules); } catch (\LogicException $e) { $output->writeln('' . $e->getMessage() . ''); return; @@ -77,7 +80,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if (!empty($modulesToChange)) { $force = $input->getOption(self::INPUT_KEY_FORCE); if (!$force) { - $constraints = $status->checkConstraints($isEnable, $modulesToChange); + $constraints = $this->getStatus()->checkConstraints($isEnable, $modulesToChange); if ($constraints) { $output->writeln( "Unable to change status of modules because of the following constraints:" @@ -86,20 +89,7 @@ protected function execute(InputInterface $input, OutputInterface $output) return; } } - $status->setIsEnabled($isEnable, $modulesToChange); - if ($isEnable) { - $output->writeln('The following modules have been enabled:'); - $output->writeln('- ' . implode("\n- ", $modulesToChange) . ''); - $output->writeln(''); - $output->writeln( - 'To make sure that the enabled modules are properly registered,' - . " run 'setup:upgrade'." - ); - } else { - $output->writeln('The following modules have been disabled:'); - $output->writeln('- ' . implode("\n- ", $modulesToChange) . ''); - $output->writeln(''); - } + $this->setIsEnabled($isEnable, $modulesToChange, $output); $this->cleanup($input, $output); if ($force) { $output->writeln( @@ -112,6 +102,44 @@ protected function execute(InputInterface $input, OutputInterface $output) } } + /** + * Enable/disable modules + * + * @param bool $isEnable + * @param string[] $modulesToChange + * @param OutputInterface $output + * @return void + */ + private function setIsEnabled($isEnable, $modulesToChange, $output) + { + $this->getStatus()->setIsEnabled($isEnable, $modulesToChange); + if ($isEnable) { + $output->writeln('The following modules have been enabled:'); + $output->writeln('- ' . implode("\n- ", $modulesToChange) . ''); + $output->writeln(''); + if ($this->getDeploymentConfig()->isAvailable()) { + $output->writeln( + 'To make sure that the enabled modules are properly registered,' + . " run 'setup:upgrade'." + ); + } + } else { + $output->writeln('The following modules have been disabled:'); + $output->writeln('- ' . implode("\n- ", $modulesToChange) . ''); + $output->writeln(''); + } + } + + /** + * Get module status + * + * @return Status + */ + private function getStatus() + { + return $this->objectManager->get(Status::class); + } + /** * Validate list of modules and return error messages * @@ -134,4 +162,18 @@ protected function validate(array $modules) * @return bool */ abstract protected function isEnable(); + + /** + * Get deployment config + * + * @return DeploymentConfig + * @deprecated + */ + private function getDeploymentConfig() + { + if (!($this->deploymentConfig instanceof DeploymentConfig)) { + return $this->objectManager->get(DeploymentConfig::class); + } + return $this->deploymentConfig; + } } diff --git a/setup/src/Magento/Setup/Console/Command/DiCompileCommand.php b/setup/src/Magento/Setup/Console/Command/DiCompileCommand.php index 96f8fb7db1ccd..484ea598d9f31 100644 --- a/setup/src/Magento/Setup/Console/Command/DiCompileCommand.php +++ b/setup/src/Magento/Setup/Console/Command/DiCompileCommand.php @@ -3,15 +3,17 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ - namespace Magento\Setup\Console\Command; +use Magento\Framework\ObjectManagerInterface; +use Magento\Framework\Filesystem\DriverInterface; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; use Magento\Framework\Filesystem; use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Framework\Filesystem\DriverInterface; -use Magento\Framework\ObjectManagerInterface; use Magento\Framework\App\DeploymentConfig; use Magento\Framework\Component\ComponentRegistrar; +use Magento\Framework\Config\ConfigOptionsListConstants; use Magento\Setup\Model\ObjectManagerProvider; use Magento\Setup\Module\Di\App\Task\Manager; use Magento\Setup\Module\Di\App\Task\OperationFactory; @@ -19,8 +21,6 @@ use Magento\Setup\Module\Di\App\Task\OperationInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\ProgressBar; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; /** * Command to run compile in single-tenant mode @@ -107,8 +107,10 @@ protected function configure() private function checkEnvironment() { $messages = []; - if (!$this->deploymentConfig->isAvailable()) { - $messages[] = 'You cannot run this command because the Magento application is not installed.'; + $config = $this->deploymentConfig->get(ConfigOptionsListConstants::KEY_MODULES); + if (!$config) { + $messages[] = 'You cannot run this command because modules are not enabled. You can enable modules by' + . ' running the \'module:enable --all\' command.'; } /** diff --git a/setup/src/Magento/Setup/Controller/ComponentGrid.php b/setup/src/Magento/Setup/Controller/ComponentGrid.php index 06862187f9d05..a3db50df89fe8 100644 --- a/setup/src/Magento/Setup/Controller/ComponentGrid.php +++ b/setup/src/Magento/Setup/Controller/ComponentGrid.php @@ -6,6 +6,8 @@ namespace Magento\Setup\Controller; +use Magento\Setup\Model\DateTime\TimezoneProvider; + /** * Controller for component grid tasks * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -51,11 +53,16 @@ class ComponentGrid extends \Zend\Mvc\Controller\AbstractActionController */ private $timezone; + /** + * @var \Magento\Framework\ObjectManagerInterface + */ + private $objectManager; + /** * @param \Magento\Framework\Composer\ComposerInformation $composerInformation * @param \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider - * @param \Magento\Setup\Model\MarketplaceManager $marketplaceManager * @param \Magento\Setup\Model\UpdatePackagesCache $updatePackagesCache + * @param \Magento\Setup\Model\MarketplaceManager $marketplaceManager */ public function __construct( \Magento\Framework\Composer\ComposerInformation $composerInformation, @@ -64,13 +71,40 @@ public function __construct( \Magento\Setup\Model\MarketplaceManager $marketplaceManager ) { $this->composerInformation = $composerInformation; - $objectManager = $objectManagerProvider->get(); - $this->enabledModuleList = $objectManager->get('Magento\Framework\Module\ModuleList'); - $this->fullModuleList = $objectManager->get('Magento\Framework\Module\FullModuleList'); - $this->packageInfo = $objectManager->get('Magento\Framework\Module\PackageInfoFactory')->create(); + $this->objectManager = $objectManagerProvider->get(); + $this->enabledModuleList = $this->objectManager->get('Magento\Framework\Module\ModuleList'); + $this->fullModuleList = $this->objectManager->get('Magento\Framework\Module\FullModuleList'); + $this->packageInfo = $this->objectManager->get('Magento\Framework\Module\PackageInfoFactory')->create(); $this->marketplaceManager = $marketplaceManager; $this->updatePackagesCache = $updatePackagesCache; - $this->timezone = $objectManager->get('Magento\Framework\Stdlib\DateTime\TimezoneInterface'); + } + + /** + * Get timezone + * + * @return \Magento\Framework\Stdlib\DateTime\TimezoneInterface|null + */ + private function getTimezone() + { + if ($this->timezone === null) { + $this->timezone = $this->objectManager->get('Magento\Setup\Model\DateTime\TimezoneProvider')->get(); + } + return $this->timezone; + } + + /** + * Set timezone + * + * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone + * @return void + * @throws \Exception + */ + public function setTimezone(\Magento\Framework\Stdlib\DateTime\TimezoneInterface $timezone) + { + if ($this->timezone !== null) { + throw new \Exception('timezone is already set'); + } + $this->timezone = $timezone; } /** @@ -214,12 +248,12 @@ private function formatLastSyncData($packagesForInstall, $lastSyncData) private function formatSyncDate($syncDate) { return [ - 'date' => $this->timezone->formatDateTime( + 'date' => $this->getTimezone()->formatDateTime( new \DateTime('@'.$syncDate), \IntlDateFormatter::MEDIUM, \IntlDateFormatter::NONE ), - 'time' => $this->timezone->formatDateTime( + 'time' => $this->getTimezone()->formatDateTime( new \DateTime('@'.$syncDate), \IntlDateFormatter::NONE, \IntlDateFormatter::MEDIUM diff --git a/setup/src/Magento/Setup/Controller/Install.php b/setup/src/Magento/Setup/Controller/Install.php index 2eea8c52bef87..132a42b98f609 100644 --- a/setup/src/Magento/Setup/Controller/Install.php +++ b/setup/src/Magento/Setup/Controller/Install.php @@ -48,6 +48,11 @@ class Install extends AbstractActionController */ protected $sampleDataState; + /** + * @var \Magento\Framework\App\DeploymentConfig + */ + private $deploymentConfig; + /** * Default Constructor * @@ -89,6 +94,7 @@ public function startAction() $this->log->clear(); $json = new JsonModel; try { + $this->checkForPriorInstall(); $data = array_merge( $this->importDeploymentConfigForm(), $this->importUserConfigForm(), @@ -106,6 +112,7 @@ public function startAction() $json->setVariable('messages', $this->installer->getInstallInfo()[Installer::INFO_MESSAGE]); } catch (\Exception $e) { $this->log->logError($e); + $json->setVariable('messages', $e->getMessage()); $json->setVariable('success', false); } return $json; @@ -145,6 +152,19 @@ public function progressAction() return $json->setVariables(['progress' => $percent, 'success' => $success, 'console' => $contents]); } + /** + * Checks for prior install + * + * @return void + * @throws \Magento\Setup\Exception + */ + private function checkForPriorInstall() + { + if ($this->getDeploymentConfig()->isAvailable()) { + throw new \Magento\Setup\Exception('Magento application is already installed.'); + } + } + /** * Maps data from request to format of deployment config model * @@ -242,4 +262,20 @@ private function importAdminUserForm() $result[AdminAccount::KEY_LAST_NAME] = $result[AdminAccount::KEY_USER]; return $result; } + + /** + * Get Deployment Config + * + * @return \Magento\Framework\App\DeploymentConfig + * + * @deprecated + */ + private function getDeploymentConfig() + { + if ($this->deploymentConfig === null) { + $this->deploymentConfig = $this->installer->getObjectManagerProvider()->get() + ->get(\Magento\Framework\App\DeploymentConfig::class); + } + return $this->deploymentConfig; + } } diff --git a/setup/src/Magento/Setup/Model/ConfigGenerator.php b/setup/src/Magento/Setup/Model/ConfigGenerator.php index 3bb06a96b95b6..c2a209234e9df 100644 --- a/setup/src/Magento/Setup/Model/ConfigGenerator.php +++ b/setup/src/Magento/Setup/Model/ConfigGenerator.php @@ -64,6 +64,8 @@ public function __construct(Random $random, DeploymentConfig $deploymentConfig) /** * Creates install segment config data * + * @deprecated + * * @return ConfigData */ public function createInstallConfig() diff --git a/setup/src/Magento/Setup/Model/ConfigOptionsList.php b/setup/src/Magento/Setup/Model/ConfigOptionsList.php index 0a2d8f7127feb..7ef7b41a54d53 100644 --- a/setup/src/Magento/Setup/Model/ConfigOptionsList.php +++ b/setup/src/Magento/Setup/Model/ConfigOptionsList.php @@ -163,7 +163,6 @@ public function getOptions() public function createConfig(array $data, DeploymentConfig $deploymentConfig) { $configData = []; - $configData[] = $this->configGenerator->createInstallConfig($deploymentConfig); $configData[] = $this->configGenerator->createCryptConfig($data, $deploymentConfig); $configData[] = $this->configGenerator->createSessionConfig($data); $definitionConfig = $this->configGenerator->createDefinitionsConfig($data); diff --git a/setup/src/Magento/Setup/Model/DateTime/DateTimeProvider.php b/setup/src/Magento/Setup/Model/DateTime/DateTimeProvider.php new file mode 100644 index 0000000000000..073b6ee027bea --- /dev/null +++ b/setup/src/Magento/Setup/Model/DateTime/DateTimeProvider.php @@ -0,0 +1,63 @@ +tzProvider = $tzProvider; + $this->objectManagerProvider = $objectManagerProvider; + } + + /** + * Get instance of DateTime + * + * @return \Magento\Framework\Stdlib\DateTime\DateTime + */ + public function get() + { + if (!$this->dateTime) { + $this->dateTime = $this->objectManagerProvider->get()->create( + 'Magento\Framework\Stdlib\DateTime\DateTime', + ['localeDate' => $this->tzProvider->get()] + ); + } + return $this->dateTime; + } +} diff --git a/setup/src/Magento/Setup/Model/DateTime/TimezoneProvider.php b/setup/src/Magento/Setup/Model/DateTime/TimezoneProvider.php new file mode 100644 index 0000000000000..dfff802bc793c --- /dev/null +++ b/setup/src/Magento/Setup/Model/DateTime/TimezoneProvider.php @@ -0,0 +1,55 @@ +objectManagerProvider = $objectManagerProvider; + } + + /** + * Get instance of Timezone + * + * @return \Magento\Framework\Stdlib\DateTime\Timezone + */ + public function get() + { + if (!$this->timezone) { + $this->timezone = $this->objectManagerProvider->get()->create( + 'Magento\Framework\Stdlib\DateTime\Timezone', + ['scopeType' => ScopeConfigInterface::SCOPE_TYPE_DEFAULT] + ); + } + return $this->timezone; + } +} diff --git a/setup/src/Magento/Setup/Model/Installer.php b/setup/src/Magento/Setup/Model/Installer.php index a5da578b24eef..2874decd68fbc 100644 --- a/setup/src/Magento/Setup/Model/Installer.php +++ b/setup/src/Magento/Setup/Model/Installer.php @@ -13,6 +13,7 @@ use Magento\Framework\App\ResourceConnection\Config; use Magento\Framework\Component\ComponentRegistrar; use Magento\Framework\Config\ConfigOptionsListConstants; +use Magento\Framework\Config\Data\ConfigData; use Magento\Framework\Filesystem; use Magento\Framework\Exception\FileSystemException; use Magento\Framework\Model\ResourceModel\Db\Context; @@ -319,6 +320,7 @@ public function install($request) $script[] = ['Caches clearing:', 'cleanCaches', []]; $script[] = ['Disabling Maintenance Mode:', 'setMaintenanceMode', [0]]; $script[] = ['Post installation file permissions check...', 'checkApplicationFilePermissions', []]; + $script[] = ['Write installation date...', 'writeInstallationDate', []]; $estimatedModules = $this->createModulesConfig($request); $total = count($script) + 3 * count(array_filter($estimatedModules)); @@ -346,6 +348,20 @@ public function install($request) } } + /** + * Writes installation date to the configuration + * + * @return void + * @SuppressWarnings(PHPMD.UnusedPrivateMethod) Called by install() via callback. + */ + private function writeInstallationDate() + { + $dateData = new ConfigData(ConfigFilePool::APP_ENV); + $dateData->set(ConfigOptionsListConstants::CONFIG_PATH_INSTALL_DATE, date('r')); + $configData = [$dateData->getFileKey() => $dateData->getData()]; + $this->deploymentConfigWriter->saveConfig($configData); + } + /** * Creates modules deployment configuration segment * @@ -356,11 +372,9 @@ public function install($request) private function createModulesConfig($request) { $all = array_keys($this->moduleLoader->load()); - $currentModules = []; - if ($this->deploymentConfig->isAvailable()) { - $deploymentConfig = $this->deploymentConfigReader->load(); - $currentModules = isset($deploymentConfig['modules']) ? $deploymentConfig['modules'] : [] ; - } + $deploymentConfig = $this->deploymentConfigReader->load(); + $currentModules = isset($deploymentConfig[ConfigOptionsListConstants::KEY_MODULES]) + ? $deploymentConfig[ConfigOptionsListConstants::KEY_MODULES] : [] ; $enable = $this->readListOfModules($all, $request, self::ENABLE_MODULES); $disable = $this->readListOfModules($all, $request, self::DISABLE_MODULES); $result = []; @@ -466,16 +480,24 @@ public function installDeploymentConfig($data) $this->checkInstallationFilePermissions(); $userData = is_array($data) ? $data : $data->getArrayCopy(); $this->setupConfigModel->process($userData); - if ($this->deploymentConfig->isAvailable()) { - $deploymentConfigData = $this->deploymentConfig->get(ConfigOptionsListConstants::CONFIG_PATH_CRYPT_KEY); - if (isset($deploymentConfigData)) { - $this->installInfo[ConfigOptionsListConstants::KEY_ENCRYPTION_KEY] = $deploymentConfigData; - } + $deploymentConfigData = $this->deploymentConfig->get(ConfigOptionsListConstants::CONFIG_PATH_CRYPT_KEY); + if (isset($deploymentConfigData)) { + $this->installInfo[ConfigOptionsListConstants::KEY_ENCRYPTION_KEY] = $deploymentConfigData; } // reset object manager now that there is a deployment config $this->objectManagerProvider->reset(); } + /** + * Get Object Manager Provider + * + * @return ObjectManagerProvider + */ + public function getObjectManagerProvider() + { + return $this->objectManagerProvider; + } + /** * Set up setup_module table to register modules' versions, skip this process if it already exists * @@ -725,6 +747,8 @@ private function setupFlagTable( */ public function installSchema() { + $this->assertDbConfigExists(); + $this->assertDbAccessible(); $setup = $this->setupFactory->create($this->context->getResources()); $this->setupModuleRegistry($setup); $this->setupCoreTables($setup); @@ -740,6 +764,8 @@ public function installSchema() */ public function installDataFixtures() { + $this->assertDbConfigExists(); + $this->assertDbAccessible(); $setup = $this->dataSetupFactory->create(); $this->checkInstallationFilePermissions(); $this->log->log('Data install/update:'); @@ -763,9 +789,6 @@ private function handleDBSchemaData($setup, $type) throw new \Magento\Setup\Exception("Unsupported operation type $type is requested"); } - $this->assertDeploymentConfigExists(); - $this->assertDbAccessible(); - $resource = new \Magento\Framework\Module\ModuleResource($this->context); $verType = $type . '-version'; $installType = $type . '-install'; @@ -825,6 +848,20 @@ private function handleDBSchemaData($setup, $type) } } + /** + * @return void + * @throws \Magento\Setup\Exception + */ + private function assertDbConfigExists() + { + $config = $this->deploymentConfig->get(ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTION_DEFAULT); + if (!$config) { + throw new \Magento\Setup\Exception( + "Can't run this operation: configuration for DB connection is absent." + ); + } + } + /** * Installs user configuration * @@ -922,7 +959,7 @@ private function installOrderIncrementPrefix($orderIncrementPrefix) */ public function installAdminUser($data) { - $this->assertDeploymentConfigExists(); + $this->assertDbConfigExists(); $setup = $this->setupFactory->create($this->context->getResources()); $adminAccount = $this->adminAccountFactory->create($setup, (array)$data); $adminAccount->save(); @@ -936,10 +973,15 @@ public function installAdminUser($data) */ public function updateModulesSequence($keepGeneratedCode = false) { - $this->assertDeploymentConfigExists(); + $config = $this->deploymentConfig->get(ConfigOptionsListConstants::KEY_MODULES); + if (!$config) { + throw new \Magento\Setup\Exception( + "Can't run this operation: deployment configuration is absent." + . " Run 'magento setup:config:set --help' for options." + ); + } $this->cleanCaches(); - if (!$keepGeneratedCode) { $this->cleanupGeneratedCode(); } @@ -1035,27 +1077,24 @@ public function getInstallInfo() */ public function cleanupDb() { - // stops cleanup if configuration does not exist - if ($this->deploymentConfig->isAvailable()) { - $config = $this->deploymentConfig->get(ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTION_DEFAULT); - if ($config) { - try { - $connection = $this->connectionFactory->create($config); - if (!$connection) { - $this->log->log("Can't create connection to database - skipping database cleanup"); - } - } catch (\Exception $e) { - $this->log->log($e->getMessage() . ' - skipping database cleanup'); - return; + $config = $this->deploymentConfig->get(ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTION_DEFAULT); + if ($config) { + try { + $connection = $this->connectionFactory->create($config); + if (!$connection) { + $this->log->log("Can't create connection to database - skipping database cleanup"); } - $dbName = $connection->quoteIdentifier($config[ConfigOptionsListConstants::KEY_NAME]); - $this->log->log("Cleaning up database {$dbName}"); - $connection->query("DROP DATABASE IF EXISTS {$dbName}"); - $connection->query("CREATE DATABASE IF NOT EXISTS {$dbName}"); + } catch (\Exception $e) { + $this->log->log($e->getMessage() . ' - skipping database cleanup'); return; } + $dbName = $connection->quoteIdentifier($config[ConfigOptionsListConstants::KEY_NAME]); + $this->log->log("Cleaning up database {$dbName}"); + $connection->query("DROP DATABASE IF EXISTS {$dbName}"); + $connection->query("CREATE DATABASE IF NOT EXISTS {$dbName}"); + } else { + $this->log->log('No database connection defined - skipping database cleanup'); } - $this->log->log('No database connection defined - skipping database cleanup'); } /** @@ -1085,8 +1124,12 @@ private function deleteDeploymentConfig() /** * Validates that deployment configuration exists * + * @deprecated + * * @throws \Magento\Setup\Exception * @return void + * + * @SuppressWarnings(PHPMD.UnusedPrivateMethod) */ private function assertDeploymentConfigExists() { diff --git a/setup/src/Magento/Setup/Model/ObjectManagerProvider.php b/setup/src/Magento/Setup/Model/ObjectManagerProvider.php index 060b804cb9323..c2c30dda09604 100644 --- a/setup/src/Magento/Setup/Model/ObjectManagerProvider.php +++ b/setup/src/Magento/Setup/Model/ObjectManagerProvider.php @@ -51,15 +51,6 @@ public function get() $initParams = $this->serviceLocator->get(InitParamListener::BOOTSTRAP_PARAM); $factory = Bootstrap::createObjectManagerFactory(BP, $initParams); $this->objectManager = $factory->create($initParams); - $this->objectManager->configure( - [ - 'Magento\Framework\Stdlib\DateTime\Timezone' => [ - 'arguments' => [ - 'scopeType' => \Magento\Framework\App\Config\ScopeConfigInterface::SCOPE_TYPE_DEFAULT - ] - ] - ] - ); } return $this->objectManager; } diff --git a/setup/src/Magento/Setup/Model/UpdatePackagesCache.php b/setup/src/Magento/Setup/Model/UpdatePackagesCache.php index 918097d9eeffd..a8e390db4e74d 100644 --- a/setup/src/Magento/Setup/Model/UpdatePackagesCache.php +++ b/setup/src/Magento/Setup/Model/UpdatePackagesCache.php @@ -11,9 +11,12 @@ use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Filesystem; use Magento\Framework\Composer\MagentoComposerApplicationFactory; +use Magento\Framework\ObjectManagerInterface; /** * Class UpdatePackagesCache manages information about available for update packages though the cache file. + * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class UpdatePackagesCache { @@ -51,6 +54,11 @@ class UpdatePackagesCache */ private $pathToCacheFile = 'update_composer_packages.json'; + /** + * @var ObjectManagerInterface + */ + private $objectManager; + /** * Constructor * @@ -68,10 +76,38 @@ public function __construct( ) { $this->application = $applicationFactory->create(); $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR); - $this->dateTime = $objectManagerProvider->get()->get('Magento\Framework\Stdlib\DateTime\DateTime'); + $this->objectManager = $objectManagerProvider->get(); $this->composerInformation = $composerInformation; } + /** + * Get datetime + * + * @return \Magento\Framework\Stdlib\DateTime\DateTime + */ + private function getDateTime() + { + if ($this->dateTime === null) { + $this->dateTime = $this->objectManager->get('Magento\Setup\Model\DateTime\DateTimeProvider')->get(); + } + return $this->dateTime; + } + + /** + * Set datetime + * + * @param \Magento\Framework\Stdlib\DateTime\DateTime $dateTime + * @return void + * @throws \Exception + */ + public function setDateTime(\Magento\Framework\Stdlib\DateTime\DateTime $dateTime) + { + if ($this->dateTime !== null) { + throw new \Exception('dateTime is already set'); + } + $this->dateTime = $dateTime; + } + /** * Sync and cache list of available for update versions for packages * @@ -172,7 +208,7 @@ private function getPackageAvailableVersions($package) private function savePackagesForUpdateToCache($availableVersions) { $syncInfo = []; - $syncInfo['lastSyncDate'] = $this->dateTime->gmtTimestamp(); + $syncInfo['lastSyncDate'] = $this->getDateTime()->gmtTimestamp(); $syncInfo['packages'] = $availableVersions; $data = json_encode($syncInfo, JSON_UNESCAPED_SLASHES); try { diff --git a/setup/src/Magento/Setup/Mvc/Bootstrap/InitParamListener.php b/setup/src/Magento/Setup/Mvc/Bootstrap/InitParamListener.php index 769b3b634d021..777f87515d665 100644 --- a/setup/src/Magento/Setup/Mvc/Bootstrap/InitParamListener.php +++ b/setup/src/Magento/Setup/Mvc/Bootstrap/InitParamListener.php @@ -8,6 +8,7 @@ use Magento\Framework\App\Bootstrap as AppBootstrap; use Magento\Framework\App\Filesystem\DirectoryList; +use Magento\Framework\App\Request\Http; use Magento\Framework\App\State; use Magento\Framework\Filesystem; use Magento\Framework\Shell\ComplexParameter; @@ -47,9 +48,7 @@ class InitParamListener implements ListenerAggregateInterface, FactoryInterface */ private $controllersToSkip = [ 'Magento\Setup\Controller\Session', - 'Magento\Setup\Controller\Install', 'Magento\Setup\Controller\Success' - ]; /** @@ -102,7 +101,7 @@ public function onBootstrap(MvcEvent $e) /** * Check if user login * - * @param object $event + * @param \Zend\Mvc\MvcEvent $event * @return bool * @throws \Magento\Framework\Exception\LocalizedException */ @@ -117,25 +116,31 @@ public function authPreDispatch($event) $application = $event->getApplication(); $serviceManager = $application->getServiceManager(); if ($serviceManager->get('Magento\Framework\App\DeploymentConfig')->isAvailable()) { + /** @var \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider */ $objectManagerProvider = $serviceManager->get('Magento\Setup\Model\ObjectManagerProvider'); /** @var \Magento\Framework\ObjectManagerInterface $objectManager */ $objectManager = $objectManagerProvider->get(); /** @var \Magento\Framework\App\State $adminAppState */ $adminAppState = $objectManager->get('Magento\Framework\App\State'); $adminAppState->setAreaCode(\Magento\Framework\App\Area::AREA_ADMIN); - $objectManager->create( - 'Magento\Backend\Model\Auth\Session', + /** @var \Magento\Backend\Model\Session\AdminConfig $sessionConfig */ + $sessionConfig = $objectManager->get(\Magento\Backend\Model\Session\AdminConfig::class); + $cookiePath = $this->getSetupCookiePath($objectManager); + $sessionConfig->setCookiePath($cookiePath); + /** @var \Magento\Backend\Model\Auth\Session $adminSession */ + $adminSession = $objectManager->create( + \Magento\Backend\Model\Auth\Session::class, [ - 'sessionConfig' => $objectManager->get('Magento\Backend\Model\Session\AdminConfig'), + 'sessionConfig' => $sessionConfig, 'appState' => $adminAppState ] ); - - if (!$objectManager->get('Magento\Backend\Model\Auth')->isLoggedIn()) { + if (!$objectManager->get(\Magento\Backend\Model\Auth::class)->isLoggedIn()) { + $adminSession->destroy(); $response = $event->getResponse(); - $response->getHeaders()->addHeaderLine('Location', 'index.php/session/unlogin'); + $baseUrl = Http::getDistroBaseUrlPath($_SERVER); + $response->getHeaders()->addHeaderLine('Location', $baseUrl . 'index.php/session/unlogin'); $response->setStatusCode(302); - $event->stopPropagation(); return $response; } @@ -144,6 +149,25 @@ public function authPreDispatch($event) return false; } + /** + * Get cookie path + * + * @param \Magento\Framework\ObjectManagerInterface $objectManager + * @return string + */ + private function getSetupCookiePath(\Magento\Framework\ObjectManagerInterface $objectManager) + { + /** @var \Magento\Backend\App\BackendAppList $backendAppList */ + $backendAppList = $objectManager->get(\Magento\Backend\App\BackendAppList::class); + $backendApp = $backendAppList->getBackendApp('setup'); + /** @var \Magento\Backend\Model\UrlFactory $backendUrlFactory */ + $backendUrlFactory = $objectManager->get(\Magento\Backend\Model\UrlFactory::class); + $baseUrl = parse_url($backendUrlFactory->create()->getBaseUrl(), PHP_URL_PATH); + $baseUrl = \Magento\Framework\App\Request\Http::getUrlNoScript($baseUrl); + $cookiePath = $baseUrl . $backendApp->getCookiePath(); + return $cookiePath; + } + /** * {@inheritdoc} */ diff --git a/setup/src/Magento/Setup/Test/Unit/Console/Command/DiCompileCommandTest.php b/setup/src/Magento/Setup/Test/Unit/Console/Command/DiCompileCommandTest.php index 163fc13c515f7..3199790b0da1d 100644 --- a/setup/src/Magento/Setup/Test/Unit/Console/Command/DiCompileCommandTest.php +++ b/setup/src/Magento/Setup/Test/Unit/Console/Command/DiCompileCommandTest.php @@ -12,13 +12,13 @@ class DiCompileCommandTest extends \PHPUnit_Framework_TestCase { /** @var \Magento\Framework\App\DeploymentConfig|\PHPUnit_Framework_MockObject_MockObject */ - private $deploymentConfig; + private $deploymentConfigMock; /** @var \Magento\Setup\Module\Di\App\Task\Manager|\PHPUnit_Framework_MockObject_MockObject */ - private $manager; + private $managerMock; /** @var \Magento\Framework\ObjectManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ - private $objectManager; + private $objectManagerMock; /** @var DiCompileCommand|\PHPUnit_Framework_MockObject_MockObject */ private $command; @@ -27,28 +27,28 @@ class DiCompileCommandTest extends \PHPUnit_Framework_TestCase private $cacheMock; /** @var \Magento\Framework\Filesystem|\PHPUnit_Framework_MockObject_MockObject */ - private $filesystem; + private $filesystemMock; - /** @var \Magento\Framework\Filesystem\Driver\File | \PHPUnit_Framework_MockObject_MockObject*/ - private $fileDriver; + /** @var \Magento\Framework\Filesystem\Driver\File|\PHPUnit_Framework_MockObject_MockObject */ + private $fileDriverMock; - /** @var \Magento\Framework\App\Filesystem\DirectoryList | \PHPUnit_Framework_MockObject_MockObject*/ - private $directoryList; + /** @var \Magento\Framework\App\Filesystem\DirectoryList|\PHPUnit_Framework_MockObject_MockObject */ + private $directoryListMock; /** @var \Magento\Framework\Component\ComponentRegistrar|\PHPUnit_Framework_MockObject_MockObject */ - private $componentRegistrar; + private $componentRegistrarMock; public function setUp() { - $this->deploymentConfig = $this->getMock('Magento\Framework\App\DeploymentConfig', [], [], '', false); - $objectManagerProvider = $this->getMock( + $this->deploymentConfigMock = $this->getMock('Magento\Framework\App\DeploymentConfig', [], [], '', false); + $objectManagerProviderMock = $this->getMock( 'Magento\Setup\Model\ObjectManagerProvider', [], [], '', false ); - $this->objectManager = $this->getMockForAbstractClass( + $this->objectManagerMock = $this->getMockForAbstractClass( 'Magento\Framework\ObjectManagerInterface', [], '', @@ -58,91 +58,87 @@ public function setUp() ->disableOriginalConstructor() ->getMock(); - $objectManagerProvider->expects($this->once()) + $objectManagerProviderMock->expects($this->once()) ->method('get') - ->willReturn($this->objectManager); - $this->manager = $this->getMock('Magento\Setup\Module\Di\App\Task\Manager', [], [], '', false); - $this->directoryList = $this->getMock('Magento\Framework\App\Filesystem\DirectoryList', [], [], '', false); - $this->filesystem = $this->getMockBuilder('Magento\Framework\Filesystem') + ->willReturn($this->objectManagerMock); + $this->managerMock = $this->getMock('Magento\Setup\Module\Di\App\Task\Manager', [], [], '', false); + $this->directoryListMock = $this->getMock('Magento\Framework\App\Filesystem\DirectoryList', [], [], '', false); + $this->filesystemMock = $this->getMockBuilder('Magento\Framework\Filesystem') ->disableOriginalConstructor() ->getMock(); - $this->fileDriver = $this->getMockBuilder('Magento\Framework\Filesystem\Driver\File') + $this->fileDriverMock = $this->getMockBuilder('Magento\Framework\Filesystem\Driver\File') ->disableOriginalConstructor() ->getMock(); - $this->componentRegistrar = $this->getMock( + $this->componentRegistrarMock = $this->getMock( '\Magento\Framework\Component\ComponentRegistrar', [], [], '', false ); - $this->componentRegistrar->expects($this->any())->method('getPaths')->willReturnMap([ + $this->componentRegistrarMock->expects($this->any())->method('getPaths')->willReturnMap([ [ComponentRegistrar::MODULE, ['/path/to/module/one', '/path/to/module/two']], [ComponentRegistrar::LIBRARY, ['/path/to/library/one', '/path/to/library/two']], ]); $this->command = new DiCompileCommand( - $this->deploymentConfig, - $this->directoryList, - $this->manager, - $objectManagerProvider, - $this->filesystem, - $this->fileDriver, - $this->componentRegistrar + $this->deploymentConfigMock, + $this->directoryListMock, + $this->managerMock, + $objectManagerProviderMock, + $this->filesystemMock, + $this->fileDriverMock, + $this->componentRegistrarMock ); } - public function testExecuteDiExists() + public function testExecuteModulesNotEnabled() { - $diPath = '/root/magento/var/di'; - $this->deploymentConfig->expects($this->once())->method('isAvailable')->willReturn(true); - $this->fileDriver->expects($this->atLeastOnce())->method('isExists')->with($diPath)->willReturn(true); - $this->directoryList->expects($this->atLeastOnce())->method('getPath')->willReturn($diPath); - $tester = new CommandTester($this->command); - $tester->execute([]); - $this->assertContains("delete '/root/magento/var/di'", $tester->getDisplay()); - } - - public function testExecuteNotInstalled() - { - $this->directoryList->expects($this->atLeastOnce())->method('getPath')->willReturn(null); - $this->deploymentConfig->expects($this->once())->method('isAvailable')->willReturn(false); + $this->directoryListMock->expects($this->atLeastOnce())->method('getPath')->willReturn(null); + $this->deploymentConfigMock->expects($this->once()) + ->method('get') + ->with(\Magento\Framework\Config\ConfigOptionsListConstants::KEY_MODULES) + ->willReturn(null); $tester = new CommandTester($this->command); $tester->execute([]); $this->assertEquals( - 'You cannot run this command because the Magento application is not installed.' . PHP_EOL, + 'You cannot run this command because modules are not enabled. You can enable modules by running the ' + . "'module:enable --all' command." . PHP_EOL, $tester->getDisplay() ); } public function testExecute() { - $this->directoryList->expects($this->atLeastOnce())->method('getPath')->willReturn(null); - $this->objectManager->expects($this->once()) + $this->directoryListMock->expects($this->atLeastOnce())->method('getPath')->willReturn(null); + $this->objectManagerMock->expects($this->once()) ->method('get') ->with('Magento\Framework\App\Cache') ->willReturn($this->cacheMock); $this->cacheMock->expects($this->once())->method('clean'); $writeDirectory = $this->getMock('Magento\Framework\Filesystem\Directory\WriteInterface'); $writeDirectory->expects($this->atLeastOnce())->method('delete'); - $this->filesystem->expects($this->atLeastOnce())->method('getDirectoryWrite')->willReturn($writeDirectory); + $this->filesystemMock->expects($this->atLeastOnce())->method('getDirectoryWrite')->willReturn($writeDirectory); - $this->deploymentConfig->expects($this->once())->method('isAvailable')->willReturn(true); + $this->deploymentConfigMock->expects($this->once()) + ->method('get') + ->with(\Magento\Framework\Config\ConfigOptionsListConstants::KEY_MODULES) + ->willReturn(['Magento_Catalog' => 1]); $progressBar = $this->getMockBuilder( 'Symfony\Component\Console\Helper\ProgressBar' ) ->disableOriginalConstructor() ->getMock(); - $this->objectManager->expects($this->once())->method('configure'); - $this->objectManager + $this->objectManagerMock->expects($this->once())->method('configure'); + $this->objectManagerMock ->expects($this->once()) ->method('create') ->with('Symfony\Component\Console\Helper\ProgressBar') ->willReturn($progressBar); - $this->manager->expects($this->exactly(7))->method('addOperation'); - $this->manager->expects($this->once())->method('process'); + $this->managerMock->expects($this->exactly(7))->method('addOperation'); + $this->managerMock->expects($this->once())->method('process'); $tester = new CommandTester($this->command); $tester->execute([]); $this->assertContains( diff --git a/setup/src/Magento/Setup/Test/Unit/Console/Command/ModuleEnableDisableCommandTest.php b/setup/src/Magento/Setup/Test/Unit/Console/Command/ModuleEnableDisableCommandTest.php index 7001224977d1f..41b05cc302b19 100644 --- a/setup/src/Magento/Setup/Test/Unit/Console/Command/ModuleEnableDisableCommandTest.php +++ b/setup/src/Magento/Setup/Test/Unit/Console/Command/ModuleEnableDisableCommandTest.php @@ -14,46 +14,58 @@ class ModuleEnableDisableCommandTest extends \PHPUnit_Framework_TestCase /** * @var \Magento\Setup\Model\ObjectManagerProvider|\PHPUnit_Framework_MockObject_MockObject */ - private $objectManagerProvider; + private $objectManagerProviderMock; /** * @var \Magento\Framework\Module\Status|\PHPUnit_Framework_MockObject_MockObject */ - private $status; + private $statusMock; /** * @var \Magento\Framework\App\Cache|\PHPUnit_Framework_MockObject_MockObject */ - private $cache; + private $cacheMock; /** * @var \Magento\Framework\App\State\CleanupFiles|\PHPUnit_Framework_MockObject_MockObject */ - private $cleanupFiles; + private $cleanupFilesMock; /** * @var \Magento\Framework\Module\FullModuleList|\PHPUnit_Framework_MockObject_MockObject */ - private $fullModuleList; + private $fullModuleListMock; + + /** + * @var \Magento\Framework\App\DeploymentConfig|\PHPUnit_Framework_MockObject_MockObject + */ + private $deploymentConfigMock; protected function setUp() { - $this->objectManagerProvider = $this->getMock('Magento\Setup\Model\ObjectManagerProvider', [], [], '', false); + $this->objectManagerProviderMock = $this->getMock( + 'Magento\Setup\Model\ObjectManagerProvider', + [], + [], + '', + false + ); $objectManager = $this->getMockForAbstractClass('Magento\Framework\ObjectManagerInterface'); - $this->objectManagerProvider->expects($this->any()) + $this->objectManagerProviderMock->expects($this->any()) ->method('get') ->will($this->returnValue($objectManager)); - $this->status = $this->getMock('Magento\Framework\Module\Status', [], [], '', false); - $this->cache = $this->getMock('Magento\Framework\App\Cache', [], [], '', false); - $this->cleanupFiles = $this->getMock('Magento\Framework\App\State\CleanupFiles', [], [], '', false); - $this->fullModuleList = $this->getMock('Magento\Framework\Module\FullModuleList', [], [], '', false); + $this->statusMock = $this->getMock('Magento\Framework\Module\Status', [], [], '', false); + $this->cacheMock = $this->getMock('Magento\Framework\App\Cache', [], [], '', false); + $this->cleanupFilesMock = $this->getMock('Magento\Framework\App\State\CleanupFiles', [], [], '', false); + $this->fullModuleListMock = $this->getMock('Magento\Framework\Module\FullModuleList', [], [], '', false); + $this->deploymentConfigMock = $this->getMock(\Magento\Framework\App\DeploymentConfig::class, [], [], '', false); $objectManager->expects($this->any()) ->method('get') ->will($this->returnValueMap([ - ['Magento\Framework\Module\Status', $this->status], - ['Magento\Framework\App\Cache', $this->cache], - ['Magento\Framework\App\State\CleanupFiles', $this->cleanupFiles], - ['Magento\Framework\Module\FullModuleList', $this->fullModuleList], + ['Magento\Framework\Module\Status', $this->statusMock], + ['Magento\Framework\App\Cache', $this->cacheMock], + ['Magento\Framework\App\State\CleanupFiles', $this->cleanupFilesMock], + ['Magento\Framework\Module\FullModuleList', $this->fullModuleListMock], ])); } @@ -66,35 +78,30 @@ protected function setUp() */ public function testExecute($isEnable, $clearStaticContent, $expectedMessage) { - $this->status->expects($this->once()) + $this->statusMock->expects($this->once()) ->method('getModulesToChange') ->with($isEnable, ['Magento_Module1', 'Magento_Module2']) ->will($this->returnValue(['Magento_Module1'])); - - $this->status->expects($this->any()) + $this->statusMock->expects($this->any()) ->method('checkConstraints') ->will($this->returnValue([])); - - $this->status->expects($this->once()) + $this->statusMock->expects($this->once()) ->method('setIsEnabled') ->with($isEnable, ['Magento_Module1']); - - $this->cache->expects($this->once()) + $this->cacheMock->expects($this->once()) ->method('clean'); - $this->cleanupFiles->expects($this->once()) + $this->cleanupFilesMock->expects($this->once()) ->method('clearCodeGeneratedClasses'); - $this->cleanupFiles->expects($clearStaticContent ? $this->once() : $this->never()) + $this->cleanupFilesMock->expects($clearStaticContent ? $this->once() : $this->never()) ->method('clearMaterializedViewFiles'); - - $commandTester = $isEnable - ? new CommandTester(new ModuleEnableCommand($this->objectManagerProvider)) - : new CommandTester(new ModuleDisableCommand($this->objectManagerProvider)); + $commandTester = $this->getCommandTester($isEnable); $input = ['module' => ['Magento_Module1', 'Magento_Module2']]; if ($clearStaticContent) { $input['--clear-static-content'] = true; } $commandTester->execute($input); - $this->assertStringMatchesFormat($expectedMessage, $commandTester->getDisplay()); + $display = $commandTester->getDisplay(); + $this->assertStringMatchesFormat($expectedMessage, $display); } /** @@ -106,14 +113,16 @@ public function executeDataProvider() 'enable, do not clear static content' => [ true, false, - '%amodules have been enabled%aMagento_Module1%a' . - 'Info: Some modules might require static view files to be cleared.%a' + '%amodules have been enabled%aMagento_Module1%a' + . "Info: Some modules might require static view files to be cleared. To do this, run " + . "'module:enable' with the --clear-static-content%a" ], 'disable, do not clear static content' => [ false, false, - '%amodules have been disabled%aMagento_Module1%a' . - 'Info: Some modules might require static view files to be cleared.%a' + '%amodules have been disabled%aMagento_Module1%a' + . "Info: Some modules might require static view files to be cleared. To do this, run " + . "'module:disable' with the --clear-static-content%a" ], 'enable, clear static content' => [ true, @@ -124,17 +133,17 @@ public function executeDataProvider() false, true, '%amodules have been disabled%aMagento_Module1%aGenerated static view files cleared%a' - ], + ] ]; } public function testExecuteEnableInvalidModule() { - $this->status->expects($this->once()) + $this->statusMock->expects($this->once()) ->method('getModulesToChange') ->with(true, ['invalid']) ->willThrowException(new \LogicException('Unknown module(s): invalid')); - $commandTester = new CommandTester(new ModuleEnableCommand($this->objectManagerProvider)); + $commandTester = $this->getCommandTester(true); $input = ['module' => ['invalid']]; $commandTester->execute($input); $this->assertEquals('Unknown module(s): invalid' . PHP_EOL, $commandTester->getDisplay()); @@ -142,11 +151,11 @@ public function testExecuteEnableInvalidModule() public function testExecuteDisableInvalidModule() { - $this->status->expects($this->once()) + $this->statusMock->expects($this->once()) ->method('getModulesToChange') ->with(false, ['invalid']) ->willThrowException(new \LogicException('Unknown module(s): invalid')); - $commandTester = new CommandTester(new ModuleDisableCommand($this->objectManagerProvider)); + $commandTester = $this->getCommandTester(false); $input = ['module' => ['invalid']]; $commandTester->execute($input); $this->assertEquals('Unknown module(s): invalid' . PHP_EOL, $commandTester->getDisplay()); @@ -155,34 +164,44 @@ public function testExecuteDisableInvalidModule() /** * @param bool $isEnable * @param string $expectedMessage + * @param bool $isInstalled * * @dataProvider executeAllDataProvider */ public function testExecuteAll($isEnable, $expectedMessage) { - $this->fullModuleList->expects($this->once()) + $setupUpgradeMessage = 'To make sure that the enabled modules are properly registered, run \'setup:upgrade\'.'; + $this->fullModuleListMock->expects($this->once()) ->method('getNames') ->will($this->returnValue(['Magento_Module1', 'Magento_Module2'])); - - $this->status->expects($this->once()) + $this->statusMock->expects($this->once()) ->method('getModulesToChange') ->with($isEnable, ['Magento_Module1', 'Magento_Module2']) ->will($this->returnValue(['Magento_Module1'])); - - $this->status->expects($this->any()) + $this->statusMock->expects($this->any()) ->method('checkConstraints') ->will($this->returnValue([])); - - $this->status->expects($this->once()) + $this->statusMock->expects($this->once()) ->method('setIsEnabled') ->with($isEnable, ['Magento_Module1']); - - $commandTester = $isEnable - ? new CommandTester(new ModuleEnableCommand($this->objectManagerProvider)) - : new CommandTester(new ModuleDisableCommand($this->objectManagerProvider)); + if ($isEnable) { + $this->deploymentConfigMock->expects($this->once()) + ->method('isAvailable') + ->willReturn(['Magento_Module1']); + } else { + $this->deploymentConfigMock->expects($this->never()) + ->method('isAvailable'); + } + $commandTester = $this->getCommandTester($isEnable); $input = ['--all' => true]; $commandTester->execute($input); - $this->assertStringMatchesFormat($expectedMessage, $commandTester->getDisplay()); + $output = $commandTester->getDisplay(); + $this->assertStringMatchesFormat($expectedMessage, $output); + if ($isEnable) { + $this->assertContains($setupUpgradeMessage, $output); + } else { + $this->assertNotContains($setupUpgradeMessage, $output); + } } /** @@ -203,21 +222,16 @@ public function executeAllDataProvider() */ public function testExecuteWithConstraints($isEnable) { - $this->status->expects($this->once()) + $this->statusMock->expects($this->once()) ->method('getModulesToChange') ->with($isEnable, ['Magento_Module1', 'Magento_Module2']) ->will($this->returnValue(['Magento_Module1'])); - - $this->status->expects($this->any()) + $this->statusMock->expects($this->any()) ->method('checkConstraints') ->will($this->returnValue(['constraint1', 'constraint2'])); - - $this->status->expects($this->never()) + $this->statusMock->expects($this->never()) ->method('setIsEnabled'); - - $commandTester = $isEnable - ? new CommandTester(new ModuleEnableCommand($this->objectManagerProvider)) - : new CommandTester(new ModuleDisableCommand($this->objectManagerProvider)); + $commandTester = $this->getCommandTester($isEnable); $commandTester->execute(['module' => ['Magento_Module1', 'Magento_Module2']]); $this->assertStringMatchesFormat( 'Unable to change status of modules%aconstraint1%aconstraint2%a', @@ -244,21 +258,16 @@ public function executeWithConstraintsDataProvider() */ public function testExecuteForce($isEnable, $expectedMessage) { - $this->status->expects($this->once()) + $this->statusMock->expects($this->once()) ->method('getModulesToChange') ->with($isEnable, ['Magento_Module1', 'Magento_Module2']) ->will($this->returnValue(['Magento_Module1'])); - - $this->status->expects($this->never()) + $this->statusMock->expects($this->never()) ->method('checkConstraints'); - - $this->status->expects($this->once()) + $this->statusMock->expects($this->once()) ->method('setIsEnabled') ->with($isEnable, ['Magento_Module1']); - - $commandTester = $isEnable - ? new CommandTester(new ModuleEnableCommand($this->objectManagerProvider)) - : new CommandTester(new ModuleDisableCommand($this->objectManagerProvider)); + $commandTester = $this->getCommandTester($isEnable); $commandTester->execute(['module' => ['Magento_Module1', 'Magento_Module2'], '--force' => true]); $this->assertStringMatchesFormat( $expectedMessage . '%amodules might not function properly%a', @@ -284,21 +293,31 @@ public function executeExecuteForceDataProvider() */ public function testExecuteNoChanges($isEnable) { - $this->status->expects($this->once()) + $this->statusMock->expects($this->once()) ->method('getModulesToChange') ->with($isEnable, ['Magento_Module1', 'Magento_Module2']) ->will($this->returnValue([])); - - $this->status->expects($this->never()) + $this->statusMock->expects($this->never()) ->method('setIsEnabled'); - - $commandTester = $isEnable - ? new CommandTester(new ModuleEnableCommand($this->objectManagerProvider)) - : new CommandTester(new ModuleDisableCommand($this->objectManagerProvider)); + $commandTester = $this->getCommandTester($isEnable); $commandTester->execute(['module' => ['Magento_Module1', 'Magento_Module2']]); $this->assertStringMatchesFormat( 'No modules were changed%a', $commandTester->getDisplay() ); } + + /** + * @param bool $isEnable + * @return CommandTester + */ + private function getCommandTester($isEnable) + { + $class = $isEnable ? ModuleEnableCommand::class : ModuleDisableCommand::class; + $command = new $class($this->objectManagerProviderMock); + $deploymentConfigProperty = new \ReflectionProperty($class, 'deploymentConfig'); + $deploymentConfigProperty->setAccessible(true); + $deploymentConfigProperty->setValue($command, $this->deploymentConfigMock); + return new CommandTester($command); + } } diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/ComponentGridTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/ComponentGridTest.php new file mode 100644 index 0000000000000..e1501dd01ddf4 --- /dev/null +++ b/setup/src/Magento/Setup/Test/Unit/Controller/ComponentGridTest.php @@ -0,0 +1,280 @@ +convertedLastSyncDate = [ + 'lastSyncDate' => [ + 'date' => self::FORMATTED_DATE, + 'time' => self::FORMATTED_TIME, + ], + ]; + + $this->lastSyncData = [ + "lastSyncDate" => "1447271496", + "packages" => [ + 'magento/sample-module-one' => [ + 'name' => 'magento/sample-module-one', + 'type' => 'magento2-module', + 'version' => '1.0.0' + ] + ], + 'countOfInstall' => 0, + 'countOfUpdate' => 1 + ]; + $this->componentData = [ + 'magento/sample-module-one' => [ + 'name' => 'magento/sample-module-one', + 'type' => 'magento2-module', + 'version' => '1.0.0' + ] + ]; + $allComponentData = [ + 'magento/sample-module-two' => [ + 'name' => 'magento/sample-module-two', + 'type' => 'magento2-module', + 'version' => '1.0.0' + ] + ]; + $allComponentData = array_merge($allComponentData, $this->componentData); + $this->composerInformationMock = $this->getMock( + 'Magento\Framework\Composer\ComposerInformation', + [], + [], + '', + false + ); + /** @var ObjectManagerProvider|\PHPUnit_Framework_MockObject_MockObject $objectManagerProvider */ + $objectManagerProvider = $this->getMock('Magento\Setup\Model\ObjectManagerProvider', [], [], '', false); + $objectManager = $this->getMock('Magento\Framework\ObjectManagerInterface', [], [], '', false); + $objectManagerProvider->expects($this->once()) + ->method('get') + ->willReturn($objectManager); + $this->packageInfoFactoryMock = $this + ->getMock('Magento\Framework\Module\PackageInfoFactory', [], [], '', false); + $this->enabledModuleListMock = $this->getMock('Magento\Framework\Module\ModuleList', [], [], '', false); + $this->enabledModuleListMock->expects($this->any())->method('has')->willReturn(true); + $this->fullModuleListMock = $this->getMock('Magento\Framework\Module\FullModuleList', [], [], '', false); + $this->fullModuleListMock->expects($this->any())->method('getNames')->willReturn($allComponentData); + $this->timezoneMock = $this->getMock('Magento\Framework\Stdlib\DateTime\TimezoneInterface', [], [], '', false); + $objectManager->expects($this->any()) + ->method('get') + ->willReturnMap([ + ['Magento\Framework\Module\PackageInfoFactory', $this->packageInfoFactoryMock], + ['Magento\Framework\Module\FullModuleList', $this->fullModuleListMock], + ['Magento\Framework\Module\ModuleList', $this->enabledModuleListMock], + ['Magento\Framework\Stdlib\DateTime\TimezoneInterface', $this->timezoneMock] + ]); + + /** @var TimezoneProvider|\PHPUnit_Framework_MockObject_MockObject $timezoneProviderMock */ + $timezoneProviderMock = $this->getMock('\Magento\Setup\Model\DateTime\TimezoneProvider', [], [], '', false); + $timezoneProviderMock->expects($this->any()) + ->method('get') + ->willReturn($this->timezoneMock); + $this->packageInfo = $this->getMock('Magento\Framework\Module\PackageInfo', [], [], '', false); + $this->updatePackagesCacheMock = $this->getMock('Magento\Setup\Model\UpdatePackagesCache', [], [], '', false); + $this->marketplaceManagerMock = $this->getMock('Magento\Setup\Model\MarketplaceManager', [], [], '', false); + $this->packageInfoFactoryMock->expects($this->once())->method('create')->willReturn($this->packageInfo); + $this->controller = new ComponentGrid( + $this->composerInformationMock, + $objectManagerProvider, + $this->updatePackagesCacheMock, + $this->marketplaceManagerMock + ); + $this->controller->setTimezone($timezoneProviderMock->get()); + } + + public function testIndexAction() + { + $viewModel = $this->controller->indexAction(); + $this->assertInstanceOf('Zend\View\Model\ViewModel', $viewModel); + $this->assertTrue($viewModel->terminate()); + } + + public function testComponentsAction() + { + $this->fullModuleListMock->expects($this->once()) + ->method('getNames') + ->willReturn(['magento/sample-module1']); + $this->packageInfo->expects($this->once()) + ->method('getModuleName') + ->willReturn('Sample_Module'); + $this->packageInfo->expects($this->exactly(2)) + ->method('getPackageName') + ->willReturn($this->componentData['magento/sample-module-one']['name']); + $this->packageInfo->expects($this->exactly(2)) + ->method('getVersion') + ->willReturn($this->componentData['magento/sample-module-one']['version']); + $this->enabledModuleListMock->expects($this->once()) + ->method('has') + ->willReturn(true); + $this->composerInformationMock->expects($this->once()) + ->method('getInstalledMagentoPackages') + ->willReturn($this->componentData); + $this->composerInformationMock->expects($this->once()) + ->method('isPackageInComposerJson') + ->willReturn(true); + $this->updatePackagesCacheMock->expects($this->once()) + ->method('getPackagesForUpdate') + ->willReturn($this->lastSyncData); + $this->setupTimezoneMock(); + $jsonModel = $this->controller->componentsAction(); + $this->assertInstanceOf('Zend\View\Model\JsonModel', $jsonModel); + $variables = $jsonModel->getVariables(); + $this->assertArrayHasKey('success', $variables); + $this->assertTrue($variables['success']); + $expected = [[ + 'name' => 'magento/sample-module-one', + 'type' => 'magento2-module', + 'version' => '1.0.0', + 'update' => false, + 'uninstall' => true, + 'vendor' => 'magento', + 'moduleName' => 'Sample_Module', + 'enable' => true, + 'disable' => false + ]]; + $this->assertEquals($expected, $variables['components']); + $this->assertArrayHasKey('total', $variables); + $this->assertEquals(1, $variables['total']); + $expectedLastSyncData = array_replace($this->lastSyncData, $this->convertedLastSyncDate); + $this->assertEquals($expectedLastSyncData, $variables['lastSyncData']); + } + + public function testSyncAction() + { + $this->updatePackagesCacheMock->expects($this->once()) + ->method('syncPackagesForUpdate'); + $this->updatePackagesCacheMock->expects($this->once()) + ->method('getPackagesForUpdate') + ->willReturn($this->lastSyncData); + $this->setupTimezoneMock(); + $jsonModel = $this->controller->syncAction(); + $this->assertInstanceOf('Zend\View\Model\JsonModel', $jsonModel); + $variables = $jsonModel->getVariables(); + $this->assertArrayHasKey('success', $variables); + $this->assertTrue($variables['success']); + $expectedLastSyncData = array_replace($this->lastSyncData, $this->convertedLastSyncDate); + $this->assertEquals($expectedLastSyncData, $variables['lastSyncData']); + } + + /** + * Prepare the timezone mock to expect calls and return formatted date and time + * + * @return none + */ + private function setupTimezoneMock() + { + $this->timezoneMock->expects($this->at(0)) + ->method('formatDateTime') + ->with( + $this->isInstanceOf('\DateTime'), + \IntlDateFormatter::MEDIUM, + \IntlDateFormatter::NONE, + null, + null, + null + )->willReturn(self::FORMATTED_DATE); + $this->timezoneMock->expects($this->at(1)) + ->method('formatDateTime') + ->with( + $this->isInstanceOf('\DateTime'), + \IntlDateFormatter::NONE, + \IntlDateFormatter::MEDIUM, + null, + null, + null + )->willReturn(self::FORMATTED_TIME); + } +} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/InstallTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/InstallTest.php index b2ec9a6f86300..3adb51b012d7d 100644 --- a/setup/src/Magento/Setup/Test/Unit/Controller/InstallTest.php +++ b/setup/src/Magento/Setup/Test/Unit/Controller/InstallTest.php @@ -35,6 +35,11 @@ class InstallTest extends \PHPUnit_Framework_TestCase */ private $sampleDataState; + /** + * @var \Magento\Framework\App\DeploymentConfig|\PHPUnit_Framework_MockObject_MockObject + */ + private $deploymentConfig; + public function setUp() { $this->webLogger = $this->getMock('\Magento\Setup\Model\WebLogger', [], [], '', false); @@ -42,6 +47,7 @@ public function setUp() $this->installer = $this->getMock('\Magento\Setup\Model\Installer', [], [], '', false); $this->progressFactory = $this->getMock('\Magento\Setup\Model\Installer\ProgressFactory', [], [], '', false); $this->sampleDataState = $this->getMock('\Magento\Framework\Setup\SampleData\State', [], [], '', false); + $this->deploymentConfig = $this->getMock('\Magento\Framework\App\DeploymentConfig', [], [], '', false); $installerFactory->expects($this->once())->method('create')->with($this->webLogger) ->willReturn($this->installer); @@ -51,6 +57,11 @@ public function setUp() $this->progressFactory, $this->sampleDataState ); + + $deploymentConfigReflection = new \ReflectionClass(get_class($this->controller)); + $deploymentConfigReflectionProperty = $deploymentConfigReflection->getProperty('deploymentConfig'); + $deploymentConfigReflectionProperty->setAccessible(true); + $deploymentConfigReflectionProperty->setValue($this->controller, $this->deploymentConfig); } public function testIndexAction() @@ -65,6 +76,7 @@ public function testStartAction() $this->webLogger->expects($this->once())->method('clear'); $this->installer->expects($this->once())->method('install'); $this->installer->expects($this->exactly(2))->method('getInstallInfo'); + $this->deploymentConfig->expects($this->once())->method('isAvailable')->willReturn(false); $jsonModel = $this->controller->startAction(); $this->assertInstanceOf('\Zend\View\Model\JsonModel', $jsonModel); $variables = $jsonModel->getVariables(); @@ -74,9 +86,23 @@ public function testStartAction() $this->assertTrue($variables['success']); } - public function testStartActionException() + public function testStartActionPriorInstallException() + { + $this->webLogger->expects($this->once())->method('clear'); + $this->installer->expects($this->never())->method('install'); + $this->installer->expects($this->never())->method('getInstallInfo'); + $this->deploymentConfig->expects($this->once())->method('isAvailable')->willReturn(true); + $jsonModel = $this->controller->startAction(); + $this->assertInstanceOf('\Zend\View\Model\JsonModel', $jsonModel); + $variables = $jsonModel->getVariables(); + $this->assertArrayHasKey('success', $variables); + $this->assertArrayHasKey('messages', $variables); + $this->assertFalse($variables['success']); + } + public function testStartActionInstallException() { $this->webLogger->expects($this->once())->method('clear'); + $this->deploymentConfig->expects($this->once())->method('isAvailable')->willReturn(false); $this->installer->expects($this->once())->method('install') ->willThrowException($this->getMock('\Exception')); $jsonModel = $this->controller->startAction(); @@ -87,6 +113,7 @@ public function testStartActionWithSampleDataError() { $this->webLogger->expects($this->once())->method('clear'); $this->webLogger->expects($this->never())->method('logError'); + $this->deploymentConfig->expects($this->once())->method('isAvailable')->willReturn(false); $this->installer->method('install'); $this->sampleDataState->expects($this->once())->method('hasError')->willReturn(true); $jsonModel = $this->controller->startAction(); diff --git a/setup/src/Magento/Setup/Test/Unit/Model/ConfigOptionsListTest.php b/setup/src/Magento/Setup/Test/Unit/Model/ConfigOptionsListTest.php index b961e3f07b9de..6b860937346b9 100644 --- a/setup/src/Magento/Setup/Test/Unit/Model/ConfigOptionsListTest.php +++ b/setup/src/Magento/Setup/Test/Unit/Model/ConfigOptionsListTest.php @@ -79,7 +79,6 @@ public function testGetOptions() public function testCreateOptions() { $configDataMock = $this->getMock('Magento\Framework\Config\Data\ConfigData', [], [], '', false); - $this->generator->expects($this->once())->method('createInstallConfig')->willReturn($configDataMock); $this->generator->expects($this->once())->method('createCryptConfig')->willReturn($configDataMock); $this->generator->expects($this->once())->method('createSessionConfig')->willReturn($configDataMock); $this->generator->expects($this->once())->method('createDefinitionsConfig')->willReturn($configDataMock); @@ -88,13 +87,12 @@ public function testCreateOptions() $this->generator->expects($this->once())->method('createXFrameConfig')->willReturn($configDataMock); $this->generator->expects($this->once())->method('createCacheHostsConfig')->willReturn($configDataMock); $configData = $this->object->createConfig([], $this->deploymentConfig); - $this->assertEquals(9, count($configData)); + $this->assertEquals(8, count($configData)); } public function testCreateOptionsWithOptionalNull() { $configDataMock = $this->getMock('Magento\Framework\Config\Data\ConfigData', [], [], '', false); - $this->generator->expects($this->once())->method('createInstallConfig')->willReturn($configDataMock); $this->generator->expects($this->once())->method('createCryptConfig')->willReturn($configDataMock); $this->generator->expects($this->once())->method('createSessionConfig')->willReturn($configDataMock); $this->generator->expects($this->once())->method('createDefinitionsConfig')->willReturn(null); @@ -103,7 +101,7 @@ public function testCreateOptionsWithOptionalNull() $this->generator->expects($this->once())->method('createXFrameConfig')->willReturn($configDataMock); $this->generator->expects($this->once())->method('createCacheHostsConfig')->willReturn($configDataMock); $configData = $this->object->createConfig([], $this->deploymentConfig); - $this->assertEquals(8, count($configData)); + $this->assertEquals(7, count($configData)); } public function testValidateSuccess() diff --git a/setup/src/Magento/Setup/Test/Unit/Model/DateTime/DateTimeProviderTest.php b/setup/src/Magento/Setup/Test/Unit/Model/DateTime/DateTimeProviderTest.php new file mode 100644 index 0000000000000..4d24e73a02e26 --- /dev/null +++ b/setup/src/Magento/Setup/Test/Unit/Model/DateTime/DateTimeProviderTest.php @@ -0,0 +1,41 @@ +getMock('\Magento\Framework\Stdlib\DateTime\DateTime', [], [], '', false); + /** @var TimezoneProvider|\PHPUnit_Framework_MockObject_MockObject $timeZoneProvider */ + $timeZoneProvider = $this->getMock('\Magento\Setup\Model\DateTime\TimezoneProvider', [], [], '', false); + $timeZone = $this->getMock('\Magento\Framework\Stdlib\DateTime\Timezone', [], [], '', false); + $timeZoneProvider->expects($this->any()) + ->method('get') + ->willReturn($timeZone); + $objectManager = $this->getMockForAbstractClass('\Magento\Framework\ObjectManagerInterface', [], '', false); + $objectManager->expects($this->once()) + ->method('create') + ->with( + 'Magento\Framework\Stdlib\DateTime\DateTime', + ['localeDate' => $timeZone] + ) + ->willReturn($dateTime); + /** @var ObjectManagerProvider|\PHPUnit_Framework_MockObject_MockObject $objectManagerProvider */ + $objectManagerProvider = $this->getMock('\Magento\Setup\Model\ObjectManagerProvider', [], [], '', false); + $objectManagerProvider->expects($this->any()) + ->method('get') + ->willReturn($objectManager); + $object = new DateTimeProvider($timeZoneProvider, $objectManagerProvider); + $this->assertSame($dateTime, $object->get()); + // Assert that the provider always returns the same object + $this->assertSame($dateTime, $object->get()); + } +} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/DateTime/TimezoneProviderTest.php b/setup/src/Magento/Setup/Test/Unit/Model/DateTime/TimezoneProviderTest.php new file mode 100644 index 0000000000000..63c4df875e280 --- /dev/null +++ b/setup/src/Magento/Setup/Test/Unit/Model/DateTime/TimezoneProviderTest.php @@ -0,0 +1,35 @@ +getMock('\Magento\Framework\Stdlib\DateTime\Timezone', [], [], '', false); + $objectManager = $this->getMockForAbstractClass('\Magento\Framework\ObjectManagerInterface', [], '', false); + $objectManager->expects($this->once()) + ->method('create') + ->with( + 'Magento\Framework\Stdlib\DateTime\Timezone', + ['scopeType' => ScopeConfigInterface::SCOPE_TYPE_DEFAULT] + ) + ->willReturn($timeZone); + /** @var ObjectManagerProvider|\PHPUnit_Framework_MockObject_MockObject $objectManagerProvider */ + $objectManagerProvider = $this->getMock('\Magento\Setup\Model\ObjectManagerProvider', [], [], '', false); + $objectManagerProvider->expects($this->any()) + ->method('get') + ->willReturn($objectManager); + $object = new TimezoneProvider($objectManagerProvider); + $this->assertSame($timeZone, $object->get()); + // Assert that the provider always returns the same object + $this->assertSame($timeZone, $object->get()); + } +} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/InstallerTest.php b/setup/src/Magento/Setup/Test/Unit/Model/InstallerTest.php index e2b21aca00507..11fbc3b1ec49a 100644 --- a/setup/src/Magento/Setup/Test/Unit/Model/InstallerTest.php +++ b/setup/src/Magento/Setup/Test/Unit/Model/InstallerTest.php @@ -233,7 +233,14 @@ public function testInstall() ConfigOptionsListConstants::INPUT_KEY_ENCRYPTION_KEY => 'encryption_key', ConfigOptionsList::INPUT_KEY_BACKEND_FRONTNAME => 'backend', ]; - $this->config->expects($this->atLeastOnce())->method('isAvailable')->willReturn(true); + $this->config->expects($this->atLeastOnce()) + ->method('get') + ->willReturnMap( + [ + [ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTION_DEFAULT, null, true], + [ConfigOptionsListConstants::CONFIG_PATH_CRYPT_KEY, null, true], + ] + ); $allModules = ['Foo_One' => [], 'Bar_Two' => []]; $this->moduleLoader->expects($this->any())->method('load')->willReturn($allModules); $setup = $this->getMock('Magento\Setup\Module\Setup', [], [], '', false); @@ -296,8 +303,9 @@ public function testInstall() $this->logger->expects($this->at(34))->method('log')->with('Caches clearing:'); $this->logger->expects($this->at(37))->method('log')->with('Disabling Maintenance Mode:'); $this->logger->expects($this->at(39))->method('log')->with('Post installation file permissions check...'); - $this->logger->expects($this->at(41))->method('logSuccess')->with('Magento installation complete.'); - $this->logger->expects($this->at(43))->method('log') + $this->logger->expects($this->at(41))->method('log')->with('Write installation date...'); + $this->logger->expects($this->at(43))->method('logSuccess')->with('Magento installation complete.'); + $this->logger->expects($this->at(45))->method('log') ->with('Sample Data is installed with errors. See log file for details'); $this->object->install($request); } @@ -368,7 +376,6 @@ public function testUpdateModulesSequenceKeepGenerated() public function testUninstall() { - $this->config->expects($this->once())->method('isAvailable')->willReturn(false); $this->configReader->expects($this->once())->method('getFiles')->willReturn(['ConfigOne.php', 'ConfigTwo.php']); $configDir = $this->getMockForAbstractClass('Magento\Framework\Filesystem\Directory\WriteInterface'); $configDir @@ -433,7 +440,6 @@ public function testUninstall() public function testCleanupDb() { - $this->config->expects($this->once())->method('isAvailable')->willReturn(true); $this->config->expects($this->once()) ->method('get') ->with(ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTION_DEFAULT) @@ -452,7 +458,6 @@ public function testCleanupDb() */ private function prepareForUpdateModulesTests() { - $allModules = [ 'Foo_One' => [], 'Bar_Two' => [], @@ -479,7 +484,10 @@ private function prepareForUpdateModulesTests() ] ]; - $this->config->expects($this->atLeastOnce())->method('isAvailable')->willReturn(true); + $this->config->expects($this->atLeastOnce()) + ->method('get') + ->with(ConfigOptionsListConstants::KEY_MODULES) + ->willReturn(true); $newObject = $this->createObject(false, false); $this->configReader->expects($this->once())->method('load') diff --git a/setup/src/Magento/Setup/Test/Unit/Module/ConfigGeneratorTest.php b/setup/src/Magento/Setup/Test/Unit/Module/ConfigGeneratorTest.php index 2f3a67ebc4f81..14dbd411f3b9c 100644 --- a/setup/src/Magento/Setup/Test/Unit/Module/ConfigGeneratorTest.php +++ b/setup/src/Magento/Setup/Test/Unit/Module/ConfigGeneratorTest.php @@ -25,13 +25,6 @@ protected function setUp() $this->configGeneratorObject = new ConfigGenerator($random, $deployConfig); } - public function testCreateInstallConfig() - { - $returnValue = $this->configGeneratorObject->createInstallConfig([]); - $this->assertInstanceOf('Magento\Framework\Config\Data\ConfigData', $returnValue); - $this->assertEquals(ConfigFilePool::APP_ENV, $returnValue->getFileKey()); - } - public function testCreateCryptConfigWithInput() { $testData = [ConfigOptionsListConstants::INPUT_KEY_ENCRYPTION_KEY => 'some-test_key']; @@ -47,6 +40,16 @@ public function testCreateCryptConfigWithoutInput() $this->assertEquals(['crypt' => ['key' => md5('key')]], $returnValue->getData()); } + /** + * @deprecated + */ + public function testCreateInstallConfig() + { + $returnValue = $this->configGeneratorObject->createInstallConfig([]); + $this->assertInstanceOf('Magento\Framework\Config\Data\ConfigData', $returnValue); + $this->assertEquals(ConfigFilePool::APP_ENV, $returnValue->getFileKey()); + } + public function testCreateSessionConfigWithInput() { $testData = [ConfigOptionsListConstants::INPUT_KEY_SESSION_SAVE => 'files'];