diff --git a/app/code/Magento/AdminAnalytics/etc/db_schema.xml b/app/code/Magento/AdminAnalytics/etc/db_schema.xml index ef1a657dc8243..4d7fdff25c02c 100644 --- a/app/code/Magento/AdminAnalytics/etc/db_schema.xml +++ b/app/code/Magento/AdminAnalytics/etc/db_schema.xml @@ -9,7 +9,7 @@ xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> - diff --git a/app/code/Magento/AdminNotification/etc/db_schema.xml b/app/code/Magento/AdminNotification/etc/db_schema.xml index 8849687611193..d7bad83aa590b 100644 --- a/app/code/Magento/AdminNotification/etc/db_schema.xml +++ b/app/code/Magento/AdminNotification/etc/db_schema.xml @@ -8,18 +8,18 @@
- - - - @@ -36,7 +36,7 @@
- diff --git a/app/code/Magento/AdvancedSearch/etc/db_schema.xml b/app/code/Magento/AdvancedSearch/etc/db_schema.xml index bf85a23782095..20ab3973dd8d2 100644 --- a/app/code/Magento/AdvancedSearch/etc/db_schema.xml +++ b/app/code/Magento/AdvancedSearch/etc/db_schema.xml @@ -9,10 +9,10 @@ xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
- - + - diff --git a/app/code/Magento/Analytics/Controller/Adminhtml/Reports/Show.php b/app/code/Magento/Analytics/Controller/Adminhtml/Reports/Show.php index 9068654fa944f..5614090006f8a 100644 --- a/app/code/Magento/Analytics/Controller/Adminhtml/Reports/Show.php +++ b/app/code/Magento/Analytics/Controller/Adminhtml/Reports/Show.php @@ -27,7 +27,7 @@ class Show extends Action implements HttpGetActionInterface /** * @inheritdoc */ - const ADMIN_RESOURCE = 'Magento_Analytics::analytics_settings'; + const ADMIN_RESOURCE = 'Magento_Analytics::advanced_reporting'; /** * @param Context $context diff --git a/app/code/Magento/Analytics/Test/Mftf/Data/UserRoleData.xml b/app/code/Magento/Analytics/Test/Mftf/Data/UserRoleData.xml index 3b198644fcc9b..d015a67da34b0 100644 --- a/app/code/Magento/Analytics/Test/Mftf/Data/UserRoleData.xml +++ b/app/code/Magento/Analytics/Test/Mftf/Data/UserRoleData.xml @@ -149,7 +149,6 @@ Magento_Backend::custom Magento_Backend::tools Magento_Backend::cache - Magento_Backend::setup_wizard Magento_Backup::backup Magento_Backup::rollback Magento_Indexer::index diff --git a/app/code/Magento/Analytics/etc/di.xml b/app/code/Magento/Analytics/etc/di.xml index e06be2fb4d500..8d8ce4f83a605 100644 --- a/app/code/Magento/Analytics/etc/di.xml +++ b/app/code/Magento/Analytics/etc/di.xml @@ -163,11 +163,7 @@ payment/cashondelivery/active payment/paypal_billing_agreement/title payment/paypal_billing_agreement/active - payment/braintree/title - payment/braintree/active - payment/braintree_paypal/title - payment/braintree_paypal/active - analytics/general/vertical + analytics/general/vertical diff --git a/app/code/Magento/AsynchronousOperations/etc/db_schema.xml b/app/code/Magento/AsynchronousOperations/etc/db_schema.xml index 5cd55408838fe..f287a368c72fb 100644 --- a/app/code/Magento/AsynchronousOperations/etc/db_schema.xml +++ b/app/code/Magento/AsynchronousOperations/etc/db_schema.xml @@ -9,15 +9,15 @@ xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
- - - @@ -32,7 +32,7 @@
- - - @@ -59,7 +59,7 @@
- diff --git a/app/code/Magento/Authorization/etc/db_schema.xml b/app/code/Magento/Authorization/etc/db_schema.xml index a38828eb6efca..de0dd69ee29c2 100644 --- a/app/code/Magento/Authorization/etc/db_schema.xml +++ b/app/code/Magento/Authorization/etc/db_schema.xml @@ -8,16 +8,16 @@
- - - - - @@ -33,9 +33,9 @@
- - diff --git a/app/code/Magento/Backend/Model/Setup/MenuBuilder.php b/app/code/Magento/Backend/Model/Setup/MenuBuilder.php deleted file mode 100644 index 6bdb036d20ff9..0000000000000 --- a/app/code/Magento/Backend/Model/Setup/MenuBuilder.php +++ /dev/null @@ -1,51 +0,0 @@ -docRootLocator = $docRootLocator; - } - - /** - * Removes 'Web Setup Wizard' from the menu if doc root is pub and no setup url variable is specified. - * - * @param Builder $subject - * @param Menu $menu - * @return Menu - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - * @since 100.1.0 - */ - public function afterGetResult(Builder $subject, Menu $menu) - { - if ($this->docRootLocator->isPub()) { - $menu->remove('Magento_Backend::setup_wizard'); - } - return $menu; - } -} diff --git a/app/code/Magento/Backend/Test/Mftf/ActionGroup/AdminNavigateToSetupWizardPageActionGroup.xml b/app/code/Magento/Backend/Test/Mftf/ActionGroup/AdminNavigateToSetupWizardPageActionGroup.xml deleted file mode 100644 index 5d5a233186c1f..0000000000000 --- a/app/code/Magento/Backend/Test/Mftf/ActionGroup/AdminNavigateToSetupWizardPageActionGroup.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - - - - Open Setup Wizard Page. - - - - - diff --git a/app/code/Magento/Backend/Test/Mftf/Page/AdminSetupWizardPage.xml b/app/code/Magento/Backend/Test/Mftf/Page/AdminSetupWizardPage.xml deleted file mode 100644 index 40076ccd42b3a..0000000000000 --- a/app/code/Magento/Backend/Test/Mftf/Page/AdminSetupWizardPage.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - diff --git a/app/code/Magento/Backend/Test/Mftf/Test/AdminRedirectToAdminPanelOnLogoClickFromWizardPageTest.xml b/app/code/Magento/Backend/Test/Mftf/Test/AdminRedirectToAdminPanelOnLogoClickFromWizardPageTest.xml deleted file mode 100644 index bf74674a2c9c8..0000000000000 --- a/app/code/Magento/Backend/Test/Mftf/Test/AdminRedirectToAdminPanelOnLogoClickFromWizardPageTest.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - <description value="Check navigate to dashboard after click on logo on Setup Wizard Page"/> - </annotations> - <before> - <actionGroup ref="AdminLoginActionGroup" stepKey="loginToAdminPanel"/> - </before> - <after> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logoutFromAdmin"/> - </after> - - <actionGroup ref="AdminNavigateToSetupWizardPageActionGroup" stepKey="navigateToSetupWizardPage"/> - <actionGroup ref="AdminClickLogoActionGroup" stepKey="clickOnLogo"/> - <actionGroup ref="AssertAdminDashboardPageIsVisibleActionGroup" stepKey="checkTheDashboardPage"/> - </test> -</tests> diff --git a/app/code/Magento/Backend/Test/Unit/Model/MenuBuilderTest.php b/app/code/Magento/Backend/Test/Unit/Model/MenuBuilderTest.php deleted file mode 100644 index 7d8293bb2ed95..0000000000000 --- a/app/code/Magento/Backend/Test/Unit/Model/MenuBuilderTest.php +++ /dev/null @@ -1,50 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Backend\Test\Unit\Model; - -use Magento\Backend\Model\Menu; -use Magento\Backend\Model\Menu\Builder; -use Magento\Backend\Model\Setup\MenuBuilder; -use Magento\Framework\App\DocRootLocator; -use PHPUnit\Framework\TestCase; - -class MenuBuilderTest extends TestCase -{ - /** - * @dataProvider afterGetResultDataProvider - * - * @param string $isPub - * @param int $times - * @param bool $result - */ - public function testAfterGetResult($isPub, $times) - { - $docRootLocator = $this->createMock(DocRootLocator::class); - $docRootLocator->expects($this->once())->method('isPub')->willReturn($isPub); - $model = new MenuBuilder($docRootLocator); - /** @var Menu $menu */ - $menu = $this->createMock(Menu::class); - $menu->expects($this->exactly($times))->method('remove')->willReturn(true); - - /** @var Builder $menuBuilder */ - $menuBuilder = $this->createMock(Builder::class); - - $this->assertInstanceOf( - Menu::class, - $model->afterGetResult($menuBuilder, $menu) - ); - } - - /** - * @return array - */ - public function afterGetResultDataProvider() - { - return [[true, 1], [false, 0]]; - } -} diff --git a/app/code/Magento/Backend/etc/acl.xml b/app/code/Magento/Backend/etc/acl.xml index cf9471e75bed9..693b6025896f0 100644 --- a/app/code/Magento/Backend/etc/acl.xml +++ b/app/code/Magento/Backend/etc/acl.xml @@ -53,7 +53,6 @@ <resource id="Magento_Backend::flush_static_files" title="Flush Static Files" translate="title" sortOrder="30" /> </resource> </resource> - <resource id="Magento_Backend::setup_wizard" title="Web Setup Wizard" translate="title" sortOrder="20" /> </resource> <resource id="Magento_Backend::system_other_settings" title="Other Settings" translate="title" sortOrder="80" /> </resource> diff --git a/app/code/Magento/Backend/etc/adminhtml/di.xml b/app/code/Magento/Backend/etc/adminhtml/di.xml index 1bfc504cf50e9..4d41a1f5c0b5a 100644 --- a/app/code/Magento/Backend/etc/adminhtml/di.xml +++ b/app/code/Magento/Backend/etc/adminhtml/di.xml @@ -138,9 +138,6 @@ <argument name="isIncludesAvailable" xsi:type="boolean">false</argument> </arguments> </type> - <type name="Magento\Backend\Model\Menu\Builder"> - <plugin name="SetupMenuBuilder" type="Magento\Backend\Model\Setup\MenuBuilder" /> - </type> <type name="Magento\Config\Model\Config\Structure\ElementVisibility\ConcealInProduction"> <arguments> <argument name="configs" xsi:type="array"> diff --git a/app/code/Magento/Backend/etc/adminhtml/menu.xml b/app/code/Magento/Backend/etc/adminhtml/menu.xml index b6f62310c179e..33a3dc362528e 100644 --- a/app/code/Magento/Backend/etc/adminhtml/menu.xml +++ b/app/code/Magento/Backend/etc/adminhtml/menu.xml @@ -27,6 +27,5 @@ <add id="Magento_Backend::stores_attributes" title="Attributes" translate="title" module="Magento_Backend" sortOrder="40" parent="Magento_Backend::stores" resource="Magento_Backend::stores_attributes"/> <add id="Magento_Backend::other_settings" title="Other Settings" translate="title" module="Magento_Backend" sortOrder="50" parent="Magento_Backend::stores" resource="Magento_Backend::stores_other_settings"/> <add id="Magento_Backend::system_other_settings" title="Other Settings" translate="title" module="Magento_Backend" sortOrder="80" parent="Magento_Backend::system" resource="Magento_Backend::system_other_settings"/> - <add id="Magento_Backend::setup_wizard" action="adminhtml/backendapp/redirect/app/setup" title="Web Setup Wizard" translate="title" module="Magento_Backend" sortOrder="80" parent="Magento_Backend::system_tools" resource="Magento_Backend::setup_wizard"/> </menu> </config> diff --git a/app/code/Magento/Backend/etc/di.xml b/app/code/Magento/Backend/etc/di.xml index c526703da9975..65f73f028eb20 100644 --- a/app/code/Magento/Backend/etc/di.xml +++ b/app/code/Magento/Backend/etc/di.xml @@ -153,20 +153,6 @@ </argument> </arguments> </type> - <virtualType name="Magento\Setup\BackendApp" type="Magento\Backend\App\BackendApp"> - <arguments> - <argument name="cookiePath" xsi:type="string">setup</argument> - <argument name="startupPage" xsi:type="string">setup</argument> - <argument name="aclResourceName" xsi:type="string">Magento_Backend::setup_wizard</argument> - </arguments> - </virtualType> - <type name="Magento\Backend\App\BackendAppList"> - <arguments> - <argument name="backendApps" xsi:type="array"> - <item name="setup" xsi:type="object">Magento\Setup\BackendApp</item> - </argument> - </arguments> - </type> <type name="Magento\Framework\App\Response\HeaderManager"> <arguments> <argument name="headerProviderList" xsi:type="array"> diff --git a/app/code/Magento/Backend/i18n/en_US.csv b/app/code/Magento/Backend/i18n/en_US.csv index 53f7fe90cbbe5..e0643518bde30 100644 --- a/app/code/Magento/Backend/i18n/en_US.csv +++ b/app/code/Magento/Backend/i18n/en_US.csv @@ -312,7 +312,6 @@ Attributes,Attributes "Connect Manager","Connect Manager" "Package Extensions","Package Extensions" Tools,Tools -"Web Setup Wizard","Web Setup Wizard" Currency,Currency Communications,Communications Services,Services diff --git a/app/code/Magento/Braintree/Block/Adminhtml/Form/Field/CcTypes.php b/app/code/Magento/Braintree/Block/Adminhtml/Form/Field/CcTypes.php deleted file mode 100644 index 7987068c3dbb1..0000000000000 --- a/app/code/Magento/Braintree/Block/Adminhtml/Form/Field/CcTypes.php +++ /dev/null @@ -1,63 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Block\Adminhtml\Form\Field; - -use Magento\Braintree\Helper\CcType; -use Magento\Framework\View\Element\Context; -use Magento\Framework\View\Element\Html\Select; - -/** - * Class CcTypes - */ -class CcTypes extends Select -{ - /** - * @var CcType - */ - private $ccTypeHelper; - - /** - * Constructor - * - * @param Context $context - * @param CcType $ccTypeHelper - * @param array $data - */ - public function __construct( - Context $context, - CcType $ccTypeHelper, - array $data = [] - ) { - parent::__construct($context, $data); - $this->ccTypeHelper = $ccTypeHelper; - } - - /** - * Render block HTML - * - * @return string - */ - protected function _toHtml() - { - if (!$this->getOptions()) { - $this->setOptions($this->ccTypeHelper->getCcTypes()); - } - $this->setClass('cc-type-select'); - $this->setExtraParams('multiple="multiple"'); - return parent::_toHtml(); - } - - /** - * Sets name for input element - * - * @param string $value - * @return $this - */ - public function setInputName($value) - { - return $this->setName($value . '[]'); - } -} diff --git a/app/code/Magento/Braintree/Block/Adminhtml/Form/Field/Countries.php b/app/code/Magento/Braintree/Block/Adminhtml/Form/Field/Countries.php deleted file mode 100644 index 05eaa16c009a0..0000000000000 --- a/app/code/Magento/Braintree/Block/Adminhtml/Form/Field/Countries.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Block\Adminhtml\Form\Field; - -use Magento\Braintree\Helper\Country; -use Magento\Framework\View\Element\Context; -use Magento\Framework\View\Element\Html\Select; - -/** - * Class Countries - */ -class Countries extends Select -{ - /** - * @var Country - */ - private $countryHelper; - - /** - * Constructor - * - * @param Context $context - * @param Country $countryHelper - * @param array $data - */ - public function __construct(Context $context, Country $countryHelper, array $data = []) - { - parent::__construct($context, $data); - $this->countryHelper = $countryHelper; - } - - /** - * Render block HTML - * - * @return string - */ - protected function _toHtml() - { - if (!$this->getOptions()) { - $this->setOptions($this->countryHelper->getCountries()); - } - return parent::_toHtml(); - } - - /** - * Sets name for input element - * - * @param string $value - * @return $this - */ - public function setInputName($value) - { - return $this->setName($value); - } -} diff --git a/app/code/Magento/Braintree/Block/Adminhtml/Form/Field/CountryCreditCard.php b/app/code/Magento/Braintree/Block/Adminhtml/Form/Field/CountryCreditCard.php deleted file mode 100644 index 18142992fc78b..0000000000000 --- a/app/code/Magento/Braintree/Block/Adminhtml/Form/Field/CountryCreditCard.php +++ /dev/null @@ -1,106 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Block\Adminhtml\Form\Field; - -use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray; -use Magento\Framework\DataObject; - -/** - * Class CountryCreditCard - */ -class CountryCreditCard extends AbstractFieldArray -{ - /** - * @var Countries - */ - protected $countryRenderer = null; - - /** - * @var CcTypes - */ - protected $ccTypesRenderer = null; - - /** - * Returns renderer for country element - * - * @return Countries - */ - protected function getCountryRenderer() - { - if (!$this->countryRenderer) { - $this->countryRenderer = $this->getLayout()->createBlock( - Countries::class, - '', - ['data' => ['is_render_to_js_template' => true]] - ); - } - return $this->countryRenderer; - } - - /** - * Returns renderer for country element - * - * @return CcTypes - */ - protected function getCcTypesRenderer() - { - if (!$this->ccTypesRenderer) { - $this->ccTypesRenderer = $this->getLayout()->createBlock( - CcTypes::class, - '', - ['data' => ['is_render_to_js_template' => true]] - ); - } - return $this->ccTypesRenderer; - } - - /** - * Prepare to render - * @return void - */ - protected function _prepareToRender() - { - $this->addColumn( - 'country_id', - [ - 'label' => __('Country'), - 'renderer' => $this->getCountryRenderer(), - ] - ); - $this->addColumn( - 'cc_types', - [ - 'label' => __('Allowed Credit Card Types'), - 'renderer' => $this->getCcTypesRenderer(), - ] - ); - $this->_addAfter = false; - $this->_addButtonLabel = __('Add Rule'); - } - - /** - * Prepare existing row data object - * - * @param DataObject $row - * @return void - */ - protected function _prepareArrayRow(DataObject $row) - { - $country = $row->getCountryId(); - $options = []; - if ($country) { - $options['option_' . $this->getCountryRenderer()->calcOptionHash($country)] - = 'selected="selected"'; - - $ccTypes = $row->getCcTypes(); - foreach ($ccTypes as $cardType) { - $options['option_' . $this->getCcTypesRenderer()->calcOptionHash($cardType)] - = 'selected="selected"'; - } - } - $row->setData('option_extra_attrs', $options); - } -} diff --git a/app/code/Magento/Braintree/Block/Customer/CardRenderer.php b/app/code/Magento/Braintree/Block/Customer/CardRenderer.php deleted file mode 100644 index 55ba049f72297..0000000000000 --- a/app/code/Magento/Braintree/Block/Customer/CardRenderer.php +++ /dev/null @@ -1,75 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Block\Customer; - -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Framework\View\Element\Template; -use Magento\Vault\Api\Data\PaymentTokenInterface; -use Magento\Vault\Block\AbstractCardRenderer; - -/** - * @api - * @since 100.1.0 - */ -class CardRenderer extends AbstractCardRenderer -{ - /** - * Can render specified token - * - * @param PaymentTokenInterface $token - * @return boolean - * @since 100.1.0 - */ - public function canRender(PaymentTokenInterface $token) - { - return $token->getPaymentMethodCode() === ConfigProvider::CODE; - } - - /** - * @return string - * @since 100.1.0 - */ - public function getNumberLast4Digits() - { - return $this->getTokenDetails()['maskedCC']; - } - - /** - * @return string - * @since 100.1.0 - */ - public function getExpDate() - { - return $this->getTokenDetails()['expirationDate']; - } - - /** - * @return string - * @since 100.1.0 - */ - public function getIconUrl() - { - return $this->getIconForType($this->getTokenDetails()['type'])['url']; - } - - /** - * @return int - * @since 100.1.0 - */ - public function getIconHeight() - { - return $this->getIconForType($this->getTokenDetails()['type'])['height']; - } - - /** - * @return int - * @since 100.1.0 - */ - public function getIconWidth() - { - return $this->getIconForType($this->getTokenDetails()['type'])['width']; - } -} diff --git a/app/code/Magento/Braintree/Block/Customer/PayPal/VaultTokenRenderer.php b/app/code/Magento/Braintree/Block/Customer/PayPal/VaultTokenRenderer.php deleted file mode 100644 index 1405349e2d45f..0000000000000 --- a/app/code/Magento/Braintree/Block/Customer/PayPal/VaultTokenRenderer.php +++ /dev/null @@ -1,91 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Block\Customer\PayPal; - -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider; -use Magento\Framework\View\Element\Template; -use Magento\Vault\Api\Data\PaymentTokenInterface; -use Magento\Vault\Block\AbstractTokenRenderer; - -/** - * Class VaultTokenRenderer - * - * @api - * @since 100.1.3 - */ -class VaultTokenRenderer extends AbstractTokenRenderer -{ - /** - * @var Config - */ - private $config; - - /** - * Initialize dependencies. - * - * @param Template\Context $context - * @param Config $config - * @param array $data - */ - public function __construct( - Template\Context $context, - Config $config, - array $data = [] - ) { - parent::__construct($context, $data); - $this->config = $config; - } - - /** - * @inheritdoc - * @since 100.1.3 - */ - public function getIconUrl() - { - return $this->config->getPayPalIcon()['url']; - } - - /** - * @inheritdoc - * @since 100.1.3 - */ - public function getIconHeight() - { - return $this->config->getPayPalIcon()['height']; - } - - /** - * @inheritdoc - * @since 100.1.3 - */ - public function getIconWidth() - { - return $this->config->getPayPalIcon()['width']; - } - - /** - * Can render specified token - * - * @param PaymentTokenInterface $token - * @return boolean - * @since 100.1.3 - */ - public function canRender(PaymentTokenInterface $token) - { - return $token->getPaymentMethodCode() === ConfigProvider::PAYPAL_CODE; - } - - /** - * Get email of PayPal payer - * @return string - * @since 100.1.3 - */ - public function getPayerEmail() - { - return $this->getTokenDetails()['payerEmail']; - } -} diff --git a/app/code/Magento/Braintree/Block/Form.php b/app/code/Magento/Braintree/Block/Form.php deleted file mode 100644 index 8a727ae87262f..0000000000000 --- a/app/code/Magento/Braintree/Block/Form.php +++ /dev/null @@ -1,143 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Block; - -use Magento\Backend\Model\Session\Quote; -use Magento\Braintree\Gateway\Config\Config as GatewayConfig; -use Magento\Braintree\Model\Adminhtml\Source\CcType; -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Framework\View\Element\Template\Context; -use Magento\Payment\Block\Form\Cc; -use Magento\Payment\Helper\Data; -use Magento\Payment\Model\Config; -use Magento\Vault\Model\VaultPaymentInterface; - -/** - * Class Form - */ -class Form extends Cc -{ - /** - * @var Quote - */ - protected $sessionQuote; - - /** - * @var Config - */ - protected $gatewayConfig; - - /** - * @var CcType - */ - protected $ccType; - - /** - * @var Data - */ - private $paymentDataHelper; - - /** - * @param Context $context - * @param Config $paymentConfig - * @param Quote $sessionQuote - * @param GatewayConfig $gatewayConfig - * @param CcType $ccType - * @param Data $paymentDataHelper - * @param array $data - */ - public function __construct( - Context $context, - Config $paymentConfig, - Quote $sessionQuote, - GatewayConfig $gatewayConfig, - CcType $ccType, - Data $paymentDataHelper, - array $data = [] - ) { - parent::__construct($context, $paymentConfig, $data); - $this->sessionQuote = $sessionQuote; - $this->gatewayConfig = $gatewayConfig; - $this->ccType = $ccType; - $this->paymentDataHelper = $paymentDataHelper; - } - - /** - * Get list of available card types of order billing address country - * @return array - */ - public function getCcAvailableTypes() - { - $configuredCardTypes = $this->getConfiguredCardTypes(); - $countryId = $this->sessionQuote->getQuote()->getBillingAddress()->getCountryId(); - return $this->filterCardTypesForCountry($configuredCardTypes, $countryId); - } - - /** - * Check if cvv validation is available - * @return boolean - */ - public function useCvv() - { - return $this->gatewayConfig->isCvvEnabled($this->sessionQuote->getStoreId()); - } - - /** - * Check if vault enabled - * @return bool - */ - public function isVaultEnabled() - { - $vaultPayment = $this->getVaultPayment(); - return $vaultPayment->isActive($this->sessionQuote->getStoreId()); - } - - /** - * Get card types available for Braintree - * @return array - */ - private function getConfiguredCardTypes() - { - $types = $this->ccType->getCcTypeLabelMap(); - $configCardTypes = array_fill_keys( - $this->gatewayConfig->getAvailableCardTypes($this->sessionQuote->getStoreId()), - '' - ); - - return array_intersect_key($types, $configCardTypes); - } - - /** - * Filter card types for specific country - * @param array $configCardTypes - * @param string $countryId - * @return array - */ - private function filterCardTypesForCountry(array $configCardTypes, $countryId) - { - $filtered = $configCardTypes; - $countryCardTypes = $this->gatewayConfig->getCountryAvailableCardTypes( - $countryId, - $this->sessionQuote->getStoreId() - ); - - // filter card types only if specific card types are set for country - if (!empty($countryCardTypes)) { - $availableTypes = array_fill_keys($countryCardTypes, ''); - $filtered = array_intersect_key($filtered, $availableTypes); - } - return $filtered; - } - - /** - * Get configured vault payment for Braintree - * @return VaultPaymentInterface - */ - private function getVaultPayment() - { - return $this->paymentDataHelper->getMethodInstance(ConfigProvider::CC_VAULT_CODE); - } -} diff --git a/app/code/Magento/Braintree/Block/Info.php b/app/code/Magento/Braintree/Block/Info.php deleted file mode 100644 index 0ce468384821a..0000000000000 --- a/app/code/Magento/Braintree/Block/Info.php +++ /dev/null @@ -1,26 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Block; - -use Magento\Framework\Phrase; -use Magento\Payment\Block\ConfigurableInfo; - -/** - * Class Info - */ -class Info extends ConfigurableInfo -{ - /** - * Returns label - * - * @param string $field - * @return Phrase - */ - protected function getLabel($field) - { - return __($field); - } -} diff --git a/app/code/Magento/Braintree/Block/Payment.php b/app/code/Magento/Braintree/Block/Payment.php deleted file mode 100644 index 1ba2f862e2fe5..0000000000000 --- a/app/code/Magento/Braintree/Block/Payment.php +++ /dev/null @@ -1,66 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Block; - -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Checkout\Model\ConfigProviderInterface; -use Magento\Framework\View\Element\Template; -use Magento\Framework\View\Element\Template\Context; - -/** - * Class Payment - * - * @api - * @since 100.1.0 - */ -class Payment extends Template -{ - /** - * @var ConfigProviderInterface - */ - private $config; - - /** - * Constructor - * - * @param Context $context - * @param ConfigProviderInterface $config - * @param array $data - */ - public function __construct( - Context $context, - ConfigProviderInterface $config, - array $data = [] - ) { - parent::__construct($context, $data); - $this->config = $config; - } - - /** - * @return string - * @since 100.1.0 - */ - public function getPaymentConfig() - { - $payment = $this->config->getConfig()['payment']; - $config = $payment[$this->getCode()]; - $config['code'] = $this->getCode(); - $config['clientTokenUrl'] = $this->_urlBuilder->getUrl( - 'braintree/payment/getClientToken', - ['_secure' => true] - ); - return json_encode($config, JSON_UNESCAPED_SLASHES); - } - - /** - * @return string - * @since 100.1.0 - */ - public function getCode() - { - return ConfigProvider::CODE; - } -} diff --git a/app/code/Magento/Braintree/Block/Paypal/Button.php b/app/code/Magento/Braintree/Block/Paypal/Button.php deleted file mode 100644 index fe829cf9f1fdd..0000000000000 --- a/app/code/Magento/Braintree/Block/Paypal/Button.php +++ /dev/null @@ -1,190 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Block\Paypal; - -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Catalog\Block\ShortcutInterface; -use Magento\Checkout\Model\Session; -use Magento\Framework\Locale\ResolverInterface; -use Magento\Framework\View\Element\Template; -use Magento\Framework\View\Element\Template\Context; -use Magento\Payment\Model\MethodInterface; - -/** - * Class Button - */ -class Button extends Template implements ShortcutInterface -{ - const ALIAS_ELEMENT_INDEX = 'alias'; - - const BUTTON_ELEMENT_INDEX = 'button_id'; - - /** - * @var ResolverInterface - */ - private $localeResolver; - - /** - * @var Session - */ - private $checkoutSession; - - /** - * @var Config - */ - private $config; - - /** - * @var ConfigProvider - */ - private $configProvider; - - /** - * @var MethodInterface - */ - private $payment; - - /** - * @param Context $context - * @param ResolverInterface $localeResolver - * @param Session $checkoutSession - * @param Config $config - * @param ConfigProvider $configProvider - * @param MethodInterface $payment - * @param array $data - */ - public function __construct( - Context $context, - ResolverInterface $localeResolver, - Session $checkoutSession, - Config $config, - ConfigProvider $configProvider, - MethodInterface $payment, - array $data = [] - ) { - parent::__construct($context, $data); - - $this->localeResolver = $localeResolver; - $this->checkoutSession = $checkoutSession; - $this->config = $config; - $this->configProvider = $configProvider; - $this->payment = $payment; - } - - /** - * @inheritdoc - */ - protected function _toHtml() - { - if ($this->isActive()) { - return parent::_toHtml(); - } - - return ''; - } - - /** - * @inheritdoc - */ - public function getAlias() - { - return $this->getData(self::ALIAS_ELEMENT_INDEX); - } - - /** - * Returns container id. - * - * @return string - */ - public function getContainerId() - { - return $this->getData(self::BUTTON_ELEMENT_INDEX); - } - - /** - * Returns locale. - * - * @return string - */ - public function getLocale() - { - return $this->localeResolver->getLocale(); - } - - /** - * Returns currency. - * - * @return string - */ - public function getCurrency() - { - return $this->checkoutSession->getQuote()->getCurrency()->getBaseCurrencyCode(); - } - - /** - * Returns amount. - * - * @return float - */ - public function getAmount() - { - return $this->checkoutSession->getQuote()->getBaseGrandTotal(); - } - - /** - * Returns if is active. - * - * @return bool - */ - public function isActive() - { - return $this->payment->isAvailable($this->checkoutSession->getQuote()) && - $this->config->isDisplayShoppingCart(); - } - - /** - * Returns merchant name. - * - * @return string - */ - public function getMerchantName() - { - return $this->config->getMerchantName(); - } - - /** - * Returns client token. - * - * @return string|null - */ - public function getClientToken() - { - return $this->configProvider->getClientToken(); - } - - /** - * Returns action success. - * - * @return string - */ - public function getActionSuccess() - { - return $this->getUrl(ConfigProvider::CODE . '/paypal/review', ['_secure' => true]); - } - - /** - * Gets environment value. - * - * @return string - */ - public function getEnvironment(): string - { - return $this->configProvider->getConfig()['payment'][ConfigProvider::CODE]['environment']; - } -} diff --git a/app/code/Magento/Braintree/Block/Paypal/Checkout/Review.php b/app/code/Magento/Braintree/Block/Paypal/Checkout/Review.php deleted file mode 100644 index 77625035a56ae..0000000000000 --- a/app/code/Magento/Braintree/Block/Paypal/Checkout/Review.php +++ /dev/null @@ -1,37 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Block\Paypal\Checkout; - -use Magento\Paypal\Block\Express; - -/** - * Class Review - * - * @api - * @since 100.1.0 - */ -class Review extends Express\Review -{ - /** - * Controller path - * - * @var string - * @since 100.1.0 - */ - protected $_controllerPath = 'braintree/paypal'; - - /** - * Does not allow editing payment information as customer has gone through paypal flow already - * - * @return null - * @codeCoverageIgnore - * @since 100.1.0 - */ - public function getEditUrl() - { - return null; - } -} diff --git a/app/code/Magento/Braintree/Controller/Adminhtml/Payment/GetClientToken.php b/app/code/Magento/Braintree/Controller/Adminhtml/Payment/GetClientToken.php deleted file mode 100644 index 4b9721a693f08..0000000000000 --- a/app/code/Magento/Braintree/Controller/Adminhtml/Payment/GetClientToken.php +++ /dev/null @@ -1,76 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Controller\Adminhtml\Payment; - -use Magento\Backend\App\Action; -use Magento\Backend\App\Action\Context; -use Magento\Backend\Model\Session\Quote; -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\Request\PaymentDataBuilder; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Framework\Controller\ResultFactory; - -/** - * Retrieves client token. - */ -class GetClientToken extends Action -{ - const ADMIN_RESOURCE = 'Magento_Braintree::get_client_token'; - - /** - * @var Config - */ - private $config; - - /** - * @var BraintreeAdapterFactory - */ - private $adapterFactory; - - /** - * @var Quote - */ - private $quoteSession; - - /** - * @param Context $context - * @param Config $config - * @param BraintreeAdapterFactory $adapterFactory - * @param Quote $quoteSession - */ - public function __construct( - Context $context, - Config $config, - BraintreeAdapterFactory $adapterFactory, - Quote $quoteSession - ) { - parent::__construct($context); - $this->config = $config; - $this->adapterFactory = $adapterFactory; - $this->quoteSession = $quoteSession; - } - - /** - * @inheritdoc - */ - public function execute() - { - $params = []; - $response = $this->resultFactory->create(ResultFactory::TYPE_JSON); - - $storeId = $this->quoteSession->getStoreId(); - $merchantAccountId = $this->config->getMerchantAccountId($storeId); - if (!empty($merchantAccountId)) { - $params[PaymentDataBuilder::MERCHANT_ACCOUNT_ID] = $merchantAccountId; - } - - $clientToken = $this->adapterFactory->create($storeId) - ->generate($params); - $response->setData(['clientToken' => $clientToken]); - - return $response; - } -} diff --git a/app/code/Magento/Braintree/Controller/Adminhtml/Payment/GetNonce.php b/app/code/Magento/Braintree/Controller/Adminhtml/Payment/GetNonce.php deleted file mode 100644 index 47c875807b7a8..0000000000000 --- a/app/code/Magento/Braintree/Controller/Adminhtml/Payment/GetNonce.php +++ /dev/null @@ -1,13 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Controller\Adminhtml\Payment; - -/** - * Class GetNonce - */ -class GetNonce extends \Magento\Braintree\Controller\Payment\GetNonce -{ -} diff --git a/app/code/Magento/Braintree/Controller/Adminhtml/Report/Index.php b/app/code/Magento/Braintree/Controller/Adminhtml/Report/Index.php deleted file mode 100644 index 6f3c435d5fbad..0000000000000 --- a/app/code/Magento/Braintree/Controller/Adminhtml/Report/Index.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Controller\Adminhtml\Report; - -use Magento\Backend\App\Action; -use Magento\Backend\App\Action\Context; -use Magento\Backend\Model\View\Result\Page; -use Magento\Framework\View\Result\PageFactory; - -/** - * Braintree Settlement Report controller - */ -class Index extends Action -{ - /** - * @var PageFactory - */ - protected $resultPageFactory; - - const ADMIN_RESOURCE = 'Magento_Braintree::settlement_report'; - - /** - * @param Context $context - * @param PageFactory $resultPageFactory - */ - public function __construct( - Context $context, - PageFactory $resultPageFactory - ) { - parent::__construct($context); - $this->resultPageFactory = $resultPageFactory; - } - - /** - * Index action - * - * @return Page - */ - public function execute() - { - /** @var Page $resultPage */ - $resultPage = $this->resultPageFactory->create(); - $resultPage->setActiveMenu(static::ADMIN_RESOURCE); - $resultPage - ->getConfig() - ->getTitle() - ->prepend(__('Braintree Settlement Report')); - - return $resultPage; - } -} diff --git a/app/code/Magento/Braintree/Controller/Payment/GetNonce.php b/app/code/Magento/Braintree/Controller/Payment/GetNonce.php deleted file mode 100644 index f8b152ded1556..0000000000000 --- a/app/code/Magento/Braintree/Controller/Payment/GetNonce.php +++ /dev/null @@ -1,90 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Controller\Payment; - -use Magento\Braintree\Gateway\Command\GetPaymentNonceCommand; -use Magento\Framework\App\Action\Action; -use Magento\Framework\App\Action\Context; -use Magento\Framework\Controller\ResultFactory; -use Magento\Framework\Controller\ResultInterface; -use Magento\Framework\Session\SessionManagerInterface; -use Magento\Framework\Webapi\Exception; -use Psr\Log\LoggerInterface; - -/** - * Class GetNonce - */ -class GetNonce extends Action -{ - /** - * @var LoggerInterface - */ - private $logger; - - /** - * @var SessionManagerInterface - */ - private $session; - - /** - * @var GetPaymentNonceCommand - */ - private $command; - - /** - * @param Context $context - * @param LoggerInterface $logger - * @param SessionManagerInterface $session - * @param GetPaymentNonceCommand $command - */ - public function __construct( - Context $context, - LoggerInterface $logger, - SessionManagerInterface $session, - GetPaymentNonceCommand $command - ) { - parent::__construct($context); - $this->logger = $logger; - $this->session = $session; - $this->command = $command; - } - - /** - * @inheritdoc - */ - public function execute() - { - $response = $this->resultFactory->create(ResultFactory::TYPE_JSON); - - try { - $publicHash = $this->getRequest()->getParam('public_hash'); - $customerId = $this->session->getCustomerId(); - $result = $this->command->execute( - ['public_hash' => $publicHash, 'customer_id' => $customerId, 'store_id' => $this->session->getStoreId()] - ) - ->get(); - $response->setData(['paymentMethodNonce' => $result['paymentMethodNonce']]); - } catch (\Exception $e) { - $this->logger->critical($e); - return $this->processBadRequest($response); - } - - return $response; - } - - /** - * Return response for bad request - * @param ResultInterface $response - * @return ResultInterface - */ - private function processBadRequest(ResultInterface $response) - { - $response->setHttpResponseCode(Exception::HTTP_BAD_REQUEST); - $response->setData(['message' => __('Sorry, but something went wrong')]); - - return $response; - } -} diff --git a/app/code/Magento/Braintree/Controller/Paypal/AbstractAction.php b/app/code/Magento/Braintree/Controller/Paypal/AbstractAction.php deleted file mode 100644 index e0ed996019576..0000000000000 --- a/app/code/Magento/Braintree/Controller/Paypal/AbstractAction.php +++ /dev/null @@ -1,80 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Controller\Paypal; - -use Magento\Checkout\Model\Session; -use Magento\Framework\App\Action\Action; -use Magento\Framework\App\Action\Context; -use Magento\Quote\Api\Data\CartInterface; -use Magento\Framework\App\RequestInterface; -use Magento\Framework\Controller\Result\Redirect; -use Magento\Braintree\Gateway\Config\PayPal\Config; - -/** - * Abstract class AbstractAction - */ -abstract class AbstractAction extends Action -{ - /** - * @var Config - */ - protected $config; - - /** - * @var Session - */ - protected $checkoutSession; - - /** - * Constructor - * - * @param Context $context - * @param Config $config - * @param Session $checkoutSession - */ - public function __construct( - Context $context, - Config $config, - Session $checkoutSession - ) { - parent::__construct($context); - $this->config = $config; - $this->checkoutSession = $checkoutSession; - } - - /** - * Check whether payment method is enabled - * - * @inheritdoc - */ - public function dispatch(RequestInterface $request) - { - if (!$this->config->isActive() || !$this->config->isDisplayShoppingCart()) { - $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true); - - /** @var Redirect $resultRedirect */ - $resultRedirect = $this->resultRedirectFactory->create(); - $resultRedirect->setPath('noRoute'); - - return $resultRedirect; - } - - return parent::dispatch($request); - } - - /** - * @param CartInterface $quote - * @return void - * @throws \InvalidArgumentException - */ - protected function validateQuote($quote) - { - if (!$quote || !$quote->getItemsCount()) { - throw new \InvalidArgumentException(__('Checkout failed to initialize. Verify and try again.')); - } - } -} diff --git a/app/code/Magento/Braintree/Controller/Paypal/PlaceOrder.php b/app/code/Magento/Braintree/Controller/Paypal/PlaceOrder.php deleted file mode 100644 index ea8a44a1122b4..0000000000000 --- a/app/code/Magento/Braintree/Controller/Paypal/PlaceOrder.php +++ /dev/null @@ -1,84 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Controller\Paypal; - -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Model\Paypal\Helper; -use Magento\Checkout\Model\Session; -use Magento\Framework\App\Action\Context; -use Magento\Framework\App\Action\HttpPostActionInterface; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\Controller\ResultFactory; -use Magento\Framework\Exception\LocalizedException; -use Psr\Log\LoggerInterface; - -/** - * Class PlaceOrder - */ -class PlaceOrder extends AbstractAction implements HttpPostActionInterface -{ - /** - * @var Helper\OrderPlace - */ - private $orderPlace; - - /** - * Logger for exception details - * - * @var LoggerInterface - */ - private $logger; - - /** - * Constructor - * - * @param Context $context - * @param Config $config - * @param Session $checkoutSession - * @param Helper\OrderPlace $orderPlace - * @param LoggerInterface|null $logger - */ - public function __construct( - Context $context, - Config $config, - Session $checkoutSession, - Helper\OrderPlace $orderPlace, - LoggerInterface $logger = null - ) { - parent::__construct($context, $config, $checkoutSession); - $this->orderPlace = $orderPlace; - $this->logger = $logger ?: ObjectManager::getInstance()->get(LoggerInterface::class); - } - - /** - * @inheritdoc - * - * @throws LocalizedException - */ - public function execute() - { - $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); - $agreement = array_keys($this->getRequest()->getPostValue('agreement', [])); - $quote = $this->checkoutSession->getQuote(); - - try { - $this->validateQuote($quote); - - $this->orderPlace->execute($quote, $agreement); - - /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ - return $resultRedirect->setPath('checkout/onepage/success', ['_secure' => true]); - } catch (\Exception $e) { - $this->logger->critical($e); - $this->messageManager->addExceptionMessage( - $e, - __('The order #%1 cannot be processed.', $quote->getReservedOrderId()) - ); - } - - return $resultRedirect->setPath('checkout/cart', ['_secure' => true]); - } -} diff --git a/app/code/Magento/Braintree/Controller/Paypal/Review.php b/app/code/Magento/Braintree/Controller/Paypal/Review.php deleted file mode 100644 index 2923db6fa88c3..0000000000000 --- a/app/code/Magento/Braintree/Controller/Paypal/Review.php +++ /dev/null @@ -1,115 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Controller\Paypal; - -use Magento\Checkout\Model\Session; -use Magento\Framework\App\Action\Context; -use Magento\Framework\Controller\ResultFactory; -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Model\Paypal\Helper\QuoteUpdater; -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\App\Action\HttpPostActionInterface; -use Magento\Framework\App\Action\HttpGetActionInterface; -use Magento\Payment\Model\Method\Logger; - -/** - * Class Review - */ -class Review extends AbstractAction implements HttpPostActionInterface, HttpGetActionInterface -{ - /** - * @var QuoteUpdater - */ - private $quoteUpdater; - - /** - * @var Logger - */ - private $logger; - - /** - * @var string - */ - private static $paymentMethodNonce = 'payment_method_nonce'; - - /** - * Constructor - * - * @param Context $context - * @param Config $config - * @param Session $checkoutSession - * @param QuoteUpdater $quoteUpdater - * @param Logger $logger - */ - public function __construct( - Context $context, - Config $config, - Session $checkoutSession, - QuoteUpdater $quoteUpdater, - Logger $logger - ) { - parent::__construct($context, $config, $checkoutSession); - $this->quoteUpdater = $quoteUpdater; - $this->logger = $logger; - } - - /** - * @inheritdoc - */ - public function execute() - { - $requestData = json_decode( - $this->getRequest()->getPostValue('result', '{}'), - true - ); - $this->logger->debug($requestData); - $quote = $this->checkoutSession->getQuote(); - - try { - $this->validateQuote($quote); - - if ($requestData && $this->validateRequestData($requestData)) { - $this->quoteUpdater->execute( - $requestData['nonce'], - $requestData['details'], - $quote - ); - } elseif (!$quote->getPayment()->getAdditionalInformation(self::$paymentMethodNonce)) { - throw new LocalizedException(__('Checkout failed to initialize. Verify and try again.')); - } - - /** @var \Magento\Framework\View\Result\Page $resultPage */ - $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE); - - /** @var \Magento\Braintree\Block\Paypal\Checkout\Review $reviewBlock */ - $reviewBlock = $resultPage->getLayout()->getBlock('braintree.paypal.review'); - - $reviewBlock->setQuote($quote); - $reviewBlock->getChildBlock('shipping_method')->setData('quote', $quote); - - return $resultPage; - } catch (\Exception $e) { - $this->messageManager->addExceptionMessage($e, $e->getMessage()); - } - - /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ - $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); - - return $resultRedirect->setPath('checkout/cart', ['_secure' => true]); - } - - /** - * Validate request data - * - * @param array $requestData - * @return boolean - */ - private function validateRequestData(array $requestData) - { - return !empty($requestData['nonce']) && !empty($requestData['details']); - } -} diff --git a/app/code/Magento/Braintree/Controller/Paypal/SaveShippingMethod.php b/app/code/Magento/Braintree/Controller/Paypal/SaveShippingMethod.php deleted file mode 100644 index 5dd19d7acf7ae..0000000000000 --- a/app/code/Magento/Braintree/Controller/Paypal/SaveShippingMethod.php +++ /dev/null @@ -1,83 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Controller\Paypal; - -use Magento\Checkout\Model\Session; -use Magento\Framework\View\Result\Page; -use Magento\Framework\App\Action\Context; -use Magento\Framework\Controller\ResultFactory; -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Model\Paypal\Helper\ShippingMethodUpdater; - -/** - * Class SaveShippingMethod - */ -class SaveShippingMethod extends AbstractAction -{ - /** - * @var ShippingMethodUpdater - */ - private $shippingMethodUpdater; - - /** - * Constructor - * - * @param Context $context - * @param Config $config - * @param Session $checkoutSession - * @param ShippingMethodUpdater $shippingMethodUpdater - */ - public function __construct( - Context $context, - Config $config, - Session $checkoutSession, - ShippingMethodUpdater $shippingMethodUpdater - ) { - parent::__construct($context, $config, $checkoutSession); - $this->shippingMethodUpdater = $shippingMethodUpdater; - } - - /** - * @inheritdoc - */ - public function execute() - { - $isAjax = $this->getRequest()->getParam('isAjax'); - $quote = $this->checkoutSession->getQuote(); - - try { - $this->validateQuote($quote); - - $this->shippingMethodUpdater->execute( - $this->getRequest()->getParam('shipping_method'), - $quote - ); - - if ($isAjax) { - /** @var Page $response */ - $response = $this->resultFactory->create(ResultFactory::TYPE_PAGE); - $layout = $response->addHandle('paypal_express_review_details')->getLayout(); - - $response = $layout->getBlock('page.block')->toHtml(); - $this->getResponse()->setBody($response); - - return; - } - } catch (\Exception $e) { - $this->messageManager->addExceptionMessage($e, $e->getMessage()); - } - - $path = $this->_url->getUrl('*/*/review', ['_secure' => true]); - - if ($isAjax) { - $this->getResponse()->setBody(sprintf('<script>window.location.href = "%s";</script>', $path)); - - return; - } - - $this->_redirect($path); - } -} diff --git a/app/code/Magento/Braintree/Gateway/Command/CaptureStrategyCommand.php b/app/code/Magento/Braintree/Gateway/Command/CaptureStrategyCommand.php deleted file mode 100644 index d35906c929b2a..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Command/CaptureStrategyCommand.php +++ /dev/null @@ -1,195 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Command; - -use Braintree\Transaction; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Braintree\Model\Adapter\BraintreeSearchAdapter; -use Magento\Framework\Api\FilterBuilder; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Payment\Gateway\Command\CommandPoolInterface; -use Magento\Payment\Gateway\CommandInterface; -use Magento\Payment\Gateway\Data\OrderAdapterInterface; -use Magento\Payment\Gateway\Helper\ContextHelper; -use Magento\Sales\Api\Data\OrderPaymentInterface; -use Magento\Sales\Api\Data\TransactionInterface; -use Magento\Sales\Api\TransactionRepositoryInterface; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; - -/** - * Braintree capture implementation. - * - * @SuppressWarnings(PHPMD) - */ -class CaptureStrategyCommand implements CommandInterface -{ - /** - * Braintree authorize and capture command - */ - const SALE = 'sale'; - - /** - * Braintree capture command - */ - const CAPTURE = 'settlement'; - - /** - * Braintree vault capture command - */ - const VAULT_CAPTURE = 'vault_capture'; - - /** - * @var CommandPoolInterface - */ - private $commandPool; - - /** - * @var TransactionRepositoryInterface - */ - private $transactionRepository; - - /** - * @var FilterBuilder - */ - private $filterBuilder; - - /** - * @var SearchCriteriaBuilder - */ - private $searchCriteriaBuilder; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * @var BraintreeAdapterFactory - */ - private $braintreeAdapterFactory; - - /** - * @var BraintreeSearchAdapter - */ - private $braintreeSearchAdapter; - - /** - * Constructor - * - * @param CommandPoolInterface $commandPool - * @param TransactionRepositoryInterface $repository - * @param FilterBuilder $filterBuilder - * @param SearchCriteriaBuilder $searchCriteriaBuilder - * @param SubjectReader $subjectReader - * @param BraintreeAdapterFactory $braintreeAdapterFactory - * @param BraintreeSearchAdapter $braintreeSearchAdapter - */ - public function __construct( - CommandPoolInterface $commandPool, - TransactionRepositoryInterface $repository, - FilterBuilder $filterBuilder, - SearchCriteriaBuilder $searchCriteriaBuilder, - SubjectReader $subjectReader, - BraintreeAdapterFactory $braintreeAdapterFactory, - BraintreeSearchAdapter $braintreeSearchAdapter - ) { - $this->commandPool = $commandPool; - $this->transactionRepository = $repository; - $this->filterBuilder = $filterBuilder; - $this->searchCriteriaBuilder = $searchCriteriaBuilder; - $this->subjectReader = $subjectReader; - $this->braintreeAdapterFactory = $braintreeAdapterFactory; - $this->braintreeSearchAdapter = $braintreeSearchAdapter; - } - - /** - * @inheritdoc - */ - public function execute(array $commandSubject) - { - /** @var \Magento\Payment\Gateway\Data\PaymentDataObjectInterface $paymentDO */ - $paymentDO = $this->subjectReader->readPayment($commandSubject); - $command = $this->getCommand($paymentDO); - - return $this->commandPool->get($command)->execute($commandSubject); - } - - /** - * Get execution command name. - * - * @param PaymentDataObjectInterface $paymentDO - * @return string - */ - private function getCommand(PaymentDataObjectInterface $paymentDO) - { - $payment = $paymentDO->getPayment(); - ContextHelper::assertOrderPayment($payment); - - // if capture transaction does not exist then execute capture command - $existsCapture = $this->isExistsCaptureTransaction($payment); - - // do capture for authorization transaction - if (!$existsCapture && !$this->isExpiredAuthorization($payment, $paymentDO->getOrder())) { - return self::CAPTURE; - } - - // process capture for payment via Vault - return self::VAULT_CAPTURE; - } - - /** - * Checks if authorization transaction does not expired yet. - * - * @param OrderPaymentInterface $payment - * @param OrderAdapterInterface $orderAdapter - * @return bool - */ - private function isExpiredAuthorization(OrderPaymentInterface $payment, OrderAdapterInterface $orderAdapter) - { - $adapter = $this->braintreeAdapterFactory->create($orderAdapter->getStoreId()); - $collection = $adapter->search( - [ - $this->braintreeSearchAdapter->id()->is($payment->getLastTransId()), - $this->braintreeSearchAdapter->status()->is(Transaction::AUTHORIZATION_EXPIRED) - ] - ); - - return $collection->maximumCount() > 0; - } - - /** - * Check if capture transaction already exists - * - * @param OrderPaymentInterface $payment - * @return bool - */ - private function isExistsCaptureTransaction(OrderPaymentInterface $payment) - { - $this->searchCriteriaBuilder->addFilters( - [ - $this->filterBuilder - ->setField('payment_id') - ->setValue($payment->getId()) - ->create(), - ] - ); - - $this->searchCriteriaBuilder->addFilters( - [ - $this->filterBuilder - ->setField('txn_type') - ->setValue(TransactionInterface::TYPE_CAPTURE) - ->create(), - ] - ); - - $searchCriteria = $this->searchCriteriaBuilder->create(); - - $count = $this->transactionRepository->getList($searchCriteria)->getTotalCount(); - return (boolean) $count; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Command/GetPaymentNonceCommand.php b/app/code/Magento/Braintree/Gateway/Command/GetPaymentNonceCommand.php deleted file mode 100644 index 672aa02a0db6d..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Command/GetPaymentNonceCommand.php +++ /dev/null @@ -1,92 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Gateway\Command; - -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Braintree\Gateway\Validator\PaymentNonceResponseValidator; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Payment\Gateway\Command\Result\ArrayResultFactory; -use Magento\Payment\Gateway\CommandInterface; -use Magento\Vault\Api\PaymentTokenManagementInterface; - -/** - * Class GetPaymentNonceCommand - */ -class GetPaymentNonceCommand implements CommandInterface -{ - - /** - * @var PaymentTokenManagementInterface - */ - private $tokenManagement; - - /** - * @var BraintreeAdapterFactory - */ - private $adapterFactory; - - /** - * @var ArrayResultFactory - */ - private $resultFactory; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * @var PaymentNonceResponseValidator - */ - private $responseValidator; - - /** - * @param PaymentTokenManagementInterface $tokenManagement - * @param BraintreeAdapterFactory $adapterFactory - * @param ArrayResultFactory $resultFactory - * @param SubjectReader $subjectReader - * @param PaymentNonceResponseValidator $responseValidator - */ - public function __construct( - PaymentTokenManagementInterface $tokenManagement, - BraintreeAdapterFactory $adapterFactory, - ArrayResultFactory $resultFactory, - SubjectReader $subjectReader, - PaymentNonceResponseValidator $responseValidator - ) { - $this->tokenManagement = $tokenManagement; - $this->adapterFactory = $adapterFactory; - $this->resultFactory = $resultFactory; - $this->subjectReader = $subjectReader; - $this->responseValidator = $responseValidator; - } - - /** - * @inheritdoc - * @throws \Exception - */ - public function execute(array $commandSubject) - { - $publicHash = $this->subjectReader->readPublicHash($commandSubject); - $customerId = $this->subjectReader->readCustomerId($commandSubject); - $paymentToken = $this->tokenManagement->getByPublicHash($publicHash, $customerId); - if (!$paymentToken) { - throw new \Exception('No available payment tokens'); - } - - $storeId = $this->subjectReader->readStoreId($commandSubject); - $data = $this->adapterFactory->create($storeId) - ->createNonce($paymentToken->getGatewayToken()); - $result = $this->responseValidator->validate(['response' => ['object' => $data]]); - - if (!$result->isValid()) { - throw new \Exception(__(implode("\n", $result->getFailsDescription()))); - } - - return $this->resultFactory->create(['array' => ['paymentMethodNonce' => $data->paymentMethodNonce->nonce]]); - } -} diff --git a/app/code/Magento/Braintree/Gateway/Config/CanVoidHandler.php b/app/code/Magento/Braintree/Gateway/Config/CanVoidHandler.php deleted file mode 100644 index 0466216bdb7d2..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Config/CanVoidHandler.php +++ /dev/null @@ -1,45 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Config; - -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Config\ValueHandlerInterface; -use Magento\Sales\Model\Order\Payment; - -class CanVoidHandler implements ValueHandlerInterface -{ - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * CanVoidHandler constructor. - * @param SubjectReader $subjectReader - */ - public function __construct( - SubjectReader $subjectReader - ) { - $this->subjectReader = $subjectReader; - } - - /** - * Retrieve method configured value - * - * @param array $subject - * @param int|null $storeId - * - * @return mixed - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function handle(array $subject, $storeId = null) - { - $paymentDO = $this->subjectReader->readPayment($subject); - - $payment = $paymentDO->getPayment(); - return $payment instanceof Payment && !(bool)$payment->getAmountPaid(); - } -} diff --git a/app/code/Magento/Braintree/Gateway/Config/Config.php b/app/code/Magento/Braintree/Gateway/Config/Config.php deleted file mode 100644 index 905b802061aa6..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Config/Config.php +++ /dev/null @@ -1,267 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Config; - -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\Serialize\Serializer\Json; - -/** - * Class Config - */ -class Config extends \Magento\Payment\Gateway\Config\Config -{ - const KEY_ENVIRONMENT = 'environment'; - const KEY_ACTIVE = 'active'; - const KEY_MERCHANT_ID = 'merchant_id'; - const KEY_MERCHANT_ACCOUNT_ID = 'merchant_account_id'; - const KEY_PUBLIC_KEY = 'public_key'; - const KEY_PRIVATE_KEY = 'private_key'; - const KEY_COUNTRY_CREDIT_CARD = 'countrycreditcard'; - const KEY_CC_TYPES = 'cctypes'; - const KEY_CC_TYPES_BRAINTREE_MAPPER = 'cctypes_braintree_mapper'; - const KEY_SDK_URL = 'sdk_url'; - const KEY_USE_CVV = 'useccv'; - const KEY_VERIFY_3DSECURE = 'verify_3dsecure'; - const KEY_THRESHOLD_AMOUNT = 'threshold_amount'; - const KEY_VERIFY_ALLOW_SPECIFIC = 'verify_all_countries'; - const KEY_VERIFY_SPECIFIC = 'verify_specific_countries'; - const VALUE_3DSECURE_ALL = 0; - const CODE_3DSECURE = 'three_d_secure'; - const FRAUD_PROTECTION = 'fraudprotection'; - - /** - * @var \Magento\Framework\Serialize\Serializer\Json - */ - private $serializer; - - /** - * Braintree config constructor - * - * @param ScopeConfigInterface $scopeConfig - * @param null|string $methodCode - * @param string $pathPattern - * @param Json|null $serializer - */ - public function __construct( - ScopeConfigInterface $scopeConfig, - $methodCode = null, - $pathPattern = self::DEFAULT_PATH_PATTERN, - Json $serializer = null - ) { - parent::__construct($scopeConfig, $methodCode, $pathPattern); - $this->serializer = $serializer ?: \Magento\Framework\App\ObjectManager::getInstance() - ->get(Json::class); - } - - /** - * Get list of available dynamic descriptors keys - * @var array - */ - private static $dynamicDescriptorKeys = [ - 'name', 'phone', 'url' - ]; - - /** - * Return the country specific card type config - * - * @param int|null $storeId - * @return array - */ - public function getCountrySpecificCardTypeConfig($storeId = null) - { - $countryCardTypes = $this->getValue(self::KEY_COUNTRY_CREDIT_CARD, $storeId); - if (!$countryCardTypes) { - return []; - } - $countryCardTypes = $this->serializer->unserialize($countryCardTypes); - return is_array($countryCardTypes) ? $countryCardTypes : []; - } - - /** - * Retrieve available credit card types - * - * @param int|null $storeId - * @return array - */ - public function getAvailableCardTypes($storeId = null) - { - $ccTypes = $this->getValue(self::KEY_CC_TYPES, $storeId); - - return !empty($ccTypes) ? explode(',', $ccTypes) : []; - } - - /** - * Retrieve mapper between Magento and Braintree card types - * - * @return array - */ - public function getCcTypesMapper() - { - $result = json_decode( - $this->getValue(self::KEY_CC_TYPES_BRAINTREE_MAPPER), - true - ); - - return is_array($result) ? $result : []; - } - - /** - * Gets list of card types available for country. - * - * @param string $country - * @param int|null $storeId - * @return array - */ - public function getCountryAvailableCardTypes($country, $storeId = null) - { - $types = $this->getCountrySpecificCardTypeConfig($storeId); - - return (!empty($types[$country])) ? $types[$country] : []; - } - - /** - * Checks if cvv field is enabled. - * - * @param int|null $storeId - * @return bool - */ - public function isCvvEnabled($storeId = null) - { - return (bool) $this->getValue(self::KEY_USE_CVV, $storeId); - } - - /** - * Checks if 3d secure verification enabled. - * - * @param int|null $storeId - * @return bool - */ - public function isVerify3DSecure($storeId = null) - { - return (bool) $this->getValue(self::KEY_VERIFY_3DSECURE, $storeId); - } - - /** - * Gets threshold amount for 3d secure. - * - * @param int|null $storeId - * @return float - */ - public function getThresholdAmount($storeId = null) - { - return (double) $this->getValue(self::KEY_THRESHOLD_AMOUNT, $storeId); - } - - /** - * Gets list of specific countries for 3d secure. - * - * @param int|null $storeId - * @return array - */ - public function get3DSecureSpecificCountries($storeId = null) - { - if ((int) $this->getValue(self::KEY_VERIFY_ALLOW_SPECIFIC, $storeId) == self::VALUE_3DSECURE_ALL) { - return []; - } - - return explode(',', $this->getValue(self::KEY_VERIFY_SPECIFIC, $storeId)); - } - - /** - * Gets value of configured environment. - * - * Possible values: production or sandbox. - * - * @param int|null $storeId - * @return string - */ - public function getEnvironment($storeId = null) - { - return $this->getValue(Config::KEY_ENVIRONMENT, $storeId); - } - - /** - * Gets merchant ID. - * - * @param int|null $storeId - * @return string - */ - public function getMerchantId($storeId = null) - { - return $this->getValue(Config::KEY_MERCHANT_ID, $storeId); - } - - /** - * Gets Merchant account ID. - * - * @param int|null $storeId - * @return string - */ - public function getMerchantAccountId($storeId = null) - { - return $this->getValue(self::KEY_MERCHANT_ACCOUNT_ID, $storeId); - } - - /** - * Returns SDK url. - * - * @return string - */ - public function getSdkUrl() - { - return $this->getValue(Config::KEY_SDK_URL); - } - - /** - * Gets Hosted Fields SDK Url - * - * @return string - */ - public function getHostedFieldsSdkUrl(): string - { - return $this->getValue('hosted_fields_sdk_url'); - } - - /** - * Checks if fraud protection is enabled. - * - * @param int|null $storeId - * @return bool - */ - public function hasFraudProtection($storeId = null) - { - return (bool) $this->getValue(Config::FRAUD_PROTECTION, $storeId); - } - - /** - * Gets Payment configuration status. - * - * @param int|null $storeId - * @return bool - */ - public function isActive($storeId = null) - { - return (bool) $this->getValue(self::KEY_ACTIVE, $storeId); - } - - /** - * Gets list of configured dynamic descriptors. - * - * @param int|null $storeId - * @return array - */ - public function getDynamicDescriptors($storeId = null) - { - $values = []; - foreach (self::$dynamicDescriptorKeys as $key) { - $value = $this->getValue('descriptor_' . $key, $storeId); - if (!empty($value)) { - $values[$key] = $value; - } - } - return $values; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Config/PayPal/Config.php b/app/code/Magento/Braintree/Gateway/Config/PayPal/Config.php deleted file mode 100644 index e7d8724082fb3..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Config/PayPal/Config.php +++ /dev/null @@ -1,141 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Config\PayPal; - -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Payment\Model\CcConfig; - -/** - * Class Config - */ -class Config extends \Magento\Payment\Gateway\Config\Config -{ - const KEY_ACTIVE = 'active'; - - const KEY_TITLE = 'title'; - - const KEY_DISPLAY_ON_SHOPPING_CART = 'display_on_shopping_cart'; - - const KEY_ALLOW_TO_EDIT_SHIPPING_ADDRESS = 'allow_shipping_address_override'; - - const KEY_MERCHANT_NAME_OVERRIDE = 'merchant_name_override'; - - const KEY_REQUIRE_BILLING_ADDRESS = 'require_billing_address'; - - /** - * @var CcConfig - */ - private $ccConfig; - - /** - * @var array - */ - private $icon = []; - - /** - * Initialize dependencies. - * - * @param ScopeConfigInterface $scopeConfig - * @param CcConfig $ccConfig - * @param null $methodCode - * @param string $pathPattern - */ - public function __construct( - ScopeConfigInterface $scopeConfig, - CcConfig $ccConfig, - $methodCode = null, - $pathPattern = self::DEFAULT_PATH_PATTERN - ) { - parent::__construct($scopeConfig, $methodCode, $pathPattern); - $this->ccConfig = $ccConfig; - } - - /** - * Get Payment configuration status - * - * @return bool - */ - public function isActive() - { - return (bool) $this->getValue(self::KEY_ACTIVE); - } - - /** - * @return bool - */ - public function isDisplayShoppingCart() - { - return (bool) $this->getValue(self::KEY_DISPLAY_ON_SHOPPING_CART); - } - - /** - * Is shipping address can be editable on PayPal side - * - * @return bool - */ - public function isAllowToEditShippingAddress() - { - return (bool) $this->getValue(self::KEY_ALLOW_TO_EDIT_SHIPPING_ADDRESS); - } - - /** - * Get merchant name to display in PayPal popup - * - * @return string - */ - public function getMerchantName() - { - return $this->getValue(self::KEY_MERCHANT_NAME_OVERRIDE); - } - - /** - * Is billing address can be required - * - * @return string - */ - public function isRequiredBillingAddress() - { - return $this->getValue(self::KEY_REQUIRE_BILLING_ADDRESS); - } - - /** - * Get title of payment - * - * @return string - */ - public function getTitle() - { - return $this->getValue(self::KEY_TITLE); - } - - /** - * Is need to skip order review - * @return bool - */ - public function isSkipOrderReview() - { - return (bool) $this->getValue('skip_order_review'); - } - - /** - * Get PayPal icon - * @return array - */ - public function getPayPalIcon() - { - if (empty($this->icon)) { - $asset = $this->ccConfig->createAsset('Magento_Braintree::images/paypal.png'); - list($width, $height) = getimagesize($asset->getSourceFile()); - $this->icon = [ - 'url' => $asset->getUrl(), - 'width' => $width, - 'height' => $height - ]; - } - - return $this->icon; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Http/Client/AbstractTransaction.php b/app/code/Magento/Braintree/Gateway/Http/Client/AbstractTransaction.php deleted file mode 100644 index ef35152bf7e95..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Http/Client/AbstractTransaction.php +++ /dev/null @@ -1,82 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Gateway\Http\Client; - -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Payment\Gateway\Http\ClientException; -use Magento\Payment\Gateway\Http\ClientInterface; -use Magento\Payment\Gateway\Http\TransferInterface; -use Magento\Payment\Model\Method\Logger; -use Psr\Log\LoggerInterface; - -/** - * Class AbstractTransaction - */ -abstract class AbstractTransaction implements ClientInterface -{ - /** - * @var LoggerInterface - */ - protected $logger; - - /** - * @var Logger - */ - protected $customLogger; - - /** - * @var BraintreeAdapterFactory - */ - protected $adapterFactory; - - /** - * Constructor - * - * @param LoggerInterface $logger - * @param Logger $customLogger - * @param BraintreeAdapterFactory $adapterFactory - */ - public function __construct(LoggerInterface $logger, Logger $customLogger, BraintreeAdapterFactory $adapterFactory) - { - $this->logger = $logger; - $this->customLogger = $customLogger; - $this->adapterFactory = $adapterFactory; - } - - /** - * @inheritdoc - */ - public function placeRequest(TransferInterface $transferObject) - { - $data = $transferObject->getBody(); - $log = [ - 'request' => $data, - 'client' => static::class - ]; - $response['object'] = []; - - try { - $response['object'] = $this->process($data); - } catch (\Exception $e) { - $message = __($e->getMessage() ?: 'Sorry, but something went wrong'); - $this->logger->critical($message); - throw new ClientException($message); - } finally { - $log['response'] = (array) $response['object']; - $this->customLogger->debug($log); - } - - return $response; - } - - /** - * Process http request - * @param array $data - * @return \Braintree\Result\Error|\Braintree\Result\Successful - */ - abstract protected function process(array $data); -} diff --git a/app/code/Magento/Braintree/Gateway/Http/Client/TransactionRefund.php b/app/code/Magento/Braintree/Gateway/Http/Client/TransactionRefund.php deleted file mode 100644 index 6d43929db7675..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Http/Client/TransactionRefund.php +++ /dev/null @@ -1,24 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Http\Client; - -use Magento\Braintree\Gateway\Request\PaymentDataBuilder; - -class TransactionRefund extends AbstractTransaction -{ - /** - * Process http request - * @param array $data - * @return \Braintree\Result\Error|\Braintree\Result\Successful - */ - protected function process(array $data) - { - $storeId = $data['store_id'] ?? null; - - return $this->adapterFactory->create($storeId) - ->refund($data['transaction_id'], $data[PaymentDataBuilder::AMOUNT]); - } -} diff --git a/app/code/Magento/Braintree/Gateway/Http/Client/TransactionSale.php b/app/code/Magento/Braintree/Gateway/Http/Client/TransactionSale.php deleted file mode 100644 index 0e4481a43bc89..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Http/Client/TransactionSale.php +++ /dev/null @@ -1,24 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Http\Client; - -/** - * Class TransactionSale - */ -class TransactionSale extends AbstractTransaction -{ - /** - * @inheritdoc - */ - protected function process(array $data) - { - $storeId = $data['store_id'] ?? null; - // sending store id and other additional keys are restricted by Braintree API - unset($data['store_id']); - - return $this->adapterFactory->create($storeId)->sale($data); - } -} diff --git a/app/code/Magento/Braintree/Gateway/Http/Client/TransactionSubmitForSettlement.php b/app/code/Magento/Braintree/Gateway/Http/Client/TransactionSubmitForSettlement.php deleted file mode 100644 index 6760e724fd3a6..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Http/Client/TransactionSubmitForSettlement.php +++ /dev/null @@ -1,26 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Http\Client; - -use Magento\Braintree\Gateway\Request\CaptureDataBuilder; -use Magento\Braintree\Gateway\Request\PaymentDataBuilder; - -/** - * Class TransactionSubmitForSettlement - */ -class TransactionSubmitForSettlement extends AbstractTransaction -{ - /** - * @inheritdoc - */ - protected function process(array $data) - { - $storeId = $data['store_id'] ?? null; - - return $this->adapterFactory->create($storeId) - ->submitForSettlement($data[CaptureDataBuilder::TRANSACTION_ID], $data[PaymentDataBuilder::AMOUNT]); - } -} diff --git a/app/code/Magento/Braintree/Gateway/Http/Client/TransactionVoid.php b/app/code/Magento/Braintree/Gateway/Http/Client/TransactionVoid.php deleted file mode 100644 index 0a940839fc154..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Http/Client/TransactionVoid.php +++ /dev/null @@ -1,21 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Http\Client; - -class TransactionVoid extends AbstractTransaction -{ - /** - * Process http request - * @param array $data - * @return \Braintree\Result\Error|\Braintree\Result\Successful - */ - protected function process(array $data) - { - $storeId = $data['store_id'] ?? null; - - return $this->adapterFactory->create($storeId)->void($data['transaction_id']); - } -} diff --git a/app/code/Magento/Braintree/Gateway/Http/TransferFactory.php b/app/code/Magento/Braintree/Gateway/Http/TransferFactory.php deleted file mode 100644 index c6e4601c59d04..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Http/TransferFactory.php +++ /dev/null @@ -1,41 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Http; - -use Magento\Payment\Gateway\Http\TransferBuilder; -use Magento\Payment\Gateway\Http\TransferFactoryInterface; -use Magento\Payment\Gateway\Http\TransferInterface; -use Magento\Payment\Gateway\ConfigInterface; - -class TransferFactory implements TransferFactoryInterface -{ - /** - * @var TransferBuilder - */ - private $transferBuilder; - - /** - * @param TransferBuilder $transferBuilder - */ - public function __construct( - TransferBuilder $transferBuilder - ) { - $this->transferBuilder = $transferBuilder; - } - - /** - * Builds gateway transfer object - * - * @param array $request - * @return TransferInterface - */ - public function create(array $request) - { - return $this->transferBuilder - ->setBody($request) - ->build(); - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/AddressDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/AddressDataBuilder.php deleted file mode 100644 index f7d3aae823e56..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/AddressDataBuilder.php +++ /dev/null @@ -1,135 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Payment\Gateway\Request\BuilderInterface; -use Magento\Braintree\Gateway\SubjectReader; - -/** - * Class AddressDataBuilder - */ -class AddressDataBuilder implements BuilderInterface -{ - /** - * ShippingAddress block name - */ - const SHIPPING_ADDRESS = 'shipping'; - - /** - * BillingAddress block name - */ - const BILLING_ADDRESS = 'billing'; - - /** - * The first name value must be less than or equal to 255 characters. - */ - const FIRST_NAME = 'firstName'; - - /** - * The last name value must be less than or equal to 255 characters. - */ - const LAST_NAME = 'lastName'; - - /** - * The customer’s company. 255 character maximum. - */ - const COMPANY = 'company'; - - /** - * The street address. Maximum 255 characters, and must contain at least 1 digit. - * Required when AVS rules are configured to require street address. - */ - const STREET_ADDRESS = 'streetAddress'; - - /** - * The extended address information—such as apartment or suite number. 255 character maximum. - */ - const EXTENDED_ADDRESS = 'extendedAddress'; - - /** - * The locality/city. 255 character maximum. - */ - const LOCALITY = 'locality'; - - /** - * The state or province. For PayPal addresses, the region must be a 2-letter abbreviation; - * for all other payment methods, it must be less than or equal to 255 characters. - */ - const REGION = 'region'; - - /** - * The postal code. Postal code must be a string of 5 or 9 alphanumeric digits, - * optionally separated by a dash or a space. Spaces, hyphens, - * and all other special characters are ignored. - */ - const POSTAL_CODE = 'postalCode'; - - /** - * The ISO 3166-1 alpha-2 country code specified in an address. - * The gateway only accepts specific alpha-2 values. - * - * @link https://developers.braintreepayments.com/reference/general/countries/php#list-of-countries - */ - const COUNTRY_CODE = 'countryCodeAlpha2'; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * Constructor - * - * @param SubjectReader $subjectReader - */ - public function __construct(SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - - $order = $paymentDO->getOrder(); - $result = []; - - $billingAddress = $order->getBillingAddress(); - if ($billingAddress) { - $result[self::BILLING_ADDRESS] = [ - self::FIRST_NAME => $billingAddress->getFirstname(), - self::LAST_NAME => $billingAddress->getLastname(), - self::COMPANY => $billingAddress->getCompany(), - self::STREET_ADDRESS => $billingAddress->getStreetLine1(), - self::EXTENDED_ADDRESS => $billingAddress->getStreetLine2(), - self::LOCALITY => $billingAddress->getCity(), - self::REGION => $billingAddress->getRegionCode(), - self::POSTAL_CODE => $billingAddress->getPostcode(), - self::COUNTRY_CODE => $billingAddress->getCountryId() - ]; - } - - $shippingAddress = $order->getShippingAddress(); - if ($shippingAddress) { - $result[self::SHIPPING_ADDRESS] = [ - self::FIRST_NAME => $shippingAddress->getFirstname(), - self::LAST_NAME => $shippingAddress->getLastname(), - self::COMPANY => $shippingAddress->getCompany(), - self::STREET_ADDRESS => $shippingAddress->getStreetLine1(), - self::EXTENDED_ADDRESS => $shippingAddress->getStreetLine2(), - self::LOCALITY => $shippingAddress->getCity(), - self::REGION => $shippingAddress->getRegionCode(), - self::POSTAL_CODE => $shippingAddress->getPostcode(), - self::COUNTRY_CODE => $shippingAddress->getCountryId() - ]; - } - - return $result; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/BillingAddressDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/BillingAddressDataBuilder.php deleted file mode 100644 index 403c4d72fe358..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/BillingAddressDataBuilder.php +++ /dev/null @@ -1,112 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Payment\Gateway\Request\BuilderInterface; -use Magento\Braintree\Gateway\SubjectReader; - -/** - * Class BillingAddressDataBuilder - */ -class BillingAddressDataBuilder implements BuilderInterface -{ - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * BillingAddress block name - */ - private const BILLING_ADDRESS = 'billing'; - - /** - * The customer’s company. 255 character maximum. - */ - private const COMPANY = 'company'; - - /** - * The first name value must be less than or equal to 255 characters. - */ - private const FIRST_NAME = 'firstName'; - - /** - * The last name value must be less than or equal to 255 characters. - */ - private const LAST_NAME = 'lastName'; - - /** - * The street address. Maximum 255 characters, and must contain at least 1 digit. - * Required when AVS rules are configured to require street address. - */ - private const STREET_ADDRESS = 'streetAddress'; - - /** - * The postal code. Postal code must be a string of 5 or 9 alphanumeric digits, - * optionally separated by a dash or a space. Spaces, hyphens, - * and all other special characters are ignored. - */ - private const POSTAL_CODE = 'postalCode'; - - /** - * The ISO 3166-1 alpha-2 country code specified in an address. - * The gateway only accepts specific alpha-2 values. - * - * @link https://developers.braintreepayments.com/reference/general/countries/php#list-of-countries - */ - private const COUNTRY_CODE = 'countryCodeAlpha2'; - - /** - * The extended address information—such as apartment or suite number. 255 character maximum. - */ - private const EXTENDED_ADDRESS = 'extendedAddress'; - - /** - * The locality/city. 255 character maximum. - */ - private const LOCALITY = 'locality'; - - /** - * The state or province. For PayPal addresses, the region must be a 2-letter abbreviation; - */ - private const REGION = 'region'; - - /** - * @param SubjectReader $subjectReader - */ - public function __construct(SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - - $result = []; - $order = $paymentDO->getOrder(); - - $billingAddress = $order->getBillingAddress(); - if ($billingAddress) { - $result[self::BILLING_ADDRESS] = [ - self::REGION => $billingAddress->getRegionCode(), - self::POSTAL_CODE => $billingAddress->getPostcode(), - self::COUNTRY_CODE => $billingAddress->getCountryId(), - self::FIRST_NAME => $billingAddress->getFirstname(), - self::STREET_ADDRESS => $billingAddress->getStreetLine1(), - self::LAST_NAME => $billingAddress->getLastname(), - self::COMPANY => $billingAddress->getCompany(), - self::EXTENDED_ADDRESS => $billingAddress->getStreetLine2(), - self::LOCALITY => $billingAddress->getCity() - ]; - } - - return $result; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/CaptureDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/CaptureDataBuilder.php deleted file mode 100644 index 6f3a262d7efb4..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/CaptureDataBuilder.php +++ /dev/null @@ -1,56 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Framework\Exception\LocalizedException; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Request\BuilderInterface; -use Magento\Payment\Helper\Formatter; - -/** - * Class CaptureDataBuilder - */ -class CaptureDataBuilder implements BuilderInterface -{ - use Formatter; - - const TRANSACTION_ID = 'transaction_id'; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * Constructor - * - * @param SubjectReader $subjectReader - */ - public function __construct(SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - - $payment = $paymentDO->getPayment(); - - $transactionId = $payment->getCcTransId(); - if (!$transactionId) { - throw new LocalizedException(__('No authorization transaction to proceed capture.')); - } - - return [ - self::TRANSACTION_ID => $transactionId, - PaymentDataBuilder::AMOUNT => $this->formatPrice($this->subjectReader->readAmount($buildSubject)) - ]; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/ChannelDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/ChannelDataBuilder.php deleted file mode 100644 index 77e1659351bef..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/ChannelDataBuilder.php +++ /dev/null @@ -1,60 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Framework\App\ObjectManager; -use Magento\Framework\App\ProductMetadataInterface; -use Magento\Payment\Gateway\Config\Config; -use Magento\Payment\Gateway\Request\BuilderInterface; - -/** - * Class BnCodeDataBuilder - */ -class ChannelDataBuilder implements BuilderInterface -{ - /** - * @var string - */ - private static $channel = 'channel'; - - /** - * @var string - */ - private static $channelValue = 'Magento2_Cart_%s_BT'; - - /** - * @var ProductMetadataInterface - */ - private $productMetadata; - - /** - * @var Config - */ - private $config; - - /** - * Constructor - * - * @param ProductMetadataInterface $productMetadata - * @param Config $config - */ - public function __construct(ProductMetadataInterface $productMetadata, Config $config = null) - { - $this->productMetadata = $productMetadata; - $this->config = $config ?: ObjectManager::getInstance()->get(Config::class); - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - $channel = $this->config->getValue('channel'); - return [ - self::$channel => $channel ?: sprintf(self::$channelValue, $this->productMetadata->getEdition()) - ]; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/CustomerDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/CustomerDataBuilder.php deleted file mode 100644 index 6b3403bcd15c1..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/CustomerDataBuilder.php +++ /dev/null @@ -1,82 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Payment\Gateway\Request\BuilderInterface; -use Magento\Braintree\Gateway\SubjectReader; - -/** - * Class CustomerDataBuilder - */ -class CustomerDataBuilder implements BuilderInterface -{ - /** - * Customer block name - */ - const CUSTOMER = 'customer'; - - /** - * The first name value must be less than or equal to 255 characters. - */ - const FIRST_NAME = 'firstName'; - - /** - * The last name value must be less than or equal to 255 characters. - */ - const LAST_NAME = 'lastName'; - - /** - * The customer’s company. 255 character maximum. - */ - const COMPANY = 'company'; - - /** - * The customer’s email address, comprised of ASCII characters. - */ - const EMAIL = 'email'; - - /** - * Phone number. Phone must be 10-14 characters and can - * only contain numbers, dashes, parentheses and periods. - */ - const PHONE = 'phone'; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * Constructor - * - * @param SubjectReader $subjectReader - */ - public function __construct(SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - - $order = $paymentDO->getOrder(); - $billingAddress = $order->getBillingAddress(); - - return [ - self::CUSTOMER => [ - self::FIRST_NAME => $billingAddress->getFirstname(), - self::LAST_NAME => $billingAddress->getLastname(), - self::COMPANY => $billingAddress->getCompany(), - self::PHONE => $billingAddress->getTelephone(), - self::EMAIL => $billingAddress->getEmail(), - ] - ]; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/DescriptorDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/DescriptorDataBuilder.php deleted file mode 100644 index aac603bfb621a..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/DescriptorDataBuilder.php +++ /dev/null @@ -1,53 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Request\BuilderInterface; -use Magento\Braintree\Gateway\Config\Config; - -/** - * Class DescriptorDataBuilder - */ -class DescriptorDataBuilder implements BuilderInterface -{ - /** - * @var string - */ - private static $descriptorKey = 'descriptor'; - - /** - * @var Config - */ - private $config; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * @param Config $config - * @param SubjectReader $subjectReader - */ - public function __construct(Config $config, SubjectReader $subjectReader) - { - $this->config = $config; - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $order = $paymentDO->getOrder(); - - $values = $this->config->getDynamicDescriptors($order->getStoreId()); - return !empty($values) ? [self::$descriptorKey => $values] : []; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/KountPaymentDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/KountPaymentDataBuilder.php deleted file mode 100644 index 8538667778504..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/KountPaymentDataBuilder.php +++ /dev/null @@ -1,67 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Braintree\Observer\DataAssignObserver; -use Magento\Payment\Gateway\Request\BuilderInterface; - -/** - * Class KountPaymentDataBuilder - */ -class KountPaymentDataBuilder implements BuilderInterface -{ - /** - * Additional data for Advanced Fraud Tools - */ - const DEVICE_DATA = 'deviceData'; - - /** - * @var Config - */ - private $config; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * Constructor - * - * @param Config $config - * @param SubjectReader $subjectReader - */ - public function __construct(Config $config, SubjectReader $subjectReader) - { - $this->config = $config; - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - $result = []; - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $order = $paymentDO->getOrder(); - - if (!$this->config->hasFraudProtection($order->getStoreId())) { - return $result; - } - - $payment = $paymentDO->getPayment(); - $data = $payment->getAdditionalInformation(); - - if (isset($data[DataAssignObserver::DEVICE_DATA])) { - $result[self::DEVICE_DATA] = $data[DataAssignObserver::DEVICE_DATA]; - } - - return $result; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/MerchantAccountDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/MerchantAccountDataBuilder.php deleted file mode 100644 index 6dc40e76322df..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/MerchantAccountDataBuilder.php +++ /dev/null @@ -1,64 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Gateway\Request; - -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Request\BuilderInterface; - -/** - * Adds Merchant Account ID to the request if it was specified in the configuration. - */ -class MerchantAccountDataBuilder implements BuilderInterface -{ - /** - * The merchant account ID used to create a transaction. - * Currency is also determined by merchant account ID. - * If no merchant account ID is specified, Braintree will use your default merchant account. - */ - private static $merchantAccountId = 'merchantAccountId'; - - /** - * @var Config - */ - private $config; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * Constructor - * - * @param Config $config - * @param SubjectReader $subjectReader - */ - public function __construct(Config $config, SubjectReader $subjectReader) - { - $this->config = $config; - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject): array - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $order = $paymentDO->getOrder(); - - $result = []; - $merchantAccountId = $this->config->getMerchantAccountId($order->getStoreId()); - if (!empty($merchantAccountId)) { - $result[self::$merchantAccountId] = $merchantAccountId; - } - - return $result; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/PayPal/DeviceDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/PayPal/DeviceDataBuilder.php deleted file mode 100644 index 7d0d9dad0db06..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/PayPal/DeviceDataBuilder.php +++ /dev/null @@ -1,52 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request\PayPal; - -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Braintree\Observer\DataAssignObserver; -use Magento\Payment\Gateway\Request\BuilderInterface; - -/** - * Class DeviceDataBuilder - */ -class DeviceDataBuilder implements BuilderInterface -{ - /** - * @var string - */ - private static $deviceDataKey = 'deviceData'; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * DeviceDataBuilder constructor. - * @param SubjectReader $subjectReader - */ - public function __construct(SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - $result = []; - $paymentDO = $this->subjectReader->readPayment($buildSubject); - - $payment = $paymentDO->getPayment(); - $data = $payment->getAdditionalInformation(); - if (!empty($data[DataAssignObserver::DEVICE_DATA])) { - $result[self::$deviceDataKey] = $data[DataAssignObserver::DEVICE_DATA]; - } - - return $result; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/PayPal/VaultDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/PayPal/VaultDataBuilder.php deleted file mode 100644 index 4d63ee4125b74..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/PayPal/VaultDataBuilder.php +++ /dev/null @@ -1,62 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request\PayPal; - -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Request\BuilderInterface; -use Magento\Vault\Model\Ui\VaultConfigProvider; - -/** - * Vault Data Builder - */ -class VaultDataBuilder implements BuilderInterface -{ - /** - * Additional options in request to gateway - */ - private static $optionsKey = 'options'; - - /** - * The option that determines whether the payment method associated with - * the successful transaction should be stored in the Vault. - */ - private static $storeInVaultOnSuccess = 'storeInVaultOnSuccess'; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * VaultDataBuilder constructor. - * @param SubjectReader $subjectReader - */ - public function __construct(SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - $result = []; - $paymentDO = $this->subjectReader->readPayment($buildSubject); - - $payment = $paymentDO->getPayment(); - $data = $payment->getAdditionalInformation(); - // the payment token could be stored only if a customer checks the Vault flow on storefront - // see https://developers.braintreepayments.com/guides/paypal/vault/javascript/v2#invoking-the-vault-flow - if (!empty($data[VaultConfigProvider::IS_ACTIVE_CODE])) { - $result[self::$optionsKey] = [ - self::$storeInVaultOnSuccess => true - ]; - } - - return $result; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/PaymentDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/PaymentDataBuilder.php deleted file mode 100644 index fe75ce86cca2f..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/PaymentDataBuilder.php +++ /dev/null @@ -1,84 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Braintree\Observer\DataAssignObserver; -use Magento\Payment\Gateway\Request\BuilderInterface; -use Magento\Payment\Helper\Formatter; - -/** - * Payment Data Builder - */ -class PaymentDataBuilder implements BuilderInterface -{ - use Formatter; - - /** - * The billing amount of the request. This value must be greater than 0, - * and must match the currency format of the merchant account. - */ - const AMOUNT = 'amount'; - - /** - * One-time-use token that references a payment method provided by your customer, - * such as a credit card or PayPal account. - * - * The nonce serves as proof that the user has authorized payment (e.g. credit card number or PayPal details). - * This should be sent to your server and used with any of Braintree's server-side client libraries - * that accept new or saved payment details. - * This can be passed instead of a payment_method_token parameter. - */ - const PAYMENT_METHOD_NONCE = 'paymentMethodNonce'; - - /** - * @deprecated - * @see \Magento\Braintree\Gateway\Request\MerchantAccountDataBuilder - */ - const MERCHANT_ACCOUNT_ID = 'merchantAccountId'; - - /** - * Order ID - */ - const ORDER_ID = 'orderId'; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * @param Config $config - * @param SubjectReader $subjectReader - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function __construct(Config $config, SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - - $payment = $paymentDO->getPayment(); - $order = $paymentDO->getOrder(); - - $result = [ - self::AMOUNT => $this->formatPrice($this->subjectReader->readAmount($buildSubject)), - self::PAYMENT_METHOD_NONCE => $payment->getAdditionalInformation( - DataAssignObserver::PAYMENT_METHOD_NONCE - ), - self::ORDER_ID => $order->getOrderIncrementId() - ]; - - return $result; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/RefundDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/RefundDataBuilder.php deleted file mode 100644 index 1c25646311160..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/RefundDataBuilder.php +++ /dev/null @@ -1,69 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Request\BuilderInterface; -use Magento\Payment\Helper\Formatter; -use Magento\Sales\Api\Data\TransactionInterface; -use Magento\Sales\Model\Order\Payment; - -class RefundDataBuilder implements BuilderInterface -{ - use Formatter; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * Constructor - * - * @param SubjectReader $subjectReader - */ - public function __construct(SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * Builds ENV request - * - * @param array $buildSubject - * @return array - */ - public function build(array $buildSubject) - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - - /** @var Payment $payment */ - $payment = $paymentDO->getPayment(); - - $amount = null; - try { - $amount = $this->formatPrice($this->subjectReader->readAmount($buildSubject)); - } catch (\InvalidArgumentException $e) { - // pass - } - - /* - * we should remember that Payment sets Capture txn id of current Invoice into ParentTransactionId Field - * We should also support previous implementations of Magento Braintree - - * and cut off '-capture' postfix from transaction ID to support backward compatibility - */ - $txnId = str_replace( - '-' . TransactionInterface::TYPE_CAPTURE, - '', - $payment->getParentTransactionId() - ); - - return [ - 'transaction_id' => $txnId, - PaymentDataBuilder::AMOUNT => $amount - ]; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/SettlementDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/SettlementDataBuilder.php deleted file mode 100644 index f614410025a6b..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/SettlementDataBuilder.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Payment\Gateway\Request\BuilderInterface; - -/** - * Class SettlementDataBuilder - */ -class SettlementDataBuilder implements BuilderInterface -{ - const SUBMIT_FOR_SETTLEMENT = 'submitForSettlement'; - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - return [ - 'options' => [ - self::SUBMIT_FOR_SETTLEMENT => true - ] - ]; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/StoreConfigBuilder.php b/app/code/Magento/Braintree/Gateway/Request/StoreConfigBuilder.php deleted file mode 100644 index 014df33690fa0..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/StoreConfigBuilder.php +++ /dev/null @@ -1,42 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Payment\Gateway\Request\BuilderInterface; -use Magento\Braintree\Gateway\SubjectReader; - -/** - * This builder is used for correct store resolving and used only to retrieve correct store ID. - * The data from this build won't be send to Braintree Gateway. - */ -class StoreConfigBuilder implements BuilderInterface -{ - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * @param SubjectReader $subjectReader - */ - public function __construct(SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $order = $paymentDO->getOrder(); - - return [ - 'store_id' => $order->getStoreId() - ]; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/ThreeDSecureDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/ThreeDSecureDataBuilder.php deleted file mode 100644 index 520aa58457753..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/ThreeDSecureDataBuilder.php +++ /dev/null @@ -1,82 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Braintree\Gateway\Config\Config; -use Magento\Payment\Gateway\Data\OrderAdapterInterface; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Request\BuilderInterface; -use Magento\Payment\Helper\Formatter; - -/** - * Class ThreeDSecureDataBuilder - */ -class ThreeDSecureDataBuilder implements BuilderInterface -{ - use Formatter; - - /** - * @var Config - */ - private $config; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * Constructor - * - * @param Config $config - * @param SubjectReader $subjectReader - */ - public function __construct(Config $config, SubjectReader $subjectReader) - { - $this->config = $config; - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - $result = []; - - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $amount = $this->formatPrice($this->subjectReader->readAmount($buildSubject)); - - if ($this->is3DSecureEnabled($paymentDO->getOrder(), $amount)) { - $result['options'][Config::CODE_3DSECURE] = ['required' => true]; - } - return $result; - } - - /** - * Check if 3d secure is enabled - * @param OrderAdapterInterface $order - * @param float $amount - * @return bool - */ - private function is3DSecureEnabled(OrderAdapterInterface $order, $amount) - { - $storeId = $order->getStoreId(); - if (!$this->config->isVerify3DSecure($storeId) - || $amount < $this->config->getThresholdAmount($storeId) - ) { - return false; - } - - $billingAddress = $order->getBillingAddress(); - $specificCounties = $this->config->get3DSecureSpecificCountries($storeId); - if (!empty($specificCounties) && !in_array($billingAddress->getCountryId(), $specificCounties)) { - return false; - } - - return true; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/VaultCaptureDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/VaultCaptureDataBuilder.php deleted file mode 100644 index 950634ba2d9e2..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/VaultCaptureDataBuilder.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Framework\Exception\LocalizedException; -use Magento\Payment\Gateway\Command\CommandException; -use Magento\Payment\Gateway\Request\BuilderInterface; -use Magento\Payment\Helper\Formatter; - -/** - * Class VaultCaptureDataBuilder - */ -class VaultCaptureDataBuilder implements BuilderInterface -{ - use Formatter; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * Constructor - * - * @param SubjectReader $subjectReader - */ - public function __construct(SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - - $payment = $paymentDO->getPayment(); - $extensionAttributes = $payment->getExtensionAttributes(); - $paymentToken = $extensionAttributes->getVaultPaymentToken(); - if ($paymentToken === null) { - throw new CommandException(__('The Payment Token is not available to perform the request.')); - } - return [ - 'amount' => $this->formatPrice($this->subjectReader->readAmount($buildSubject)), - 'paymentMethodToken' => $paymentToken->getGatewayToken() - ]; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/VaultDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/VaultDataBuilder.php deleted file mode 100644 index daa78dcc6f99d..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/VaultDataBuilder.php +++ /dev/null @@ -1,37 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Payment\Gateway\Request\BuilderInterface; - -/** - * Vault Data Builder - */ -class VaultDataBuilder implements BuilderInterface -{ - /** - * Additional options in request to gateway - */ - const OPTIONS = 'options'; - - /** - * The option that determines whether the payment method associated with - * the successful transaction should be stored in the Vault. - */ - const STORE_IN_VAULT_ON_SUCCESS = 'storeInVaultOnSuccess'; - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - return [ - self::OPTIONS => [ - self::STORE_IN_VAULT_ON_SUCCESS => true - ] - ]; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/VaultThreeDSecureDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/VaultThreeDSecureDataBuilder.php deleted file mode 100644 index 5441067b9d813..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/VaultThreeDSecureDataBuilder.php +++ /dev/null @@ -1,55 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Request\BuilderInterface; - -/** - * Since we can't validate 3Dsecure for sequence multishipping orders based on vault tokens, - * we skip 3D secure verification for vault transactions. - * For common vault transaction original 3d secure verification builder is called. - */ -class VaultThreeDSecureDataBuilder implements BuilderInterface -{ - /** - * @var ThreeDSecureDataBuilder - */ - private $threeDSecureDataBuilder; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * Constructor - * - * @param ThreeDSecureDataBuilder $threeDSecureDataBuilder - * @param SubjectReader $subjectReader - */ - public function __construct( - ThreeDSecureDataBuilder $threeDSecureDataBuilder, - SubjectReader $subjectReader - ) { - $this->threeDSecureDataBuilder = $threeDSecureDataBuilder; - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function build(array $buildSubject) - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - $payment = $paymentDO->getPayment(); - if ($payment->getAdditionalInformation('is_multishipping')) { - return []; - } - - return $this->threeDSecureDataBuilder->build($buildSubject); - } -} diff --git a/app/code/Magento/Braintree/Gateway/Request/VoidDataBuilder.php b/app/code/Magento/Braintree/Gateway/Request/VoidDataBuilder.php deleted file mode 100644 index 0bbda28cd344b..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Request/VoidDataBuilder.php +++ /dev/null @@ -1,47 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Request; - -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Request\BuilderInterface; -use Magento\Sales\Model\Order\Payment; - -class VoidDataBuilder implements BuilderInterface -{ - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * Constructor - * - * @param SubjectReader $subjectReader - */ - public function __construct(SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * Builds ENV request - * - * @param array $buildSubject - * @return array - */ - public function build(array $buildSubject) - { - $paymentDO = $this->subjectReader->readPayment($buildSubject); - - /** @var Payment $payment */ - $payment = $paymentDO->getPayment(); - - return [ - 'transaction_id' => $payment->getParentTransactionId() - ?: $payment->getLastTransId() - ]; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Response/CancelDetailsHandler.php b/app/code/Magento/Braintree/Gateway/Response/CancelDetailsHandler.php deleted file mode 100644 index 3d6ed025791bf..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Response/CancelDetailsHandler.php +++ /dev/null @@ -1,43 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Gateway\Response; - -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Response\HandlerInterface; -use Magento\Sales\Model\Order\Payment; - -/** - * Handles response details for order cancellation request. - */ -class CancelDetailsHandler implements HandlerInterface -{ - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * @param SubjectReader $subjectReader - */ - public function __construct(SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function handle(array $handlingSubject, array $response) - { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - /** @var Payment $orderPayment */ - $orderPayment = $paymentDO->getPayment(); - $orderPayment->setIsTransactionClosed(true); - $orderPayment->setShouldCloseParentTransaction(true); - } -} diff --git a/app/code/Magento/Braintree/Gateway/Response/CardDetailsHandler.php b/app/code/Magento/Braintree/Gateway/Response/CardDetailsHandler.php deleted file mode 100644 index 32abeac4c8ffb..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Response/CardDetailsHandler.php +++ /dev/null @@ -1,92 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Response; - -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Helper\ContextHelper; -use Magento\Payment\Gateway\Response\HandlerInterface; -use Magento\Sales\Api\Data\OrderPaymentInterface; - -/** - * Class CardDetailsHandler - */ -class CardDetailsHandler implements HandlerInterface -{ - const CARD_TYPE = 'cardType'; - - const CARD_EXP_MONTH = 'expirationMonth'; - - const CARD_EXP_YEAR = 'expirationYear'; - - const CARD_LAST4 = 'last4'; - - const CARD_NUMBER = 'cc_number'; - - /** - * @var Config - */ - private $config; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * Constructor - * - * @param Config $config - * @param SubjectReader $subjectReader - */ - public function __construct( - Config $config, - SubjectReader $subjectReader - ) { - $this->config = $config; - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function handle(array $handlingSubject, array $response) - { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - $transaction = $this->subjectReader->readTransaction($response); - - /** - * @TODO after changes in sales module should be refactored for new interfaces - */ - $payment = $paymentDO->getPayment(); - ContextHelper::assertOrderPayment($payment); - - $creditCard = $transaction->creditCard; - $payment->setCcLast4($creditCard[self::CARD_LAST4]); - $payment->setCcExpMonth($creditCard[self::CARD_EXP_MONTH]); - $payment->setCcExpYear($creditCard[self::CARD_EXP_YEAR]); - - $payment->setCcType($this->getCreditCardType($creditCard[self::CARD_TYPE])); - - // set card details to additional info - $payment->setAdditionalInformation(self::CARD_NUMBER, 'xxxx-' . $creditCard[self::CARD_LAST4]); - $payment->setAdditionalInformation(OrderPaymentInterface::CC_TYPE, $creditCard[self::CARD_TYPE]); - } - - /** - * Get type of credit card mapped from Braintree - * - * @param string $type - * @return array - */ - private function getCreditCardType($type) - { - $replaced = str_replace(' ', '-', strtolower($type)); - $mapper = $this->config->getCcTypesMapper(); - - return $mapper[$replaced]; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Response/PayPal/VaultDetailsHandler.php b/app/code/Magento/Braintree/Gateway/Response/PayPal/VaultDetailsHandler.php deleted file mode 100644 index 7d38c2bf7d2ed..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Response/PayPal/VaultDetailsHandler.php +++ /dev/null @@ -1,128 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Response\PayPal; - -use Braintree\Transaction; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Framework\Intl\DateTimeFactory; -use Magento\Payment\Gateway\Response\HandlerInterface; -use Magento\Payment\Model\InfoInterface; -use Magento\Sales\Api\Data\OrderPaymentExtensionInterface; -use Magento\Sales\Api\Data\OrderPaymentExtensionInterfaceFactory; -use Magento\Vault\Api\Data\PaymentTokenFactoryInterface; -use Magento\Vault\Api\Data\PaymentTokenInterface; - -/** - * Vault Details Handler - */ -class VaultDetailsHandler implements HandlerInterface -{ - /** - * @var PaymentTokenFactoryInterface - */ - private $paymentTokenFactory; - - /** - * @var OrderPaymentExtensionInterfaceFactory - */ - private $paymentExtensionFactory; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * @var DateTimeFactory - */ - private $dateTimeFactory; - - /** - * @param PaymentTokenFactoryInterface $paymentTokenFactory - * @param OrderPaymentExtensionInterfaceFactory $paymentExtensionFactory - * @param SubjectReader $subjectReader - * @param DateTimeFactory $dateTimeFactory - */ - public function __construct( - PaymentTokenFactoryInterface $paymentTokenFactory, - OrderPaymentExtensionInterfaceFactory $paymentExtensionFactory, - SubjectReader $subjectReader, - DateTimeFactory $dateTimeFactory - ) { - $this->paymentTokenFactory = $paymentTokenFactory; - $this->paymentExtensionFactory = $paymentExtensionFactory; - $this->subjectReader = $subjectReader; - $this->dateTimeFactory = $dateTimeFactory; - } - - /** - * @inheritdoc - */ - public function handle(array $handlingSubject, array $response) - { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - $transaction = $this->subjectReader->readTransaction($response); - $payment = $paymentDO->getPayment(); - - // add vault payment token entity to extension attributes - $paymentToken = $this->getVaultPaymentToken($transaction); - if ($paymentToken !== null) { - $extensionAttributes = $this->getExtensionAttributes($payment); - $extensionAttributes->setVaultPaymentToken($paymentToken); - } - } - - /** - * Get vault payment token entity - * - * @param \Braintree\Transaction $transaction - * @return PaymentTokenInterface|null - */ - private function getVaultPaymentToken(Transaction $transaction) - { - // Check token existing in gateway response - $token = $transaction->paypalDetails->token; - if (empty($token)) { - return null; - } - - /** @var PaymentTokenInterface $paymentToken */ - $paymentToken = $this->paymentTokenFactory->create(PaymentTokenFactoryInterface::TOKEN_TYPE_ACCOUNT); - $paymentToken->setGatewayToken($token); - $paymentToken->setExpiresAt($this->getExpirationDate()); - $details = json_encode([ - 'payerEmail' => $transaction->paypalDetails->payerEmail - ]); - $paymentToken->setTokenDetails($details); - - return $paymentToken; - } - - /** - * @return string - */ - private function getExpirationDate() - { - $expDate = $this->dateTimeFactory->create('now', new \DateTimeZone('UTC')); - $expDate->add(new \DateInterval('P1Y')); - return $expDate->format('Y-m-d 00:00:00'); - } - - /** - * Get payment extension attributes - * @param InfoInterface $payment - * @return OrderPaymentExtensionInterface - */ - private function getExtensionAttributes(InfoInterface $payment) - { - $extensionAttributes = $payment->getExtensionAttributes(); - if ($extensionAttributes === null) { - $extensionAttributes = $this->paymentExtensionFactory->create(); - $payment->setExtensionAttributes($extensionAttributes); - } - return $extensionAttributes; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Response/PayPalDetailsHandler.php b/app/code/Magento/Braintree/Gateway/Response/PayPalDetailsHandler.php deleted file mode 100644 index 97bb312af4bd4..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Response/PayPalDetailsHandler.php +++ /dev/null @@ -1,53 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Response; - -use Magento\Payment\Gateway\Response\HandlerInterface; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Sales\Api\Data\OrderPaymentInterface; - -/** - * Class PayPalDetailsHandler - */ -class PayPalDetailsHandler implements HandlerInterface -{ - const PAYMENT_ID = 'paymentId'; - - const PAYER_EMAIL = 'payerEmail'; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * Constructor - * - * @param SubjectReader $subjectReader - */ - public function __construct(SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function handle(array $handlingSubject, array $response) - { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - - /** @var \Braintree\Transaction $transaction */ - $transaction = $this->subjectReader->readTransaction($response); - - /** @var OrderPaymentInterface $payment */ - $payment = $paymentDO->getPayment(); - - $payPal = $this->subjectReader->readPayPal($transaction); - $payment->setAdditionalInformation(self::PAYMENT_ID, $payPal[self::PAYMENT_ID]); - $payment->setAdditionalInformation(self::PAYER_EMAIL, $payPal[self::PAYER_EMAIL]); - } -} diff --git a/app/code/Magento/Braintree/Gateway/Response/PaymentDetailsHandler.php b/app/code/Magento/Braintree/Gateway/Response/PaymentDetailsHandler.php deleted file mode 100644 index a95ea76c2e633..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Response/PaymentDetailsHandler.php +++ /dev/null @@ -1,81 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Response; - -use Magento\Braintree\Observer\DataAssignObserver; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Response\HandlerInterface; -use Magento\Sales\Api\Data\OrderPaymentInterface; - -/** - * Payment Details Handler - */ -class PaymentDetailsHandler implements HandlerInterface -{ - const AVS_POSTAL_RESPONSE_CODE = 'avsPostalCodeResponseCode'; - - const AVS_STREET_ADDRESS_RESPONSE_CODE = 'avsStreetAddressResponseCode'; - - const CVV_RESPONSE_CODE = 'cvvResponseCode'; - - const PROCESSOR_AUTHORIZATION_CODE = 'processorAuthorizationCode'; - - const PROCESSOR_RESPONSE_CODE = 'processorResponseCode'; - - const PROCESSOR_RESPONSE_TEXT = 'processorResponseText'; - - /** - * List of additional details - * @var array - */ - protected $additionalInformationMapping = [ - self::AVS_POSTAL_RESPONSE_CODE, - self::AVS_STREET_ADDRESS_RESPONSE_CODE, - self::CVV_RESPONSE_CODE, - self::PROCESSOR_AUTHORIZATION_CODE, - self::PROCESSOR_RESPONSE_CODE, - self::PROCESSOR_RESPONSE_TEXT, - ]; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * Constructor - * - * @param SubjectReader $subjectReader - */ - public function __construct(SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function handle(array $handlingSubject, array $response) - { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - /** @var \Braintree\Transaction $transaction */ - $transaction = $this->subjectReader->readTransaction($response); - /** @var OrderPaymentInterface $payment */ - $payment = $paymentDO->getPayment(); - - $payment->setCcTransId($transaction->id); - $payment->setLastTransId($transaction->id); - - //remove previously set payment nonce - $payment->unsAdditionalInformation(DataAssignObserver::PAYMENT_METHOD_NONCE); - foreach ($this->additionalInformationMapping as $item) { - if (!isset($transaction->$item)) { - continue; - } - $payment->setAdditionalInformation($item, $transaction->$item); - } - } -} diff --git a/app/code/Magento/Braintree/Gateway/Response/RefundHandler.php b/app/code/Magento/Braintree/Gateway/Response/RefundHandler.php deleted file mode 100644 index 9592f1cd3737e..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Response/RefundHandler.php +++ /dev/null @@ -1,23 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Response; - -use Magento\Sales\Model\Order\Payment; - -class RefundHandler extends VoidHandler -{ - /** - * Whether parent transaction should be closed - * - * @param Payment $orderPayment - * @return bool - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - protected function shouldCloseParentTransaction(Payment $orderPayment) - { - return !(bool)$orderPayment->getCreditmemo()->getInvoice()->canRefund(); - } -} diff --git a/app/code/Magento/Braintree/Gateway/Response/RiskDataHandler.php b/app/code/Magento/Braintree/Gateway/Response/RiskDataHandler.php deleted file mode 100644 index d4976ff18e0ee..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Response/RiskDataHandler.php +++ /dev/null @@ -1,76 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Response; - -use Magento\Payment\Gateway\Helper\ContextHelper; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Response\HandlerInterface; - -/** - * Class RiskDataHandler - */ -class RiskDataHandler implements HandlerInterface -{ - /** - * Risk data id - */ - const RISK_DATA_ID = 'riskDataId'; - - /** - * The possible values of the risk decision are Not Evaluated, Approve, Review, and Decline - */ - const RISK_DATA_DECISION = 'riskDataDecision'; - - /** - * Risk data Review status - */ - private static $statusReview = 'Review'; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * Constructor - * - * @param SubjectReader $subjectReader - */ - public function __construct(SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * Handles response - * - * @param array $handlingSubject - * @param array $response - * @return void - */ - public function handle(array $handlingSubject, array $response) - { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - - /** @var \Braintree\Transaction $transaction */ - $transaction = $this->subjectReader->readTransaction($response); - - if (!isset($transaction->riskData)) { - return; - } - - $payment = $paymentDO->getPayment(); - ContextHelper::assertOrderPayment($payment); - - $payment->setAdditionalInformation(self::RISK_DATA_ID, $transaction->riskData->id); - $payment->setAdditionalInformation(self::RISK_DATA_DECISION, $transaction->riskData->decision); - - // mark payment as fraud - if ($transaction->riskData->decision === self::$statusReview) { - $payment->setIsFraudDetected(true); - } - } -} diff --git a/app/code/Magento/Braintree/Gateway/Response/ThreeDSecureDetailsHandler.php b/app/code/Magento/Braintree/Gateway/Response/ThreeDSecureDetailsHandler.php deleted file mode 100644 index 8d61660f03ce5..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Response/ThreeDSecureDetailsHandler.php +++ /dev/null @@ -1,70 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Response; - -use Braintree\Transaction; -use Magento\Payment\Gateway\Helper\ContextHelper; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Response\HandlerInterface; -use Magento\Sales\Api\Data\OrderPaymentInterface; - -/** - * Class ThreeDSecureDetailsHandler - */ -class ThreeDSecureDetailsHandler implements HandlerInterface -{ - const LIABILITY_SHIFTED = 'liabilityShifted'; - - const LIABILITY_SHIFT_POSSIBLE = 'liabilityShiftPossible'; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * Constructor - * - * @param SubjectReader $subjectReader - */ - public function __construct(SubjectReader $subjectReader) - { - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function handle(array $handlingSubject, array $response) - { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - /** - * @TODO after changes in sales module should be refactored for new interfaces - */ - /** @var OrderPaymentInterface $payment */ - $payment = $paymentDO->getPayment(); - ContextHelper::assertOrderPayment($payment); - - /** @var Transaction $transaction */ - $transaction = $this->subjectReader->readTransaction($response); - - if ($payment->hasAdditionalInformation(self::LIABILITY_SHIFTED)) { - // remove 3d secure details for reorder - $payment->unsAdditionalInformation(self::LIABILITY_SHIFTED); - $payment->unsAdditionalInformation(self::LIABILITY_SHIFT_POSSIBLE); - } - - if (empty($transaction->threeDSecureInfo)) { - return; - } - - /** @var \Braintree\ThreeDSecureInfo $info */ - $info = $transaction->threeDSecureInfo; - $payment->setAdditionalInformation(self::LIABILITY_SHIFTED, $info->liabilityShifted ? 'Yes' : 'No'); - $shiftPossible = $info->liabilityShiftPossible ? 'Yes' : 'No'; - $payment->setAdditionalInformation(self::LIABILITY_SHIFT_POSSIBLE, $shiftPossible); - } -} diff --git a/app/code/Magento/Braintree/Gateway/Response/TransactionIdHandler.php b/app/code/Magento/Braintree/Gateway/Response/TransactionIdHandler.php deleted file mode 100644 index 18888bdcf3d4a..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Response/TransactionIdHandler.php +++ /dev/null @@ -1,88 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Response; - -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Response\HandlerInterface; -use Magento\Sales\Model\Order\Payment; - -class TransactionIdHandler implements HandlerInterface -{ - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * TransactionIdHandler constructor. - * @param SubjectReader $subjectReader - */ - public function __construct( - SubjectReader $subjectReader - ) { - $this->subjectReader = $subjectReader; - } - - /** - * Handles response - * - * @param array $handlingSubject - * @param array $response - * @return void - */ - public function handle(array $handlingSubject, array $response) - { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - - if ($paymentDO->getPayment() instanceof Payment) { - /** @var \Braintree\Transaction $transaction */ - $transaction = $this->subjectReader->readTransaction($response); - - /** @var Payment $orderPayment */ - $orderPayment = $paymentDO->getPayment(); - $this->setTransactionId( - $orderPayment, - $transaction - ); - - $orderPayment->setIsTransactionClosed($this->shouldCloseTransaction()); - $closed = $this->shouldCloseParentTransaction($orderPayment); - $orderPayment->setShouldCloseParentTransaction($closed); - } - } - - /** - * @param Payment $orderPayment - * @param \Braintree\Transaction $transaction - * @return void - */ - protected function setTransactionId(Payment $orderPayment, \Braintree\Transaction $transaction) - { - $orderPayment->setTransactionId($transaction->id); - } - - /** - * Whether transaction should be closed - * - * @return bool - */ - protected function shouldCloseTransaction() - { - return false; - } - - /** - * Whether parent transaction should be closed - * - * @param Payment $orderPayment - * @return bool - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - protected function shouldCloseParentTransaction(Payment $orderPayment) - { - return false; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Response/VaultDetailsHandler.php b/app/code/Magento/Braintree/Gateway/Response/VaultDetailsHandler.php deleted file mode 100644 index 8880f9c1b1a3e..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Response/VaultDetailsHandler.php +++ /dev/null @@ -1,179 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Response; - -use Braintree\Transaction; -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\Serialize\Serializer\Json; -use Magento\Payment\Gateway\Response\HandlerInterface; -use Magento\Payment\Model\InfoInterface; -use Magento\Sales\Api\Data\OrderPaymentExtensionInterface; -use Magento\Sales\Api\Data\OrderPaymentExtensionInterfaceFactory; -use Magento\Vault\Api\Data\PaymentTokenFactoryInterface; -use Magento\Vault\Api\Data\PaymentTokenInterface; - -/** - * Vault Details Handler - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class VaultDetailsHandler implements HandlerInterface -{ - /** - * @var PaymentTokenFactoryInterface - */ - protected $paymentTokenFactory; - - /** - * @var OrderPaymentExtensionInterfaceFactory - */ - protected $paymentExtensionFactory; - - /** - * @var SubjectReader - */ - protected $subjectReader; - - /** - * @var Config - */ - protected $config; - - /** - * @var Json - */ - private $serializer; - - /** - * VaultDetailsHandler constructor. - * - * @param PaymentTokenFactoryInterface $paymentTokenFactory - * @param OrderPaymentExtensionInterfaceFactory $paymentExtensionFactory - * @param Config $config - * @param SubjectReader $subjectReader - * @param Json|null $serializer - * @throws \RuntimeException - */ - public function __construct( - PaymentTokenFactoryInterface $paymentTokenFactory, - OrderPaymentExtensionInterfaceFactory $paymentExtensionFactory, - Config $config, - SubjectReader $subjectReader, - Json $serializer = null - ) { - $this->paymentTokenFactory = $paymentTokenFactory; - $this->paymentExtensionFactory = $paymentExtensionFactory; - $this->config = $config; - $this->subjectReader = $subjectReader; - $this->serializer = $serializer ?: ObjectManager::getInstance()->get(Json::class); - } - - /** - * @inheritdoc - */ - public function handle(array $handlingSubject, array $response) - { - $paymentDO = $this->subjectReader->readPayment($handlingSubject); - $transaction = $this->subjectReader->readTransaction($response); - $payment = $paymentDO->getPayment(); - - // add vault payment token entity to extension attributes - $paymentToken = $this->getVaultPaymentToken($transaction); - if (null !== $paymentToken) { - $extensionAttributes = $this->getExtensionAttributes($payment); - $extensionAttributes->setVaultPaymentToken($paymentToken); - } - } - - /** - * Get vault payment token entity - * - * @param \Braintree\Transaction $transaction - * @return PaymentTokenInterface|null - */ - protected function getVaultPaymentToken(Transaction $transaction) - { - // Check token existing in gateway response - $token = $transaction->creditCardDetails->token; - if (empty($token)) { - return null; - } - - /** @var PaymentTokenInterface $paymentToken */ - $paymentToken = $this->paymentTokenFactory->create(PaymentTokenFactoryInterface::TOKEN_TYPE_CREDIT_CARD); - $paymentToken->setGatewayToken($token); - $paymentToken->setExpiresAt($this->getExpirationDate($transaction)); - - $paymentToken->setTokenDetails($this->convertDetailsToJSON([ - 'type' => $this->getCreditCardType($transaction->creditCardDetails->cardType), - 'maskedCC' => $transaction->creditCardDetails->last4, - 'expirationDate' => $transaction->creditCardDetails->expirationDate - ])); - - return $paymentToken; - } - - /** - * @param Transaction $transaction - * @return string - */ - private function getExpirationDate(Transaction $transaction) - { - $expDate = new \DateTime( - $transaction->creditCardDetails->expirationYear - . '-' - . $transaction->creditCardDetails->expirationMonth - . '-' - . '01' - . ' ' - . '00:00:00', - new \DateTimeZone('UTC') - ); - $expDate->add(new \DateInterval('P1M')); - return $expDate->format('Y-m-d 00:00:00'); - } - - /** - * Convert payment token details to JSON - * @param array $details - * @return string - */ - private function convertDetailsToJSON($details) - { - $json = $this->serializer->serialize($details); - return $json ? $json : '{}'; - } - - /** - * Get type of credit card mapped from Braintree - * - * @param string $type - * @return array - */ - private function getCreditCardType($type) - { - $replaced = str_replace(' ', '-', strtolower($type)); - $mapper = $this->config->getCcTypesMapper(); - - return $mapper[$replaced]; - } - - /** - * Get payment extension attributes - * @param InfoInterface $payment - * @return OrderPaymentExtensionInterface - */ - private function getExtensionAttributes(InfoInterface $payment) - { - $extensionAttributes = $payment->getExtensionAttributes(); - if (null === $extensionAttributes) { - $extensionAttributes = $this->paymentExtensionFactory->create(); - $payment->setExtensionAttributes($extensionAttributes); - } - return $extensionAttributes; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Response/VoidHandler.php b/app/code/Magento/Braintree/Gateway/Response/VoidHandler.php deleted file mode 100644 index 246a75b0efb8c..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Response/VoidHandler.php +++ /dev/null @@ -1,44 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Response; - -use Magento\Sales\Model\Order\Payment; - -class VoidHandler extends TransactionIdHandler -{ - /** - * @param Payment $orderPayment - * @param \Braintree\Transaction $transaction - * @return void - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - protected function setTransactionId(Payment $orderPayment, \Braintree\Transaction $transaction) - { - return; - } - - /** - * Whether transaction should be closed - * - * @return bool - */ - protected function shouldCloseTransaction() - { - return true; - } - - /** - * Whether parent transaction should be closed - * - * @param Payment $orderPayment - * @return bool - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - protected function shouldCloseParentTransaction(Payment $orderPayment) - { - return true; - } -} diff --git a/app/code/Magento/Braintree/Gateway/SubjectReader.php b/app/code/Magento/Braintree/Gateway/SubjectReader.php deleted file mode 100644 index 7cf00233e7f8f..0000000000000 --- a/app/code/Magento/Braintree/Gateway/SubjectReader.php +++ /dev/null @@ -1,133 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway; - -use Braintree\Transaction; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Payment\Gateway\Helper; -use Magento\Vault\Api\Data\PaymentTokenInterface; - -/** - * Class SubjectReader - */ -class SubjectReader -{ - /** - * Reads response object from subject - * - * @param array $subject - * @return object - */ - public function readResponseObject(array $subject) - { - $response = Helper\SubjectReader::readResponse($subject); - if (!isset($response['object']) || !is_object($response['object'])) { - throw new \InvalidArgumentException('Response object does not exist'); - } - - return $response['object']; - } - - /** - * Reads payment from subject - * - * @param array $subject - * @return PaymentDataObjectInterface - */ - public function readPayment(array $subject) - { - return Helper\SubjectReader::readPayment($subject); - } - - /** - * Reads transaction from the subject. - * - * @param array $subject - * @return Transaction - * @throws \InvalidArgumentException if the subject doesn't contain transaction details. - */ - public function readTransaction(array $subject) - { - if (!isset($subject['object']) || !is_object($subject['object'])) { - throw new \InvalidArgumentException('Response object does not exist.'); - } - - if (!isset($subject['object']->transaction) - || !$subject['object']->transaction instanceof Transaction - ) { - throw new \InvalidArgumentException('The object is not a class \Braintree\Transaction.'); - } - - return $subject['object']->transaction; - } - - /** - * Reads amount from subject - * - * @param array $subject - * @return mixed - */ - public function readAmount(array $subject) - { - return Helper\SubjectReader::readAmount($subject); - } - - /** - * Reads customer id from subject - * - * @param array $subject - * @return int - */ - public function readCustomerId(array $subject) - { - if (!isset($subject['customer_id'])) { - throw new \InvalidArgumentException('The "customerId" field does not exists'); - } - - return (int) $subject['customer_id']; - } - - /** - * Reads public hash from subject - * - * @param array $subject - * @return string - */ - public function readPublicHash(array $subject) - { - if (empty($subject[PaymentTokenInterface::PUBLIC_HASH])) { - throw new \InvalidArgumentException('The "public_hash" field does not exists'); - } - - return $subject[PaymentTokenInterface::PUBLIC_HASH]; - } - - /** - * Reads PayPal details from transaction object - * - * @param Transaction $transaction - * @return array - */ - public function readPayPal(Transaction $transaction) - { - if (!isset($transaction->paypal)) { - throw new \InvalidArgumentException('Transaction has\'t paypal attribute'); - } - - return $transaction->paypal; - } - - /** - * Reads store's ID, otherwise returns null. - * - * @param array $subject - * @return int|null - */ - public function readStoreId(array $subject) - { - return $subject['store_id'] ?? null; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Validator/CancelResponseValidator.php b/app/code/Magento/Braintree/Gateway/Validator/CancelResponseValidator.php deleted file mode 100644 index 5e31547e9503c..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Validator/CancelResponseValidator.php +++ /dev/null @@ -1,90 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Gateway\Validator; - -use Braintree\Error\ErrorCollection; -use Braintree\Error\Validation; -use Magento\Payment\Gateway\Validator\AbstractValidator; -use Magento\Payment\Gateway\Validator\ResultInterface; -use Magento\Payment\Gateway\Validator\ResultInterfaceFactory; -use Magento\Braintree\Gateway\SubjectReader; - -/** - * Decorates the general response validator to handle specific cases. - * - * This validator decorates the general response validator to handle specific cases like - * an expired or already voided on Braintree side authorization transaction. - */ -class CancelResponseValidator extends AbstractValidator -{ - /** - * @var int - */ - private static $acceptableTransactionCode = 91504; - - /** - * @var GeneralResponseValidator - */ - private $generalResponseValidator; - - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * @param ResultInterfaceFactory $resultFactory - * @param GeneralResponseValidator $generalResponseValidator - * @param SubjectReader $subjectReader - */ - public function __construct( - ResultInterfaceFactory $resultFactory, - GeneralResponseValidator $generalResponseValidator, - SubjectReader $subjectReader - ) { - parent::__construct($resultFactory); - $this->generalResponseValidator = $generalResponseValidator; - $this->subjectReader = $subjectReader; - } - - /** - * @inheritdoc - */ - public function validate(array $validationSubject): ResultInterface - { - $result = $this->generalResponseValidator->validate($validationSubject); - if (!$result->isValid()) { - $response = $this->subjectReader->readResponseObject($validationSubject); - if ($this->isErrorAcceptable($response->errors)) { - $result = $this->createResult(true, [__('Transaction is cancelled offline.')]); - } - } - - return $result; - } - - /** - * Checks if error collection has an acceptable error code. - * - * @param ErrorCollection $errorCollection - * @return bool - */ - private function isErrorAcceptable(ErrorCollection $errorCollection): bool - { - $errors = $errorCollection->deepAll(); - // there is should be only one acceptable error - if (count($errors) > 1) { - return false; - } - - /** @var Validation $error */ - $error = array_pop($errors); - - return (int)$error->code === self::$acceptableTransactionCode; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Validator/ErrorCodeProvider.php b/app/code/Magento/Braintree/Gateway/Validator/ErrorCodeProvider.php deleted file mode 100644 index 2f73dd8f380dc..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Validator/ErrorCodeProvider.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Gateway\Validator; - -use Braintree\Error\ErrorCollection; -use Braintree\Error\Validation; -use Braintree\Result\Error; -use Braintree\Result\Successful; -use Braintree\Transaction; - -/** - * Processes errors codes from Braintree response. - */ -class ErrorCodeProvider -{ - /** - * Retrieves list of error codes from Braintree response. - * - * @param Successful|Error $response - * @return array - */ - public function getErrorCodes($response): array - { - $result = []; - if (!$response instanceof Error) { - return $result; - } - - /** @var ErrorCollection $collection */ - $collection = $response->errors; - - /** @var Validation $error */ - foreach ($collection->deepAll() as $error) { - $result[] = $error->code; - } - - if (isset($response->transaction) && $response->transaction) { - if ($response->transaction->status === Transaction::GATEWAY_REJECTED) { - $result[] = $response->transaction->gatewayRejectionReason; - } - - if ($response->transaction->status === Transaction::PROCESSOR_DECLINED) { - $result[] = $response->transaction->processorResponseCode; - } - } - - return $result; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Validator/GeneralResponseValidator.php b/app/code/Magento/Braintree/Gateway/Validator/GeneralResponseValidator.php deleted file mode 100644 index 6aac588c38374..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Validator/GeneralResponseValidator.php +++ /dev/null @@ -1,81 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Validator; - -use Braintree\Result\Error; -use Braintree\Result\Successful; -use Magento\Payment\Gateway\Validator\AbstractValidator; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Validator\ResultInterfaceFactory; - -class GeneralResponseValidator extends AbstractValidator -{ - /** - * @var SubjectReader - */ - protected $subjectReader; - - /** - * @var ErrorCodeProvider - */ - private $errorCodeProvider; - - /** - * Constructor - * - * @param ResultInterfaceFactory $resultFactory - * @param SubjectReader $subjectReader - * @param ErrorCodeProvider $errorCodeProvider - */ - public function __construct( - ResultInterfaceFactory $resultFactory, - SubjectReader $subjectReader, - ErrorCodeProvider $errorCodeProvider - ) { - parent::__construct($resultFactory); - $this->subjectReader = $subjectReader; - $this->errorCodeProvider = $errorCodeProvider; - } - - /** - * @inheritdoc - */ - public function validate(array $validationSubject) - { - /** @var Successful|Error $response */ - $response = $this->subjectReader->readResponseObject($validationSubject); - - $isValid = true; - $errorMessages = []; - - foreach ($this->getResponseValidators() as $validator) { - $validationResult = $validator($response); - - if (!$validationResult[0]) { - $isValid = $validationResult[0]; - $errorMessages = array_merge($errorMessages, $validationResult[1]); - } - } - $errorCodes = $this->errorCodeProvider->getErrorCodes($response); - - return $this->createResult($isValid, $errorMessages, $errorCodes); - } - - /** - * @return array - */ - protected function getResponseValidators() - { - return [ - function ($response) { - return [ - property_exists($response, 'success') && $response->success === true, - [$response->message ?? __('Braintree error response.')] - ]; - } - ]; - } -} diff --git a/app/code/Magento/Braintree/Gateway/Validator/PaymentNonceResponseValidator.php b/app/code/Magento/Braintree/Gateway/Validator/PaymentNonceResponseValidator.php deleted file mode 100644 index 12c6af4ee3c58..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Validator/PaymentNonceResponseValidator.php +++ /dev/null @@ -1,30 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Validator; - -/** - * Class PaymentNonceResponseValidator - */ -class PaymentNonceResponseValidator extends GeneralResponseValidator -{ - /** - * @return array - */ - protected function getResponseValidators() - { - return array_merge( - parent::getResponseValidators(), - [ - function ($response) { - return [ - !empty($response->paymentMethodNonce) && !empty($response->paymentMethodNonce->nonce), - [__('Payment method nonce can\'t be retrieved.')] - ]; - } - ] - ); - } -} diff --git a/app/code/Magento/Braintree/Gateway/Validator/ResponseValidator.php b/app/code/Magento/Braintree/Gateway/Validator/ResponseValidator.php deleted file mode 100644 index 70e94125f2b96..0000000000000 --- a/app/code/Magento/Braintree/Gateway/Validator/ResponseValidator.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Gateway\Validator; - -use Braintree\Result\Error; -use Braintree\Result\Successful; -use Braintree\Transaction; -use Magento\Payment\Gateway\Validator\ResultInterfaceFactory; - -/** - * Class ResponseValidator - */ -class ResponseValidator extends GeneralResponseValidator -{ - /** - * @return array - */ - protected function getResponseValidators() - { - return array_merge( - parent::getResponseValidators(), - [ - function ($response) { - return [ - $response instanceof Successful - && isset($response->transaction) - && in_array( - $response->transaction->status, - [Transaction::AUTHORIZED, Transaction::SUBMITTED_FOR_SETTLEMENT, Transaction::SETTLING] - ), - [__('Wrong transaction status')] - ]; - } - ] - ); - } -} diff --git a/app/code/Magento/Braintree/Helper/CcType.php b/app/code/Magento/Braintree/Helper/CcType.php deleted file mode 100644 index 078912c6128fd..0000000000000 --- a/app/code/Magento/Braintree/Helper/CcType.php +++ /dev/null @@ -1,47 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Helper; - -use Magento\Braintree\Model\Adminhtml\Source\CcType as CcTypeSource; - -/** - * Class CcType - */ -class CcType -{ - /** - * All possible credit card types - * - * @var array - */ - private $ccTypes = []; - - /** - * @var \Magento\Braintree\Model\Adminhtml\Source\CcType - */ - private $ccTypeSource; - - /** - * @param CcType $ccTypeSource - */ - public function __construct(CcTypeSource $ccTypeSource) - { - $this->ccTypeSource = $ccTypeSource; - } - - /** - * All possible credit card types - * - * @return array - */ - public function getCcTypes() - { - if (!$this->ccTypes) { - $this->ccTypes = $this->ccTypeSource->toOptionArray(); - } - return $this->ccTypes; - } -} diff --git a/app/code/Magento/Braintree/Helper/Country.php b/app/code/Magento/Braintree/Helper/Country.php deleted file mode 100644 index 18a1a303d649e..0000000000000 --- a/app/code/Magento/Braintree/Helper/Country.php +++ /dev/null @@ -1,56 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Helper; - -use Magento\Directory\Model\ResourceModel\Country\CollectionFactory; -use Magento\Braintree\Model\Adminhtml\System\Config\Country as CountryConfig; - -/** - * Class Country - */ -class Country -{ - /** - * @var CollectionFactory - */ - private $collectionFactory; - - /** - * @var CountryConfig - */ - private $countryConfig; - - /** - * @var array - */ - private $countries; - - /** - * @param CollectionFactory $factory - * @param CountryConfig $countryConfig - */ - public function __construct(CollectionFactory $factory, CountryConfig $countryConfig) - { - $this->collectionFactory = $factory; - $this->countryConfig = $countryConfig; - } - - /** - * Returns countries array - * - * @return array - */ - public function getCountries() - { - if (!$this->countries) { - $this->countries = $this->collectionFactory->create() - ->addFieldToFilter('country_id', ['nin' => $this->countryConfig->getExcludedCountries()]) - ->loadData() - ->toOptionArray(false); - } - return $this->countries; - } -} diff --git a/app/code/Magento/Braintree/Model/Adapter/BraintreeAdapter.php b/app/code/Magento/Braintree/Model/Adapter/BraintreeAdapter.php deleted file mode 100644 index fd1fe81b5eba8..0000000000000 --- a/app/code/Magento/Braintree/Model/Adapter/BraintreeAdapter.php +++ /dev/null @@ -1,193 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Adapter; - -use Braintree\ClientToken; -use Braintree\Configuration; -use Braintree\CreditCard; -use Braintree\PaymentMethodNonce; -use Braintree\Transaction; -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Model\Adminhtml\Source\Environment; - -/** - * Class BraintreeAdapter - * Use \Magento\Braintree\Model\Adapter\BraintreeAdapterFactory to create new instance of adapter. - * @codeCoverageIgnore - */ -class BraintreeAdapter -{ - /** - * @var Config - */ - private $config; - - /** - * @param string $merchantId - * @param string $publicKey - * @param string $privateKey - * @param string $environment - */ - public function __construct($merchantId, $publicKey, $privateKey, $environment) - { - $this->merchantId($merchantId); - $this->publicKey($publicKey); - $this->privateKey($privateKey); - - if ($environment === Environment::ENVIRONMENT_PRODUCTION) { - $this->environment(Environment::ENVIRONMENT_PRODUCTION); - } else { - $this->environment(Environment::ENVIRONMENT_SANDBOX); - } - } - - /** - * Initializes credentials. - * - * @return void - * @deprecated is not used anymore - */ - protected function initCredentials() - { - if ($this->config->getValue(Config::KEY_ENVIRONMENT) == Environment::ENVIRONMENT_PRODUCTION) { - $this->environment(Environment::ENVIRONMENT_PRODUCTION); - } else { - $this->environment(Environment::ENVIRONMENT_SANDBOX); - } - $this->merchantId($this->config->getValue(Config::KEY_MERCHANT_ID)); - $this->publicKey($this->config->getValue(Config::KEY_PUBLIC_KEY)); - $this->privateKey($this->config->getValue(Config::KEY_PRIVATE_KEY)); - } - - /** - * @param string|null $value - * @return mixed - */ - public function environment($value = null) - { - return Configuration::environment($value); - } - - /** - * @param string|null $value - * @return mixed - */ - public function merchantId($value = null) - { - return Configuration::merchantId($value); - } - - /** - * @param string|null $value - * @return mixed - */ - public function publicKey($value = null) - { - return Configuration::publicKey($value); - } - - /** - * @param string|null $value - * @return mixed - */ - public function privateKey($value = null) - { - return Configuration::privateKey($value); - } - - /** - * @param array $params - * @return \Braintree\Result\Successful|\Braintree\Result\Error|null - */ - public function generate(array $params = []) - { - try { - return ClientToken::generate($params); - } catch (\Exception $e) { - return null; - } - } - - /** - * @param string $token - * @return \Braintree\CreditCard|null - */ - public function find($token) - { - try { - return CreditCard::find($token); - } catch (\Exception $e) { - return null; - } - } - - /** - * @param array $filters - * @return \Braintree\ResourceCollection - */ - public function search(array $filters) - { - return Transaction::search($filters); - } - - /** - * @param string $token - * @return \Braintree\Result\Successful|\Braintree\Result\Error - */ - public function createNonce($token) - { - return PaymentMethodNonce::create($token); - } - - /** - * @param array $attributes - * @return \Braintree\Result\Successful|\Braintree\Result\Error - */ - public function sale(array $attributes) - { - return Transaction::sale($attributes); - } - - /** - * @param string $transactionId - * @param null|float $amount - * @return \Braintree\Result\Successful|\Braintree\Result\Error - */ - public function submitForSettlement($transactionId, $amount = null) - { - return Transaction::submitForSettlement($transactionId, $amount); - } - - /** - * @param string $transactionId - * @return \Braintree\Result\Successful|\Braintree\Result\Error - */ - public function void($transactionId) - { - return Transaction::void($transactionId); - } - - /** - * @param string $transactionId - * @param null|float $amount - * @return \Braintree\Result\Successful|\Braintree\Result\Error - */ - public function refund($transactionId, $amount = null) - { - return Transaction::refund($transactionId, $amount); - } - - /** - * Clone original transaction - * @param string $transactionId - * @param array $attributes - * @return mixed - */ - public function cloneTransaction($transactionId, array $attributes) - { - return Transaction::cloneTransaction($transactionId, $attributes); - } -} diff --git a/app/code/Magento/Braintree/Model/Adapter/BraintreeAdapterFactory.php b/app/code/Magento/Braintree/Model/Adapter/BraintreeAdapterFactory.php deleted file mode 100644 index 2c3f137eb1686..0000000000000 --- a/app/code/Magento/Braintree/Model/Adapter/BraintreeAdapterFactory.php +++ /dev/null @@ -1,56 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Adapter; - -use Magento\Braintree\Gateway\Config\Config; -use Magento\Framework\ObjectManagerInterface; - -/** - * This factory is preferable to use for Braintree adapter instance creation. - */ -class BraintreeAdapterFactory -{ - /** - * @var ObjectManagerInterface - */ - private $objectManager; - - /** - * @var Config - */ - private $config; - - /** - * @param ObjectManagerInterface $objectManager - * @param Config $config - */ - public function __construct(ObjectManagerInterface $objectManager, Config $config) - { - $this->config = $config; - $this->objectManager = $objectManager; - } - - /** - * Creates instance of Braintree Adapter. - * - * @param int|null $storeId if null is provided as an argument, then current scope will be resolved - * by \Magento\Framework\App\Config\ScopeCodeResolver (useful for most cases) but for adminhtml area the store - * should be provided as the argument for correct config settings loading. - * @return BraintreeAdapter - */ - public function create($storeId = null) - { - return $this->objectManager->create( - BraintreeAdapter::class, - [ - 'merchantId' => $this->config->getMerchantId($storeId), - 'publicKey' => $this->config->getValue(Config::KEY_PUBLIC_KEY, $storeId), - 'privateKey' => $this->config->getValue(Config::KEY_PRIVATE_KEY, $storeId), - 'environment' => $this->config->getEnvironment($storeId), - ] - ); - } -} diff --git a/app/code/Magento/Braintree/Model/Adapter/BraintreeSearchAdapter.php b/app/code/Magento/Braintree/Model/Adapter/BraintreeSearchAdapter.php deleted file mode 100644 index 167ff13a06fe8..0000000000000 --- a/app/code/Magento/Braintree/Model/Adapter/BraintreeSearchAdapter.php +++ /dev/null @@ -1,108 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Adapter; - -use Braintree\MultipleValueNode; -use Braintree\RangeNode; -use Braintree\TextNode; -use Braintree\Transaction; -use Braintree\TransactionSearch; - -/** - * Class Braintree Search Adapter - * @codeCoverageIgnore - */ -class BraintreeSearchAdapter -{ - /** - * @return TextNode - * @SuppressWarnings(PHPMD.ShortMethodName) - */ - public function id() - { - return TransactionSearch::id(); - } - - /** - * @return MultipleValueNode - */ - public function merchantAccountId() - { - return TransactionSearch::merchantAccountId(); - } - - /** - * @return TextNode - */ - public function orderId() - { - return TransactionSearch::orderId(); - } - - /** - * @return TextNode - */ - public function paypalPaymentId() - { - return TransactionSearch::paypalPaymentId(); - } - - /** - * @return MultipleValueNode - */ - public function createdUsing() - { - return TransactionSearch::createdUsing(); - } - - /** - * @return MultipleValueNode - */ - public function type() - { - return TransactionSearch::type(); - } - - /** - * @return RangeNode - */ - public function createdAt() - { - return TransactionSearch::createdAt(); - } - - /** - * @return RangeNode - */ - public function amount() - { - return TransactionSearch::amount(); - } - - /** - * @return MultipleValueNode - */ - public function status() - { - return TransactionSearch::status(); - } - - /** - * @return TextNode - */ - public function settlementBatchId() - { - return TransactionSearch::settlementBatchId(); - } - - /** - * @return MultipleValueNode - */ - public function paymentInstrumentType() - { - return TransactionSearch::paymentInstrumentType(); - } -} diff --git a/app/code/Magento/Braintree/Model/Adminhtml/Source/CcType.php b/app/code/Magento/Braintree/Model/Adminhtml/Source/CcType.php deleted file mode 100644 index 3c90b4b266b51..0000000000000 --- a/app/code/Magento/Braintree/Model/Adminhtml/Source/CcType.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Adminhtml\Source; - -/** - * Class CcType - * @codeCoverageIgnore - */ -class CcType extends \Magento\Payment\Model\Source\Cctype -{ - /** - * List of specific credit card types - * @var array - */ - private $specificCardTypesList = [ - 'CUP' => 'China Union Pay' - ]; - - /** - * Allowed credit card types - * - * @return string[] - */ - public function getAllowedTypes() - { - return ['VI', 'MC', 'AE', 'DI', 'JCB', 'MI', 'DN', 'CUP']; - } - - /** - * Returns credit cards types - * - * @return array - */ - public function getCcTypeLabelMap() - { - return array_merge($this->specificCardTypesList, $this->_paymentConfig->getCcTypes()); - } - - /** - * @inheritdoc - */ - public function toOptionArray() - { - $allowed = $this->getAllowedTypes(); - $options = []; - - foreach ($this->getCcTypeLabelMap() as $code => $name) { - if (in_array($code, $allowed)) { - $options[] = ['value' => $code, 'label' => $name]; - } - } - - return $options; - } -} diff --git a/app/code/Magento/Braintree/Model/Adminhtml/Source/Environment.php b/app/code/Magento/Braintree/Model/Adminhtml/Source/Environment.php deleted file mode 100644 index 77cf05a611b70..0000000000000 --- a/app/code/Magento/Braintree/Model/Adminhtml/Source/Environment.php +++ /dev/null @@ -1,36 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Adminhtml\Source; - -use Magento\Framework\Option\ArrayInterface; - -/** - * Class Environment - */ -class Environment implements ArrayInterface -{ - const ENVIRONMENT_PRODUCTION = 'production'; - const ENVIRONMENT_SANDBOX = 'sandbox'; - - /** - * Possible environment types - * - * @return array - */ - public function toOptionArray() - { - return [ - [ - 'value' => self::ENVIRONMENT_SANDBOX, - 'label' => 'Sandbox', - ], - [ - 'value' => self::ENVIRONMENT_PRODUCTION, - 'label' => 'Production' - ] - ]; - } -} diff --git a/app/code/Magento/Braintree/Model/Adminhtml/Source/PaymentAction.php b/app/code/Magento/Braintree/Model/Adminhtml/Source/PaymentAction.php deleted file mode 100644 index 595d8b4792a62..0000000000000 --- a/app/code/Magento/Braintree/Model/Adminhtml/Source/PaymentAction.php +++ /dev/null @@ -1,34 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Adminhtml\Source; - -use Magento\Framework\Option\ArrayInterface; -use Magento\Payment\Model\MethodInterface; - -/** - * Class PaymentAction - */ -class PaymentAction implements ArrayInterface -{ - /** - * Possible actions on order place - * - * @return array - */ - public function toOptionArray() - { - return [ - [ - 'value' => MethodInterface::ACTION_AUTHORIZE, - 'label' => __('Authorize'), - ], - [ - 'value' => MethodInterface::ACTION_AUTHORIZE_CAPTURE, - 'label' => __('Authorize and Capture'), - ] - ]; - } -} diff --git a/app/code/Magento/Braintree/Model/Adminhtml/System/Config/Country.php b/app/code/Magento/Braintree/Model/Adminhtml/System/Config/Country.php deleted file mode 100644 index ae154e768ed09..0000000000000 --- a/app/code/Magento/Braintree/Model/Adminhtml/System/Config/Country.php +++ /dev/null @@ -1,101 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Adminhtml\System\Config; - -use Magento\Directory\Model\ResourceModel\Country\Collection; -use Magento\Framework\Option\ArrayInterface; - -/** - * Class Country - */ -class Country implements ArrayInterface -{ - /** - * @var array - */ - protected $options; - - /** - * Countries - * - * @var \Magento\Directory\Model\ResourceModel\Country\Collection - */ - protected $countryCollection; - - /** - * Countries not supported by Braintree - */ - protected $excludedCountries = [ - 'MM', - 'IR', - 'SD', - 'BY', - 'CI', - 'CD', - 'CG', - 'IQ', - 'LR', - 'LB', - 'KP', - 'SL', - 'SY', - 'ZW', - 'AL', - 'BA', - 'MK', - 'ME', - 'RS' - ]; - - /** - * @param \Magento\Directory\Model\ResourceModel\Country\Collection $countryCollection - */ - public function __construct(Collection $countryCollection) - { - $this->countryCollection = $countryCollection; - } - - /** - * @param bool $isMultiselect - * @return array - */ - public function toOptionArray($isMultiselect = false) - { - if (!$this->options) { - $this->options = $this->countryCollection - ->addFieldToFilter('country_id', ['nin' => $this->getExcludedCountries()]) - ->loadData() - ->toOptionArray(false); - } - - $options = $this->options; - if (!$isMultiselect) { - array_unshift($options, ['value' => '', 'label' => __('--Please Select--')]); - } - - return $options; - } - - /** - * If country is in list of restricted (not supported by Braintree) - * - * @param string $countryId - * @return boolean - */ - public function isCountryRestricted($countryId) - { - return in_array($countryId, $this->getExcludedCountries()); - } - - /** - * Return list of excluded countries - * @return array - */ - public function getExcludedCountries() - { - return $this->excludedCountries; - } -} diff --git a/app/code/Magento/Braintree/Model/Adminhtml/System/Config/CountryCreditCard.php b/app/code/Magento/Braintree/Model/Adminhtml/System/Config/CountryCreditCard.php deleted file mode 100644 index 2a9923a333cef..0000000000000 --- a/app/code/Magento/Braintree/Model/Adminhtml/System/Config/CountryCreditCard.php +++ /dev/null @@ -1,136 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Adminhtml\System\Config; - -use Magento\Framework\App\Cache\TypeListInterface; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\App\Config\Value; -use Magento\Framework\Data\Collection\AbstractDb; -use Magento\Framework\Math\Random; -use Magento\Framework\Model\Context; -use Magento\Framework\Model\ResourceModel\AbstractResource; -use Magento\Framework\Registry; -use Magento\Framework\Serialize\Serializer\Json; - -/** - * Class CountryCreditCard - */ -class CountryCreditCard extends Value -{ - /** - * @var \Magento\Framework\Math\Random - */ - protected $mathRandom; - - /** - * @var \Magento\Framework\Serialize\Serializer\Json - */ - private $serializer; - - /** - * @param \Magento\Framework\Model\Context $context - * @param \Magento\Framework\Registry $registry - * @param \Magento\Framework\App\Config\ScopeConfigInterface $config - * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList - * @param \Magento\Framework\Math\Random $mathRandom - * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource - * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection - * @param array $data - * @param \Magento\Framework\Serialize\Serializer\Json $serializer - */ - public function __construct( - Context $context, - Registry $registry, - ScopeConfigInterface $config, - TypeListInterface $cacheTypeList, - Random $mathRandom, - AbstractResource $resource = null, - AbstractDb $resourceCollection = null, - array $data = [], - Json $serializer = null - ) { - $this->mathRandom = $mathRandom; - $this->serializer = $serializer ?: \Magento\Framework\App\ObjectManager::getInstance() - ->get(Json::class); - parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); - } - - /** - * Prepare data before save - * - * @return $this - */ - public function beforeSave() - { - $value = $this->getValue(); - if (!is_array($value)) { - try { - $value = $this->serializer->unserialize($value); - } catch (\InvalidArgumentException $e) { - $value = []; - } - } - $result = []; - foreach ($value as $data) { - if (empty($data['country_id']) || empty($data['cc_types'])) { - continue; - } - $country = $data['country_id']; - if (array_key_exists($country, $result)) { - $result[$country] = $this->appendUniqueCountries($result[$country], $data['cc_types']); - } else { - $result[$country] = $data['cc_types']; - } - } - $this->setValue($this->serializer->serialize($result)); - return $this; - } - - /** - * Process data after load - * - * @return $this - */ - public function afterLoad() - { - if ($this->getValue()) { - $value = $this->serializer->unserialize($this->getValue()); - if (is_array($value)) { - $this->setValue($this->encodeArrayFieldValue($value)); - } - } - return $this; - } - - /** - * Encode value to be used in \Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray - * - * @param array $value - * @return array - */ - protected function encodeArrayFieldValue(array $value) - { - $result = []; - foreach ($value as $country => $creditCardType) { - $id = $this->mathRandom->getUniqueHash('_'); - $result[$id] = ['country_id' => $country, 'cc_types' => $creditCardType]; - } - return $result; - } - - /** - * Append unique countries to list of exists and reindex keys - * - * @param array $countriesList - * @param array $inputCountriesList - * @return array - */ - private function appendUniqueCountries(array $countriesList, array $inputCountriesList) - { - $result = array_merge($countriesList, $inputCountriesList); - return array_values(array_unique($result)); - } -} diff --git a/app/code/Magento/Braintree/Model/AvsEmsCodeMapper.php b/app/code/Magento/Braintree/Model/AvsEmsCodeMapper.php deleted file mode 100644 index f9fae8a469b1d..0000000000000 --- a/app/code/Magento/Braintree/Model/AvsEmsCodeMapper.php +++ /dev/null @@ -1,71 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model; - -use Magento\Braintree\Gateway\Response\PaymentDetailsHandler; -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Payment\Api\PaymentVerificationInterface; -use Magento\Sales\Api\Data\OrderPaymentInterface; - -/** - * Processes AVS codes mapping from Braintree transaction to - * electronic merchant systems standard. - * - * @see https://developers.braintreepayments.com/reference/response/transaction - * @see http://www.emsecommerce.net/avs_cvv2_response_codes.htm - */ -class AvsEmsCodeMapper implements PaymentVerificationInterface -{ - /** - * Default code for mismatching mapping. - * - * @var string - */ - private static $unavailableCode = ''; - - /** - * List of mapping AVS codes - * - * @var array - */ - private static $avsMap = [ - 'MM' => 'Y', - 'NM' => 'A', - 'MN' => 'Z', - 'NN' => 'N', - 'UU' => 'U', - 'II' => 'U', - 'AA' => 'E' - ]; - - /** - * Gets payment AVS verification code. - * - * @param OrderPaymentInterface $orderPayment - * @return string - * @throws \InvalidArgumentException If specified order payment has different payment method code. - */ - public function getCode(OrderPaymentInterface $orderPayment) - { - if ($orderPayment->getMethod() !== ConfigProvider::CODE) { - throw new \InvalidArgumentException( - 'The "' . $orderPayment->getMethod() . '" does not supported by Braintree AVS mapper.' - ); - } - - $additionalInfo = $orderPayment->getAdditionalInformation(); - if (empty($additionalInfo[PaymentDetailsHandler::AVS_POSTAL_RESPONSE_CODE]) || - empty($additionalInfo[PaymentDetailsHandler::AVS_STREET_ADDRESS_RESPONSE_CODE]) - ) { - return self::$unavailableCode; - } - - $streetCode = $additionalInfo[PaymentDetailsHandler::AVS_STREET_ADDRESS_RESPONSE_CODE]; - $zipCode = $additionalInfo[PaymentDetailsHandler::AVS_POSTAL_RESPONSE_CODE]; - $key = $zipCode . $streetCode; - return isset(self::$avsMap[$key]) ? self::$avsMap[$key] : self::$unavailableCode; - } -} diff --git a/app/code/Magento/Braintree/Model/CvvEmsCodeMapper.php b/app/code/Magento/Braintree/Model/CvvEmsCodeMapper.php deleted file mode 100644 index b91bc1ced4980..0000000000000 --- a/app/code/Magento/Braintree/Model/CvvEmsCodeMapper.php +++ /dev/null @@ -1,66 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model; - -use Magento\Braintree\Gateway\Response\PaymentDetailsHandler; -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Payment\Api\PaymentVerificationInterface; -use Magento\Sales\Api\Data\OrderPaymentInterface; - -/** - * Processes CVV codes mapping from Braintree transaction to - * electronic merchant systems standard. - * - * @see https://developers.braintreepayments.com/reference/response/transaction - * @see http://www.emsecommerce.net/avs_cvv2_response_codes.htm - */ -class CvvEmsCodeMapper implements PaymentVerificationInterface -{ - /** - * Default code for mismatch mapping - * - * @var string - */ - private static $notProvidedCode = 'P'; - - /** - * List of mapping CVV codes - * - * @var array - */ - private static $cvvMap = [ - 'M' => 'M', - 'N' => 'N', - 'U' => 'P', - 'I' => 'P', - 'S' => 'S', - 'A' => '' - ]; - - /** - * Gets payment CVV verification code. - * - * @param OrderPaymentInterface $orderPayment - * @return string - * @throws \InvalidArgumentException If specified order payment has different payment method code. - */ - public function getCode(OrderPaymentInterface $orderPayment) - { - if ($orderPayment->getMethod() !== ConfigProvider::CODE) { - throw new \InvalidArgumentException( - 'The "' . $orderPayment->getMethod() . '" does not supported by Braintree CVV mapper.' - ); - } - - $additionalInfo = $orderPayment->getAdditionalInformation(); - if (empty($additionalInfo[PaymentDetailsHandler::CVV_RESPONSE_CODE])) { - return self::$notProvidedCode; - } - - $cvv = $additionalInfo[PaymentDetailsHandler::CVV_RESPONSE_CODE]; - return isset(self::$cvvMap[$cvv]) ? self::$cvvMap[$cvv] : self::$notProvidedCode; - } -} diff --git a/app/code/Magento/Braintree/Model/InstantPurchase/CreditCard/AvailabilityChecker.php b/app/code/Magento/Braintree/Model/InstantPurchase/CreditCard/AvailabilityChecker.php deleted file mode 100644 index e413393a5ddb2..0000000000000 --- a/app/code/Magento/Braintree/Model/InstantPurchase/CreditCard/AvailabilityChecker.php +++ /dev/null @@ -1,42 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\InstantPurchase\CreditCard; - -use Magento\Braintree\Gateway\Config\Config; -use Magento\InstantPurchase\PaymentMethodIntegration\AvailabilityCheckerInterface; - -/** - * Availability of Braintree vaults for instant purchase. - */ -class AvailabilityChecker implements AvailabilityCheckerInterface -{ - /** - * @var Config - */ - private $config; - - /** - * AvailabilityChecker constructor. - * @param Config $config - */ - public function __construct(Config $config) - { - $this->config = $config; - } - - /** - * @inheritdoc - */ - public function isAvailable(): bool - { - if ($this->config->isVerify3DSecure()) { - // Support of 3D secure not implemented for instant purchase yet. - return false; - } - - return true; - } -} diff --git a/app/code/Magento/Braintree/Model/InstantPurchase/CreditCard/TokenFormatter.php b/app/code/Magento/Braintree/Model/InstantPurchase/CreditCard/TokenFormatter.php deleted file mode 100644 index e74881b196892..0000000000000 --- a/app/code/Magento/Braintree/Model/InstantPurchase/CreditCard/TokenFormatter.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\InstantPurchase\CreditCard; - -use Magento\InstantPurchase\PaymentMethodIntegration\PaymentTokenFormatterInterface; -use Magento\Vault\Api\Data\PaymentTokenInterface; - -/** - * Braintree stored credit card formatter. - */ -class TokenFormatter implements PaymentTokenFormatterInterface -{ - /** - * Most used credit card types - * @var array - */ - public static $baseCardTypes = [ - 'AE' => 'American Express', - 'VI' => 'Visa', - 'MC' => 'MasterCard', - 'DI' => 'Discover', - 'JBC' => 'JBC', - 'CUP' => 'China Union Pay', - 'MI' => 'Maestro', - ]; - - /** - * @inheritdoc - */ - public function formatPaymentToken(PaymentTokenInterface $paymentToken): string - { - $details = json_decode($paymentToken->getTokenDetails() ?: '{}', true); - if (!isset($details['type'], $details['maskedCC'], $details['expirationDate'])) { - throw new \InvalidArgumentException('Invalid Braintree credit card token details.'); - } - - if (isset(self::$baseCardTypes[$details['type']])) { - $ccType = self::$baseCardTypes[$details['type']]; - } else { - $ccType = $details['type']; - } - - $formatted = sprintf( - '%s: %s, %s: %s (%s: %s)', - __('Credit Card'), - $ccType, - __('ending'), - $details['maskedCC'], - __('expires'), - $details['expirationDate'] - ); - - return $formatted; - } -} diff --git a/app/code/Magento/Braintree/Model/InstantPurchase/PayPal/TokenFormatter.php b/app/code/Magento/Braintree/Model/InstantPurchase/PayPal/TokenFormatter.php deleted file mode 100644 index 019710aafb7d2..0000000000000 --- a/app/code/Magento/Braintree/Model/InstantPurchase/PayPal/TokenFormatter.php +++ /dev/null @@ -1,34 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\InstantPurchase\PayPal; - -use Magento\InstantPurchase\PaymentMethodIntegration\PaymentTokenFormatterInterface; -use Magento\Vault\Api\Data\PaymentTokenInterface; - -/** - * Braintree PayPal token formatter. - */ -class TokenFormatter implements PaymentTokenFormatterInterface -{ - /** - * @inheritdoc - */ - public function formatPaymentToken(PaymentTokenInterface $paymentToken): string - { - $details = json_decode($paymentToken->getTokenDetails() ?: '{}', true); - if (!isset($details['payerEmail'])) { - throw new \InvalidArgumentException('Invalid Braintree PayPal token details.'); - } - - $formatted = sprintf( - '%s: %s', - __('PayPal'), - $details['payerEmail'] - ); - - return $formatted; - } -} diff --git a/app/code/Magento/Braintree/Model/InstantPurchase/PaymentAdditionalInformationProvider.php b/app/code/Magento/Braintree/Model/InstantPurchase/PaymentAdditionalInformationProvider.php deleted file mode 100644 index 8ec3ee41a7270..0000000000000 --- a/app/code/Magento/Braintree/Model/InstantPurchase/PaymentAdditionalInformationProvider.php +++ /dev/null @@ -1,45 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\InstantPurchase; - -use Magento\Braintree\Gateway\Command\GetPaymentNonceCommand; -use Magento\InstantPurchase\PaymentMethodIntegration\PaymentAdditionalInformationProviderInterface; -use Magento\Vault\Api\Data\PaymentTokenInterface; - -/** - * Provides Braintree specific payment additional information for instant purchase. - */ -class PaymentAdditionalInformationProvider implements PaymentAdditionalInformationProviderInterface -{ - /** - * @var GetPaymentNonceCommand - */ - private $getPaymentNonceCommand; - - /** - * PaymentAdditionalInformationProvider constructor. - * @param GetPaymentNonceCommand $getPaymentNonceCommand - */ - public function __construct(GetPaymentNonceCommand $getPaymentNonceCommand) - { - $this->getPaymentNonceCommand = $getPaymentNonceCommand; - } - - /** - * @inheritdoc - */ - public function getAdditionalInformation(PaymentTokenInterface $paymentToken): array - { - $paymentMethodNonce = $this->getPaymentNonceCommand->execute([ - PaymentTokenInterface::CUSTOMER_ID => $paymentToken->getCustomerId(), - PaymentTokenInterface::PUBLIC_HASH => $paymentToken->getPublicHash(), - ])->get()['paymentMethodNonce']; - - return [ - 'payment_method_nonce' => $paymentMethodNonce, - ]; - } -} diff --git a/app/code/Magento/Braintree/Model/LocaleResolver.php b/app/code/Magento/Braintree/Model/LocaleResolver.php deleted file mode 100644 index 418149b2978ae..0000000000000 --- a/app/code/Magento/Braintree/Model/LocaleResolver.php +++ /dev/null @@ -1,108 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model; - -use Magento\Framework\Locale\ResolverInterface; -use Magento\Braintree\Gateway\Config\PayPal\Config; - -/** - * Resolves locale for PayPal Express. - */ -class LocaleResolver implements ResolverInterface -{ - /** - * @var ResolverInterface - */ - private $resolver; - - /** - * @var Config - */ - private $config; - - /** - * Mapping Magento locales on PayPal locales. - * - * @var array - */ - private $localeMap = [ - 'zh_Hans_CN' => 'zh_CN', - 'zh_Hant_HK' => 'zh_HK', - 'zh_Hant_TW' => 'zh_TW' - ]; - - /** - * @param ResolverInterface $resolver - * @param Config $config - */ - public function __construct(ResolverInterface $resolver, Config $config) - { - $this->resolver = $resolver; - $this->config = $config; - } - - /** - * @inheritdoc - */ - public function getDefaultLocalePath() - { - return $this->resolver->getDefaultLocalePath(); - } - - /** - * @inheritdoc - */ - public function setDefaultLocale($locale) - { - return $this->resolver->setDefaultLocale($locale); - } - - /** - * @inheritdoc - */ - public function getDefaultLocale() - { - return $this->resolver->getDefaultLocale(); - } - - /** - * @inheritdoc - */ - public function setLocale($locale = null) - { - return $this->resolver->setLocale($locale); - } - - /** - * Gets store's locale or the `en_US` locale if store's locale does not supported by PayPal. - * - * @return string - * @see https://braintree.github.io/braintree-web/current/PayPalCheckout.html#createPayment - */ - public function getLocale() - { - $locale = $this->localeMap[$this->resolver->getLocale()] ?? $this->resolver->getLocale(); - $allowedLocales = $this->config->getValue('supported_locales'); - - return strpos($allowedLocales, (string) $locale) !== false ? $locale : 'en_US'; - } - - /** - * @inheritdoc - */ - public function emulate($scopeId) - { - return $this->resolver->emulate($scopeId); - } - - /** - * @inheritdoc - */ - public function revert() - { - return $this->resolver->revert(); - } -} diff --git a/app/code/Magento/Braintree/Model/Multishipping/PlaceOrder.php b/app/code/Magento/Braintree/Model/Multishipping/PlaceOrder.php deleted file mode 100644 index a95d7a922f9bd..0000000000000 --- a/app/code/Magento/Braintree/Model/Multishipping/PlaceOrder.php +++ /dev/null @@ -1,182 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Model\Multishipping; - -use Magento\Braintree\Gateway\Command\GetPaymentNonceCommand; -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Braintree\Observer\DataAssignObserver; -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider as PaypalConfigProvider; -use Magento\Multishipping\Model\Checkout\Type\Multishipping\PlaceOrderInterface; -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Api\Data\OrderPaymentExtensionInterface; -use Magento\Sales\Api\Data\OrderPaymentExtensionInterfaceFactory; -use Magento\Sales\Api\Data\OrderPaymentInterface; -use Magento\Sales\Api\OrderManagementInterface; -use Magento\Vault\Api\Data\PaymentTokenInterface; - -/** - * Order payments processing for multishipping checkout flow. - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class PlaceOrder implements PlaceOrderInterface -{ - /** - * @var OrderManagementInterface - */ - private $orderManagement; - - /** - * @var OrderPaymentExtensionInterfaceFactory - */ - private $paymentExtensionFactory; - - /** - * @var GetPaymentNonceCommand - */ - private $getPaymentNonceCommand; - - /** - * @param OrderManagementInterface $orderManagement - * @param OrderPaymentExtensionInterfaceFactory $paymentExtensionFactory - * @param GetPaymentNonceCommand $getPaymentNonceCommand - */ - public function __construct( - OrderManagementInterface $orderManagement, - OrderPaymentExtensionInterfaceFactory $paymentExtensionFactory, - GetPaymentNonceCommand $getPaymentNonceCommand - ) { - $this->orderManagement = $orderManagement; - $this->paymentExtensionFactory = $paymentExtensionFactory; - $this->getPaymentNonceCommand = $getPaymentNonceCommand; - } - - /** - * @inheritdoc - */ - public function place(array $orderList): array - { - if (empty($orderList)) { - return []; - } - - $errorList = []; - $firstOrder = $this->orderManagement->place(array_shift($orderList)); - // get payment token from first placed order - $paymentToken = $this->getPaymentToken($firstOrder); - - foreach ($orderList as $order) { - try { - /** @var OrderInterface $order */ - $orderPayment = $order->getPayment(); - $this->setVaultPayment($orderPayment, $paymentToken); - $this->orderManagement->place($order); - } catch (\Exception $e) { - $incrementId = $order->getIncrementId(); - $errorList[$incrementId] = $e; - } - } - - return $errorList; - } - - /** - * Sets vault payment method. - * - * @param OrderPaymentInterface $orderPayment - * @param PaymentTokenInterface $paymentToken - * @return void - */ - private function setVaultPayment(OrderPaymentInterface $orderPayment, PaymentTokenInterface $paymentToken): void - { - $vaultMethod = $this->getVaultPaymentMethod( - $orderPayment->getMethod() - ); - $orderPayment->setMethod($vaultMethod); - - $publicHash = $paymentToken->getPublicHash(); - $customerId = $paymentToken->getCustomerId(); - $result = $this->getPaymentNonceCommand->execute( - ['public_hash' => $publicHash, 'customer_id' => $customerId] - ) - ->get(); - - $orderPayment->setAdditionalInformation( - DataAssignObserver::PAYMENT_METHOD_NONCE, - $result['paymentMethodNonce'] - ); - $orderPayment->setAdditionalInformation( - PaymentTokenInterface::PUBLIC_HASH, - $publicHash - ); - $orderPayment->setAdditionalInformation( - PaymentTokenInterface::CUSTOMER_ID, - $customerId - ); - $orderPayment->setAdditionalInformation( - 'is_multishipping', - 1 - ); - } - - /** - * Returns vault payment method. - * - * For placing sequence of orders, we need to replace the original method on the vault method. - * - * @param string $method - * @return string - */ - private function getVaultPaymentMethod(string $method): string - { - $vaultPaymentMap = [ - ConfigProvider::CODE => ConfigProvider::CC_VAULT_CODE, - PaypalConfigProvider::PAYPAL_CODE => PaypalConfigProvider::PAYPAL_VAULT_CODE - ]; - - return $vaultPaymentMap[$method] ?? $method; - } - - /** - * Returns payment token. - * - * @param OrderInterface $order - * @return PaymentTokenInterface - * @throws \BadMethodCallException - */ - private function getPaymentToken(OrderInterface $order): PaymentTokenInterface - { - $orderPayment = $order->getPayment(); - $extensionAttributes = $this->getExtensionAttributes($orderPayment); - $paymentToken = $extensionAttributes->getVaultPaymentToken(); - - if ($paymentToken === null) { - throw new \BadMethodCallException('Vault Payment Token should be defined for placed order payment.'); - } - - return $paymentToken; - } - - /** - * Gets payment extension attributes. - * - * @param OrderPaymentInterface $payment - * @return OrderPaymentExtensionInterface - */ - private function getExtensionAttributes(OrderPaymentInterface $payment): OrderPaymentExtensionInterface - { - $extensionAttributes = $payment->getExtensionAttributes(); - if (null === $extensionAttributes) { - $extensionAttributes = $this->paymentExtensionFactory->create(); - $payment->setExtensionAttributes($extensionAttributes); - } - - return $extensionAttributes; - } -} diff --git a/app/code/Magento/Braintree/Model/Paypal/Helper/AbstractHelper.php b/app/code/Magento/Braintree/Model/Paypal/Helper/AbstractHelper.php deleted file mode 100644 index 58c2f1d454899..0000000000000 --- a/app/code/Magento/Braintree/Model/Paypal/Helper/AbstractHelper.php +++ /dev/null @@ -1,34 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Paypal\Helper; - -use Magento\Quote\Model\Quote; - -/** - * Abstract class AbstractHelper - */ -abstract class AbstractHelper -{ - /** - * Make sure addresses will be saved without validation errors - * - * @param Quote $quote - * @return void - */ - protected function disabledQuoteAddressValidation(Quote $quote) - { - $billingAddress = $quote->getBillingAddress(); - $billingAddress->setShouldIgnoreValidation(true); - - if (!$quote->getIsVirtual()) { - $shippingAddress = $quote->getShippingAddress(); - $shippingAddress->setShouldIgnoreValidation(true); - if (!$billingAddress->getEmail()) { - $billingAddress->setSameAsBilling(1); - } - } - } -} diff --git a/app/code/Magento/Braintree/Model/Paypal/Helper/OrderPlace.php b/app/code/Magento/Braintree/Model/Paypal/Helper/OrderPlace.php deleted file mode 100644 index f448cd4c19785..0000000000000 --- a/app/code/Magento/Braintree/Model/Paypal/Helper/OrderPlace.php +++ /dev/null @@ -1,134 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Model\Paypal\Helper; - -use Magento\Braintree\Model\Paypal\OrderCancellationService; -use Magento\Checkout\Api\AgreementsValidatorInterface; -use Magento\Checkout\Helper\Data; -use Magento\Checkout\Model\Type\Onepage; -use Magento\Customer\Model\Group; -use Magento\Customer\Model\Session; -use Magento\Framework\Exception\LocalizedException; -use Magento\Quote\Api\CartManagementInterface; -use Magento\Quote\Model\Quote; - -/** - * Class OrderPlace - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) - */ -class OrderPlace extends AbstractHelper -{ - /** - * @var CartManagementInterface - */ - private $cartManagement; - - /** - * @var AgreementsValidatorInterface - */ - private $agreementsValidator; - - /** - * @var Session - */ - private $customerSession; - - /** - * @var Data - */ - private $checkoutHelper; - - /** - * @var OrderCancellationService - */ - private $orderCancellationService; - - /** - * @param CartManagementInterface $cartManagement - * @param AgreementsValidatorInterface $agreementsValidator - * @param Session $customerSession - * @param Data $checkoutHelper - * @param OrderCancellationService $orderCancellationService - */ - public function __construct( - CartManagementInterface $cartManagement, - AgreementsValidatorInterface $agreementsValidator, - Session $customerSession, - Data $checkoutHelper, - OrderCancellationService $orderCancellationService - ) { - $this->cartManagement = $cartManagement; - $this->agreementsValidator = $agreementsValidator; - $this->customerSession = $customerSession; - $this->checkoutHelper = $checkoutHelper; - $this->orderCancellationService = $orderCancellationService; - } - - /** - * Execute operation - * - * @param Quote $quote - * @param array $agreement - * @return void - * @throws \Exception - */ - public function execute(Quote $quote, array $agreement) - { - if (!$this->agreementsValidator->isValid($agreement)) { - $errorMsg = __( - "The order wasn't placed. First, agree to the terms and conditions, then try placing your order again." - ); - throw new LocalizedException($errorMsg); - } - - if ($this->getCheckoutMethod($quote) === Onepage::METHOD_GUEST) { - $this->prepareGuestQuote($quote); - } - - $this->disabledQuoteAddressValidation($quote); - - $quote->collectTotals(); - $this->cartManagement->placeOrder($quote->getId()); - } - - /** - * Get checkout method - * - * @param Quote $quote - * @return string - */ - private function getCheckoutMethod(Quote $quote) - { - if ($this->customerSession->isLoggedIn()) { - return Onepage::METHOD_CUSTOMER; - } - if (!$quote->getCheckoutMethod()) { - if ($this->checkoutHelper->isAllowedGuestCheckout($quote)) { - $quote->setCheckoutMethod(Onepage::METHOD_GUEST); - } else { - $quote->setCheckoutMethod(Onepage::METHOD_REGISTER); - } - } - - return $quote->getCheckoutMethod(); - } - - /** - * Prepare quote for guest checkout order submit - * - * @param Quote $quote - * @return void - */ - private function prepareGuestQuote(Quote $quote) - { - $quote->setCustomerId(null) - ->setCustomerEmail($quote->getBillingAddress()->getEmail()) - ->setCustomerIsGuest(true) - ->setCustomerGroupId(Group::NOT_LOGGED_IN_ID); - } -} diff --git a/app/code/Magento/Braintree/Model/Paypal/Helper/QuoteUpdater.php b/app/code/Magento/Braintree/Model/Paypal/Helper/QuoteUpdater.php deleted file mode 100644 index 197b398380f74..0000000000000 --- a/app/code/Magento/Braintree/Model/Paypal/Helper/QuoteUpdater.php +++ /dev/null @@ -1,217 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Paypal\Helper; - -use Magento\Quote\Model\Quote; -use Magento\Quote\Model\Quote\Address; -use Magento\Quote\Model\Quote\Payment; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider; -use Magento\Framework\Exception\LocalizedException; -use Magento\Braintree\Observer\DataAssignObserver; -use Magento\Braintree\Gateway\Config\PayPal\Config; - -/** - * Class QuoteUpdater - */ -class QuoteUpdater extends AbstractHelper -{ - /** - * @var Config - */ - private $config; - - /** - * @var CartRepositoryInterface - */ - private $quoteRepository; - - /** - * Constructor - * - * @param Config $config - * @param CartRepositoryInterface $quoteRepository - */ - public function __construct( - Config $config, - CartRepositoryInterface $quoteRepository - ) { - $this->config = $config; - $this->quoteRepository = $quoteRepository; - } - - /** - * Execute operation - * - * @param string $nonce - * @param array $details - * @param Quote $quote - * @return void - * @throws \InvalidArgumentException - * @throws LocalizedException - */ - public function execute($nonce, array $details, Quote $quote) - { - if (empty($nonce) || empty($details)) { - throw new \InvalidArgumentException('The "nonce" and "details" fields does not exists'); - } - - $payment = $quote->getPayment(); - - $payment->setMethod(ConfigProvider::PAYPAL_CODE); - $payment->setAdditionalInformation(DataAssignObserver::PAYMENT_METHOD_NONCE, $nonce); - - $this->updateQuote($quote, $details); - } - - /** - * Update quote data - * - * @param Quote $quote - * @param array $details - * @return void - */ - private function updateQuote(Quote $quote, array $details) - { - $quote->setMayEditShippingAddress(false); - $quote->setMayEditShippingMethod(true); - - $this->updateQuoteAddress($quote, $details); - $this->disabledQuoteAddressValidation($quote); - - $quote->collectTotals(); - - /** - * Unset shipping assignment to prevent from saving / applying outdated data - * @see \Magento\Quote\Model\QuoteRepository\SaveHandler::processShippingAssignment - */ - if ($quote->getExtensionAttributes()) { - $quote->getExtensionAttributes()->setShippingAssignments(null); - } - - $this->quoteRepository->save($quote); - } - - /** - * Update quote address - * - * @param Quote $quote - * @param array $details - * @return void - */ - private function updateQuoteAddress(Quote $quote, array $details) - { - if (!$quote->getIsVirtual()) { - $this->updateShippingAddress($quote, $details); - } - - $this->updateBillingAddress($quote, $details); - } - - /** - * Update shipping address - * (PayPal doesn't provide detailed shipping info: prefix, suffix) - * - * @param Quote $quote - * @param array $details - * @return void - */ - private function updateShippingAddress(Quote $quote, array $details) - { - $shippingAddress = $quote->getShippingAddress(); - - $shippingAddress->setLastname($this->getShippingRecipientLastName($details)); - $shippingAddress->setFirstname($this->getShippingRecipientFirstName($details)); - $shippingAddress->setEmail($details['email']); - - $shippingAddress->setCollectShippingRates(true); - - $this->updateAddressData($shippingAddress, $details['shippingAddress']); - - // PayPal's address supposes not saving against customer account - $shippingAddress->setSaveInAddressBook(false); - $shippingAddress->setSameAsBilling(false); - $shippingAddress->unsCustomerAddressId(); - } - - /** - * Update billing address - * - * @param Quote $quote - * @param array $details - * @return void - */ - private function updateBillingAddress(Quote $quote, array $details) - { - $billingAddress = $quote->getBillingAddress(); - - if ($this->config->isRequiredBillingAddress() && !empty($details['billingAddress'])) { - $this->updateAddressData($billingAddress, $details['billingAddress']); - } else { - $this->updateAddressData($billingAddress, $details['shippingAddress']); - } - - $billingAddress->setFirstname($details['firstName']); - $billingAddress->setLastname($details['lastName']); - $billingAddress->setEmail($details['email']); - - // PayPal's address supposes not saving against customer account - $billingAddress->setSaveInAddressBook(false); - $billingAddress->setSameAsBilling(false); - $billingAddress->unsCustomerAddressId(); - } - - /** - * Sets address data from exported address - * - * @param Address $address - * @param array $addressData - * @return void - */ - private function updateAddressData(Address $address, array $addressData) - { - $extendedAddress = isset($addressData['line2']) - ? $addressData['line2'] - : null; - - $address->setStreet([$addressData['line1'], $extendedAddress]); - $address->setCity($addressData['city']); - $address->setRegionCode($addressData['state']); - $address->setCountryId($addressData['countryCode']); - $address->setPostcode($addressData['postalCode']); - - // PayPal's address supposes not saving against customer account - $address->setSaveInAddressBook(false); - $address->setSameAsBilling(false); - $address->setCustomerAddressId(null); - } - - /** - * Returns shipping recipient first name. - * - * @param array $details - * @return string - */ - private function getShippingRecipientFirstName(array $details) - { - return isset($details['shippingAddress']['recipientName']) - ? explode(' ', $details['shippingAddress']['recipientName'], 2)[0] - : $details['firstName']; - } - - /** - * Returns shipping recipient last name. - * - * @param array $details - * @return string - */ - private function getShippingRecipientLastName(array $details) - { - return isset($details['shippingAddress']['recipientName']) - ? explode(' ', $details['shippingAddress']['recipientName'], 2)[1] - : $details['lastName']; - } -} diff --git a/app/code/Magento/Braintree/Model/Paypal/Helper/ShippingMethodUpdater.php b/app/code/Magento/Braintree/Model/Paypal/Helper/ShippingMethodUpdater.php deleted file mode 100644 index 2ad10075291ec..0000000000000 --- a/app/code/Magento/Braintree/Model/Paypal/Helper/ShippingMethodUpdater.php +++ /dev/null @@ -1,69 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Paypal\Helper; - -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Quote\Model\Quote; - -/** - * Class ShippingMethodUpdater - */ -class ShippingMethodUpdater extends AbstractHelper -{ - /** - * @var Config - */ - private $config; - - /** - * @var CartRepositoryInterface - */ - private $quoteRepository; - - /** - * Constructor - * - * @param Config $config - * @param CartRepositoryInterface $quoteRepository - */ - public function __construct( - Config $config, - CartRepositoryInterface $quoteRepository - ) { - $this->config = $config; - $this->quoteRepository = $quoteRepository; - } - - /** - * Execute operation - * - * @param string $shippingMethod - * @param Quote $quote - * @return void - * @throws \InvalidArgumentException - */ - public function execute($shippingMethod, Quote $quote) - { - if (empty($shippingMethod)) { - throw new \InvalidArgumentException('The "shippingMethod" field does not exists.'); - } - - if (!$quote->getIsVirtual()) { - $shippingAddress = $quote->getShippingAddress(); - if ($shippingMethod !== $shippingAddress->getShippingMethod()) { - $this->disabledQuoteAddressValidation($quote); - - $shippingAddress->setShippingMethod($shippingMethod); - $shippingAddress->setCollectShippingRates(true); - - $quote->collectTotals(); - - $this->quoteRepository->save($quote); - } - } - } -} diff --git a/app/code/Magento/Braintree/Model/Paypal/OrderCancellationService.php b/app/code/Magento/Braintree/Model/Paypal/OrderCancellationService.php deleted file mode 100644 index 29757e35ea6f4..0000000000000 --- a/app/code/Magento/Braintree/Model/Paypal/OrderCancellationService.php +++ /dev/null @@ -1,77 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Model\Paypal; - -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Api\OrderRepositoryInterface; - -/** - * The service to cancel an order and void authorization transaction. - */ -class OrderCancellationService -{ - /** - * @var OrderRepositoryInterface - */ - private $orderRepository; - - /** - * @var SearchCriteriaBuilder - */ - private $searchCriteriaBuilder; - - /** - * @param SearchCriteriaBuilder $searchCriteriaBuilder - * @param OrderRepositoryInterface $orderRepository - */ - public function __construct( - SearchCriteriaBuilder $searchCriteriaBuilder, - OrderRepositoryInterface $orderRepository - ) { - $this->searchCriteriaBuilder = $searchCriteriaBuilder; - $this->orderRepository = $orderRepository; - } - - /** - * Cancels an order and authorization transaction. - * - * @param string $incrementId - * @return bool - */ - public function execute(string $incrementId): bool - { - $order = $this->getOrder($incrementId); - if ($order === null) { - return false; - } - - // `\Magento\Sales\Model\Service\OrderService::cancel` cannot be used for cancellation as the service uses - // the order repository with outdated payment method instance (ex. contains Vault instead of Braintree) - $order->cancel(); - $this->orderRepository->save($order); - return true; - } - - /** - * Gets order by increment ID. - * - * @param string $incrementId - * @return OrderInterface|null - */ - private function getOrder(string $incrementId) - { - $searchCriteria = $this->searchCriteriaBuilder->addFilter(OrderInterface::INCREMENT_ID, $incrementId) - ->create(); - - $items = $this->orderRepository->getList($searchCriteria) - ->getItems(); - - return array_pop($items); - } -} diff --git a/app/code/Magento/Braintree/Model/Report/ConditionAppliers/ApplierInterface.php b/app/code/Magento/Braintree/Model/Report/ConditionAppliers/ApplierInterface.php deleted file mode 100644 index 96940078864d5..0000000000000 --- a/app/code/Magento/Braintree/Model/Report/ConditionAppliers/ApplierInterface.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Report\ConditionAppliers; - -/** - * Braintree filter condition applier interface - */ -interface ApplierInterface -{ - const EQ = 'eq'; - const QTEQ = 'gteq'; - const LTEQ = 'lteq'; - const IN = 'in'; - const LIKE = 'like'; - - /** - * Apply filter condition - * - * @param object $field - * @param string $condition - * @param mixed $value - * @return bool - */ - public function apply($field, $condition, $value); -} diff --git a/app/code/Magento/Braintree/Model/Report/ConditionAppliers/AppliersPool.php b/app/code/Magento/Braintree/Model/Report/ConditionAppliers/AppliersPool.php deleted file mode 100644 index 3f8af0c6c7cb5..0000000000000 --- a/app/code/Magento/Braintree/Model/Report/ConditionAppliers/AppliersPool.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Report\ConditionAppliers; - -/** - * Class AppliersPool - */ -class AppliersPool -{ - /** - * @var \Magento\Braintree\Model\Report\ConditionAppliers\ApplierInterface[] - */ - private $appliersPool = []; - - /** - * AppliersPool constructor. - * @param ApplierInterface[] $appliers - */ - public function __construct(array $appliers) - { - $this->appliersPool = $appliers; - $this->checkAppliers(); - } - - /** - * Check appliers's types - * - * @return bool - */ - private function checkAppliers() - { - foreach ($this->appliersPool as $applier) { - if (!($applier instanceof ApplierInterface)) { - throw new \InvalidArgumentException('Report filter applier must implement ApplierInterface'); - } - } - return true; - } - - /** - * Get condition applier for filter - * @param object $filter - * @return null|ApplierInterface - */ - public function getApplier($filter) - { - if (is_object($filter)) { - $filterClass = get_class($filter); - if (array_key_exists($filterClass, $this->appliersPool)) { - return $this->appliersPool[$filterClass]; - } - } - return null; - } -} diff --git a/app/code/Magento/Braintree/Model/Report/ConditionAppliers/MultipleValue.php b/app/code/Magento/Braintree/Model/Report/ConditionAppliers/MultipleValue.php deleted file mode 100644 index 1286428d7d84b..0000000000000 --- a/app/code/Magento/Braintree/Model/Report/ConditionAppliers/MultipleValue.php +++ /dev/null @@ -1,45 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Report\ConditionAppliers; - -use Braintree\MultipleValueNode; - -/** - * MultipleValue applier - */ -class MultipleValue implements ApplierInterface -{ - /** - * Apply filter condition - * - * @param MultipleValueNode $field - * @param string $condition - * @param mixed $value - * @return bool - */ - public function apply($field, $condition, $value) - { - $result = false; - - switch ($condition) { - case ApplierInterface::IN: - $field->in($value); - $result = true; - break; - case ApplierInterface::EQ: - $field->is($value); - $result = true; - break; - case ApplierInterface::LIKE: - $value = trim($value, "% \r\n\t"); - $field->is($value); - $result = true; - break; - } - - return $result; - } -} diff --git a/app/code/Magento/Braintree/Model/Report/ConditionAppliers/Range.php b/app/code/Magento/Braintree/Model/Report/ConditionAppliers/Range.php deleted file mode 100644 index b202e85b4a0f5..0000000000000 --- a/app/code/Magento/Braintree/Model/Report/ConditionAppliers/Range.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Report\ConditionAppliers; - -use Braintree\RangeNode; - -/** - * Range applier - */ -class Range implements ApplierInterface -{ - /** - * Apply filter condition - * - * @param RangeNode $field - * @param string $condition - * @param mixed $value - * @return bool - */ - public function apply($field, $condition, $value) - { - $result = false; - - switch ($condition) { - case ApplierInterface::QTEQ: - $field->greaterThanOrEqualTo($value); - $result = true; - break; - case ApplierInterface::LTEQ: - $field->lessThanOrEqualTo($value); - $result = true; - break; - } - - return $result; - } -} diff --git a/app/code/Magento/Braintree/Model/Report/ConditionAppliers/Text.php b/app/code/Magento/Braintree/Model/Report/ConditionAppliers/Text.php deleted file mode 100644 index 236c089cff903..0000000000000 --- a/app/code/Magento/Braintree/Model/Report/ConditionAppliers/Text.php +++ /dev/null @@ -1,41 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Report\ConditionAppliers; - -use Braintree\TextNode; - -/** - * Text applier - */ -class Text implements ApplierInterface -{ - /** - * Apply filter condition - * - * @param TextNode $field - * @param string $condition - * @param mixed $value - * @return bool - */ - public function apply($field, $condition, $value) - { - $result = false; - - $value = trim($value, "% \r\n\t"); - switch ($condition) { - case ApplierInterface::EQ: - $field->is($value); - $result = true; - break; - case ApplierInterface::LIKE: - $field->contains($value); - $result = true; - break; - } - - return $result; - } -} diff --git a/app/code/Magento/Braintree/Model/Report/FilterMapper.php b/app/code/Magento/Braintree/Model/Report/FilterMapper.php deleted file mode 100644 index c9b17ae584231..0000000000000 --- a/app/code/Magento/Braintree/Model/Report/FilterMapper.php +++ /dev/null @@ -1,103 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Report; - -use Magento\Braintree\Model\Adapter\BraintreeSearchAdapter; -use Magento\Braintree\Model\Report\ConditionAppliers\AppliersPool; - -/** - * Class FilterMapper - */ -class FilterMapper -{ - /** - * @var array - */ - private $searchFieldsToFiltersMap = []; - - /** - * @var \Magento\Braintree\Model\Report\ConditionAppliers\AppliersPool - */ - private $appliersPool; - - /** - * @var \Magento\Braintree\Model\Adapter\BraintreeSearchAdapter - */ - private $braintreeSearchAdapter; - - /** - */ - public function __construct( - AppliersPool $appliersPool, - BraintreeSearchAdapter $braintreeSearchAdapter - ) { - $this->appliersPool = $appliersPool; - $this->braintreeSearchAdapter = $braintreeSearchAdapter; - $this->initFieldsToFiltersMap(); - } - - /** - * Init fields map with Braintree filters - * @return void - */ - private function initFieldsToFiltersMap() - { - $this->searchFieldsToFiltersMap = [ - 'id' => $this->braintreeSearchAdapter->id(), - 'merchantAccountId' => $this->braintreeSearchAdapter->merchantAccountId(), - 'orderId' => $this->braintreeSearchAdapter->orderId(), - 'paypalDetails_paymentId' => $this->braintreeSearchAdapter->paypalPaymentId(), - 'createdUsing' => $this->braintreeSearchAdapter->createdUsing(), - 'type' => $this->braintreeSearchAdapter->type(), - 'createdAt' => $this->braintreeSearchAdapter->createdAt(), - 'amount' => $this->braintreeSearchAdapter->amount(), - 'status' => $this->braintreeSearchAdapter->status(), - 'settlementBatchId' => $this->braintreeSearchAdapter->settlementBatchId(), - 'paymentInstrumentType' => $this->braintreeSearchAdapter->paymentInstrumentType() - ]; - } - - /** - * Get filter with applied conditions - * @param string $field - * @param array $conditionMap - * @return null|object - */ - public function getFilter($field, array $conditionMap) - { - if (!isset($this->searchFieldsToFiltersMap[$field])) { - return null; - } - - $fieldFilter = $this->searchFieldsToFiltersMap[$field]; - if ($this->applyConditions($fieldFilter, $conditionMap)) { - return $fieldFilter; - } - - return null; - } - - /** - * Apply conditions to filter - * - * @param object $fieldFilter - * @param array $conditionMap - * @return bool - */ - private function applyConditions($fieldFilter, array $conditionMap) - { - $applier = $this->appliersPool->getApplier($fieldFilter); - - $conditionsAppliedCounter = 0; - foreach ($conditionMap as $conditionKey => $value) { - if ($applier->apply($fieldFilter, $conditionKey, $value)) { - $conditionsAppliedCounter ++; - } - } - - return $conditionsAppliedCounter > 0; - } -} diff --git a/app/code/Magento/Braintree/Model/Report/Row/TransactionMap.php b/app/code/Magento/Braintree/Model/Report/Row/TransactionMap.php deleted file mode 100644 index 99feb511c7375..0000000000000 --- a/app/code/Magento/Braintree/Model/Report/Row/TransactionMap.php +++ /dev/null @@ -1,216 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Report\Row; - -use Braintree\Transaction; -use DateTime; -use Magento\Framework\Api\AttributeValueFactory; -use Magento\Framework\Api\Search\DocumentInterface; - -/** - * Class TransactionMap - */ -class TransactionMap implements DocumentInterface -{ - const TRANSACTION_FIELD_MAP_DELIMITER = '_'; - - /** - * @var AttributeValueFactory - */ - private $attributeValueFactory; - - /** - * @var Transaction - */ - private $transaction; - - /** - * @var array - */ - public static $simpleFieldsMap = [ - 'id', - 'merchantAccountId', - 'orderId', - 'paymentInstrumentType', - 'paypalDetails_paymentId', - 'type', - 'createdAt', - 'amount', - 'processorSettlementResponseCode', - 'status', - 'processorSettlementResponseText', - 'refundIds', - 'settlementBatchId', - 'currencyIsoCode' - ]; - - /** - * @param AttributeValueFactory $attributeValueFactory - * @param Transaction $transaction - */ - public function __construct( - AttributeValueFactory $attributeValueFactory, - Transaction $transaction - ) { - $this->attributeValueFactory = $attributeValueFactory; - $this->transaction = $transaction; - } - - /** - * Get Id - * - * @return string - */ - public function getId() - { - return $this->getMappedValue('id'); - } - - /** - * Set Id - * - * @param int $id - * @return void - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function setId($id) - { - } - - /** - * Get an attribute value. - * - * @param string $attributeCode - * @return \Magento\Framework\Api\AttributeInterface|null - */ - public function getCustomAttribute($attributeCode) - { - /** @var \Magento\Framework\Api\AttributeInterface $attributeValue */ - $attributeValue = $this->attributeValueFactory->create(); - $attributeValue->setAttributeCode($attributeCode); - $attributeValue->setValue($this->getMappedValue($attributeCode)); - return $attributeValue; - } - - /** - * Set an attribute value for a given attribute code - * - * @param string $attributeCode - * @param mixed $attributeValue - * @return $this - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function setCustomAttribute($attributeCode, $attributeValue) - { - return $this; - } - - /** - * Retrieve custom attributes values. - * - * @return \Magento\Framework\Api\AttributeInterface[]|null - */ - public function getCustomAttributes() - { - $shouldBeLocalized = ['paymentInstrumentType', 'type', 'status']; - $output = []; - foreach ($this->getMappedValues() as $key => $value) { - $attribute = $this->attributeValueFactory->create(); - if (in_array($key, $shouldBeLocalized)) { - $value = __($value); - } - $output[] = $attribute->setAttributeCode($key)->setValue($value); - } - return $output; - } - - /** - * Set array of custom attributes - * - * @param \Magento\Framework\Api\AttributeInterface[] $attributes - * @return $this - * @throws \LogicException - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function setCustomAttributes(array $attributes) - { - return $this; - } - - /** - * Get mapped value - * - * @param string $key - * @return mixed - */ - private function getMappedValue($key) - { - if (!in_array($key, static::$simpleFieldsMap)) { - return null; - } - - $val = $this->getTransactionFieldValue($key); - $val = $this->convertToText($val); - return $val; - } - - /** - * @return array - */ - private function getMappedValues() - { - $result = []; - - foreach (static::$simpleFieldsMap as $key) { - $val = $this->getTransactionFieldValue($key); - $val = $this->convertToText($val); - $result[$key] = $val; - } - - return $result; - } - - /** - * Recursive get transaction field value - * - * @param string $key - * @return Transaction|mixed|null - */ - private function getTransactionFieldValue($key) - { - $keys = explode(self::TRANSACTION_FIELD_MAP_DELIMITER, $key); - $result = $this->transaction; - foreach ($keys as $k) { - if (!isset($result->$k)) { - $result = null; - break; - } - $result = $result->$k; - } - return $result; - } - - /** - * Convert value to text representation - * - * @param string $val - * @return string - */ - private function convertToText($val) - { - if (is_object($val)) { - switch (get_class($val)) { - case 'DateTime': - /** @var DateTime $val */ - $val = $val->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT); - } - } elseif (is_array($val)) { - $val = implode(', ', $val); - } - - return (string) $val; - } -} diff --git a/app/code/Magento/Braintree/Model/Report/TransactionsCollection.php b/app/code/Magento/Braintree/Model/Report/TransactionsCollection.php deleted file mode 100644 index a237b64bf58ee..0000000000000 --- a/app/code/Magento/Braintree/Model/Report/TransactionsCollection.php +++ /dev/null @@ -1,245 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Report; - -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Braintree\Model\Report\Row\TransactionMap; -use Magento\Framework\Api\Search\SearchResultInterface; -use Magento\Framework\Api\SearchCriteriaInterface; -use Magento\Framework\Data\Collection; -use Magento\Framework\Data\Collection\EntityFactoryInterface; - -/** - * Class TransactionsCollection - */ -class TransactionsCollection extends Collection implements SearchResultInterface -{ - /** - * Transaction maximum count - */ - const TRANSACTION_MAXIMUM_COUNT = 100; - - /** - * Item object class name - * - * @var string - */ - protected $_itemObjectClass = TransactionMap::class; - - /** - * @var array - */ - private $filtersList = []; - - /** - * @var FilterMapper - */ - private $filterMapper; - - /** - * @var BraintreeAdapterFactory - */ - private $braintreeAdapterFactory; - - /** - * @var \Braintree\ResourceCollection | null - */ - private $collection; - - /** - * @param EntityFactoryInterface $entityFactory - * @param BraintreeAdapterFactory $braintreeAdapterFactory - * @param FilterMapper $filterMapper - */ - public function __construct( - EntityFactoryInterface $entityFactory, - BraintreeAdapterFactory $braintreeAdapterFactory, - FilterMapper $filterMapper - ) { - parent::__construct($entityFactory); - $this->filterMapper = $filterMapper; - $this->braintreeAdapterFactory = $braintreeAdapterFactory; - } - - /** - * @return \Magento\Framework\Api\Search\DocumentInterface[] - */ - public function getItems() - { - if (!$this->fetchIdsCollection()) { - return []; - } - - $result = []; - $counter = 0; - $pageSize = $this->getPageSize(); - $skipCounter = ($this->_curPage - 1) * $pageSize; - - // To optimize the processing of large searches, data is retrieved from the server lazily. - foreach ($this->collection as $item) { - if ($skipCounter > 0) { - $skipCounter --; - } else { - $entity = $this->_entityFactory->create($this->_itemObjectClass, ['transaction' => $item]); - if ($entity) { - $result[] = $entity; - - $counter ++; - if ($pageSize && $counter >= $pageSize) { - break; - } - } - } - } - - return $result; - } - - /** - * Fetch collection from Braintree - * @return \Braintree\ResourceCollection|null - */ - protected function fetchIdsCollection() - { - if (empty($this->filtersList)) { - return null; - } - - // Fetch all transaction IDs in order to filter - if (empty($this->collection)) { - $filters = $this->getFilters(); - $this->collection = $this->braintreeAdapterFactory->create() - ->search($filters); - } - - return $this->collection; - } - - /** - * Set items list. - * - * @param \Magento\Framework\Api\Search\DocumentInterface[] $items - * @return $this - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function setItems(array $items = null) - { - return $this; - } - - /** - * @return \Magento\Framework\Api\Search\AggregationInterface - */ - public function getAggregations() - { - return null; - } - - /** - * @param \Magento\Framework\Api\Search\AggregationInterface $aggregations - * @return $this - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function setAggregations($aggregations) - { - return $this; - } - - /** - * Get search criteria. - * - * @return \Magento\Framework\Api\Search\SearchCriteriaInterface - */ - public function getSearchCriteria() - { - return null; - } - - /** - * Set search criteria. - * - * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria - * @return $this - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function setSearchCriteria(SearchCriteriaInterface $searchCriteria) - { - return $this; - } - - /** - * Get total count. - * - * @return int - */ - public function getTotalCount() - { - $collection = $this->fetchIdsCollection(); - return null === $collection ? 0 : $collection->maximumCount(); - } - - /** - * Retrieve collection page size - * - * @return int - */ - public function getPageSize() - { - $pageSize = parent::getPageSize(); - return $pageSize === null ? static::TRANSACTION_MAXIMUM_COUNT : $pageSize; - } - - /** - * Set total count. - * - * @param int $totalCount - * @return $this - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function setTotalCount($totalCount) - { - return $this; - } - - /** - * @inheritdoc - */ - public function addFieldToFilter($field, $condition) - { - if (is_array($field)) { - return $this; - } - - if (!is_array($condition)) { - $condition = ['eq' => $condition]; - } - - $this->addFilterToList($this->filterMapper->getFilter($field, $condition)); - - return $this; - } - - /** - * Add filter to list - * - * @param object $filter - * @return void - */ - private function addFilterToList($filter) - { - if (null !== $filter) { - $this->filtersList[] = $filter; - } - } - - /** - * @return array - */ - private function getFilters() - { - return $this->filtersList; - } -} diff --git a/app/code/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProvider.php b/app/code/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProvider.php deleted file mode 100644 index 91585c1690548..0000000000000 --- a/app/code/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProvider.php +++ /dev/null @@ -1,84 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Ui\Adminhtml\PayPal; - -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider as PayPalConfigProvider; -use Magento\Framework\UrlInterface; -use Magento\Framework\View\Element\Template; -use Magento\Vault\Api\Data\PaymentTokenInterface; -use Magento\Vault\Model\Ui\TokenUiComponentInterfaceFactory; -use Magento\Vault\Model\Ui\TokenUiComponentProviderInterface; - -/** - * Gets Ui component configuration for Braintree PayPal Vault - */ -class TokenUiComponentProvider implements TokenUiComponentProviderInterface -{ - - /** - * @var TokenUiComponentInterfaceFactory - */ - private $componentFactory; - - /** - * @var UrlInterface - */ - private $urlBuilder; - - /** - * @var Config - */ - private $config; - - /** - * @param TokenUiComponentInterfaceFactory $componentFactory - * @param UrlInterface $urlBuilder - * @param Config $config - */ - public function __construct( - TokenUiComponentInterfaceFactory $componentFactory, - UrlInterface $urlBuilder, - Config $config - ) { - $this->componentFactory = $componentFactory; - $this->urlBuilder = $urlBuilder; - $this->config = $config; - } - - /** - * @inheritdoc - */ - public function getComponentForToken(PaymentTokenInterface $paymentToken) - { - $data = json_decode($paymentToken->getTokenDetails() ?: '{}', true); - $data['icon'] = $this->config->getPayPalIcon(); - $component = $this->componentFactory->create( - [ - 'config' => [ - 'code' => PayPalConfigProvider::PAYPAL_VAULT_CODE, - 'nonceUrl' => $this->getNonceRetrieveUrl(), - TokenUiComponentProviderInterface::COMPONENT_DETAILS => $data, - TokenUiComponentProviderInterface::COMPONENT_PUBLIC_HASH => $paymentToken->getPublicHash(), - 'template' => 'Magento_Braintree::form/paypal/vault.phtml' - ], - 'name' => Template::class - ] - ); - - return $component; - } - - /** - * Get url to retrieve payment method nonce - * @return string - */ - private function getNonceRetrieveUrl() - { - return $this->urlBuilder->getUrl(ConfigProvider::CODE . '/payment/getnonce', ['_secure' => true]); - } -} diff --git a/app/code/Magento/Braintree/Model/Ui/Adminhtml/TokenUiComponentProvider.php b/app/code/Magento/Braintree/Model/Ui/Adminhtml/TokenUiComponentProvider.php deleted file mode 100644 index a404f2003a76f..0000000000000 --- a/app/code/Magento/Braintree/Model/Ui/Adminhtml/TokenUiComponentProvider.php +++ /dev/null @@ -1,73 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Ui\Adminhtml; - -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Framework\UrlInterface; -use Magento\Framework\View\Element\Template; -use Magento\Vault\Api\Data\PaymentTokenInterface; -use Magento\Vault\Model\Ui\TokenUiComponentInterfaceFactory; -use Magento\Vault\Model\Ui\TokenUiComponentProviderInterface; - -/** - * Class TokenProvider - */ -class TokenUiComponentProvider implements TokenUiComponentProviderInterface -{ - - /** - * @var TokenUiComponentInterfaceFactory - */ - private $componentFactory; - - /** - * @var \Magento\Framework\UrlInterface - */ - private $urlBuilder; - - /** - * @param TokenUiComponentInterfaceFactory $componentFactory - * @param UrlInterface $urlBuilder - */ - public function __construct( - TokenUiComponentInterfaceFactory $componentFactory, - UrlInterface $urlBuilder - ) { - $this->componentFactory = $componentFactory; - $this->urlBuilder = $urlBuilder; - } - - /** - * @inheritdoc - */ - public function getComponentForToken(PaymentTokenInterface $paymentToken) - { - $data = json_decode($paymentToken->getTokenDetails() ?: '{}', true); - $component = $this->componentFactory->create( - [ - 'config' => [ - 'code' => ConfigProvider::CC_VAULT_CODE, - 'nonceUrl' => $this->getNonceRetrieveUrl(), - TokenUiComponentProviderInterface::COMPONENT_DETAILS => $data, - TokenUiComponentProviderInterface::COMPONENT_PUBLIC_HASH => $paymentToken->getPublicHash(), - 'template' => 'Magento_Braintree::form/vault.phtml' - ], - 'name' => Template::class - ] - ); - - return $component; - } - - /** - * Get url to retrieve payment method nonce - * @return string - */ - private function getNonceRetrieveUrl() - { - return $this->urlBuilder->getUrl(ConfigProvider::CODE . '/payment/getnonce', ['_secure' => true]); - } -} diff --git a/app/code/Magento/Braintree/Model/Ui/ConfigProvider.php b/app/code/Magento/Braintree/Model/Ui/ConfigProvider.php deleted file mode 100644 index 1ba696839a95d..0000000000000 --- a/app/code/Magento/Braintree/Model/Ui/ConfigProvider.php +++ /dev/null @@ -1,118 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Ui; - -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\Request\PaymentDataBuilder; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Checkout\Model\ConfigProviderInterface; -use Magento\Framework\Session\SessionManagerInterface; - -/** - * Class ConfigProvider - * - * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) - */ -class ConfigProvider implements ConfigProviderInterface -{ - const CODE = 'braintree'; - - const CC_VAULT_CODE = 'braintree_cc_vault'; - - /** - * @var Config - */ - private $config; - - /** - * @var BraintreeAdapterFactory - */ - private $adapterFactory; - - /** - * @var string - */ - private $clientToken = ''; - - /** - * @var SessionManagerInterface - */ - private $session; - - /** - * Constructor - * - * @param Config $config - * @param BraintreeAdapterFactory $adapterFactory - * @param SessionManagerInterface $session - */ - public function __construct( - Config $config, - BraintreeAdapterFactory $adapterFactory, - SessionManagerInterface $session - ) { - $this->config = $config; - $this->adapterFactory = $adapterFactory; - $this->session = $session; - } - - /** - * Retrieve assoc array of checkout configuration - * - * @return array - */ - public function getConfig() - { - $storeId = $this->session->getStoreId(); - $isActive = $this->config->isActive($storeId); - return [ - 'payment' => [ - self::CODE => [ - 'isActive' => $isActive, - 'clientToken' => $isActive ? $this->getClientToken() : null, - 'ccTypesMapper' => $this->config->getCcTypesMapper(), - 'sdkUrl' => $this->config->getSdkUrl(), - 'hostedFieldsSdkUrl' => $this->config->getHostedFieldsSdkUrl(), - 'countrySpecificCardTypes' => $this->config->getCountrySpecificCardTypeConfig($storeId), - 'availableCardTypes' => $this->config->getAvailableCardTypes($storeId), - 'useCvv' => $this->config->isCvvEnabled($storeId), - 'environment' => $this->config->getEnvironment($storeId), - 'hasFraudProtection' => $this->config->hasFraudProtection($storeId), - 'merchantId' => $this->config->getMerchantId($storeId), - 'ccVaultCode' => self::CC_VAULT_CODE, - ], - Config::CODE_3DSECURE => [ - 'enabled' => $this->config->isVerify3DSecure($storeId), - 'thresholdAmount' => $this->config->getThresholdAmount($storeId), - 'specificCountries' => $this->config->get3DSecureSpecificCountries($storeId), - ], - ], - ]; - } - - /** - * Generate a new client token if necessary - * - * @return string - */ - public function getClientToken() - { - if (empty($this->clientToken)) { - $params = []; - - $storeId = $this->session->getStoreId(); - $merchantAccountId = $this->config->getMerchantAccountId($storeId); - if (!empty($merchantAccountId)) { - $params[PaymentDataBuilder::MERCHANT_ACCOUNT_ID] = $merchantAccountId; - } - - $this->clientToken = $this->adapterFactory->create($storeId) - ->generate($params); - } - - return $this->clientToken; - } -} diff --git a/app/code/Magento/Braintree/Model/Ui/PayPal/ConfigProvider.php b/app/code/Magento/Braintree/Model/Ui/PayPal/ConfigProvider.php deleted file mode 100644 index e6c5ee22c62b4..0000000000000 --- a/app/code/Magento/Braintree/Model/Ui/PayPal/ConfigProvider.php +++ /dev/null @@ -1,71 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Ui\PayPal; - -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Checkout\Model\ConfigProviderInterface; -use Magento\Framework\Locale\ResolverInterface; - -/** - * Class ConfigProvider - */ -class ConfigProvider implements ConfigProviderInterface -{ - const PAYPAL_CODE = 'braintree_paypal'; - - const PAYPAL_VAULT_CODE = 'braintree_paypal_vault'; - - /** - * @var Config - */ - private $config; - - /** - * @var ResolverInterface - */ - private $resolver; - - /** - * Initialize dependencies. - * - * @param Config $config - * @param ResolverInterface $resolver - */ - public function __construct(Config $config, ResolverInterface $resolver) - { - $this->config = $config; - $this->resolver = $resolver; - } - - /** - * Retrieve assoc array of checkout configuration - * - * @return array - */ - public function getConfig() - { - $requireBillingAddressAll = \Magento\Paypal\Model\Config::REQUIRE_BILLING_ADDRESS_ALL; - - return [ - 'payment' => [ - self::PAYPAL_CODE => [ - 'isActive' => $this->config->isActive(), - 'title' => $this->config->getTitle(), - 'isAllowShippingAddressOverride' => $this->config->isAllowToEditShippingAddress(), - 'merchantName' => $this->config->getMerchantName(), - 'locale' => $this->resolver->getLocale(), - 'paymentAcceptanceMarkSrc' => - 'https://www.paypalobjects.com/webstatic/en_US/i/buttons/pp-acceptance-medium.png', - 'vaultCode' => self::PAYPAL_VAULT_CODE, - 'skipOrderReview' => $this->config->isSkipOrderReview(), - 'paymentIcon' => $this->config->getPayPalIcon(), - 'isRequiredBillingAddress' => - (int)$this->config->isRequiredBillingAddress() === $requireBillingAddressAll - ] - ] - ]; - } -} diff --git a/app/code/Magento/Braintree/Model/Ui/PayPal/TokenUiComponentProvider.php b/app/code/Magento/Braintree/Model/Ui/PayPal/TokenUiComponentProvider.php deleted file mode 100644 index d8a50d8cfa2a9..0000000000000 --- a/app/code/Magento/Braintree/Model/Ui/PayPal/TokenUiComponentProvider.php +++ /dev/null @@ -1,73 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Ui\PayPal; - -use Magento\Braintree\Model\Ui\ConfigProvider as CommonConfigProvider; -use Magento\Framework\UrlInterface; -use Magento\Vault\Api\Data\PaymentTokenInterface; -use Magento\Vault\Model\Ui\TokenUiComponentInterface; -use Magento\Vault\Model\Ui\TokenUiComponentInterfaceFactory; -use Magento\Vault\Model\Ui\TokenUiComponentProviderInterface; - -/** - * Class TokenUiComponentProvider - */ -class TokenUiComponentProvider implements TokenUiComponentProviderInterface -{ - /** - * @var TokenUiComponentInterfaceFactory - */ - private $componentFactory; - - /** - * @var \Magento\Framework\UrlInterface - */ - private $urlBuilder; - - /** - * @param TokenUiComponentInterfaceFactory $componentFactory - * @param UrlInterface $urlBuilder - */ - public function __construct( - TokenUiComponentInterfaceFactory $componentFactory, - UrlInterface $urlBuilder - ) { - $this->componentFactory = $componentFactory; - $this->urlBuilder = $urlBuilder; - } - - /** - * Get UI component for token - * @param PaymentTokenInterface $paymentToken - * @return TokenUiComponentInterface - */ - public function getComponentForToken(PaymentTokenInterface $paymentToken) - { - $jsonDetails = json_decode($paymentToken->getTokenDetails() ?: '{}', true); - $component = $this->componentFactory->create( - [ - 'config' => [ - 'code' => ConfigProvider::PAYPAL_VAULT_CODE, - 'nonceUrl' => $this->getNonceRetrieveUrl(), - TokenUiComponentProviderInterface::COMPONENT_DETAILS => $jsonDetails, - TokenUiComponentProviderInterface::COMPONENT_PUBLIC_HASH => $paymentToken->getPublicHash() - ], - 'name' => 'Magento_Braintree/js/view/payment/method-renderer/paypal-vault' - ] - ); - - return $component; - } - - /** - * Get url to retrieve payment method nonce - * @return string - */ - private function getNonceRetrieveUrl() - { - return $this->urlBuilder->getUrl(CommonConfigProvider::CODE . '/payment/getnonce', ['_secure' => true]); - } -} diff --git a/app/code/Magento/Braintree/Model/Ui/TokenUiComponentProvider.php b/app/code/Magento/Braintree/Model/Ui/TokenUiComponentProvider.php deleted file mode 100644 index da2b2225e19d4..0000000000000 --- a/app/code/Magento/Braintree/Model/Ui/TokenUiComponentProvider.php +++ /dev/null @@ -1,72 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Ui; - -use Magento\Vault\Api\Data\PaymentTokenInterface; -use Magento\Vault\Model\Ui\TokenUiComponentInterface; -use Magento\Vault\Model\Ui\TokenUiComponentProviderInterface; -use Magento\Vault\Model\Ui\TokenUiComponentInterfaceFactory; -use Magento\Framework\UrlInterface; - -/** - * Class TokenUiComponentProvider - */ -class TokenUiComponentProvider implements TokenUiComponentProviderInterface -{ - /** - * @var TokenUiComponentInterfaceFactory - */ - private $componentFactory; - - /** - * @var \Magento\Framework\UrlInterface - */ - private $urlBuilder; - - /** - * @param TokenUiComponentInterfaceFactory $componentFactory - * @param UrlInterface $urlBuilder - */ - public function __construct( - TokenUiComponentInterfaceFactory $componentFactory, - UrlInterface $urlBuilder - ) { - $this->componentFactory = $componentFactory; - $this->urlBuilder = $urlBuilder; - } - - /** - * Get UI component for token - * @param PaymentTokenInterface $paymentToken - * @return TokenUiComponentInterface - */ - public function getComponentForToken(PaymentTokenInterface $paymentToken) - { - $jsonDetails = json_decode($paymentToken->getTokenDetails() ?: '{}', true); - $component = $this->componentFactory->create( - [ - 'config' => [ - 'code' => ConfigProvider::CC_VAULT_CODE, - 'nonceUrl' => $this->getNonceRetrieveUrl(), - TokenUiComponentProviderInterface::COMPONENT_DETAILS => $jsonDetails, - TokenUiComponentProviderInterface::COMPONENT_PUBLIC_HASH => $paymentToken->getPublicHash() - ], - 'name' => 'Magento_Braintree/js/view/payment/method-renderer/vault' - ] - ); - - return $component; - } - - /** - * Get url to retrieve payment method nonce - * @return string - */ - private function getNonceRetrieveUrl() - { - return $this->urlBuilder->getUrl(ConfigProvider::CODE . '/payment/getnonce', ['_secure' => true]); - } -} diff --git a/app/code/Magento/Braintree/Observer/AddPaypalShortcuts.php b/app/code/Magento/Braintree/Observer/AddPaypalShortcuts.php deleted file mode 100644 index ea16745a24117..0000000000000 --- a/app/code/Magento/Braintree/Observer/AddPaypalShortcuts.php +++ /dev/null @@ -1,66 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Observer; - -use Magento\Framework\Event\Observer; -use Magento\Catalog\Block\ShortcutButtons; -use Magento\Framework\Event\ObserverInterface; - -/** - * Class AddPaypalShortcuts - */ -class AddPaypalShortcuts implements ObserverInterface -{ - /** - * Alias for mini-cart block. - */ - private const PAYPAL_MINICART_ALIAS = 'mini_cart'; - - /** - * Alias for shopping cart page. - */ - private const PAYPAL_SHOPPINGCART_ALIAS = 'shopping_cart'; - - /** - * @var string[] - */ - private $buttonBlocks; - - /** - * @param string[] $buttonBlocks - */ - public function __construct(array $buttonBlocks = []) - { - $this->buttonBlocks = $buttonBlocks; - } - - /** - * Add Braintree PayPal shortcut buttons - * - * @param Observer $observer - * @return void - */ - public function execute(Observer $observer) - { - // Remove button from catalog pages - if ($observer->getData('is_catalog_product')) { - return; - } - - /** @var ShortcutButtons $shortcutButtons */ - $shortcutButtons = $observer->getEvent()->getContainer(); - - if ($observer->getData('is_shopping_cart')) { - $shortcut = $shortcutButtons->getLayout() - ->createBlock($this->buttonBlocks[self::PAYPAL_SHOPPINGCART_ALIAS]); - } else { - $shortcut = $shortcutButtons->getLayout() - ->createBlock($this->buttonBlocks[self::PAYPAL_MINICART_ALIAS]); - } - - $shortcutButtons->addShortcut($shortcut); - } -} diff --git a/app/code/Magento/Braintree/Observer/DataAssignObserver.php b/app/code/Magento/Braintree/Observer/DataAssignObserver.php deleted file mode 100644 index ac1b198d926db..0000000000000 --- a/app/code/Magento/Braintree/Observer/DataAssignObserver.php +++ /dev/null @@ -1,52 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Observer; - -use Magento\Framework\Event\Observer; -use Magento\Payment\Observer\AbstractDataAssignObserver; -use Magento\Quote\Api\Data\PaymentInterface; - -/** - * Class DataAssignObserver - */ -class DataAssignObserver extends AbstractDataAssignObserver -{ - const PAYMENT_METHOD_NONCE = 'payment_method_nonce'; - const DEVICE_DATA = 'device_data'; - - /** - * @var array - */ - protected $additionalInformationList = [ - self::PAYMENT_METHOD_NONCE, - self::DEVICE_DATA - ]; - - /** - * @param Observer $observer - * @return void - */ - public function execute(Observer $observer) - { - $data = $this->readDataArgument($observer); - - $additionalData = $data->getData(PaymentInterface::KEY_ADDITIONAL_DATA); - if (!is_array($additionalData)) { - return; - } - - $paymentInfo = $this->readPaymentModelArgument($observer); - - foreach ($this->additionalInformationList as $additionalInformationKey) { - if (isset($additionalData[$additionalInformationKey])) { - $paymentInfo->setAdditionalInformation( - $additionalInformationKey, - $additionalData[$additionalInformationKey] - ); - } - } - } -} diff --git a/app/code/Magento/Braintree/Plugin/DisableQuoteAddressValidation.php b/app/code/Magento/Braintree/Plugin/DisableQuoteAddressValidation.php deleted file mode 100644 index 03117a4e977a1..0000000000000 --- a/app/code/Magento/Braintree/Plugin/DisableQuoteAddressValidation.php +++ /dev/null @@ -1,43 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Plugin; - -use Magento\Quote\Model\QuoteManagement; -use Magento\Quote\Api\CartManagementInterface; -use Magento\Quote\Model\Quote; - -/** - * Plugin for QuoteManagement to disable quote address validation - */ -class DisableQuoteAddressValidation -{ - /** - * Disable quote address validation before submit order - * - * @param QuoteManagement $subject - * @param Quote $quote - * @param array $orderData - * @return array - * @throws \Exception - * @throws \Magento\Framework\Exception\LocalizedException - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function beforeSubmit( - QuoteManagement $subject, - Quote $quote, - $orderData = [] - ) { - if ($quote->getPayment()->getMethod() == 'braintree_paypal' && - $quote->getCheckoutMethod() == CartManagementInterface::METHOD_GUEST) { - $billingAddress = $quote->getBillingAddress(); - $billingAddress->setShouldIgnoreValidation(true); - $quote->setBillingAddress($billingAddress); - } - return [$quote, $orderData]; - } -} diff --git a/app/code/Magento/Braintree/Plugin/OrderCancellation.php b/app/code/Magento/Braintree/Plugin/OrderCancellation.php deleted file mode 100644 index 4754e89e67ada..0000000000000 --- a/app/code/Magento/Braintree/Plugin/OrderCancellation.php +++ /dev/null @@ -1,83 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Plugin; - -use Magento\Braintree\Model\Paypal\OrderCancellationService; -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider as PayPalConfigProvider; -use Magento\Framework\Exception\LocalizedException; -use Magento\Quote\Api\CartManagementInterface; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Quote\Api\Data\PaymentInterface; - -/** - * Cancels an order and an authorization transaction. - */ -class OrderCancellation -{ - /** - * @var OrderCancellationService - */ - private $orderCancellationService; - - /** - * @var CartRepositoryInterface - */ - private $quoteRepository; - - /** - * @param OrderCancellationService $orderCancellationService - * @param CartRepositoryInterface $quoteRepository - */ - public function __construct( - OrderCancellationService $orderCancellationService, - CartRepositoryInterface $quoteRepository - ) { - $this->orderCancellationService = $orderCancellationService; - $this->quoteRepository = $quoteRepository; - } - - /** - * Cancels an order if an exception occurs during the order creation. - * - * @param CartManagementInterface $subject - * @param \Closure $proceed - * @param int $cartId - * @param PaymentInterface $payment - * @return int - * @throws \Exception - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function aroundPlaceOrder( - CartManagementInterface $subject, - \Closure $proceed, - $cartId, - PaymentInterface $payment = null - ) { - try { - return $proceed($cartId, $payment); - } catch (\Exception $e) { - $quote = $this->quoteRepository->get((int) $cartId); - $payment = $quote->getPayment(); - $paymentCodes = [ - ConfigProvider::CODE, - ConfigProvider::CC_VAULT_CODE, - PayPalConfigProvider::PAYPAL_CODE, - PayPalConfigProvider::PAYPAL_VAULT_CODE - ]; - if (in_array($payment->getMethod(), $paymentCodes)) { - $incrementId = $quote->getReservedOrderId(); - if ($incrementId) { - $this->orderCancellationService->execute($incrementId); - } - } - - throw $e; - } - } -} diff --git a/app/code/Magento/Braintree/README.md b/app/code/Magento/Braintree/README.md deleted file mode 100644 index 66d872e55a21a..0000000000000 --- a/app/code/Magento/Braintree/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# Magento_Braintree module - -The Magento_Braintree module implements integration with the Braintree payment system. - -## Extensibility - -Extension developers can interact with the Magento_Braintree module. For more information about the Magento extension mechanism, see [Magento plug-ins](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html). - -[The Magento dependency injection mechanism](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html) enables you to override the functionality of the Magento_Braintree module. - -### Events - -This module observes the following events: - - - `payment_method_assign_data_braintree` event in `Magento\Braintree\Observer\DataAssignObserver` file. - - `payment_method_assign_data_braintree_paypal` event in `Magento\Braintree\Observer\DataAssignObserver` file. - - `shortcut_buttons_container` event in `Magento\Braintree\Observer\AddPaypalShortcuts` file. - -For information about an event in Magento 2, see [Events and observers](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/events-and-observers.html#events). - -### Layouts - -This module interacts with the following layouts and layout handles in the `view/adminhtml/layout` directory: - -- `braintree_paypal_review` -- `checkout_index_index` -- `multishipping_checkout_billing` -- `vault_cards_listaction` - -This module interacts with the following layout handles in the `view/frontend/layout` directory: - -- `adminhtml_system_config_edit` -- `braintree_report_index` -- `sales_order_create_index` -- `sales_order_create_load_block_billing_method` - -For more information about layouts in Magento 2, see the [Layout documentation](https://devdocs.magento.com/guides/v2.3/frontend-dev-guide/layouts/layout-overview.html). - -### UI components - -You can extend admin notifications using the `view/adminhtml/ui_component/braintree_report.xml` configuration file. - -For information about UI components in Magento 2, see [Overview of UI components](https://devdocs.magento.com/guides/v2.3/ui_comp_guide/bk-ui_comps.html). - -## Additional information - -For information about significant changes in patch releases, see [2.3.x Release information](https://devdocs.magento.com/guides/v2.3/release-notes/bk-release-notes.html). diff --git a/app/code/Magento/Braintree/Setup/Patch/Data/ConvertSerializedDataToJson.php b/app/code/Magento/Braintree/Setup/Patch/Data/ConvertSerializedDataToJson.php deleted file mode 100644 index d08bf62da8e4f..0000000000000 --- a/app/code/Magento/Braintree/Setup/Patch/Data/ConvertSerializedDataToJson.php +++ /dev/null @@ -1,111 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Setup\Patch\Data; - -use Magento\Framework\App\ResourceConnection; -use Magento\Framework\Setup\ModuleDataSetupInterface; -use Magento\Framework\Setup\Patch\DataPatchInterface; -use Magento\Framework\Setup\Patch\PatchVersionInterface; - -/** - * Convert data from php native serialized data to JSON. - */ -class ConvertSerializedDataToJson implements DataPatchInterface, PatchVersionInterface -{ - /** - * @var ModuleDataSetupInterface - */ - private $moduleDataSetup; - - /** - * @var \Magento\Framework\DB\FieldDataConverterFactory - */ - private $fieldDataConverterFactory; - - /** - * @var \Magento\Framework\DB\Select\QueryModifierFactory - */ - private $queryModifierFactory; - - /** - * ConvertSerializedDataToJson constructor. - * @param ModuleDataSetupInterface $moduleDataSetup - * @param \Magento\Framework\DB\FieldDataConverterFactory $fieldDataConverterFactory - * @param \Magento\Framework\DB\Select\QueryModifierFactory $queryModifierFactory - */ - public function __construct( - ModuleDataSetupInterface $moduleDataSetup, - \Magento\Framework\DB\FieldDataConverterFactory $fieldDataConverterFactory, - \Magento\Framework\DB\Select\QueryModifierFactory $queryModifierFactory - ) { - $this->moduleDataSetup = $moduleDataSetup; - $this->fieldDataConverterFactory = $fieldDataConverterFactory; - $this->queryModifierFactory = $queryModifierFactory; - } - - /** - * {@inheritdoc} - */ - public function apply() - { - $this->convertSerializedDataToJson(); - } - - /** - * Upgrade data to version 2.0.1, converts row data in the core_config_data table that uses the path - * payment/braintree/countrycreditcard from serialized to JSON - * - * @return void - */ - private function convertSerializedDataToJson() - { - $fieldDataConverter = $this->fieldDataConverterFactory->create( - \Magento\Framework\DB\DataConverter\SerializedToJson::class - ); - - $queryModifier = $this->queryModifierFactory->create( - 'in', - [ - 'values' => [ - 'path' => ['payment/braintree/countrycreditcard'] - ] - ] - ); - - $fieldDataConverter->convert( - $this->moduleDataSetup->getConnection(), - $this->moduleDataSetup->getTable('core_config_data'), - 'config_id', - 'value', - $queryModifier - ); - } - - /** - * {@inheritdoc} - */ - public static function getDependencies() - { - return []; - } - - /** - * {@inheritdoc} - */ - public static function getVersion() - { - return '2.0.1'; - } - - /** - * {@inheritdoc} - */ - public function getAliases() - { - return []; - } -} diff --git a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/AdminCreateNewRoleActionGroup.xml b/app/code/Magento/Braintree/Test/Mftf/ActionGroup/AdminCreateNewRoleActionGroup.xml deleted file mode 100644 index 29000563ee87f..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/AdminCreateNewRoleActionGroup.xml +++ /dev/null @@ -1,32 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="AdminCreateNewRoleActionGroup"> - <annotations> - <description>Creates a User Role using the provided Data.</description> - </annotations> - <arguments> - <argument name="role" type="string" defaultValue=""/> - <argument name="resource" type="string" defaultValue="All"/> - <argument name="scope" type="string" defaultValue="Custom"/> - <argument name="websites" type="string" defaultValue="Main Website"/> - </arguments> - - <click selector="{{AdminCreateRoleSection.create}}" stepKey="clickToAddNewRole"/> - <fillField selector="{{AdminCreateRoleSection.name}}" userInput="{{role.name}}" stepKey="setRoleName"/> - <fillField stepKey="setPassword" selector="{{AdminCreateRoleSection.password}}" userInput="{{_ENV.MAGENTO_ADMIN_PASSWORD}}"/> - <click selector="{{AdminCreateRoleSection.roleResources}}" stepKey="clickToOpenRoleResources"/> - <waitForPageLoad stepKey="waitForRoleResourcePage" time="5"/> - <click stepKey="checkSales" selector="//a[text()='Sales']"/> - <click selector="{{AdminCreateRoleSection.save}}" stepKey="clickToSaveRole"/> - <waitForPageLoad stepKey="waitForPageLoad" time="10"/> - <see userInput="You saved the role." stepKey="seeSuccessMessage"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/AdminOrderBraintreeFillActionGroup.xml b/app/code/Magento/Braintree/Test/Mftf/ActionGroup/AdminOrderBraintreeFillActionGroup.xml deleted file mode 100644 index 1e31a8a976094..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/AdminOrderBraintreeFillActionGroup.xml +++ /dev/null @@ -1,46 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="AdminOrderBraintreeFillActionGroup"> - <annotations> - <description>Fills in the Payment Method using Braintree details. PLEASE NOTE: The Braintree details are Hardcoded using 'PaymentAndShippingInfo'.</description> - </annotations> - - <!--Select Braintree Payment method on Admin Order Create Page--> - <click stepKey="chooseBraintree" selector="{{NewOrderSection.creditCardBraintree}}"/> - <waitForPageLoad stepKey="waitForBraintreeConfigs"/> - <click stepKey="openCardTypes" selector="{{NewOrderSection.openCardTypes}}"/> - <waitForPageLoad stepKey="waitForCardTypes"/> - <click stepKey="chooseCardType" selector="{{NewOrderSection.masterCard}}"/> - <waitForPageLoad stepKey="waitForCardSelected"/> - - <!--Choose Master Card from drop-down list--> - <switchToIFrame stepKey="switchToCardNumber" selector="{{NewOrderSection.cardFrame}}"/> - <waitForElementVisible selector="{{NewOrderSection.creditCardNumber}}" stepKey="waitForFillCardNumber"/> - <fillField stepKey="fillCardNumber" selector="{{NewOrderSection.creditCardNumber}}" userInput="{{PaymentAndShippingInfo.cardNumber}}"/> - <switchToIFrame stepKey="switchBackFromCard"/> - - <!--Fill expire date--> - <switchToIFrame stepKey="switchToExpirationMonth" selector="{{NewOrderSection.monthFrame}}"/> - <waitForElementVisible selector="{{NewOrderSection.expirationMonth}}" stepKey="waitForFillMonth"/> - <fillField stepKey="fillMonth" selector="{{NewOrderSection.expirationMonth}}" userInput="{{PaymentAndShippingInfo.month}}"/> - <switchToIFrame stepKey="switchBackFromMonth"/> - <switchToIFrame stepKey="switchToExpirationYear" selector="{{NewOrderSection.yearFrame}}"/> - <waitForElementVisible selector="{{NewOrderSection.expirationYear}}" stepKey="waitForFillYear"/> - <fillField stepKey="fillYear" selector="{{NewOrderSection.expirationYear}}" userInput="{{PaymentAndShippingInfo.year}}"/> - <switchToIFrame stepKey="switchBackFromYear"/> - - <!--Fill CVW code--> - <switchToIFrame stepKey="switchToCVV" selector="{{NewOrderSection.cvvFrame}}"/> - <waitForElementVisible selector="{{NewOrderSection.cvv}}" stepKey="waitForFillCVV"/> - <fillField stepKey="fillCVV" selector="{{NewOrderSection.cvv}}" userInput="{{PaymentAndShippingInfo.cvv}}"/> - <switchToIFrame stepKey="switchBackFromCVV"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/ConfigureBraintreeActionGroup.xml b/app/code/Magento/Braintree/Test/Mftf/ActionGroup/ConfigureBraintreeActionGroup.xml deleted file mode 100644 index 5e5f6d634caad..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/ConfigureBraintreeActionGroup.xml +++ /dev/null @@ -1,52 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="ConfigureBraintreeActionGroup"> - <annotations> - <description>Sets up the Braintree configuration setting using the BraintreeConfigurationSection Data Entity. PLEASE NOTE: The Action Group values are Hardcoded.</description> - </annotations> - - <!-- GoTo ConfigureBraintree fields --> - <click stepKey="clickOnSTORES" selector="{{AdminMenuSection.stores}}"/> - <waitForPageLoad stepKey="waitForConfiguration" time="2"/> - <click stepKey="clickOnConfigurations" selector="{{AdminMenuSection.configuration}}"/> - <waitForPageLoad stepKey="waitForSales" time="2"/> - <click stepKey="clickOnSales" selector="{{ConfigurationListSection.sales}}"/> - <waitForPageLoad stepKey="waitForPaymentMethods" time="2"/> - <click stepKey="clickOnPaymentMethods" selector="{{ConfigurationListSection.salesPaymentMethods}}"/> - <waitForPageLoad stepKey="waitForConfigureButton" time="2"/> - <click stepKey="clickOnConfigureButtonForBraintree" selector="{{ConfigurationPaymentSection.configureButton}}"/> - <waitForPageLoad stepKey="BraintreeSettings" time="2"/> - - <!-- Fill Braintree fields --> - <fillField stepKey="fillTitleForBraintreeSettings" selector="{{BraintreeConfiguraionSection.titleForBraintreeSettings}}" userInput="{{BraintreeConfigurationData.title}}"/> - <click stepKey="openEnvironmentSelect" selector="{{BraintreeConfiguraionSection.environment}}"/> - <click stepKey="chooseEnvironment" selector="{{BraintreeConfiguraionSection.sandbox}}"/> - <click stepKey="openPaymentActionSelect" selector="{{BraintreeConfiguraionSection.paymentActionSelect}}"/> - <click stepKey="choosePaymentAction" selector="{{BraintreeConfiguraionSection.paymentAction}}"/> - <fillField stepKey="fillMerchantID" selector="{{BraintreeConfiguraionSection.merchantID}}" userInput="{{BraintreeConfigurationData.merchantID}}"/> - <fillField stepKey="fillPublicKey" selector="{{BraintreeConfiguraionSection.publicKey}}" userInput="{{BraintreeConfigurationData.publicKey}}"/> - <fillField stepKey="fillPrivateKey" selector="{{BraintreeConfiguraionSection.privateKey}}" userInput="{{BraintreeConfigurationData.privateKey}}"/> - <click stepKey="expandEnableThisSolution" selector="{{BraintreeConfiguraionSection.enableThisSolution}}"/> - <click stepKey="chooseYesForEnableThisSolution" selector="{{BraintreeConfiguraionSection.yesForEnable}}"/> - <click stepKey="expandEnablePayPalThroughBraintree" selector="{{BraintreeConfiguraionSection.payPalThroughBraintree}}"/> - <click stepKey="chooseYesForEnablePayPalThroughBraintree" selector="{{BraintreeConfiguraionSection.yesForPayPalThroughBraintree}}"/> - <click stepKey="expandAdvancedBraintreeSettings" selector="{{BraintreeConfiguraionSection.advancedBraintreeSettings}}"/> - <fillField stepKey="fillMerchantAccountID" selector="{{BraintreeConfiguraionSection.merchantAccountID}}" userInput="{{BraintreeConfigurationData.merchantAccountID}}"/> - <click stepKey="expandCVVVerification" selector="{{BraintreeConfiguraionSection.CVVVerification}}"/> - <click stepKey="chooseYes" selector="{{BraintreeConfiguraionSection.yesForCVV}}"/> - <click stepKey="expandPayPalThroughBraintree" selector="{{BraintreeConfiguraionSection.payPalThroughBraintreeSelector}}"/> - <fillField stepKey="fillTitleForPayPalThroughBraintree" selector="{{BraintreeConfiguraionSection.titleForPayPalThroughBraintree}}" userInput="{{BraintreeConfigurationData.titleForPayPalThroughBraintree}}"/> - <click stepKey="expandPaymentAction" selector="{{BraintreeConfiguraionSection.paymentActionInPayPal}}"/> - <click stepKey="chooseAuthorize" selector="{{BraintreeConfiguraionSection.actionAuthorize}}"/> - <click stepKey="save" selector="{{BraintreeConfiguraionSection.save}}"/> - <waitForElementVisible selector="{{BraintreeConfiguraionSection.successfulMessage}}" stepKey="waitForSuccessfullyConfigured" time="10"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/DisableBraintreeActionGroup.xml b/app/code/Magento/Braintree/Test/Mftf/ActionGroup/DisableBraintreeActionGroup.xml deleted file mode 100644 index 9f8b7735fc067..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/DisableBraintreeActionGroup.xml +++ /dev/null @@ -1,19 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="DisableBraintreeActionGroup"> - <annotations> - <description>Disables the Braintree and BraintreePaypal configuration settings via the CLI.</description> - </annotations> - - <magentoCLI stepKey="disableBrainTree" command="config:set payment/braintree/active 0"/> - <magentoCLI stepKey="disableBrainTreePaypal" command="config:set payment/braintree_paypal/active 0"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/GoToAllUsersActionGroup.xml b/app/code/Magento/Braintree/Test/Mftf/ActionGroup/GoToAllUsersActionGroup.xml deleted file mode 100644 index f5cffbe81b509..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/GoToAllUsersActionGroup.xml +++ /dev/null @@ -1,21 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="GoToAllUsersActionGroup"> - <annotations> - <description>Navigate to the Users page via Backend Admin Side Menu. PLEASE NOTE: Use the amOnPage action instead.</description> - </annotations> - - <click selector="{{AdminCreateUserSection.system}}" stepKey="clickOnSystemIcon"/> - <waitForPageLoad stepKey="waitForSystemsPageToOpen"/> - <click selector="{{AdminCreateUserSection.allUsers}}" stepKey="clickToSelectUserRoles"/> - <waitForPageLoad stepKey="waitForUserRolesPageToOpen"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/GoToUserRolesActionGroup.xml b/app/code/Magento/Braintree/Test/Mftf/ActionGroup/GoToUserRolesActionGroup.xml deleted file mode 100644 index 43bdb3cb02c0d..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/GoToUserRolesActionGroup.xml +++ /dev/null @@ -1,21 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="GoToUserRolesActionGroup"> - <annotations> - <description>Navigate to the User Roles page via Backend Admin Side Menu. PLEASE NOTE: Use the amOnPage action instead.</description> - </annotations> - - <click selector="#menu-magento-backend-system" stepKey="clickOnSystemIcon"/> - <waitForPageLoad stepKey="waitForSystemsPageToOpen"/> - <click selector="//span[contains(text(), 'User Roles')]" stepKey="clickToSelectUserRoles"/> - <waitForPageLoad stepKey="waitForUserRolesPageToOpen"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/StorefrontFillCartDataActionGroup.xml b/app/code/Magento/Braintree/Test/Mftf/ActionGroup/StorefrontFillCartDataActionGroup.xml deleted file mode 100644 index 89e4bc7bca1b2..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/StorefrontFillCartDataActionGroup.xml +++ /dev/null @@ -1,36 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> - <actionGroup name="StorefrontFillCartDataActionGroup"> - <annotations> - <description>Fills Cart Data with Braintree using the provided Data Entity.</description> - </annotations> - <arguments> - <argument name="cartData" defaultValue="PaymentAndShippingInfo"/> - </arguments> - - <switchToIFrame selector="{{BraintreeConfigurationPaymentSection.cartFrame}}" stepKey="switchToIframe"/> - <waitForElementVisible selector="{{BraintreeConfigurationPaymentSection.cartCode}}" stepKey="waitCartCodeElement"/> - <fillField selector="{{BraintreeConfigurationPaymentSection.cartCode}}" userInput="{{cartData.cardNumber}}" stepKey="setCartCode"/> - <switchToIFrame stepKey="switchBack"/> - <switchToIFrame selector="{{BraintreeConfigurationPaymentSection.monthFrame}}" stepKey="switchToIframe1"/> - <waitForElementVisible selector="{{BraintreeConfigurationPaymentSection.month}}" stepKey="waitMonthElement"/> - <fillField selector="{{BraintreeConfigurationPaymentSection.month}}" userInput="{{cartData.month}}" stepKey="setMonth"/> - <switchToIFrame stepKey="switchBack1"/> - <switchToIFrame selector="{{BraintreeConfigurationPaymentSection.yearFrame}}" stepKey="switchToIframe2"/> - <waitForElementVisible selector="{{BraintreeConfigurationPaymentSection.year}}" stepKey="waitYearElement"/> - <fillField selector="{{BraintreeConfigurationPaymentSection.year}}" userInput="{{cartData.year}}" stepKey="setYear"/> - <switchToIFrame stepKey="switchBack2"/> - <switchToIFrame selector="{{BraintreeConfigurationPaymentSection.codeFrame}}" stepKey="switchToIframe3"/> - <waitForElementVisible selector="{{BraintreeConfigurationPaymentSection.verificationNumber}}" stepKey="waitVerificationNumber"/> - <fillField selector="{{BraintreeConfigurationPaymentSection.verificationNumber}}" userInput="{{cartData.cvv}}" stepKey="setVerificationNumber"/> - <switchToIFrame stepKey="SwitchBackToWindow"/> - </actionGroup> -</actionGroups> diff --git a/app/code/Magento/Braintree/Test/Mftf/Data/BraintreeData.xml b/app/code/Magento/Braintree/Test/Mftf/Data/BraintreeData.xml deleted file mode 100644 index cba402f8f43fc..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Data/BraintreeData.xml +++ /dev/null @@ -1,163 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> - <entity name="SampleBraintreeConfig" type="braintree_config_state"> - <requiredEntity type="title">SampleTitle</requiredEntity> - <requiredEntity type="payment_action">SamplePaymentAction</requiredEntity> - <requiredEntity type="environment">SampleEnvironment</requiredEntity> - <requiredEntity type="merchant_id">SampleMerchantId</requiredEntity> - <requiredEntity type="public_key">SamplePublicKey</requiredEntity> - <requiredEntity type="private_key">SamplePrivateKey</requiredEntity> - </entity> - <entity name="SampleTitle" type="title"> - <data key="value">Sample Braintree Config</data> - </entity> - <entity name="SamplePaymentAction" type="payment_action"> - <data key="value">authorize</data> - </entity> - <entity name="SampleEnvironment" type="environment"> - <data key="value">sandbox</data> - </entity> - <entity name="SampleMerchantId" type="merchant_id"> - <data key="value">someMerchantId</data> - </entity> - <entity name="SamplePublicKey" type="public_key"> - <data key="value">somePublicKey</data> - </entity> - <entity name="SamplePrivateKey" type="private_key"> - <data key="value">somePrivateKey</data> - </entity> - - <entity name="BraintreeConfig" type="braintree_config_state"> - <requiredEntity type="title">BraintreeTitle</requiredEntity> - <requiredEntity type="payment_action">PaymentAction</requiredEntity> - <requiredEntity type="environment">Environment</requiredEntity> - <requiredEntity type="merchant_id">MerchantId</requiredEntity> - <requiredEntity type="public_key">PublicKey</requiredEntity> - <requiredEntity type="private_key">PrivateKey</requiredEntity> - <requiredEntity type="active">Status</requiredEntity> - </entity> - <entity name="BraintreeTitle" type="title"> - <data key="value">Credit Card (Braintree)</data> - </entity> - <entity name="PaymentAction" type="payment_action"> - <data key="value">authorize</data> - </entity> - <entity name="Environment" type="environment"> - <data key="value">sandbox</data> - </entity> - <entity name="MerchantId" type="merchant_id"> - <data key="value">{{_CREDS.magento/braintree_enabled_fraud_merchant_id}}</data> - </entity> - <entity name="PublicKey" type="public_key"> - <data key="value">{{_CREDS.magento/braintree_enabled_fraud_public_key}}</data> - </entity> - <entity name="PrivateKey" type="private_key"> - <data key="value">{{_CREDS.magento/braintree_enabled_fraud_private_key}}</data> - </entity> - - <!-- default configuration used to restore Magento config --> - <entity name="DefaultBraintreeConfig" type="braintree_config_state"> - <requiredEntity type="title">DefaultTitle</requiredEntity> - <requiredEntity type="payment_action">DefaultPaymentAction</requiredEntity> - <requiredEntity type="environment">DefaultEnvironment</requiredEntity> - <requiredEntity type="merchant_id">DefaultMerchantId</requiredEntity> - <requiredEntity type="public_key">DefaultPublicKey</requiredEntity> - <requiredEntity type="private_key">DefaultPrivateKey</requiredEntity> - </entity> - <entity name="DefaultTitle" type="title"> - <data key="value"/> - </entity> - <entity name="DefaultPaymentAction" type="payment_action"> - <data key="value"/> - </entity> - <entity name="DefaultEnvironment" type="environment"> - <data key="value"/> - </entity> - <entity name="DefaultMerchantId" type="merchant_id"> - <data key="value"/> - </entity> - <entity name="DefaultPublicKey" type="public_key"> - <data key="value"/> - </entity> - <entity name="DefaultPrivateKey" type="private_key"> - <data key="value"/> - </entity> - - <entity name="CustomBraintreeConfigurationData" type="custom_braintree_config_state"> - <requiredEntity type="braintree_cc_vault_active">BraintreeValuteActive</requiredEntity> - <requiredEntity type="active">EnableSolution</requiredEntity> - </entity> - <entity name="BraintreeValuteActive" type="braintree_cc_vault_active"> - <data key="value">1</data> - </entity> - <entity name="EnableSolution" type="active"> - <data key="value">1</data> - </entity> - - <entity name="RollBackCustomBraintreeConfigurationData" type="custom_braintree_config_state"> - <requiredEntity type="braintree_cc_vault_active">DefaultBraintreeValuteActive</requiredEntity> - <requiredEntity type="active">DefaultEnableSolution</requiredEntity> - </entity> - <entity name="DefaultBraintreeValuteActive" type="braintree_cc_vault_active"> - <data key="value">0</data> - </entity> - <entity name="DefaultEnableSolution" type="active"> - <data key="value">0</data> - </entity> - - <entity name="testData" type="data"> - <data key="websiteName" unique="suffix">Website</data> - <data key="websiteCode" unique="suffix">new_website</data> - <data key="name" unique="suffix">Store</data> - <data key="storeCode" unique="suffix">new_store</data> - <data key="block" unique="suffix">Block</data> - </entity> - - <entity name="role" type="data"> - <data key="name" unique="suffix">Role</data> - </entity> - <entity name="NewAdmin" type="user"> - <data key="username" unique="suffix">admin</data> - <data key="firstName">John</data> - <data key="lastName">Smith</data> - <data key="password">admin123</data> - <data key="email" unique="prefix">mail@mail.com</data> - </entity> - - <entity name="PaymentAndShippingInfo" type="data"> - <data key="cardNumber">5105105105105100</data> - <data key="month">12</data> - <data key="year">20</data> - <data key="cvv">113</data> - </entity> - <entity name="StoredPaymentMethods"> - <data key="cardNumberEnding">5100</data> - <data key="cardExpire">12/2020</data> - </entity> - <entity name="VisaDefaultCard" type="data"> - <data key="cardNumber">4111111111111111</data> - <data key="month">01</data> - <data key="year">30</data> - <data key="cvv">123</data> - </entity> - <entity name="VisaDefaultCardInfo"> - <data key="cardNumberEnding">1111</data> - <data key="cardExpire">01/2030</data> - </entity> - - <entity name="BraintreeConfigurationData" type="data"> - <data key="title">Credit Card (Braintree)</data> - <data key="merchantID">MERCH_ID</data> - <data key="publicKey">PUBLIC_KEY</data> - <data key="privateKey">PRIVATE_KEY</data> - <data key="merchantAccountID">MERCH_ACCOUNT_ID</data> - <data key="titleForPayPalThroughBraintree">PayPal (Braintree)</data> - </entity> -</entities> diff --git a/app/code/Magento/Braintree/Test/Mftf/Data/ConfigData.xml b/app/code/Magento/Braintree/Test/Mftf/Data/ConfigData.xml deleted file mode 100644 index a5bc8b7d8054c..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Data/ConfigData.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<entities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataProfileSchema.xsd"> - <entity name="Enable3DSecureBraintree"> - <data key="path">payment/braintree/verify_3dsecure</data> - <data key="value">1</data> - </entity> - <entity name="Disable3DSecureBraintree"> - <data key="path">payment/braintree/verify_3dsecure</data> - <data key="value">0</data> - </entity> - <entity name="DisableVaultBraintree"> - <data key="path">payment/braintree_cc_vault/active</data> - <data key="value">0</data> - </entity> -</entities> diff --git a/app/code/Magento/Braintree/Test/Mftf/Metadata/BraintreeConfigMeta.xml b/app/code/Magento/Braintree/Test/Mftf/Metadata/BraintreeConfigMeta.xml deleted file mode 100644 index 5e3b870d65c67..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Metadata/BraintreeConfigMeta.xml +++ /dev/null @@ -1,63 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<operations xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:DataGenerator/etc/dataOperation.xsd"> - <operation name="CreateBraintreeConfigState" dataType="braintree_config_state" type="create" auth="adminFormKey" url="/admin/system_config/save/section/payment/" method="POST"> - <object key="groups" dataType="braintree_config_state"> - <object key="braintree_section" dataType="braintree_config_state"> - <object key="groups" dataType="braintree_config_state"> - <object key="braintree" dataType="braintree_config_state"> - <object key="groups" dataType="braintree_config_state"> - <object key="braintree_required" dataType="braintree_config_state"> - <object key="fields" dataType="braintree_config_state"> - <object key="title" dataType="title"> - <field key="value">string</field> - </object> - <object key="environment" dataType="environment"> - <field key="value">string</field> - </object> - <object key="payment_action" dataType="payment_action"> - <field key="value">string</field> - </object> - <object key="merchant_id" dataType="merchant_id"> - <field key="value">string</field> - </object> - <object key="public_key" dataType="public_key"> - <field key="value">string</field> - </object> - <object key="private_key" dataType="private_key"> - <field key="value">string</field> - </object> - </object> - </object> - </object> - </object> - </object> - </object> - </object> - </operation> - <operation name="CustomBraintreeConfigState" dataType="custom_braintree_config_state" type="create" auth="adminFormKey" url="/admin/system_config/save/section/payment/" method="POST"> - <object key="groups" dataType="custom_braintree_config_state"> - <object key="braintree_section" dataType="custom_braintree_config_state"> - <object key="groups" dataType="custom_braintree_config_state"> - <object key="braintree" dataType="custom_braintree_config_state"> - <object key="fields" dataType="custom_braintree_config_state"> - <object key="braintree_cc_vault_active" dataType="braintree_cc_vault_active"> - <field key="value">integer</field> - </object> - <object key="active" dataType="active"> - <field key="value">string</field> - </object> - </object> - </object> - </object> - </object> - </object> - </operation> -</operations> diff --git a/app/code/Magento/Braintree/Test/Mftf/README.md b/app/code/Magento/Braintree/Test/Mftf/README.md deleted file mode 100644 index 6ee177a9cdcd2..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Braintree Functional Tests - -The Functional Test Module for **Magento Braintree** module. diff --git a/app/code/Magento/Braintree/Test/Mftf/Section/AdminEditRoleInfoSection.xml b/app/code/Magento/Braintree/Test/Mftf/Section/AdminEditRoleInfoSection.xml deleted file mode 100644 index a34cdf15e7ad7..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Section/AdminEditRoleInfoSection.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminEditRoleInfoSection"> - <element name="roleName" type="input" selector="#role_name"/> - <element name="password" type="input" selector="#current_password"/> - <element name="roleResourcesTab" type="button" selector="#role_info_tabs_account"/> - <element name="backButton" type="button" selector="button[title='Back']"/> - <element name="resetButton" type="button" selector="button[title='Reset']"/> - <element name="deleteButton" type="button" selector="button[title='Delete Role']"/> - <element name="saveButton" type="button" selector="button[title='Save Role']"/> - <element name="message" type="text" selector=".modal-popup.confirm div.modal-content"/> - <element name="cancel" type="button" selector=".modal-popup.confirm button.action-dismiss"/> - <element name="ok" type="button" selector=".modal-popup.confirm button.action-accept" timeout="60"/> - </section> -</sections> diff --git a/app/code/Magento/Braintree/Test/Mftf/Section/AdminEditUserRoleSection.xml b/app/code/Magento/Braintree/Test/Mftf/Section/AdminEditUserRoleSection.xml deleted file mode 100644 index 216292b81162c..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Section/AdminEditUserRoleSection.xml +++ /dev/null @@ -1,19 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminEditUserRoleSection"> - <element name="usernameTextField" type="input" selector="#user_username"/> - <element name="roleNameFilterTextField" type="input" selector="#permissionsUserRolesGrid_filter_role_name"/> - <element name="searchButton" type="button" selector=".admin__data-grid-header button[title=Search]"/> - <element name="resetButton" type="button" selector="button[title='Reset Filter']"/> - <element name="roleNameInFirstRow" type="text" selector=".col-role_name"/> - <element name="searchResultFirstRow" type="text" selector=".data-grid>tbody>tr"/> - </section> -</sections> diff --git a/app/code/Magento/Braintree/Test/Mftf/Section/AdminEditUserSection.xml b/app/code/Magento/Braintree/Test/Mftf/Section/AdminEditUserSection.xml deleted file mode 100644 index cee262864d8ca..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Section/AdminEditUserSection.xml +++ /dev/null @@ -1,30 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminEditUserSection"> - <element name="system" type="input" selector="#menu-magento-backend-system"/> - <element name="allUsers" type="input" selector="//span[contains(text(), 'All Users')]"/> - <element name="create" type="input" selector="#add"/> - <element name="usernameTextField" type="input" selector="#user_username"/> - <element name="firstNameTextField" type="input" selector="#user_firstname"/> - <element name="lastNameTextField" type="input" selector="#user_lastname"/> - <element name="emailTextField" type="input" selector="#user_email"/> - <element name="passwordTextField" type="input" selector="#user_password"/> - <element name="pwConfirmationTextField" type="input" selector="#user_confirmation"/> - <element name="currentPasswordField" type="input" selector="#user_current_password"/> - <element name="userRoleTab" type="button" selector="#page_tabs_roles_section"/> - <element name="roleNameFilterTextField" type="input" selector="#permissionsUserRolesGrid_filter_role_name"/> - <element name="searchButton" type="button" selector=".admin__data-grid-header button[title=Search]"/> - <element name="resetButton" type="button" selector="button[title='Reset Filter']"/> - <element name="roleNameInFirstRow" type="text" selector=".col-role_name"/> - <element name="searchResultFirstRow" type="text" selector=".data-grid>tbody>tr"/> - <element name="saveButton" type="button" selector="#save"/> - </section> -</sections> diff --git a/app/code/Magento/Braintree/Test/Mftf/Section/AdminMenuSection.xml b/app/code/Magento/Braintree/Test/Mftf/Section/AdminMenuSection.xml deleted file mode 100644 index 24e5efdc610ff..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Section/AdminMenuSection.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminMenuSection"> - <element name="dashboard" type="button" selector="//li[@id='menu-magento-backend-dashboard']"/> - <element name="sales" type="button" selector="//li[@id='menu-magento-sales-sales']"/> - <element name="catalog" type="button" selector="//li[@id='menu-magento-catalog-catalog']"/> - <element name="customers" type="button" selector="//li[@id='menu-magento-customer-customer']"/> - <element name="marketing" type="button" selector="//li[@id='menu-magento-backend-marketing']"/> - <element name="content" type="button" selector="//li[@id='menu-magento-backend-content']"/> - <element name="reports" type="button" selector="//li[@id='menu-magento-reports-report']"/> - <element name="stores" type="button" selector="//li[@id='menu-magento-backend-stores']"/> - <element name="system" type="button" selector="//li[@id='menu-magento-backend-system']"/> - <element name="findPartners" type="button" selector="//li[@id='menu-magento-marketplace-partners']"/> - </section> -</sections> diff --git a/app/code/Magento/Braintree/Test/Mftf/Section/AdminRoleGridSection.xml b/app/code/Magento/Braintree/Test/Mftf/Section/AdminRoleGridSection.xml deleted file mode 100644 index 1cf54bf94e772..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Section/AdminRoleGridSection.xml +++ /dev/null @@ -1,19 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="AdminRoleGridSection"> - <element name="idFilterTextField" type="input" selector="#roleGrid_filter_role_id"/> - <element name="roleNameFilterTextField" type="input" selector="#roleGrid_filter_role_name"/> - <element name="searchButton" type="button" selector=".admin__data-grid-header button[title=Search]"/> - <element name="resetButton" type="button" selector="button[title='Reset Filter']"/> - <element name="roleNameInFirstRow" type="text" selector=".col-role_name"/> - <element name="searchResultFirstRow" type="text" selector=".data-grid>tbody>tr"/> - </section> -</sections> diff --git a/app/code/Magento/Braintree/Test/Mftf/Section/BraintreeConfiguraionSection.xml b/app/code/Magento/Braintree/Test/Mftf/Section/BraintreeConfiguraionSection.xml deleted file mode 100644 index f8802e9a34ae5..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Section/BraintreeConfiguraionSection.xml +++ /dev/null @@ -1,35 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="BraintreeConfiguraionSection"> - <element name="titleForBraintreeSettings" type="input" selector="//input[@id='payment_us_braintree_section_braintree_braintree_required_title']"/> - <element name="environment" type="select" selector="//select[@id='payment_us_braintree_section_braintree_braintree_required_environment']"/> - <element name="sandbox" type="select" selector="//select[@id='payment_us_braintree_section_braintree_braintree_required_environment']/option[text()='Sandbox']"/> - <element name="paymentActionSelect" type="select" selector="//select[@id='payment_us_braintree_section_braintree_braintree_required_payment_action']"/> - <element name="paymentAction" type="button" selector="//select[@id='payment_us_braintree_section_braintree_braintree_required_payment_action']/option[text()='Authorize']"/> - <element name="merchantID" type="input" selector="//input[@id='payment_us_braintree_section_braintree_braintree_required_merchant_id']"/> - <element name="publicKey" type="input" selector="//input[@id='payment_us_braintree_section_braintree_braintree_required_public_key']"/> - <element name="privateKey" type="input" selector="//input[@id='payment_us_braintree_section_braintree_braintree_required_private_key']"/> - <element name="enableThisSolution" type="select" selector="//select[@id='payment_us_braintree_section_braintree_active']"/> - <element name="yesForEnable" type="button" selector="//select[@id='payment_us_braintree_section_braintree_active']/option[text()='Yes']"/> - <element name="payPalThroughBraintree" type="select" selector="//select[@id='payment_us_braintree_section_braintree_active_braintree_paypal']"/> - <element name="yesForPayPalThroughBraintree" type="input" selector="//select[@id='payment_us_braintree_section_braintree_active_braintree_paypal']/option[text()='Yes']"/> - <element name="advancedBraintreeSettings" type="button" selector="//a[@id='payment_us_braintree_section_braintree_braintree_advanced-head']"/> - <element name="merchantAccountID" type="text" selector="//input[@id='payment_us_braintree_section_braintree_braintree_advanced_merchant_account_id']"/> - <element name="CVVVerification" type="text" selector="//select[@id='payment_us_braintree_section_braintree_braintree_advanced_useccv']"/> - <element name="yesForCVV" type="text" selector="//select[@id='payment_us_braintree_section_braintree_braintree_advanced_useccv']/option[text()='Yes']"/> - <element name="payPalThroughBraintreeSelector" type="text" selector="//a[@id='payment_us_braintree_section_braintree_braintree_paypal-head']"/> - <element name="titleForPayPalThroughBraintree" type="text" selector="//input[@id='payment_us_braintree_section_braintree_braintree_paypal_title']"/> - <element name="paymentActionInPayPal" type="text" selector="//select[@id='payment_us_braintree_section_braintree_braintree_paypal_payment_action']"/> - <element name="actionAuthorize" type="text" selector="//select[@id='payment_us_braintree_section_braintree_braintree_paypal_payment_action']/option[text()='Authorize']"/> - <element name="save" type="button" selector="//span[text()='Save Config']"/> - <element name="successfulMessage" type="text" selector="//*[@data-ui-id='messages-message-success']"/> - </section> -</sections> diff --git a/app/code/Magento/Braintree/Test/Mftf/Section/BraintreeConfigurationPaymentSection.xml b/app/code/Magento/Braintree/Test/Mftf/Section/BraintreeConfigurationPaymentSection.xml deleted file mode 100644 index 37d5204efb2c1..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Section/BraintreeConfigurationPaymentSection.xml +++ /dev/null @@ -1,24 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="BraintreeConfigurationPaymentSection"> - <element name="creditCart" type="radio" selector="#braintree"/> - <element name="paymentMethodContainer" type="block" selector=".payment-method-braintree"/> - <element name="paymentMethod" type="radio" selector="//div[@class='payment-group']//input[contains(@id, 'braintree_cc_vault_')]"/> - <element name="cartFrame" type="iframe" selector="braintree-hosted-field-number"/> - <element name="monthFrame" type="iframe" selector="braintree-hosted-field-expirationMonth"/> - <element name="yearFrame" type="iframe" selector="braintree-hosted-field-expirationYear"/> - <element name="codeFrame" type="iframe" selector="braintree-hosted-field-cvv"/> - <element name="cartCode" type="input" selector="#credit-card-number"/> - <element name="month" type="input" selector="#expiration-month"/> - <element name="year" type="input" selector="#expiration-year"/> - <element name="verificationNumber" type="input" selector="#cvv"/> - </section> -</sections> diff --git a/app/code/Magento/Braintree/Test/Mftf/Section/ConfigurationPaymentSection.xml b/app/code/Magento/Braintree/Test/Mftf/Section/ConfigurationPaymentSection.xml deleted file mode 100644 index 2192dd935c331..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Section/ConfigurationPaymentSection.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="ConfigurationPaymentSection"> - <element name="configureButton" type="button" selector="//button[@id='payment_us_braintree_section_braintree-head']"/> - </section> -</sections> diff --git a/app/code/Magento/Braintree/Test/Mftf/Section/StoresSubmenuSection.xml b/app/code/Magento/Braintree/Test/Mftf/Section/StoresSubmenuSection.xml deleted file mode 100644 index 806762f826462..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Section/StoresSubmenuSection.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> - <section name="StoresSubmenuSection"> - <element name="configuration" type="button" selector="//li[@id='menu-magento-backend-stores']//li[@data-ui-id='menu-magento-config-system-config']"/> - </section> -</sections> diff --git a/app/code/Magento/Braintree/Test/Mftf/Test/BraintreeCreditCardOnCheckoutTest.xml b/app/code/Magento/Braintree/Test/Mftf/Test/BraintreeCreditCardOnCheckoutTest.xml deleted file mode 100644 index f06e63a2a29c1..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Test/BraintreeCreditCardOnCheckoutTest.xml +++ /dev/null @@ -1,123 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="BraintreeCreditCardOnCheckoutTest"> - <annotations> - <features value="Braintree"/> - <stories value="MAGETWO-91624 - Braintree saved cards use billing address the same as shipping"/> - <title value="Use saved for Braintree credit card on checkout with selecting billing address"/> - <description value="Use saved for Braintree credit card on checkout with selecting billing address"/> - <severity value="MAJOR"/> - <testCaseId value="MAGETWO-93767"/> - <group value="braintree"/> - <skip> - <issueId value="MQE-1576"/> - </skip> - </annotations> - - <before> - <createData entity="_defaultCategory" stepKey="category"/> - <createData entity="SimpleProduct" stepKey="product"> - <requiredEntity createDataKey="category"/> - </createData> - <createData entity="Simple_US_Customer" stepKey="customer"/> - <createData entity="BraintreeConfig" stepKey="BraintreeConfigurationData"/> - <createData entity="CustomBraintreeConfigurationData" stepKey="CustomBraintreeConfigurationData"/> - <magentoCron stepKey="runCronIndex" groups="index"/> - </before> - - <after> - <deleteData createDataKey="product" stepKey="deleteProduct1"/> - <deleteData createDataKey="customer" stepKey="deleteCustomer"/> - <deleteData createDataKey="category" stepKey="deleteCategory"/> - <createData entity="DefaultBraintreeConfig" stepKey="DefaultBraintreeConfig"/> - <createData entity="RollBackCustomBraintreeConfigurationData" stepKey="RollBackCustomBraintreeConfigurationData"/> - <actionGroup ref="StorefrontSignOutActionGroup" stepKey="StorefrontSignOutActionGroup"/> - </after> - <!--Go to storefront--> - <amOnPage url="" stepKey="DoToStorefront"/> - <!--Create account--> - <actionGroup ref="StorefrontOpenCustomerAccountCreatePageActionGroup" stepKey="openCreateAccountPage"/> - <actionGroup ref="StorefrontFillCustomerAccountCreationFormActionGroup" stepKey="fillCreateAccountForm"> - <argument name="customer" value="Simple_US_Customer"/> - </actionGroup> - <actionGroup ref="StorefrontClickCreateAnAccountCustomerAccountCreationFormActionGroup" stepKey="submitCreateAccountForm"/> - <actionGroup ref="AssertMessageCustomerCreateAccountActionGroup" stepKey="seeSuccessMessage"> - <argument name="messageType" value="success"/> - <argument name="message" value="Thank you for registering with Main Website Store."/> - </actionGroup> - <!--Add product to cart--> - <amOnPage url="$$product.sku$$.html" stepKey="goToProductPage"/> - <waitForPageLoad stepKey="waitForPageLoad"/> - <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart"/> - <waitForPageLoad stepKey="waitForPageLoad1"/> - <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage"/> - <!--Proceed to checkout--> - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="GoToCheckoutFromMinicartActionGroup"/> - - <actionGroup ref="LoggedInCheckoutFillNewBillingAddressActionGroup" stepKey="LoggedInCheckoutFillNewBillingAddressActionGroup"> - <argument name="Address" value="US_Address_CA"/> - </actionGroup> - <waitForPageLoad stepKey="waitForPageLoad2"/> - <click selector="{{CheckoutShippingSection.next}}" stepKey="clickNext"/> - <waitForElement selector="{{CheckoutPaymentSection.paymentSectionTitle}}" time="30" stepKey="waitForPaymentSectionLoaded"/> - <!--Fill cart data--> - <click selector="{{BraintreeConfigurationPaymentSection.creditCart}}" stepKey="SelectBraintreePaymentMethod"/> - <waitForPageLoad stepKey="waitForPageLoad3"/> - <scrollTo selector="{{BraintreeConfigurationPaymentSection.creditCart}}" stepKey="ScrollToCreditCardSection"/> - <actionGroup ref="StorefrontFillCartDataActionGroup" stepKey="StorefrontFillCartDataActionGroup"/> - <waitForPageLoad stepKey="waitForPageLoad4"/> - <!--Place order--> - <click selector="{{BraintreeConfigurationPaymentSection.paymentMethodContainer}}{{CheckoutPaymentSection.placeOrder}}" - stepKey="PlaceOrder"/> - <waitForPageLoad stepKey="waitForPageLoad5"/> - - <!--Add product to cart again--> - <amOnPage url="$$product.sku$$.html" stepKey="goToProductPage1"/> - <waitForPageLoad stepKey="waitForPageLoad6"/> - <click selector="{{StorefrontProductActionSection.addToCart}}" stepKey="addProductToCart1"/> - <waitForPageLoad stepKey="waitForPageLoad7"/> - <waitForElementVisible selector="{{StorefrontMessagesSection.success}}" stepKey="waitForSuccessMessage2"/> - <!--Proceed to checkout--> - <actionGroup ref="GoToCheckoutFromMinicartActionGroup" stepKey="GoToCheckoutFromMinicartActionGroup1"/> - <click selector="{{CheckoutPaymentSection.addressAction('New Address')}}" stepKey="clickOnNewAddress"/> - <waitForPageLoad stepKey="waitForPageLoad8"/> - <actionGroup ref="LoggedInCheckoutFillNewBillingAddressActionGroup" stepKey="LoggedInCheckoutFillNewBillingAddressActionGroup1"> - <argument name="Address" value="US_Address_NY"/> - </actionGroup> - <click selector="{{CheckoutPaymentSection.addressAction('Ship here')}}" stepKey="SaveAddress"/> - <waitForPageLoad stepKey="waitForPageLoad9"/> - <click selector="{{CheckoutShippingSection.next}}" stepKey="clickNext1"/> - <waitForPageLoad stepKey="waitForPageLoad10"/> - <click selector="{{BraintreeConfigurationPaymentSection.paymentMethod}}" stepKey="SelectBraintreePaymentMethod1"/> - <waitForPageLoad stepKey="waitForPageLoad11"/> - <!--Place order--> - <click selector="{{CheckoutPaymentSection.placeOrder}}" stepKey="PlaceOrder1"/> - <waitForPageLoad stepKey="waitForPageLoad13"/> - - <click selector="{{CheckoutOrderSummarySection.orderNumber}}" stepKey="ClickOnOrderNumber"/> - <waitForPageLoad stepKey="waitForPageLoad14"/> - <!--Check billing and shipping addresses also additional Address info--> - <click selector="{{CheckoutPaymentSection.addressBook}}" stepKey="goToAddressBook"/> - <grabTextFrom selector="{{CheckoutOrderSummarySection.shippingAddress}}" stepKey="shippingAddr"/> - <grabTextFrom selector="{{CheckoutOrderSummarySection.billingAddress}}" stepKey="billingAddr"/> - <grabTextFrom selector="{{CheckoutOrderSummarySection.additionalAddress}}" stepKey="additionalAddress"/> - <see userInput="Shipping Address" stepKey="seeShippingAddress"/> - <see userInput="Billing Address" stepKey="seeBillingAddress"/> - <assertEquals stepKey="assertValuesAreEqual"> - <actualResult type="const">$billingAddr</actualResult> - <expectedResult type="const">$shippingAddr</expectedResult> - </assertEquals> - <assertNotEquals stepKey="assertValuesAreNotEqual"> - <actualResult type="const">$billingAddr</actualResult> - <expectedResult type="const">$additionalAddress</expectedResult> - </assertNotEquals> - </test> -</tests> diff --git a/app/code/Magento/Braintree/Test/Mftf/Test/CreateAnAdminOrderUsingBraintreePaymentTest.xml b/app/code/Magento/Braintree/Test/Mftf/Test/CreateAnAdminOrderUsingBraintreePaymentTest.xml deleted file mode 100644 index 3052bba3c5ae9..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Test/CreateAnAdminOrderUsingBraintreePaymentTest.xml +++ /dev/null @@ -1,114 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="CreateAnAdminOrderUsingBraintreePaymentTest1Test"> - <annotations> - <features value="Backend"/> - <stories value="Creation an admin order using Braintree payment"/> - <title value="Create order using Braintree payment"/> - <description value="Admin should be able to create order using Braintree payment"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-93677"/> - <group value="braintree"/> - <skip> - <issueId value="MQE-1576"/> - </skip> - </annotations> - <before> - <!--Login As Admin--> - <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> - - <!--CreateNewProduct--> - <createData entity="_defaultCategory" stepKey="createCategory"/> - <createData entity="_defaultProduct" stepKey="createProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!--Create New Customer--> - <createData stepKey="createCustomer" entity="Simple_US_Customer"/> - <magentoCron stepKey="runCronIndex" groups="index"/> - </before> - - - <!--Configure Braintree--> - <actionGroup ref="ConfigureBraintreeActionGroup" stepKey="configureBraintree"/> - - <!--Create New Role--> - <actionGroup ref="GoToUserRolesActionGroup" stepKey="GoToUserRoles"/> - <waitForPageLoad stepKey="waitForAllRoles" time="15"/> - <actionGroup ref="AdminCreateNewRoleActionGroup" stepKey="AdminCreateNewRole"/> - - <!--Create new admin user--> - <actionGroup ref="GoToAllUsersActionGroup" stepKey="GoToAllUsers"/> - <waitForPageLoad stepKey="waitForUsers" time="15"/> - <actionGroup ref="AdminCreateUserActionGroup" stepKey="AdminCreateNewUser"> - <argument name="role" value="role"/> - <argument name="User" value="NewAdmin"/> - </actionGroup> - - <!--SignOut--> - <actionGroup ref="AdminLogoutActionGroup" stepKey="signOutFromAdmin"/> - - <!--Log in as new user--> - <actionGroup ref="LoginNewUser" stepKey="signInNewUser"/> - <waitForPageLoad stepKey="waitForLogin" time="3"/> - - <!--Create New Order--> - <actionGroup ref="NavigateToNewOrderPageExistingCustomerActionGroup" stepKey="navigateToNewOrder"> - <argument name="customer" value="Simple_US_Customer"/> - </actionGroup> - - <!--Add Product to Order--> - <actionGroup ref="AddSimpleProductToOrderActionGroup" stepKey="addProduct"> - <argument name="product" value="_defaultProduct"/> - </actionGroup> - - <!--Fill Order Customer Information--> - <actionGroup ref="FillOrderCustomerInformationActionGroup" stepKey="fillCustomerAddress"> - <argument name="customer" value="Simple_US_Customer"/> - <argument name="address" value="US_Address_TX"/> - </actionGroup> - - <!--Select Shipping--> - <actionGroup ref="OrderSelectFlatRateShippingActionGroup" stepKey="selectFlatRateShipping"/> - <waitForPageLoad stepKey="waitForShippingToFinish"/> - - <!--Pay with Braintree --> - <actionGroup ref="useBraintreeForMasterCard" stepKey="selectCardWithBraintree"/> - - <!--Submit Order--> - <click stepKey="submitOrder" selector="{{NewOrderSection.submitOrder}}"/> - <waitForPageLoad stepKey="waitForSaveConfig"/> - <waitForElementVisible selector="{{NewOrderSection.successMessage}}" stepKey="waitForSuccessMessage"/> - - <after> - <!-- Disable BrainTree --> - <actionGroup ref="DisableBraintreeActionGroup" stepKey="disableBrainTree"/> - - <!--SignOut--> - <actionGroup ref="SignOut" stepKey="signOutFromNewUser"/> - <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> - - <!--Delete Product--> - <deleteData stepKey="deleteProduct" createDataKey="createProduct"/> - - <!--Delete Customer--> - <deleteData stepKey="deleteCustomer" createDataKey="createCustomer"/> - - <!--Delete User --> - <actionGroup ref="GoToAllUsersActionGroup" stepKey="GoBackToAllUsers"/> - <actionGroup ref="AdminDeleteNewUserActionGroup" stepKey="AdminDeleteUserActionGroup"/> - - <!--Delete Role--> - <actionGroup ref="GoToUserRolesActionGroup" stepKey="GoBackToUserRoles"/> - <actionGroup ref="AdminDeleteRoleActionGroup" stepKey="AdminDeleteRoleActionGroup"/> - </after> - </test> -</tests> diff --git a/app/code/Magento/Braintree/Test/Mftf/Test/CretateAdminOrderWithOnlinePaymentIncludingTaxAndDiscountTest.xml b/app/code/Magento/Braintree/Test/Mftf/Test/CretateAdminOrderWithOnlinePaymentIncludingTaxAndDiscountTest.xml deleted file mode 100644 index 9a843370f2c8e..0000000000000 --- a/app/code/Magento/Braintree/Test/Mftf/Test/CretateAdminOrderWithOnlinePaymentIncludingTaxAndDiscountTest.xml +++ /dev/null @@ -1,133 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - /** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> - -<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/testSchema.xsd"> - <test name="CreateAdminOrderPayedWithOnlinePaymentIncludingTaxAndDiscountTest"> - <annotations> - <features value="Braintree"/> - <stories value="Get access to a New Credit Memo Page from Invoice for Order payed with online payment via Admin"/> - <title value="Admin should be able to open a New Credit Memo Page from Invoice Page for Order with tax and discount and payed using online payment method"/> - <description value="Admin should be able to open a New Credit Memo Page from Invoice Page for Order with tax and discount and payed using online payment method"/> - <severity value="CRITICAL"/> - <testCaseId value="MAGETWO-94472"/> - <group value="braintree"/> - <skip> - <issueId value="MQE-1576"/> - </skip> - </annotations> - - <before> - <!--Create Default Category--> - <createData entity="SimpleSubCategory" stepKey="createCategory"/> - - <!--Create Simple product--> - <createData entity="_defaultProduct" stepKey="simpleProduct"> - <requiredEntity createDataKey="createCategory"/> - </createData> - - <!--Create Tax Rule is based on default tax rates (Stores>Tax Rule) US-CA-*-Rate 1 = 8.2500 US-NY-*-Rate 1 = 8.3750 --> - <createData entity="SimpleTaxRule" stepKey="createTaxRule"/> - - <!--Configure Braintree Payment method--> - <createData entity="BraintreeConfig" stepKey="BraintreeConfigurationData"/> - <createData entity="CustomBraintreeConfigurationData" stepKey="enableBraintree"/> - - <!--Create Retailer Customer with US_CA address--> - <createData entity="Simple_US_Customer_CA" stepKey="simpleCustomer"> - <field key="group_id">3</field> - </createData> - - <magentoCron stepKey="runCronIndex" groups="index"/> - - <!--Login as Admin User--> - <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> - </before> - - <after> - <!--Delete Cart Price Rule--> - <actionGroup ref="AdminDeleteCartPriceRuleForRetailerActionGroup" stepKey="deleteSalesRule"/> - - <!--Set to default configuration Tax Shipping Class--> - <actionGroup ref="setDefaultShippingTaxClass" stepKey="setdefaultClass"/> - - <!--Delete Simple Sub Category--> - <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> - - <!--Delete Simple Product--> - <deleteData createDataKey="simpleProduct" stepKey="deleteSimpleProduct"/> - - <!-- Delete Tax Rule --> - <deleteData createDataKey="createTaxRule" stepKey="deleteTaxRule"/> - - <!-- Rollback Braintree to Default --> - <createData entity="RollBackCustomBraintreeConfigurationData" stepKey="rollbackBraintreeConfig"/> - - <!--Delete Customer--> - <deleteData createDataKey="simpleCustomer" stepKey="deleteSimpleCustomer"/> - - <!--Log Out--> - <actionGroup ref="AdminLogoutActionGroup" stepKey="logout"/> - </after> - - <!-- Create a cart price rule with 10% discount for whole cart --> - <click selector="{{AdminMenuSection.marketing}}" stepKey="clickOnMarketing"/> - <waitForPageLoad stepKey="waitForMarketing"/> - <click selector="{{CartPriceRulesSubmenuSection.cartPriceRules}}" stepKey="clickOnCartPriceRules"/> - <waitForPageLoad stepKey="waitForCartPriceRules"/> - <click selector="{{AdminCartPriceRulesSection.addNewRuleButton}}" stepKey="clickAddNewRule"/> - <fillField selector="{{AdminCartPriceRulesFormSection.ruleName}}" userInput="{{SimpleSalesRule.name}}" stepKey="fillRuleName"/> - <selectOption selector="{{AdminCartPriceRulesFormSection.websites}}" userInput="Main Website" stepKey="selectWebsites"/> - <actionGroup ref="SelectRetailerCustomerGroupActionGroup" stepKey="selectRetailerCustomerGroup"/> - <click selector="{{AdminCartPriceRulesFormSection.actionsHeader}}" stepKey="clickToExpandActions"/> - <selectOption selector="{{AdminCartPriceRulesFormSection.apply}}" userInput="Percent of product price discount" stepKey="selectActionType"/> - <fillField selector="{{AdminCartPriceRulesFormSection.discountAmount}}" userInput="10" stepKey="fillDiscountAmount"/> - <click selector="{{AdminCartPriceRulesFormSection.save}}" stepKey="clickSaveButton"/> - <waitForPageLoad stepKey="waitForCartRuleLoad"/> - <see selector="{{AdminCartPriceRulesSection.messages}}" userInput="You saved the rule." stepKey="seeSuccessMessage"/> - - <!--Set Taxable Goods for Shipping Tax Class--> - <actionGroup ref="ChangeShippingTaxClassActionGroup" stepKey="changeShippingTaxClass"/> - - <!--Adding Special price to product--> - <actionGroup ref="AdminProductPageOpenByIdActionGroup" stepKey="openAdminProductEditPage"> - <argument name="productId" value="$$simpleProduct.id$$"/> - </actionGroup> - <actionGroup ref="AddSpecialPriceToProductActionGroup" stepKey="addSpecialPrice"/> - <actionGroup ref="SaveProductFormActionGroup" stepKey="saveProductForm"/> - - <!--Create New Order--> - <actionGroup ref="NavigateToNewOrderPageExistingCustomerActionGroup" stepKey="navigateToNewOrderWithExistingCustomer"> - <argument name="customer" value="$$simpleCustomer$$"/> - </actionGroup> - - <!--Add a product to order--> - <actionGroup ref="AddSimpleProductToOrderActionGroup" stepKey="addProductToOrder"> - <argument name="product" value="$$simpleProduct$$"/> - </actionGroup> - - <!--Select FlatRate shipping method--> - <actionGroup ref="OrderSelectFlatRateShippingActionGroup" stepKey="orderSelectFlatRateShippingMethod"/> - - <!--Select Braintree online Payment method --> - <actionGroup ref="AdminOrderBraintreeFillActionGroup" stepKey="selectCreditCardPayment"/> - - <!--Submit Order--> - <click stepKey="submitOrder" selector="{{NewOrderSection.submitOrder}}"/> - <waitForPageLoad stepKey="waitForSubmitOrder"/> - <see selector="{{AdminOrderDetailsMessagesSection.successMessage}}" userInput="You created the order." stepKey="seeOrderSuccessMessage" after="waitForSubmitOrder"/> - - <!-- Create New invoice--> - <actionGroup ref="AdminFastCreateInvoiceActionGroup" stepKey="createInvoice"/> - - <!--Get access to Credit Memo page from Invoice page--> - <click selector="{{AdminInvoiceMainActionsSection.openNewCreditMemoFromInvoice}}" stepKey="clickCreateNewCreditMemo"/> - <waitForPageLoad stepKey="waitForLoadNewCreditMemoPage"/> - <see selector="{{AdminCreditMemoOrderInformationSection.orderStatus}}" userInput="Processing" stepKey="seeNewCreditMemo"/> - </test> -</tests> diff --git a/app/code/Magento/Braintree/Test/Unit/Block/FormTest.php b/app/code/Magento/Braintree/Test/Unit/Block/FormTest.php deleted file mode 100644 index d7df3ebb610a6..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Block/FormTest.php +++ /dev/null @@ -1,198 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Block; - -use Magento\Backend\Model\Session\Quote; -use Magento\Braintree\Block\Form; -use Magento\Braintree\Gateway\Config\Config as GatewayConfig; -use Magento\Braintree\Model\Adminhtml\Source\CcType; -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Payment\Helper\Data; -use Magento\Payment\Model\Config; -use Magento\Vault\Model\VaultPaymentInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Block\Form. - */ -class FormTest extends TestCase -{ - public static $baseCardTypes = [ - 'AE' => 'American Express', - 'VI' => 'Visa', - 'MC' => 'MasterCard', - 'DI' => 'Discover', - 'JBC' => 'JBC', - 'CUP' => 'China Union Pay', - 'MI' => 'Maestro', - ]; - - public static $configCardTypes = [ - 'AE', 'VI', 'MC', 'DI', 'JBC' - ]; - - /** - * @var Form - */ - private $block; - - /** - * @var Quote|MockObject - */ - private $sessionQuoteMock; - - /** - * @var Config|MockObject - */ - private $gatewayConfigMock; - - /** - * @var CcType|MockObject - */ - private $ccTypeMock; - - /** - * @var Data|MockObject - */ - private $paymentDataHelperMock; - - /** - * @var string - */ - private $storeId = '1'; - - protected function setUp(): void - { - $this->initCcTypeMock(); - $this->initSessionQuoteMock(); - $this->initGatewayConfigMock(); - - $this->paymentDataHelperMock = $this->getMockBuilder(Data::class) - ->disableOriginalConstructor() - ->setMethods(['getMethodInstance']) - ->getMock(); - - $managerHelper = new ObjectManager($this); - $this->block = $managerHelper->getObject(Form::class, [ - 'paymentConfig' => $managerHelper->getObject(Config::class), - 'sessionQuote' => $this->sessionQuoteMock, - 'gatewayConfig' => $this->gatewayConfigMock, - 'ccType' => $this->ccTypeMock, - 'paymentDataHelper' =>$this->paymentDataHelperMock, - ]); - } - - /** - * @covers \Magento\Braintree\Block\Form::getCcAvailableTypes - * @param string $countryId - * @param array $availableTypes - * @param array $expected - * @dataProvider countryCardTypesDataProvider - */ - public function testGetCcAvailableTypes($countryId, array $availableTypes, array $expected) - { - $this->sessionQuoteMock->expects(static::once()) - ->method('getCountryId') - ->willReturn($countryId); - - $this->gatewayConfigMock->expects(static::once()) - ->method('getAvailableCardTypes') - ->with($this->storeId) - ->willReturn(self::$configCardTypes); - - $this->gatewayConfigMock->expects(static::once()) - ->method('getCountryAvailableCardTypes') - ->with($countryId, $this->storeId) - ->willReturn($availableTypes); - - $result = $this->block->getCcAvailableTypes(); - static::assertEquals($expected, array_values($result)); - } - - /** - * Get country card types testing data - * @return array - */ - public function countryCardTypesDataProvider() - { - return [ - ['US', ['AE', 'VI'], ['American Express', 'Visa']], - ['UK', ['VI'], ['Visa']], - ['CA', ['MC'], ['MasterCard']], - ['UA', [], ['American Express', 'Visa', 'MasterCard', 'Discover', 'JBC']], - ]; - } - - /** - * @covers \Magento\Braintree\Block\Form::isVaultEnabled - */ - public function testIsVaultEnabled() - { - $vaultPayment = $this->getMockForAbstractClass(VaultPaymentInterface::class); - $this->paymentDataHelperMock->expects(static::once()) - ->method('getMethodInstance') - ->with(ConfigProvider::CC_VAULT_CODE) - ->willReturn($vaultPayment); - - $vaultPayment->expects(static::once()) - ->method('isActive') - ->with($this->storeId) - ->willReturn(true); - - static::assertTrue($this->block->isVaultEnabled()); - } - - /** - * Create mock for credit card type - */ - private function initCcTypeMock() - { - $this->ccTypeMock = $this->getMockBuilder(CcType::class) - ->disableOriginalConstructor() - ->setMethods(['getCcTypeLabelMap']) - ->getMock(); - - $this->ccTypeMock->expects(static::any()) - ->method('getCcTypeLabelMap') - ->willReturn(self::$baseCardTypes); - } - - /** - * Create mock for session quote - */ - private function initSessionQuoteMock() - { - $this->sessionQuoteMock = $this->getMockBuilder(Quote::class) - ->disableOriginalConstructor() - ->setMethods(['getQuote', 'getBillingAddress', 'getCountryId', '__wakeup', 'getStoreId']) - ->getMock(); - - $this->sessionQuoteMock->expects(static::any()) - ->method('getQuote') - ->willReturnSelf(); - $this->sessionQuoteMock->expects(static::any()) - ->method('getBillingAddress') - ->willReturnSelf(); - $this->sessionQuoteMock->expects(static::any()) - ->method('getStoreId') - ->willReturn($this->storeId); - } - - /** - * Create mock for gateway config - */ - private function initGatewayConfigMock() - { - $this->gatewayConfigMock = $this->getMockBuilder(GatewayConfig::class) - ->disableOriginalConstructor() - ->setMethods(['getCountryAvailableCardTypes', 'getAvailableCardTypes']) - ->getMock(); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Controller/Adminhtml/Payment/GetClientTokenTest.php b/app/code/Magento/Braintree/Test/Unit/Controller/Adminhtml/Payment/GetClientTokenTest.php deleted file mode 100644 index 034a31f78f308..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Controller/Adminhtml/Payment/GetClientTokenTest.php +++ /dev/null @@ -1,121 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Controller\Adminhtml\Payment; - -use Magento\Backend\App\Action\Context; -use Magento\Backend\Model\Session\Quote; -use Magento\Braintree\Controller\Adminhtml\Payment\GetClientToken; -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Model\Adapter\BraintreeAdapter; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Framework\Controller\ResultFactory; -use Magento\Framework\Controller\ResultInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Controller\Adminhtml\Payment\GetClientToken - */ -class GetClientTokenTest extends TestCase -{ - /** - * @var GetClientToken - */ - private $action; - - /** - * @var Config|MockObject - */ - private $configMock; - - /** - * @var BraintreeAdapterFactory|MockObject - */ - private $adapterFactoryMock; - - /** - * @var Quote|MockObject - */ - private $quoteSessionMock; - - /** - * @var ResultFactory|MockObject - */ - private $resultFactoryMock; - - protected function setUp(): void - { - $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - $context = $this->getMockBuilder(Context::class) - ->disableOriginalConstructor() - ->setMethods(['getResultFactory']) - ->getMock(); - $context->expects(static::any()) - ->method('getResultFactory') - ->willReturn($this->resultFactoryMock); - $this->configMock = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->setMethods(['getMerchantAccountId']) - ->getMock(); - $this->adapterFactoryMock = $this->getMockBuilder(BraintreeAdapterFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - $this->quoteSessionMock = $this->getMockBuilder(Quote::class) - ->disableOriginalConstructor() - ->setMethods(['getStoreId']) - ->getMock(); - - $managerHelper = new ObjectManager($this); - $this->action = $managerHelper->getObject(GetClientToken::class, [ - 'context' => $context, - 'config' => $this->configMock, - 'adapterFactory' => $this->adapterFactoryMock, - 'quoteSession' => $this->quoteSessionMock, - ]); - } - - public function testExecute() - { - $storeId = '1'; - $clientToken = 'client_token'; - $responseMock = $this->getMockBuilder(ResultInterface::class) - ->setMethods(['setHttpResponseCode', 'renderResult', 'setHeader', 'setData']) - ->getMockForAbstractClass(); - $responseMock->expects(static::once()) - ->method('setData') - ->with(['clientToken' => $clientToken]) - ->willReturn($responseMock); - $this->resultFactoryMock->expects(static::once()) - ->method('create') - ->willReturn($responseMock); - $this->quoteSessionMock->expects(static::once()) - ->method('getStoreId') - ->willReturn($storeId); - $this->configMock->expects(static::once()) - ->method('getMerchantAccountId') - ->with($storeId) - ->willReturn(null); - $adapterMock = $this->getMockBuilder(BraintreeAdapter::class) - ->disableOriginalConstructor() - ->setMethods(['generate']) - ->getMock(); - $adapterMock->expects(static::once()) - ->method('generate') - ->willReturn($clientToken); - $this->adapterFactoryMock->expects(static::once()) - ->method('create') - ->willReturn($adapterMock); - - $this->action->execute(); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Controller/Payment/GetNonceTest.php b/app/code/Magento/Braintree/Test/Unit/Controller/Payment/GetNonceTest.php deleted file mode 100644 index 0e789cdc1530b..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Controller/Payment/GetNonceTest.php +++ /dev/null @@ -1,208 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Controller\Payment; - -use Magento\Braintree\Controller\Payment\GetNonce; -use Magento\Braintree\Gateway\Command\GetPaymentNonceCommand; -use Magento\Customer\Model\Session; -use Magento\Framework\App\Action\Context; -use Magento\Framework\App\Request\Http; -use Magento\Framework\App\RequestInterface; -use Magento\Framework\Controller\ResultFactory; -use Magento\Framework\Controller\ResultInterface; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Framework\Webapi\Exception; -use Magento\Payment\Gateway\Command\ResultInterface as CommandResultInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Psr\Log\LoggerInterface; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class GetNonceTest extends TestCase -{ - /** - * @var GetNonce - */ - private $action; - - /** - * @var GetPaymentNonceCommand|MockObject - */ - private $commandMock; - - /** - * @var Session|MockObject - */ - private $sessionMock; - - /** - * @var LoggerInterface|MockObject - */ - private $loggerMock; - - /** - * @var ResultFactory|MockObject - */ - private $resultFactoryMock; - - /** - * @var ResultInterface|MockObject - */ - private $resultMock; - - /** - * @var Http|MockObject - */ - private $requestMock; - - /** - * @var CommandResultInterface|MockObject - */ - private $commandResultMock; - - protected function setUp(): void - { - $this->initResultFactoryMock(); - - $this->requestMock = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->setMethods(['getParam']) - ->getMockForAbstractClass(); - - $this->commandMock = $this->getMockBuilder(GetPaymentNonceCommand::class) - ->disableOriginalConstructor() - ->setMethods(['execute', '__wakeup']) - ->getMock(); - - $this->commandResultMock = $this->getMockBuilder(CommandResultInterface::class) - ->setMethods(['get']) - ->getMockForAbstractClass(); - - $this->sessionMock = $this->getMockBuilder(Session::class) - ->disableOriginalConstructor() - ->setMethods(['getCustomerId', 'getStoreId']) - ->getMock(); - $this->sessionMock->expects(static::once()) - ->method('getStoreId') - ->willReturn(null); - - $this->loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); - - $context = $this->getMockBuilder(Context::class) - ->disableOriginalConstructor() - ->getMock(); - $context->expects(static::any()) - ->method('getRequest') - ->willReturn($this->requestMock); - $context->expects(static::any()) - ->method('getResultFactory') - ->willReturn($this->resultFactoryMock); - - $managerHelper = new ObjectManager($this); - $this->action = $managerHelper->getObject(GetNonce::class, [ - 'context' => $context, - 'logger' => $this->loggerMock, - 'session' => $this->sessionMock, - 'command' => $this->commandMock, - ]); - } - - /** - * @covers \Magento\Braintree\Controller\Payment\GetNonce::execute - */ - public function testExecuteWithException() - { - $this->requestMock->expects(static::once()) - ->method('getParam') - ->with('public_hash') - ->willReturn(null); - - $this->sessionMock->expects(static::once()) - ->method('getCustomerId') - ->willReturn(null); - - $exception = new \Exception('The "publicHash" field does not exists'); - $this->commandMock->expects(static::once()) - ->method('execute') - ->willThrowException($exception); - - $this->loggerMock->expects(static::once()) - ->method('critical') - ->with($exception); - - $this->resultMock->expects(static::once()) - ->method('setHttpResponseCode') - ->with(Exception::HTTP_BAD_REQUEST); - $this->resultMock->expects(static::once()) - ->method('setData') - ->with(['message' => 'Sorry, but something went wrong']); - - $this->action->execute(); - } - - /** - * @covers \Magento\Braintree\Controller\Payment\GetNonce::execute - */ - public function testExecute() - { - $customerId = 1; - $publicHash = '65b7bae0dcb690d93'; - $nonce = 'f1hc45'; - - $this->requestMock->expects(static::once()) - ->method('getParam') - ->with('public_hash') - ->willReturn($publicHash); - - $this->sessionMock->expects(static::once()) - ->method('getCustomerId') - ->willReturn($customerId); - - $this->commandResultMock->expects(static::once()) - ->method('get') - ->willReturn([ - 'paymentMethodNonce' => $nonce - ]); - $this->commandMock->expects(static::once()) - ->method('execute') - ->willReturn($this->commandResultMock); - - $this->resultMock->expects(static::once()) - ->method('setData') - ->with(['paymentMethodNonce' => $nonce]); - - $this->loggerMock->expects(static::never()) - ->method('critical'); - - $this->resultMock->expects(static::never()) - ->method('setHttpResponseCode'); - - $this->action->execute(); - } - - /** - * Create mock for result factory object - */ - private function initResultFactoryMock() - { - $this->resultMock = $this->getMockBuilder(ResultInterface::class) - ->setMethods(['setHttpResponseCode', 'renderResult', 'setHeader', 'setData']) - ->getMockForAbstractClass(); - - $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $this->resultFactoryMock->expects(static::once()) - ->method('create') - ->willReturn($this->resultMock); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/PlaceOrderTest.php b/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/PlaceOrderTest.php deleted file mode 100644 index 0d9f39da2741e..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/PlaceOrderTest.php +++ /dev/null @@ -1,225 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Controller\Paypal; - -use Magento\Braintree\Controller\Paypal\PlaceOrder; -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Model\Paypal\Helper\OrderPlace; -use Magento\Checkout\Model\Session; -use Magento\Framework\App\Action\Context; -use Magento\Framework\App\RequestInterface; -use Magento\Framework\Controller\ResultFactory; -use Magento\Framework\Controller\ResultInterface; -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\Exception\NotFoundException; -use Magento\Framework\Message\ManagerInterface; -use Magento\Quote\Model\Quote; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Psr\Log\LoggerInterface; - -/** - * @see \Magento\Braintree\Controller\Paypal\PlaceOrder - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class PlaceOrderTest extends TestCase -{ - /** - * @var OrderPlace|MockObject - */ - private $orderPlace; - - /** - * @var Config|MockObject - */ - private $config; - - /** - * @var Session|MockObject - */ - private $checkoutSession; - - /** - * @var RequestInterface|MockObject - */ - private $request; - - /** - * @var ResultFactory|MockObject - */ - private $resultFactory; - - /** - * @var ManagerInterface|MockObject - */ - private $messageManager; - - /** - * @var PlaceOrder - */ - private $placeOrder; - - /** - * @var MockObject - */ - private $logger; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - /** @var Context|MockObject $context */ - $context = $this->getMockBuilder(Context::class) - ->disableOriginalConstructor() - ->getMock(); - $this->request = $this->getMockBuilder(RequestInterface::class) - ->setMethods(['getPostValue']) - ->getMockForAbstractClass(); - $this->resultFactory = $this->getMockBuilder(ResultFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->checkoutSession = $this->getMockBuilder(Session::class) - ->disableOriginalConstructor() - ->getMock(); - $this->config = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); - $this->orderPlace = $this->getMockBuilder(OrderPlace::class) - ->disableOriginalConstructor() - ->getMock(); - $this->messageManager = $this->getMockBuilder(ManagerInterface::class) - ->getMockForAbstractClass(); - - $context->method('getRequest') - ->willReturn($this->request); - $context->method('getResultFactory') - ->willReturn($this->resultFactory); - $context->method('getMessageManager') - ->willReturn($this->messageManager); - - $this->logger = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - $this->placeOrder = new PlaceOrder( - $context, - $this->config, - $this->checkoutSession, - $this->orderPlace, - $this->logger - ); - } - - /** - * Checks if an order is placed successfully. - * - * @throws LocalizedException - * @throws NotFoundException - */ - public function testExecute() - { - $agreement = ['test-data']; - - $quoteMock = $this->getQuoteMock(); - $quoteMock->method('getItemsCount') - ->willReturn(1); - - $resultMock = $this->getResultMock(); - $resultMock->method('setPath') - ->with('checkout/onepage/success') - ->willReturnSelf(); - - $this->resultFactory->method('create') - ->with(ResultFactory::TYPE_REDIRECT) - ->willReturn($resultMock); - - $this->request->method('getPostValue') - ->with('agreement', []) - ->willReturn($agreement); - - $this->checkoutSession->method('getQuote') - ->willReturn($quoteMock); - - $this->orderPlace->method('execute') - ->with($quoteMock, [0]); - - $this->messageManager->expects(self::never()) - ->method('addExceptionMessage'); - - self::assertEquals($this->placeOrder->execute(), $resultMock); - } - - /** - * Checks a negative scenario during place order action. - * - * @throws LocalizedException - * @throws NotFoundException - */ - public function testExecuteException() - { - $agreement = ['test-data']; - - $quote = $this->getQuoteMock(); - $quote->method('getItemsCount') - ->willReturn(0); - $quote->method('getReservedOrderId') - ->willReturn('000000111'); - - $resultMock = $this->getResultMock(); - $resultMock->method('setPath') - ->with('checkout/cart') - ->willReturnSelf(); - - $this->resultFactory->method('create') - ->with(ResultFactory::TYPE_REDIRECT) - ->willReturn($resultMock); - - $this->request->method('getPostValue') - ->with('agreement', []) - ->willReturn($agreement); - - $this->checkoutSession->method('getQuote') - ->willReturn($quote); - - $this->orderPlace->expects(self::never()) - ->method('execute'); - - $this->messageManager->method('addExceptionMessage') - ->with( - self::isInstanceOf('\InvalidArgumentException'), - 'The order #000000111 cannot be processed.' - ); - - self::assertEquals($this->placeOrder->execute(), $resultMock); - } - - /** - * Gets mock object for a result. - * - * @return ResultInterface|MockObject - */ - private function getResultMock() - { - return $this->getMockBuilder(ResultInterface::class) - ->setMethods(['setPath']) - ->getMockForAbstractClass(); - } - - /** - * Gets mock object for a quote. - * - * @return Quote|MockObject - */ - private function getQuoteMock() - { - return $this->getMockBuilder(Quote::class) - ->disableOriginalConstructor() - ->getMock(); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/ReviewTest.php b/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/ReviewTest.php deleted file mode 100644 index 8b3662a99f11d..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/ReviewTest.php +++ /dev/null @@ -1,327 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Controller\Paypal; - -use Magento\Braintree\Block\Paypal\Checkout\Review as CheckoutReview; -use Magento\Braintree\Controller\Paypal\Review; -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Model\Paypal\Helper\QuoteUpdater; -use Magento\Checkout\Model\Session; -use Magento\Framework\App\Action\Context; -use Magento\Framework\App\RequestInterface; -use Magento\Framework\Controller\Result\Redirect; -use Magento\Framework\Controller\ResultFactory; -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\Message\ManagerInterface; -use Magento\Framework\View\Element\AbstractBlock; -use Magento\Framework\View\Layout; -use Magento\Framework\View\Result\Page; -use Magento\Payment\Model\Method\Logger; -use Magento\Quote\Model\Quote; -use Magento\Quote\Model\Quote\Payment; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @see \Magento\Braintree\Controller\Paypal\Review - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class ReviewTest extends TestCase -{ - /** - * @var QuoteUpdater|MockObject - */ - private $quoteUpdaterMock; - - /** - * @var Config|MockObject - */ - private $configMock; - - /** - * @var Session|MockObject - */ - private $checkoutSessionMock; - - /** - * @var RequestInterface|MockObject - */ - private $requestMock; - - /** - * @var ResultFactory|MockObject - */ - private $resultFactoryMock; - - /** - * @var ManagerInterface|MockObject - */ - private $messageManagerMock; - - /** - * @var Review - */ - private $review; - - /** - * @var Logger|MockObject - */ - private $loggerMock; - - protected function setUp(): void - { - /** @var Context|MockObject $contextMock */ - $contextMock = $this->getMockBuilder(Context::class) - ->disableOriginalConstructor() - ->getMock(); - $this->requestMock = $this->getMockBuilder(RequestInterface::class) - ->setMethods(['getPostValue']) - ->getMockForAbstractClass(); - $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->checkoutSessionMock = $this->getMockBuilder(Session::class) - ->disableOriginalConstructor() - ->getMock(); - $this->configMock = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); - $this->quoteUpdaterMock = $this->getMockBuilder(QuoteUpdater::class) - ->disableOriginalConstructor() - ->getMock(); - $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) - ->getMockForAbstractClass(); - $this->loggerMock = $this->getMockBuilder(Logger::class) - ->disableOriginalConstructor() - ->getMock(); - - $contextMock->expects(self::once()) - ->method('getRequest') - ->willReturn($this->requestMock); - $contextMock->expects(self::once()) - ->method('getResultFactory') - ->willReturn($this->resultFactoryMock); - $contextMock->expects(self::once()) - ->method('getMessageManager') - ->willReturn($this->messageManagerMock); - - $this->review = new Review( - $contextMock, - $this->configMock, - $this->checkoutSessionMock, - $this->quoteUpdaterMock, - $this->loggerMock - ); - } - - public function testExecute() - { - $result = '{"nonce": ["test-value"], "details": ["test-value"]}'; - - $resultPageMock = $this->getResultPageMock(); - $layoutMock = $this->getLayoutMock(); - $blockMock = $this->getBlockMock(); - $quoteMock = $this->getQuoteMock(); - $childBlockMock = $this->getChildBlockMock(); - - $quoteMock->expects(self::once()) - ->method('getItemsCount') - ->willReturn(1); - - $this->requestMock->expects(self::once()) - ->method('getPostValue') - ->with('result', '{}') - ->willReturn($result); - - $this->checkoutSessionMock->expects(self::once()) - ->method('getQuote') - ->willReturn($quoteMock); - - $this->quoteUpdaterMock->expects(self::once()) - ->method('execute') - ->with(['test-value'], ['test-value'], $quoteMock); - - $this->resultFactoryMock->expects(self::once()) - ->method('create') - ->with(ResultFactory::TYPE_PAGE) - ->willReturn($resultPageMock); - - $resultPageMock->expects(self::once()) - ->method('getLayout') - ->willReturn($layoutMock); - - $layoutMock->expects(self::once()) - ->method('getBlock') - ->with('braintree.paypal.review') - ->willReturn($blockMock); - - $blockMock->expects(self::once()) - ->method('setQuote') - ->with($quoteMock); - $blockMock->expects(self::once()) - ->method('getChildBlock') - ->with('shipping_method') - ->willReturn($childBlockMock); - - $childBlockMock->expects(self::once()) - ->method('setData') - ->with('quote', $quoteMock); - - self::assertEquals($this->review->execute(), $resultPageMock); - } - - public function testExecuteException() - { - $result = '{}'; - $quoteMock = $this->getQuoteMock(); - $resultRedirectMock = $this->getResultRedirectMock(); - - $quoteMock->expects(self::once()) - ->method('getItemsCount') - ->willReturn(0); - - $this->requestMock->expects(self::once()) - ->method('getPostValue') - ->with('result', '{}') - ->willReturn($result); - - $this->checkoutSessionMock->expects(self::once()) - ->method('getQuote') - ->willReturn($quoteMock); - - $this->quoteUpdaterMock->expects(self::never()) - ->method('execute'); - - $this->messageManagerMock->expects(self::once()) - ->method('addExceptionMessage') - ->with( - self::isInstanceOf('\InvalidArgumentException'), - 'Checkout failed to initialize. Verify and try again.' - ); - - $this->resultFactoryMock->expects(self::once()) - ->method('create') - ->with(ResultFactory::TYPE_REDIRECT) - ->willReturn($resultRedirectMock); - - $resultRedirectMock->expects(self::once()) - ->method('setPath') - ->with('checkout/cart') - ->willReturnSelf(); - - self::assertEquals($this->review->execute(), $resultRedirectMock); - } - - public function testExecuteExceptionPaymentWithoutNonce() - { - $result = '{}'; - $quoteMock = $this->getQuoteMock(); - $resultRedirectMock = $this->getResultRedirectMock(); - - $quoteMock->expects(self::once()) - ->method('getItemsCount') - ->willReturn(1); - - $paymentMock = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->getMock(); - - $quoteMock->expects(self::once()) - ->method('getPayment') - ->willReturn($paymentMock); - - $this->requestMock->expects(self::once()) - ->method('getPostValue') - ->with('result', '{}') - ->willReturn($result); - - $this->checkoutSessionMock->expects(self::once()) - ->method('getQuote') - ->willReturn($quoteMock); - - $this->messageManagerMock->expects(self::once()) - ->method('addExceptionMessage') - ->with( - self::isInstanceOf(LocalizedException::class), - 'Checkout failed to initialize. Verify and try again.' - ); - - $this->resultFactoryMock->expects(self::once()) - ->method('create') - ->with(ResultFactory::TYPE_REDIRECT) - ->willReturn($resultRedirectMock); - - $resultRedirectMock->expects(self::once()) - ->method('setPath') - ->with('checkout/cart') - ->willReturnSelf(); - - self::assertEquals($this->review->execute(), $resultRedirectMock); - } - - /** - * @return Redirect|MockObject - */ - private function getResultRedirectMock() - { - return $this->getMockBuilder(Redirect::class) - ->disableOriginalConstructor() - ->getMock(); - } - - /** - * @return AbstractBlock|MockObject - */ - private function getChildBlockMock() - { - return $this->getMockBuilder(AbstractBlock::class) - ->disableOriginalConstructor() - ->getMock(); - } - - /** - * @return CheckoutReview|MockObject - */ - private function getBlockMock() - { - return $this->getMockBuilder(CheckoutReview::class) - ->disableOriginalConstructor() - ->getMock(); - } - - /** - * @return Layout|MockObject - */ - private function getLayoutMock() - { - return $this->getMockBuilder(Layout::class) - ->disableOriginalConstructor() - ->getMock(); - } - - /** - * @return Page|MockObject - */ - private function getResultPageMock() - { - return $this->getMockBuilder(Page::class) - ->disableOriginalConstructor() - ->getMock(); - } - - /** - * @return Quote|MockObject - */ - private function getQuoteMock() - { - return $this->getMockBuilder(Quote::class) - ->disableOriginalConstructor() - ->getMock(); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/SaveShippingMethodTest.php b/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/SaveShippingMethodTest.php deleted file mode 100644 index 04256be917a1e..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Controller/Paypal/SaveShippingMethodTest.php +++ /dev/null @@ -1,329 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Controller\Paypal; - -use Magento\Braintree\Block\Paypal\Checkout\Review; -use Magento\Braintree\Controller\Paypal\SaveShippingMethod; -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Model\Paypal\Helper\ShippingMethodUpdater; -use Magento\Checkout\Model\Session; -use Magento\Framework\App\Action\Context; -use Magento\Framework\App\RequestInterface; -use Magento\Framework\App\Response\RedirectInterface; -use Magento\Framework\App\ResponseInterface; -use Magento\Framework\Controller\ResultFactory; -use Magento\Framework\Message\ManagerInterface; -use Magento\Framework\UrlInterface; -use Magento\Framework\View\Layout; -use Magento\Framework\View\Result\Page; -use Magento\Quote\Model\Quote; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @see \Magento\Braintree\Controller\Paypal\SaveShippingMethod - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class SaveShippingMethodTest extends TestCase -{ - /** - * @var ShippingMethodUpdater|MockObject - */ - private $shippingMethodUpdaterMock; - - /** - * @var Config|MockObject - */ - private $configMock; - - /** - * @var Session|MockObject - */ - private $checkoutSessionMock; - - /** - * @var RequestInterface|MockObject - */ - private $requestMock; - - /** - * @var ResponseInterface|MockObject - */ - private $responseMock; - - /** - * @var RedirectInterface|MockObject - */ - protected $redirectMock; - - /** - * @var UrlInterface|MockObject - */ - private $urlMock; - - /** - * @var ResultFactory|MockObject - */ - private $resultFactoryMock; - - /** - * @var ManagerInterface|MockObject - */ - private $messageManagerMock; - - /** - * @var SaveShippingMethod - */ - private $saveShippingMethod; - - protected function setUp(): void - { - /** @var Context|MockObject $contextMock */ - $contextMock = $this->getMockBuilder(Context::class) - ->disableOriginalConstructor() - ->getMock(); - $this->requestMock = $this->getMockBuilder(RequestInterface::class) - ->getMockForAbstractClass(); - $this->redirectMock = $this->getMockBuilder(RedirectInterface::class) - ->getMockForAbstractClass(); - $this->urlMock = $this->getMockBuilder(UrlInterface::class) - ->getMockForAbstractClass(); - $this->responseMock = $this->getMockBuilder(ResponseInterface::class) - ->setMethods(['setBody']) - ->getMockForAbstractClass(); - $this->resultFactoryMock = $this->getMockBuilder(ResultFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->checkoutSessionMock = $this->getMockBuilder(Session::class) - ->disableOriginalConstructor() - ->getMock(); - $this->configMock = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); - $this->shippingMethodUpdaterMock = $this->getMockBuilder(ShippingMethodUpdater::class) - ->disableOriginalConstructor() - ->getMock(); - $this->messageManagerMock = $this->getMockBuilder(ManagerInterface::class) - ->getMockForAbstractClass(); - - $contextMock->expects(self::once()) - ->method('getRequest') - ->willReturn($this->requestMock); - $contextMock->expects(self::once()) - ->method('getRedirect') - ->willReturn($this->redirectMock); - $contextMock->expects(self::once()) - ->method('getResponse') - ->willReturn($this->responseMock); - $contextMock->expects(self::once()) - ->method('getUrl') - ->willReturn($this->urlMock); - $contextMock->expects(self::once()) - ->method('getResultFactory') - ->willReturn($this->resultFactoryMock); - $contextMock->expects(self::once()) - ->method('getMessageManager') - ->willReturn($this->messageManagerMock); - - $this->saveShippingMethod = new SaveShippingMethod( - $contextMock, - $this->configMock, - $this->checkoutSessionMock, - $this->shippingMethodUpdaterMock - ); - } - - public function testExecuteAjax() - { - $resultHtml = '<html>test</html>'; - $quoteMock = $this->getQuoteMock(); - $responsePageMock = $this->getResponsePageMock(); - $layoutMock = $this->getLayoutMock(); - $blockMock = $this->getBlockMock(); - - $quoteMock->expects(self::once()) - ->method('getItemsCount') - ->willReturn(1); - - $this->requestMock->expects(self::exactly(2)) - ->method('getParam') - ->willReturnMap( - [ - ['isAjax', null, true], - ['shipping_method', null, 'test-shipping-method'] - ] - ); - - $this->checkoutSessionMock->expects(self::once()) - ->method('getQuote') - ->willReturn($quoteMock); - - $this->shippingMethodUpdaterMock->expects(self::once()) - ->method('execute') - ->with('test-shipping-method', $quoteMock); - - $this->resultFactoryMock->expects(self::once()) - ->method('create') - ->with(ResultFactory::TYPE_PAGE) - ->willReturn($responsePageMock); - - $responsePageMock->expects(self::once()) - ->method('addHandle') - ->with('paypal_express_review_details') - ->willReturnSelf(); - - $responsePageMock->expects(self::once()) - ->method('getLayout') - ->willReturn($layoutMock); - - $layoutMock->expects(self::once()) - ->method('getBlock') - ->with('page.block') - ->willReturn($blockMock); - - $blockMock->expects(self::once()) - ->method('toHtml') - ->willReturn($resultHtml); - - $this->responseMock->expects(self::once()) - ->method('setBody') - ->with($resultHtml); - - $this->urlMock->expects(self::never()) - ->method('getUrl'); - - $this->saveShippingMethod->execute(); - } - - public function testExecuteAjaxException() - { - $redirectPath = 'path/to/redirect'; - $quoteMock = $this->getQuoteMock(); - - $quoteMock->expects(self::once()) - ->method('getItemsCount') - ->willReturn(0); - - $this->requestMock->expects(self::exactly(1)) - ->method('getParam') - ->willReturnMap( - [ - ['isAjax', null, false] - ] - ); - - $this->checkoutSessionMock->expects(self::once()) - ->method('getQuote') - ->willReturn($quoteMock); - - $this->shippingMethodUpdaterMock->expects(self::never()) - ->method('execute'); - - $this->messageManagerMock->expects(self::once()) - ->method('addExceptionMessage') - ->with( - self::isInstanceOf('\InvalidArgumentException'), - 'Checkout failed to initialize. Verify and try again.' - ); - - $this->urlMock->expects(self::once()) - ->method('getUrl') - ->with('*/*/review', ['_secure' => true]) - ->willReturn($redirectPath); - - $this->redirectMock->expects(self::once()) - ->method('redirect') - ->with($this->responseMock, $redirectPath, []); - - $this->saveShippingMethod->execute(); - } - - public function testExecuteException() - { - $redirectPath = 'path/to/redirect'; - $quoteMock = $this->getQuoteMock(); - - $quoteMock->expects(self::once()) - ->method('getItemsCount') - ->willReturn(0); - - $this->requestMock->expects(self::exactly(1)) - ->method('getParam') - ->willReturnMap( - [ - ['isAjax', null, true] - ] - ); - - $this->checkoutSessionMock->expects(self::once()) - ->method('getQuote') - ->willReturn($quoteMock); - - $this->shippingMethodUpdaterMock->expects(self::never()) - ->method('execute'); - - $this->messageManagerMock->expects(self::once()) - ->method('addExceptionMessage') - ->with( - self::isInstanceOf('\InvalidArgumentException'), - 'Checkout failed to initialize. Verify and try again.' - ); - - $this->urlMock->expects(self::once()) - ->method('getUrl') - ->with('*/*/review', ['_secure' => true]) - ->willReturn($redirectPath); - - $this->responseMock->expects(self::once()) - ->method('setBody') - ->with(sprintf('<script>window.location.href = "%s";</script>', $redirectPath)); - - $this->saveShippingMethod->execute(); - } - - /** - * @return Review|MockObject - */ - private function getBlockMock() - { - return $this->getMockBuilder(Review::class) - ->disableOriginalConstructor() - ->getMock(); - } - - /** - * @return Layout|MockObject - */ - private function getLayoutMock() - { - return $this->getMockBuilder(Layout::class) - ->disableOriginalConstructor() - ->getMock(); - } - - /** - * @return Quote|MockObject - */ - private function getQuoteMock() - { - return $this->getMockBuilder(Quote::class) - ->disableOriginalConstructor() - ->getMock(); - } - - /** - * @return Page|MockObject - */ - private function getResponsePageMock() - { - return $this->getMockBuilder(Page::class) - ->disableOriginalConstructor() - ->getMock(); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Command/CaptureStrategyCommandTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Command/CaptureStrategyCommandTest.php deleted file mode 100644 index 9b8aba54312e4..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Command/CaptureStrategyCommandTest.php +++ /dev/null @@ -1,358 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Command; - -use Braintree\IsNode; -use Braintree\ResourceCollection; -use Braintree\Transaction; -use Magento\Braintree\Gateway\Command\CaptureStrategyCommand; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Braintree\Model\Adapter\BraintreeAdapter; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Braintree\Model\Adapter\BraintreeSearchAdapter; -use Magento\Framework\Api\FilterBuilder; -use Magento\Framework\Api\Search\SearchCriteria; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Payment\Gateway\Command\CommandPoolInterface; -use Magento\Payment\Gateway\Command\GatewayCommand; -use Magento\Payment\Gateway\Data\OrderAdapterInterface; -use Magento\Payment\Gateway\Data\PaymentDataObject; -use Magento\Sales\Api\TransactionRepositoryInterface; -use Magento\Sales\Model\Order\Payment; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class CaptureStrategyCommandTest extends TestCase -{ - /** - * @var CaptureStrategyCommand - */ - private $strategyCommand; - - /** - * @var CommandPoolInterface|MockObject - */ - private $commandPool; - - /** - * @var TransactionRepositoryInterface|MockObject - */ - private $transactionRepository; - - /** - * @var FilterBuilder|MockObject - */ - private $filterBuilder; - - /** - * @var SearchCriteriaBuilder|MockObject - */ - private $searchCriteriaBuilder; - - /** - * @var Payment|MockObject - */ - private $payment; - - /** - * @var GatewayCommand|MockObject - */ - private $command; - - /** - * @var SubjectReader|MockObject - */ - private $subjectReader; - - /** - * @var BraintreeAdapter|MockObject - */ - private $braintreeAdapter; - - /** - * @var BraintreeSearchAdapter - */ - private $braintreeSearchAdapter; - - protected function setUp(): void - { - $this->commandPool = $this->getMockBuilder(CommandPoolInterface::class) - ->disableOriginalConstructor() - ->setMethods(['get', '__wakeup']) - ->getMockForAbstractClass(); - - $this->subjectReader = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->initCommandMock(); - $this->initTransactionRepositoryMock(); - $this->initFilterBuilderMock(); - $this->initSearchCriteriaBuilderMock(); - - $this->braintreeAdapter = $this->getMockBuilder(BraintreeAdapter::class) - ->disableOriginalConstructor() - ->getMock(); - /** @var BraintreeAdapterFactory|MockObject $adapterFactory */ - $adapterFactory = $this->getMockBuilder(BraintreeAdapterFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $adapterFactory->method('create') - ->willReturn($this->braintreeAdapter); - - $this->braintreeSearchAdapter = new BraintreeSearchAdapter(); - - $this->strategyCommand = new CaptureStrategyCommand( - $this->commandPool, - $this->transactionRepository, - $this->filterBuilder, - $this->searchCriteriaBuilder, - $this->subjectReader, - $adapterFactory, - $this->braintreeSearchAdapter - ); - } - - public function testCaptureExecute() - { - $paymentData = $this->getPaymentDataObjectMock(); - $subject['payment'] = $paymentData; - $lastTransId = 'txnds'; - - $this->subjectReader->method('readPayment') - ->with($subject) - ->willReturn($paymentData); - - $this->payment->method('getAuthorizationTransaction') - ->willReturn(true); - $this->payment->method('getLastTransId') - ->willReturn($lastTransId); - - $this->payment->method('getId') - ->willReturn(1); - - $this->buildSearchCriteria(); - - $this->transactionRepository->method('getTotalCount') - ->willReturn(0); - - // authorization transaction was not expired - $collection = $this->getNotExpiredExpectedCollection($lastTransId); - $collection->method('maximumCount') - ->willReturn(0); - - $this->commandPool->method('get') - ->with(CaptureStrategyCommand::CAPTURE) - ->willReturn($this->command); - - $this->strategyCommand->execute($subject); - } - - /** - * @param string $lastTransactionId - * @return ResourceCollection|MockObject - */ - private function getNotExpiredExpectedCollection($lastTransactionId) - { - $isExpectations = [ - 'id' => ['is' => $lastTransactionId], - 'status' => [Transaction::AUTHORIZATION_EXPIRED] - ]; - - $collection = $this->getMockBuilder(ResourceCollection::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->braintreeAdapter->method('search') - ->with( - self::callback( - function (array $filters) use ($isExpectations) { - foreach ($filters as $filter) { - /** @var IsNode $filter */ - if (!isset($isExpectations[$filter->name])) { - return false; - } - - if ($isExpectations[$filter->name] !== $filter->toParam()) { - return false; - } - } - - return true; - } - ) - ) - ->willReturn($collection); - - return $collection; - } - - public function testExpiredAuthorizationPerformVaultCaptureExecute() - { - $paymentData = $this->getPaymentDataObjectMock(); - $subject['payment'] = $paymentData; - $lastTransId = 'txnds'; - - $this->subjectReader->method('readPayment') - ->with($subject) - ->willReturn($paymentData); - - $this->payment->method('getAuthorizationTransaction') - ->willReturn(true); - $this->payment->method('getLastTransId') - ->willReturn($lastTransId); - - $this->payment->method('getId') - ->willReturn(1); - - $this->buildSearchCriteria(); - - $this->transactionRepository->method('getTotalCount') - ->willReturn(0); - - // authorization transaction was expired - $collection = $this->getNotExpiredExpectedCollection($lastTransId); - $collection->method('maximumCount') - ->willReturn(1); - - $this->commandPool->method('get') - ->with(CaptureStrategyCommand::VAULT_CAPTURE) - ->willReturn($this->command); - - $this->strategyCommand->execute($subject); - } - - public function testVaultCaptureExecute() - { - $paymentData = $this->getPaymentDataObjectMock(); - $subject['payment'] = $paymentData; - - $this->subjectReader->method('readPayment') - ->with($subject) - ->willReturn($paymentData); - - $this->payment->method('getAuthorizationTransaction') - ->willReturn(true); - - $this->payment->method('getId') - ->willReturn(1); - - $this->buildSearchCriteria(); - - $this->transactionRepository->method('getTotalCount') - ->willReturn(1); - - $this->commandPool->method('get') - ->with(CaptureStrategyCommand::VAULT_CAPTURE) - ->willReturn($this->command); - - $this->strategyCommand->execute($subject); - } - - /** - * Creates mock for payment data object and order payment - * @return MockObject - */ - private function getPaymentDataObjectMock() - { - $this->payment = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->getMock(); - - $mock = $this->getMockBuilder(PaymentDataObject::class) - ->setMethods(['getPayment', 'getOrder']) - ->disableOriginalConstructor() - ->getMock(); - - $mock->method('getPayment') - ->willReturn($this->payment); - - $order = $this->getMockBuilder(OrderAdapterInterface::class) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - - $mock->method('getOrder') - ->willReturn($order); - - return $mock; - } - - /** - * Creates mock for gateway command object - */ - private function initCommandMock() - { - $this->command = $this->getMockBuilder(GatewayCommand::class) - ->disableOriginalConstructor() - ->setMethods(['execute']) - ->getMock(); - - $this->command->method('execute') - ->willReturn([]); - } - - /** - * Creates mock for filter object - */ - private function initFilterBuilderMock() - { - $this->filterBuilder = $this->getMockBuilder(FilterBuilder::class) - ->disableOriginalConstructor() - ->setMethods(['setField', 'setValue', 'create', '__wakeup']) - ->getMock(); - } - - /** - * Builds search criteria - */ - private function buildSearchCriteria() - { - $this->filterBuilder->expects(self::exactly(2)) - ->method('setField') - ->willReturnSelf(); - $this->filterBuilder->expects(self::exactly(2)) - ->method('setValue') - ->willReturnSelf(); - - $searchCriteria = new SearchCriteria(); - $this->searchCriteriaBuilder->expects(self::exactly(2)) - ->method('addFilters') - ->willReturnSelf(); - $this->searchCriteriaBuilder->method('create') - ->willReturn($searchCriteria); - - $this->transactionRepository->method('getList') - ->with($searchCriteria) - ->willReturnSelf(); - } - - /** - * Create mock for search criteria object - */ - private function initSearchCriteriaBuilderMock() - { - $this->searchCriteriaBuilder = $this->getMockBuilder(SearchCriteriaBuilder::class) - ->disableOriginalConstructor() - ->setMethods(['addFilters', 'create', '__wakeup']) - ->getMock(); - } - - /** - * Create mock for transaction repository - */ - private function initTransactionRepositoryMock() - { - $this->transactionRepository = $this->getMockBuilder(TransactionRepositoryInterface::class) - ->disableOriginalConstructor() - ->setMethods(['getList', 'getTotalCount', 'delete', 'get', 'save', 'create', '__wakeup']) - ->getMockForAbstractClass(); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Command/GetPaymentNonceCommandTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Command/GetPaymentNonceCommandTest.php deleted file mode 100644 index 05346fcd984eb..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Command/GetPaymentNonceCommandTest.php +++ /dev/null @@ -1,309 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Command; - -use Magento\Braintree\Gateway\Command\GetPaymentNonceCommand; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Braintree\Gateway\Validator\PaymentNonceResponseValidator; -use Magento\Braintree\Model\Adapter\BraintreeAdapter; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Payment\Gateway\Command\Result\ArrayResult; -use Magento\Payment\Gateway\Command\Result\ArrayResultFactory; -use Magento\Payment\Gateway\Validator\ResultInterface; -use Magento\Vault\Model\PaymentToken; -use Magento\Vault\Model\PaymentTokenManagement; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class GetPaymentNonceCommandTest extends TestCase -{ - /** - * @var GetPaymentNonceCommand - */ - private $command; - - /** - * @var BraintreeAdapter|MockObject - */ - private $adapterMock; - - /** - * @var PaymentTokenManagement|MockObject - */ - private $tokenManagementMock; - - /** - * @var PaymentToken|MockObject - */ - private $paymentTokenMock; - - /** - * @var ArrayResultFactory|MockObject - */ - private $resultFactoryMock; - - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - /** - * @var PaymentNonceResponseValidator|MockObject - */ - private $responseValidatorMock; - - /** - * @var ResultInterface|MockObject - */ - private $validationResultMock; - - protected function setUp(): void - { - $this->paymentTokenMock = $this->getMockBuilder(PaymentToken::class) - ->disableOriginalConstructor() - ->setMethods(['getGatewayToken']) - ->getMock(); - - $this->tokenManagementMock = $this->getMockBuilder(PaymentTokenManagement::class) - ->disableOriginalConstructor() - ->setMethods(['getByPublicHash']) - ->getMock(); - - $this->adapterMock = $this->getMockBuilder(BraintreeAdapter::class) - ->disableOriginalConstructor() - ->setMethods(['createNonce']) - ->getMock(); - /** @var BraintreeAdapterFactory|MockObject $adapterFactoryMock */ - $adapterFactoryMock = $this->getMockBuilder(BraintreeAdapterFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $adapterFactoryMock->expects(self::any()) - ->method('create') - ->willReturn($this->adapterMock); - - $this->resultFactoryMock = $this->getMockBuilder(ArrayResultFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->setMethods(['readPublicHash', 'readCustomerId']) - ->getMock(); - - $this->validationResultMock = $this->getMockBuilder(ResultInterface::class) - ->setMethods(['isValid', 'getFailsDescription', 'getErrorCodes']) - ->getMockForAbstractClass(); - - $this->responseValidatorMock = $this->getMockBuilder(PaymentNonceResponseValidator::class) - ->disableOriginalConstructor() - ->setMethods(['validate', 'isValid', 'getFailsDescription']) - ->getMock(); - - $this->command = new GetPaymentNonceCommand( - $this->tokenManagementMock, - $adapterFactoryMock, - $this->resultFactoryMock, - $this->subjectReaderMock, - $this->responseValidatorMock - ); - } - - /** - * @covers \Magento\Braintree\Gateway\Command\GetPaymentNonceCommand::execute - */ - public function testExecuteWithExceptionForPublicHash() - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The "publicHash" field does not exists'); - $exception = new \InvalidArgumentException('The "publicHash" field does not exists'); - - $this->subjectReaderMock->expects(static::once()) - ->method('readPublicHash') - ->willThrowException($exception); - - $this->subjectReaderMock->expects(self::never()) - ->method('readCustomerId'); - - $this->command->execute([]); - } - - /** - * @covers \Magento\Braintree\Gateway\Command\GetPaymentNonceCommand::execute - */ - public function testExecuteWithExceptionForCustomerId() - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The "customerId" field does not exists'); - $publicHash = '3wv2m24d2er3'; - - $this->subjectReaderMock->expects(static::once()) - ->method('readPublicHash') - ->willReturn($publicHash); - - $exception = new \InvalidArgumentException('The "customerId" field does not exists'); - $this->subjectReaderMock->expects(static::once()) - ->method('readCustomerId') - ->willThrowException($exception); - - $this->tokenManagementMock->expects(static::never()) - ->method('getByPublicHash'); - - $this->command->execute(['publicHash' => $publicHash]); - } - - /** - * @covers \Magento\Braintree\Gateway\Command\GetPaymentNonceCommand::execute - */ - public function testExecuteWithExceptionForTokenManagement() - { - $this->expectException(\Exception::class); - $this->expectExceptionMessage('No available payment tokens'); - $publicHash = '3wv2m24d2er3'; - $customerId = 1; - - $this->subjectReaderMock->expects(static::once()) - ->method('readPublicHash') - ->willReturn($publicHash); - - $this->subjectReaderMock->expects(static::once()) - ->method('readCustomerId') - ->willReturn($customerId); - - $exception = new \Exception('No available payment tokens'); - $this->tokenManagementMock->expects(static::once()) - ->method('getByPublicHash') - ->willThrowException($exception); - - $this->paymentTokenMock->expects(self::never()) - ->method('getGatewayToken'); - - $this->command->execute(['publicHash' => $publicHash, 'customerId' => $customerId]); - } - - /** - * @covers \Magento\Braintree\Gateway\Command\GetPaymentNonceCommand::execute - */ - public function testExecuteWithFailedValidation() - { - $this->expectException(\Exception::class); - $this->expectExceptionMessage('Payment method nonce can\'t be retrieved.'); - $publicHash = '3wv2m24d2er3'; - $customerId = 1; - $token = 'jd2vnq'; - - $this->subjectReaderMock->expects(static::once()) - ->method('readPublicHash') - ->willReturn($publicHash); - - $this->subjectReaderMock->expects(static::once()) - ->method('readCustomerId') - ->willReturn($customerId); - - $this->tokenManagementMock->expects(static::once()) - ->method('getByPublicHash') - ->with($publicHash, $customerId) - ->willReturn($this->paymentTokenMock); - - $this->paymentTokenMock->expects(static::once()) - ->method('getGatewayToken') - ->willReturn($token); - - $obj = new \stdClass(); - $obj->success = false; - $this->adapterMock->expects(static::once()) - ->method('createNonce') - ->with($token) - ->willReturn($obj); - - $this->responseValidatorMock->expects(static::once()) - ->method('validate') - ->with(['response' => ['object' => $obj]]) - ->willReturn($this->validationResultMock); - - $this->validationResultMock->expects(static::once()) - ->method('isValid') - ->willReturn(false); - - $this->validationResultMock->expects(static::once()) - ->method('getFailsDescription') - ->willReturn(['Payment method nonce can\'t be retrieved.']); - - $this->resultFactoryMock->expects(static::never()) - ->method('create'); - - $this->command->execute(['publicHash' => $publicHash, 'customerId' => $customerId]); - } - - /** - * @covers \Magento\Braintree\Gateway\Command\GetPaymentNonceCommand::execute - */ - public function testExecute() - { - $publicHash = '3wv2m24d2er3'; - $customerId = 1; - $token = 'jd2vnq'; - $nonce = 's1dj23'; - - $this->subjectReaderMock->expects(static::once()) - ->method('readPublicHash') - ->willReturn($publicHash); - - $this->subjectReaderMock->expects(static::once()) - ->method('readCustomerId') - ->willReturn($customerId); - - $this->tokenManagementMock->expects(static::once()) - ->method('getByPublicHash') - ->with($publicHash, $customerId) - ->willReturn($this->paymentTokenMock); - - $this->paymentTokenMock->expects(static::once()) - ->method('getGatewayToken') - ->willReturn($token); - - $obj = new \stdClass(); - $obj->success = true; - $obj->paymentMethodNonce = new \stdClass(); - $obj->paymentMethodNonce->nonce = $nonce; - $this->adapterMock->expects(static::once()) - ->method('createNonce') - ->with($token) - ->willReturn($obj); - - $this->responseValidatorMock->expects(static::once()) - ->method('validate') - ->with(['response' => ['object' => $obj]]) - ->willReturn($this->validationResultMock); - - $this->validationResultMock->expects(static::once()) - ->method('isValid') - ->willReturn(true); - - $this->validationResultMock->expects(self::never()) - ->method('getFailsDescription'); - - $expected = $this->getMockBuilder(ArrayResult::class) - ->disableOriginalConstructor() - ->setMethods(['get']) - ->getMock(); - $expected->expects(static::once()) - ->method('get') - ->willReturn(['paymentMethodNonce' => $nonce]); - $this->resultFactoryMock->expects(static::once()) - ->method('create') - ->willReturn($expected); - - $actual = $this->command->execute(['publicHash' => $publicHash, 'customerId' => $customerId]); - self::assertEquals($expected, $actual); - self::assertEquals($nonce, $actual->get()['paymentMethodNonce']); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Config/CanVoidHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Config/CanVoidHandlerTest.php deleted file mode 100644 index d87e0100686ec..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Config/CanVoidHandlerTest.php +++ /dev/null @@ -1,76 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Config; - -use Magento\Braintree\Gateway\Config\CanVoidHandler; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Payment\Model\InfoInterface; -use Magento\Sales\Model\Order\Payment; -use PHPUnit\Framework\TestCase; - -class CanVoidHandlerTest extends TestCase -{ - public function testHandleNotOrderPayment() - { - $paymentDO = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - $subject = [ - 'payment' => $paymentDO - ]; - - $subjectReader = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $subjectReader->expects(static::once()) - ->method('readPayment') - ->willReturn($paymentDO); - - $paymentMock = $this->getMockForAbstractClass(InfoInterface::class); - - $paymentDO->expects(static::once()) - ->method('getPayment') - ->willReturn($paymentMock); - - $voidHandler = new CanVoidHandler($subjectReader); - - static::assertFalse($voidHandler->handle($subject)); - } - - public function testHandleSomeAmountWasPaid() - { - $paymentDO = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - $subject = [ - 'payment' => $paymentDO - ]; - - $subjectReader = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $subjectReader->expects(static::once()) - ->method('readPayment') - ->willReturn($paymentDO); - - $paymentMock = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->getMock(); - - $paymentDO->expects(static::once()) - ->method('getPayment') - ->willReturn($paymentMock); - - $paymentMock->expects(static::once()) - ->method('getAmountPaid') - ->willReturn(1.00); - - $voidHandler = new CanVoidHandler($subjectReader); - - static::assertFalse($voidHandler->handle($subject)); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Config/ConfigTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Config/ConfigTest.php deleted file mode 100644 index 6ac0b1400fc35..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Config/ConfigTest.php +++ /dev/null @@ -1,382 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Config; - -use Magento\Braintree\Gateway\Config\Config; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\Serialize\Serializer\Json; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Store\Model\ScopeInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class ConfigTest extends TestCase -{ - const METHOD_CODE = 'braintree'; - - /** - * @var Config - */ - private $model; - - /** - * @var ScopeConfigInterface|MockObject - */ - private $scopeConfigMock; - - /** - * @var Json|MockObject - */ - private $serializerMock; - - protected function setUp(): void - { - $this->scopeConfigMock = $this->getMockForAbstractClass(ScopeConfigInterface::class); - $this->serializerMock = $this->createMock(Json::class); - - $objectManager = new ObjectManager($this); - $this->model = $objectManager->getObject( - Config::class, - [ - 'scopeConfig' => $this->scopeConfigMock, - 'methodCode' => self::METHOD_CODE, - 'serializer' => $this->serializerMock - ] - ); - } - - /** - * @param string $encodedValue - * @param string|array $value - * @param array $expected - * @dataProvider getCountrySpecificCardTypeConfigDataProvider - */ - public function testGetCountrySpecificCardTypeConfig($encodedValue, $value, array $expected) - { - $this->scopeConfigMock->expects(static::once()) - ->method('getValue') - ->with($this->getPath(Config::KEY_COUNTRY_CREDIT_CARD), ScopeInterface::SCOPE_STORE, null) - ->willReturn($encodedValue); - - $this->serializerMock->expects($this->once()) - ->method('unserialize') - ->with($encodedValue) - ->willReturn($value); - - static::assertEquals( - $expected, - $this->model->getCountrySpecificCardTypeConfig() - ); - } - - /** - * @return array - */ - public function getCountrySpecificCardTypeConfigDataProvider() - { - return [ - 'valid data' => [ - '{"GB":["VI","AE"],"US":["DI","JCB"]}', - ['GB' => ['VI', 'AE'], 'US' => ['DI', 'JCB']], - ['GB' => ['VI', 'AE'], 'US' => ['DI', 'JCB']] - ], - 'non-array value' => [ - '""', - '', - [] - ] - ]; - } - - /** - * @param string $value - * @param array $expected - * @dataProvider getAvailableCardTypesDataProvider - */ - public function testGetAvailableCardTypes($value, $expected) - { - $this->scopeConfigMock->expects(static::once()) - ->method('getValue') - ->with($this->getPath(Config::KEY_CC_TYPES), ScopeInterface::SCOPE_STORE, null) - ->willReturn($value); - - static::assertEquals( - $expected, - $this->model->getAvailableCardTypes() - ); - } - - /** - * @return array - */ - public function getAvailableCardTypesDataProvider() - { - return [ - [ - 'AE,VI,MC,DI,JCB', - ['AE', 'VI', 'MC', 'DI', 'JCB'] - ], - [ - '', - [] - ] - ]; - } - - /** - * @param string $value - * @param array $expected - * @dataProvider getCcTypesMapperDataProvider - */ - public function testGetCcTypesMapper($value, $expected) - { - $this->scopeConfigMock->expects(static::once()) - ->method('getValue') - ->with($this->getPath(Config::KEY_CC_TYPES_BRAINTREE_MAPPER), ScopeInterface::SCOPE_STORE, null) - ->willReturn($value); - - static::assertEquals( - $expected, - $this->model->getCcTypesMapper() - ); - } - - /** - * @return array - */ - public function getCcTypesMapperDataProvider() - { - return [ - [ - '{"visa":"VI","american-express":"AE"}', - ['visa' => 'VI', 'american-express' => 'AE'] - ], - [ - '{invalid json}', - [] - ], - [ - '', - [] - ] - ]; - } - - /** - * @covers \Magento\Braintree\Gateway\Config\Config::getCountryAvailableCardTypes - * @dataProvider getCountrySpecificCardTypeConfigDataProvider - * @param string $encodedData - * @param string|array $data - * @param array $countryData - */ - public function testCountryAvailableCardTypes($encodedData, $data, array $countryData) - { - $this->scopeConfigMock->expects(static::any()) - ->method('getValue') - ->with($this->getPath(Config::KEY_COUNTRY_CREDIT_CARD), ScopeInterface::SCOPE_STORE, null) - ->willReturn($encodedData); - - $this->serializerMock->expects($this->any()) - ->method('unserialize') - ->with($encodedData) - ->willReturn($data); - - foreach ($countryData as $countryId => $types) { - $result = $this->model->getCountryAvailableCardTypes($countryId); - static::assertEquals($types, $result); - } - - if (empty($countryData)) { - static::assertEquals($data, ""); - } - } - - /** - * @covers \Magento\Braintree\Gateway\Config\Config::isCvvEnabled - */ - public function testUseCvv() - { - $this->scopeConfigMock->expects(static::any()) - ->method('getValue') - ->with($this->getPath(Config::KEY_USE_CVV), ScopeInterface::SCOPE_STORE, null) - ->willReturn(1); - - static::assertTrue($this->model->isCvvEnabled()); - } - - /** - * @param mixed $data - * @param boolean $expected - * @dataProvider verify3DSecureDataProvider - * @covers \Magento\Braintree\Gateway\Config\Config::isVerify3DSecure - */ - public function testIsVerify3DSecure($data, $expected) - { - $this->scopeConfigMock->expects(static::any()) - ->method('getValue') - ->with($this->getPath(Config::KEY_VERIFY_3DSECURE), ScopeInterface::SCOPE_STORE, null) - ->willReturn($data); - static::assertEquals($expected, $this->model->isVerify3DSecure()); - } - - /** - * Get items to verify 3d secure testing - * @return array - */ - public function verify3DSecureDataProvider() - { - return [ - ['data' => 1, 'expected' => true], - ['data' => true, 'expected' => true], - ['data' => '1', 'expected' => true], - ['data' => 0, 'expected' => false], - ['data' => '0', 'expected' => false], - ['data' => false, 'expected' => false], - ]; - } - - /** - * @param mixed $data - * @param double $expected - * @covers \Magento\Braintree\Gateway\Config\Config::getThresholdAmount - * @dataProvider thresholdAmountDataProvider - */ - public function testGetThresholdAmount($data, $expected) - { - $this->scopeConfigMock->expects(static::any()) - ->method('getValue') - ->with($this->getPath(Config::KEY_THRESHOLD_AMOUNT), ScopeInterface::SCOPE_STORE, null) - ->willReturn($data); - static::assertEquals($expected, $this->model->getThresholdAmount()); - } - - /** - * Get items for testing threshold amount - * @return array - */ - public function thresholdAmountDataProvider() - { - return [ - ['data' => '23.01', 'expected' => 23.01], - ['data' => -1.02, 'expected' => -1.02], - ['data' => true, 'expected' => 1], - ['data' => 'true', 'expected' => 0], - ['data' => 'abc', 'expected' => 0], - ['data' => false, 'expected' => 0], - ['data' => 'false', 'expected' => 0], - ['data' => 1, 'expected' => 1], - ]; - } - - /** - * @param int $value - * @param array $expected - * @covers \Magento\Braintree\Gateway\Config\Config::get3DSecureSpecificCountries - * @dataProvider threeDSecureSpecificCountriesDataProvider - */ - public function testGet3DSecureSpecificCountries($value, array $expected) - { - $this->scopeConfigMock->expects(static::at(0)) - ->method('getValue') - ->with($this->getPath(Config::KEY_VERIFY_ALLOW_SPECIFIC), ScopeInterface::SCOPE_STORE, null) - ->willReturn($value); - - if ($value !== Config::VALUE_3DSECURE_ALL) { - $this->scopeConfigMock->expects(static::at(1)) - ->method('getValue') - ->with($this->getPath(Config::KEY_VERIFY_SPECIFIC), ScopeInterface::SCOPE_STORE, null) - ->willReturn('GB,US'); - } - static::assertEquals($expected, $this->model->get3DSecureSpecificCountries()); - } - - /** - * Get variations to test specific countries for 3d secure - * @return array - */ - public function threeDSecureSpecificCountriesDataProvider() - { - return [ - ['configValue' => 0, 'expected' => []], - ['configValue' => 1, 'expected' => ['GB', 'US']], - ]; - } - - /** - * @covers \Magento\Braintree\Gateway\Config\Config::getDynamicDescriptors - * @param $name - * @param $phone - * @param $url - * @param array $expected - * @dataProvider descriptorsDataProvider - */ - public function testGetDynamicDescriptors($name, $phone, $url, array $expected) - { - $this->scopeConfigMock->expects(static::at(0)) - ->method('getValue') - ->with($this->getPath('descriptor_name'), ScopeInterface::SCOPE_STORE, null) - ->willReturn($name); - $this->scopeConfigMock->expects(static::at(1)) - ->method('getValue') - ->with($this->getPath('descriptor_phone'), ScopeInterface::SCOPE_STORE, null) - ->willReturn($phone); - $this->scopeConfigMock->expects(static::at(2)) - ->method('getValue') - ->with($this->getPath('descriptor_url'), ScopeInterface::SCOPE_STORE, null) - ->willReturn($url); - - $actual = $this->model->getDynamicDescriptors(); - static::assertEquals($expected, $actual); - } - - /** - * Get variations to test dynamic descriptors - * @return array - */ - public function descriptorsDataProvider() - { - $name = 'company * product'; - $phone = '333-22-22-333'; - $url = 'https://test.url.mage.com'; - return [ - [ - $name, $phone, $url, - 'expected' => [ - 'name' => $name, 'phone' => $phone, 'url' => $url - ] - ], - [ - $name, null, null, - 'expected' => [ - 'name' => $name - ] - ], - [ - null, null, $url, - 'expected' => [ - 'url' => $url - ] - ], - [ - null, null, null, - 'expected' => [] - ] - ]; - } - - /** - * Return config path - * - * @param string $field - * @return string - */ - private function getPath($field) - { - return sprintf(Config::DEFAULT_PATH_PATTERN, self::METHOD_CODE, $field); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionRefundTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionRefundTest.php deleted file mode 100644 index d2255737b6b76..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionRefundTest.php +++ /dev/null @@ -1,158 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Http\Client; - -use Magento\Braintree\Gateway\Http\Client\TransactionRefund; -use Magento\Braintree\Gateway\Request\PaymentDataBuilder; -use Magento\Braintree\Model\Adapter\BraintreeAdapter; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Payment\Gateway\Http\ClientException; -use Magento\Payment\Gateway\Http\TransferInterface; -use Magento\Payment\Model\Method\Logger; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Psr\Log\LoggerInterface; - -/** - * Tests \Magento\Braintree\Gateway\Http\Client\TransactionRefund. - */ -class TransactionRefundTest extends TestCase -{ - /** - * @var TransactionRefund - */ - private $client; - - /** - * @var Logger|MockObject - */ - private $loggerMock; - - /** - * @var BraintreeAdapter|MockObject - */ - private $adapterMock; - - /** - * @var string - */ - private $transactionId = 'px4kpev5'; - - /** - * @var string - */ - private $paymentAmount = '100.00'; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - /** @var LoggerInterface|MockObject $criticalLoggerMock */ - $criticalLoggerMock = $this->getMockForAbstractClass(LoggerInterface::class); - $this->loggerMock = $this->getMockBuilder(Logger::class) - ->disableOriginalConstructor() - ->getMock(); - $this->adapterMock = $this->getMockBuilder(BraintreeAdapter::class) - ->disableOriginalConstructor() - ->getMock(); - /** @var BraintreeAdapterFactory|MockObject $adapterFactoryMock */ - $adapterFactoryMock = $this->getMockBuilder(BraintreeAdapterFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $adapterFactoryMock->expects(self::once()) - ->method('create') - ->willReturn($this->adapterMock); - - $this->client = new TransactionRefund($criticalLoggerMock, $this->loggerMock, $adapterFactoryMock); - } - - /** - * @return void - */ - public function testPlaceRequestException() - { - $this->expectException(ClientException::class); - $this->expectExceptionMessage('Test messages'); - $this->loggerMock->expects($this->once()) - ->method('debug') - ->with( - [ - 'request' => $this->getTransferData(), - 'client' => TransactionRefund::class, - 'response' => [], - ] - ); - - $this->adapterMock->expects($this->once()) - ->method('refund') - ->with($this->transactionId, $this->paymentAmount) - ->willThrowException(new \Exception('Test messages')); - - /** @var TransferInterface|MockObject $transferObjectMock */ - $transferObjectMock = $this->getTransferObjectMock(); - - $this->client->placeRequest($transferObjectMock); - } - - /** - * @return void - */ - public function testPlaceRequestSuccess() - { - $response = new \stdClass(); - $response->success = true; - $this->adapterMock->expects($this->once()) - ->method('refund') - ->with($this->transactionId, $this->paymentAmount) - ->willReturn($response); - - $this->loggerMock->expects($this->once()) - ->method('debug') - ->with( - [ - 'request' => $this->getTransferData(), - 'client' => TransactionRefund::class, - 'response' => ['success' => 1], - ] - ); - - $actualResult = $this->client->placeRequest($this->getTransferObjectMock()); - - $this->assertIsObject($actualResult['object']); - $this->assertEquals(['object' => $response], $actualResult); - } - - /** - * Creates mock object for TransferInterface. - * - * @return TransferInterface|MockObject - */ - private function getTransferObjectMock() - { - $transferObjectMock = $this->getMockForAbstractClass(TransferInterface::class); - $transferObjectMock->expects($this->once()) - ->method('getBody') - ->willReturn($this->getTransferData()); - - return $transferObjectMock; - } - - /** - * Creates stub request data. - * - * @return array - */ - private function getTransferData() - { - return [ - 'transaction_id' => $this->transactionId, - PaymentDataBuilder::AMOUNT => $this->paymentAmount, - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionSaleTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionSaleTest.php deleted file mode 100644 index 3756a6b616e9d..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionSaleTest.php +++ /dev/null @@ -1,161 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Http\Client; - -use Magento\Braintree\Gateway\Http\Client\TransactionSale; -use Magento\Braintree\Model\Adapter\BraintreeAdapter; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Payment\Gateway\Http\ClientException; -use Magento\Payment\Gateway\Http\TransferInterface; -use Magento\Payment\Model\Method\Logger; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Psr\Log\LoggerInterface; - -/** - * Tests \Magento\Braintree\Gateway\Http\Client\TransactionSale. - */ -class TransactionSaleTest extends TestCase -{ - /** - * @var TransactionSale - */ - private $model; - - /** - * @var Logger|MockObject - */ - private $loggerMock; - - /** - * @var BraintreeAdapter|MockObject - */ - private $adapterMock; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - /** @var LoggerInterface|MockObject $criticalLoggerMock */ - $criticalLoggerMock = $this->getMockForAbstractClass(LoggerInterface::class); - $this->loggerMock = $this->getMockBuilder(Logger::class) - ->disableOriginalConstructor() - ->getMock(); - $this->adapterMock = $this->getMockBuilder(BraintreeAdapter::class) - ->disableOriginalConstructor() - ->getMock(); - /** @var BraintreeAdapterFactory|MockObject $adapterFactoryMock */ - $adapterFactoryMock = $this->getMockBuilder(BraintreeAdapterFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $adapterFactoryMock->expects(self::once()) - ->method('create') - ->willReturn($this->adapterMock); - - $this->model = new TransactionSale($criticalLoggerMock, $this->loggerMock, $adapterFactoryMock); - } - - /** - * Runs test placeRequest method (exception) - * - * @return void - */ - public function testPlaceRequestException() - { - $this->expectException(ClientException::class); - $this->expectExceptionMessage('Test messages'); - $this->loggerMock->expects($this->once()) - ->method('debug') - ->with( - [ - 'request' => $this->getTransferData(), - 'client' => TransactionSale::class, - 'response' => [] - ] - ); - - $this->adapterMock->expects($this->once()) - ->method('sale') - ->willThrowException(new \Exception('Test messages')); - - /** @var TransferInterface|MockObject $transferObjectMock */ - $transferObjectMock = $this->getTransferObjectMock(); - - $this->model->placeRequest($transferObjectMock); - } - - /** - * Run test placeRequest method - * - * @return void - */ - public function testPlaceRequestSuccess() - { - $response = $this->getResponseObject(); - $this->adapterMock->expects($this->once()) - ->method('sale') - ->with($this->getTransferData()) - ->willReturn($response); - - $this->loggerMock->expects($this->once()) - ->method('debug') - ->with( - [ - 'request' => $this->getTransferData(), - 'client' => TransactionSale::class, - 'response' => ['success' => 1] - ] - ); - - $actualResult = $this->model->placeRequest($this->getTransferObjectMock()); - - $this->assertIsObject($actualResult['object']); - $this->assertEquals(['object' => $response], $actualResult); - } - - /** - * Creates mock object for TransferInterface. - * - * @return TransferInterface|MockObject - */ - private function getTransferObjectMock() - { - $transferObjectMock = $this->getMockForAbstractClass(TransferInterface::class); - $transferObjectMock->expects($this->once()) - ->method('getBody') - ->willReturn($this->getTransferData()); - - return $transferObjectMock; - } - - /** - * Creates stub for a response. - * - * @return \stdClass - */ - private function getResponseObject() - { - $obj = new \stdClass(); - $obj->success = true; - - return $obj; - } - - /** - * Creates stub request data. - * - * @return array - */ - private function getTransferData() - { - return [ - 'test-data-key' => 'test-data-value' - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionSubmitForSettlementTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionSubmitForSettlementTest.php deleted file mode 100644 index 386e22dcc7b97..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionSubmitForSettlementTest.php +++ /dev/null @@ -1,119 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Http\Client; - -use Braintree\Result\Successful; -use Magento\Braintree\Gateway\Http\Client\TransactionSubmitForSettlement; -use Magento\Braintree\Model\Adapter\BraintreeAdapter; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Payment\Gateway\Http\ClientException; -use Magento\Payment\Gateway\Http\TransferInterface; -use Magento\Payment\Model\Method\Logger; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Psr\Log\LoggerInterface; - -/** - * Tests \Magento\Braintree\Gateway\Http\Client\TransactionSubmitForSettlement. - */ -class TransactionSubmitForSettlementTest extends TestCase -{ - /** - * @var TransactionSubmitForSettlement - */ - private $client; - - /** - * @var Logger|MockObject - */ - private $loggerMock; - - /** - * @var BraintreeAdapter|MockObject - */ - private $adapterMock; - - protected function setUp(): void - { - /** @var LoggerInterface|MockObject $criticalLoggerMock */ - $criticalLoggerMock = $this->getMockForAbstractClass(LoggerInterface::class); - $this->loggerMock = $this->getMockBuilder(Logger::class) - ->disableOriginalConstructor() - ->setMethods(['debug']) - ->getMock(); - - $this->adapterMock = $this->getMockBuilder(BraintreeAdapter::class) - ->disableOriginalConstructor() - ->setMethods(['submitForSettlement']) - ->getMock(); - /** @var BraintreeAdapterFactory|MockObject $adapterFactoryMock */ - $adapterFactoryMock = $this->getMockBuilder(BraintreeAdapterFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $adapterFactoryMock->method('create') - ->willReturn($this->adapterMock); - - $this->client = new TransactionSubmitForSettlement( - $criticalLoggerMock, - $this->loggerMock, - $adapterFactoryMock - ); - } - - /** - * @covers \Magento\Braintree\Gateway\Http\Client\TransactionSubmitForSettlement::placeRequest - */ - public function testPlaceRequestWithException() - { - $this->expectException(ClientException::class); - $this->expectExceptionMessage('Transaction has been declined'); - $exception = new \Exception('Transaction has been declined'); - $this->adapterMock->expects(static::once()) - ->method('submitForSettlement') - ->willThrowException($exception); - - /** @var TransferInterface|MockObject $transferObject */ - $transferObject = $this->getTransferObjectMock(); - $this->client->placeRequest($transferObject); - } - - /** - * @covers \Magento\Braintree\Gateway\Http\Client\TransactionSubmitForSettlement::process - */ - public function testPlaceRequest() - { - $data = new Successful(['success'], [true]); - $this->adapterMock->expects(static::once()) - ->method('submitForSettlement') - ->willReturn($data); - - /** @var TransferInterface|MockObject $transferObject */ - $transferObject = $this->getTransferObjectMock(); - $response = $this->client->placeRequest($transferObject); - static::assertIsObject($response['object']); - static::assertEquals(['object' => $data], $response); - } - - /** - * Creates mock for TransferInterface - * - * @return TransferInterface|MockObject - */ - private function getTransferObjectMock() - { - $mock = $this->getMockForAbstractClass(TransferInterface::class); - $mock->expects($this->once()) - ->method('getBody') - ->willReturn([ - 'transaction_id' => 'vb4c6b', - 'amount' => 124.00, - ]); - - return $mock; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionVoidTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionVoidTest.php deleted file mode 100644 index 41c30505395e8..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/Client/TransactionVoidTest.php +++ /dev/null @@ -1,151 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Http\Client; - -use Magento\Braintree\Gateway\Http\Client\TransactionVoid; -use Magento\Braintree\Model\Adapter\BraintreeAdapter; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Payment\Gateway\Http\ClientException; -use Magento\Payment\Gateway\Http\TransferInterface; -use Magento\Payment\Model\Method\Logger; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Psr\Log\LoggerInterface; - -/** - * Tests \Magento\Braintree\Gateway\Http\Client\TransactionVoid. - */ -class TransactionVoidTest extends TestCase -{ - /** - * @var TransactionVoid - */ - private $client; - - /** - * @var Logger|MockObject - */ - private $loggerMock; - - /** - * @var BraintreeAdapter|MockObject - */ - private $adapterMock; - - /** - * @var string - */ - private $transactionId = 'px4kpev5'; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - /** @var LoggerInterface|MockObject $criticalLoggerMock */ - $criticalLoggerMock = $this->getMockForAbstractClass(LoggerInterface::class); - $this->loggerMock = $this->getMockBuilder(Logger::class) - ->disableOriginalConstructor() - ->getMock(); - $this->adapterMock = $this->getMockBuilder(BraintreeAdapter::class) - ->disableOriginalConstructor() - ->getMock(); - /** @var BraintreeAdapterFactory|MockObject $adapterFactoryMock */ - $adapterFactoryMock = $this->getMockBuilder(BraintreeAdapterFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $adapterFactoryMock->expects(self::once()) - ->method('create') - ->willReturn($this->adapterMock); - - $this->client = new TransactionVoid($criticalLoggerMock, $this->loggerMock, $adapterFactoryMock); - } - - /** - * @return void - */ - public function testPlaceRequestException() - { - $this->expectException(ClientException::class); - $this->expectExceptionMessage('Test messages'); - $this->loggerMock->expects($this->once()) - ->method('debug') - ->with( - [ - 'request' => $this->getTransferData(), - 'client' => TransactionVoid::class, - 'response' => [], - ] - ); - - $this->adapterMock->expects($this->once()) - ->method('void') - ->with($this->transactionId) - ->willThrowException(new \Exception('Test messages')); - - /** @var TransferInterface|MockObject $transferObjectMock */ - $transferObjectMock = $this->getTransferObjectMock(); - - $this->client->placeRequest($transferObjectMock); - } - - /** - * @return void - */ - public function testPlaceRequestSuccess() - { - $response = new \stdClass(); - $response->success = true; - $this->adapterMock->expects($this->once()) - ->method('void') - ->with($this->transactionId) - ->willReturn($response); - - $this->loggerMock->expects($this->once()) - ->method('debug') - ->with( - [ - 'request' => $this->getTransferData(), - 'client' => TransactionVoid::class, - 'response' => ['success' => 1], - ] - ); - - $actualResult = $this->client->placeRequest($this->getTransferObjectMock()); - - $this->assertIsObject($actualResult['object']); - $this->assertEquals(['object' => $response], $actualResult); - } - - /** - * Creates mock object for TransferInterface. - * - * @return TransferInterface|MockObject - */ - private function getTransferObjectMock() - { - $transferObjectMock = $this->getMockForAbstractClass(TransferInterface::class); - $transferObjectMock->expects($this->once()) - ->method('getBody') - ->willReturn($this->getTransferData()); - - return $transferObjectMock; - } - - /** - * Creates stub request data. - * - * @return array - */ - private function getTransferData() - { - return [ - 'transaction_id' => $this->transactionId, - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/TransferFactoryTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Http/TransferFactoryTest.php deleted file mode 100644 index 1f6092ec3b5bd..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Http/TransferFactoryTest.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Http; - -use Magento\Braintree\Gateway\Http\TransferFactory; -use Magento\Payment\Gateway\Http\TransferBuilder; -use Magento\Payment\Gateway\Http\TransferInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class TransferFactoryTest extends TestCase -{ - /** - * @var TransferFactory - */ - private $transferFactory; - - /** - * @var TransferFactory - */ - private $transferMock; - - /** - * @var TransferBuilder|MockObject - */ - private $transferBuilder; - - protected function setUp(): void - { - $this->transferBuilder = $this->createMock(TransferBuilder::class); - $this->transferMock = $this->getMockForAbstractClass(TransferInterface::class); - - $this->transferFactory = new TransferFactory( - $this->transferBuilder - ); - } - - public function testCreate() - { - $request = ['data1', 'data2']; - - $this->transferBuilder->expects($this->once()) - ->method('setBody') - ->with($request) - ->willReturnSelf(); - - $this->transferBuilder->expects($this->once()) - ->method('build') - ->willReturn($this->transferMock); - - $this->assertEquals($this->transferMock, $this->transferFactory->create($request)); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/AddressDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/AddressDataBuilderTest.php deleted file mode 100644 index 6abaf6e32809c..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/AddressDataBuilderTest.php +++ /dev/null @@ -1,212 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Request; - -use Magento\Braintree\Gateway\Request\AddressDataBuilder; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\AddressAdapterInterface; -use Magento\Payment\Gateway\Data\OrderAdapterInterface; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Gateway\Request\AddressDataBuilder. - */ -class AddressDataBuilderTest extends TestCase -{ - /** - * @var PaymentDataObjectInterface|MockObject - */ - private $paymentDOMock; - - /** - * @var OrderAdapterInterface|MockObject - */ - private $orderMock; - - /** - * @var AddressDataBuilder - */ - private $builder; - - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - protected function setUp(): void - { - $this->paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - $this->orderMock = $this->getMockForAbstractClass(OrderAdapterInterface::class); - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->builder = new AddressDataBuilder($this->subjectReaderMock); - } - - public function testBuildReadPaymentException() - { - $this->expectException(\InvalidArgumentException::class); - $buildSubject = [ - 'payment' => null, - ]; - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willThrowException(new \InvalidArgumentException()); - - $this->builder->build($buildSubject); - } - - public function testBuildNoAddresses() - { - $this->paymentDOMock->expects(static::once()) - ->method('getOrder') - ->willReturn($this->orderMock); - - $this->orderMock->expects(static::once()) - ->method('getShippingAddress') - ->willReturn(null); - $this->orderMock->expects(static::once()) - ->method('getBillingAddress') - ->willReturn(null); - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - ]; - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willReturn($this->paymentDOMock); - - static::assertEquals([], $this->builder->build($buildSubject)); - } - - /** - * @param array $addressData - * @param array $expectedResult - * - * @dataProvider dataProviderBuild - */ - public function testBuild($addressData, $expectedResult) - { - $addressMock = $this->getAddressMock($addressData); - - $this->paymentDOMock->expects(static::once()) - ->method('getOrder') - ->willReturn($this->orderMock); - - $this->orderMock->expects(static::once()) - ->method('getShippingAddress') - ->willReturn($addressMock); - $this->orderMock->expects(static::once()) - ->method('getBillingAddress') - ->willReturn($addressMock); - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - ]; - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willReturn($this->paymentDOMock); - - self::assertEquals($expectedResult, $this->builder->build($buildSubject)); - } - - /** - * @return array - */ - public function dataProviderBuild() - { - return [ - [ - [ - 'first_name' => 'John', - 'last_name' => 'Smith', - 'company' => 'Magento', - 'street_1' => 'street1', - 'street_2' => 'street2', - 'city' => 'Chicago', - 'region_code' => 'IL', - 'country_id' => 'US', - 'post_code' => '00000', - ], - [ - AddressDataBuilder::SHIPPING_ADDRESS => [ - AddressDataBuilder::FIRST_NAME => 'John', - AddressDataBuilder::LAST_NAME => 'Smith', - AddressDataBuilder::COMPANY => 'Magento', - AddressDataBuilder::STREET_ADDRESS => 'street1', - AddressDataBuilder::EXTENDED_ADDRESS => 'street2', - AddressDataBuilder::LOCALITY => 'Chicago', - AddressDataBuilder::REGION => 'IL', - AddressDataBuilder::POSTAL_CODE => '00000', - AddressDataBuilder::COUNTRY_CODE => 'US', - - ], - AddressDataBuilder::BILLING_ADDRESS => [ - AddressDataBuilder::FIRST_NAME => 'John', - AddressDataBuilder::LAST_NAME => 'Smith', - AddressDataBuilder::COMPANY => 'Magento', - AddressDataBuilder::STREET_ADDRESS => 'street1', - AddressDataBuilder::EXTENDED_ADDRESS => 'street2', - AddressDataBuilder::LOCALITY => 'Chicago', - AddressDataBuilder::REGION => 'IL', - AddressDataBuilder::POSTAL_CODE => '00000', - AddressDataBuilder::COUNTRY_CODE => 'US', - ], - ], - ], - ]; - } - - /** - * @param array $addressData - * @return AddressAdapterInterface|MockObject - */ - private function getAddressMock($addressData) - { - $addressMock = $this->getMockForAbstractClass(AddressAdapterInterface::class); - - $addressMock->expects(self::exactly(2)) - ->method('getFirstname') - ->willReturn($addressData['first_name']); - $addressMock->expects(self::exactly(2)) - ->method('getLastname') - ->willReturn($addressData['last_name']); - $addressMock->expects(self::exactly(2)) - ->method('getCompany') - ->willReturn($addressData['company']); - $addressMock->expects(self::exactly(2)) - ->method('getStreetLine1') - ->willReturn($addressData['street_1']); - $addressMock->expects(self::exactly(2)) - ->method('getStreetLine2') - ->willReturn($addressData['street_2']); - $addressMock->expects(self::exactly(2)) - ->method('getCity') - ->willReturn($addressData['city']); - $addressMock->expects(self::exactly(2)) - ->method('getRegionCode') - ->willReturn($addressData['region_code']); - $addressMock->expects(self::exactly(2)) - ->method('getPostcode') - ->willReturn($addressData['post_code']); - $addressMock->expects(self::exactly(2)) - ->method('getCountryId') - ->willReturn($addressData['country_id']); - - return $addressMock; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/CaptureDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/CaptureDataBuilderTest.php deleted file mode 100644 index 5e30a3f2779cf..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/CaptureDataBuilderTest.php +++ /dev/null @@ -1,122 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Request; - -use Magento\Braintree\Gateway\Request\CaptureDataBuilder; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Framework\Exception\LocalizedException; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Sales\Model\Order\Payment; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Gateway\Request\CaptureDataBuilder. - */ -class CaptureDataBuilderTest extends TestCase -{ - /** - * @var CaptureDataBuilder - */ - private $builder; - - /** - * @var Payment|MockObject - */ - private $paymentMock; - - /** - * @var Payment|MockObject - */ - private $paymentDOMock; - - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - protected function setUp(): void - { - $this->paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - $this->paymentMock = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->getMock(); - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->builder = new CaptureDataBuilder($this->subjectReaderMock); - } - - /** - * @covers \Magento\Braintree\Gateway\Request\CaptureDataBuilder::build - */ - public function testBuildWithException() - { - $this->expectException(LocalizedException::class); - $this->expectExceptionMessage('No authorization transaction to proceed capture.'); - $amount = 10.00; - $buildSubject = [ - 'payment' => $this->paymentDOMock, - 'amount' => $amount, - ]; - - $this->paymentMock->expects(self::once()) - ->method('getCcTransId') - ->willReturn(''); - - $this->paymentDOMock->expects(self::once()) - ->method('getPayment') - ->willReturn($this->paymentMock); - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willReturn($this->paymentDOMock); - - $this->builder->build($buildSubject); - } - - /** - * @covers \Magento\Braintree\Gateway\Request\CaptureDataBuilder::build - */ - public function testBuild() - { - $transactionId = 'b3b99d'; - $amount = 10.00; - - $expected = [ - 'transaction_id' => $transactionId, - 'amount' => $amount, - ]; - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - 'amount' => $amount, - ]; - - $this->paymentMock->expects(self::once()) - ->method('getCcTransId') - ->willReturn($transactionId); - - $this->paymentDOMock->expects(self::once()) - ->method('getPayment') - ->willReturn($this->paymentMock); - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willReturn($this->paymentDOMock); - $this->subjectReaderMock->expects(self::once()) - ->method('readAmount') - ->with($buildSubject) - ->willReturn($amount); - - static::assertEquals($expected, $this->builder->build($buildSubject)); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/ChannelDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/ChannelDataBuilderTest.php deleted file mode 100644 index 56a83ab05f80b..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/ChannelDataBuilderTest.php +++ /dev/null @@ -1,103 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Request; - -use Magento\Braintree\Gateway\Request\ChannelDataBuilder; -use Magento\Framework\App\ProductMetadataInterface; -use Magento\Payment\Gateway\Config\Config; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class ChannelDataBuilderTest extends TestCase -{ - /** - * @var ProductMetadataInterface|MockObject - */ - private $productMetadata; - - /** - * @var Config|MockObject - */ - private $config; - - /** - * @var ChannelDataBuilder - */ - private $builder; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->productMetadata = $this->getMockBuilder(ProductMetadataInterface::class) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - $this->config = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); - $this->builder = new ChannelDataBuilder($this->productMetadata, $this->config); - } - - /** - * @param string $edition - * @param array $expected - * @covers \Magento\Braintree\Gateway\Request\ChannelDataBuilder::build - * @dataProvider buildDataProvider - */ - public function testBuild($edition, array $expected) - { - $buildSubject = []; - - $this->config->method('getValue') - ->with(self::equalTo('channel')) - ->willReturn(null); - - $this->productMetadata->method('getEdition') - ->willReturn($edition); - - self::assertEquals($expected, $this->builder->build($buildSubject)); - } - - /** - * Checks a case when a channel provided via payment method configuration. - */ - public function testBuildWithChannelFromConfig() - { - $channel = 'Magento2_Cart_ConfigEdition_BT'; - - $this->config->method('getValue') - ->with(self::equalTo('channel')) - ->willReturn($channel); - - $this->productMetadata->expects(self::never()) - ->method('getEdition'); - - self::assertEquals( - [ - 'channel' => $channel - ], - $this->builder->build([]) - ); - } - - /** - * Get list of variations for build test - * @return array - */ - public function buildDataProvider() - { - return [ - ['FirstEdition', ['channel' => 'Magento2_Cart_FirstEdition_BT']], - ['SecondEdition', ['channel' => 'Magento2_Cart_SecondEdition_BT']], - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/CustomerDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/CustomerDataBuilderTest.php deleted file mode 100644 index 83cd4fe697b96..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/CustomerDataBuilderTest.php +++ /dev/null @@ -1,151 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Request; - -use Magento\Braintree\Gateway\Request\CustomerDataBuilder; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\AddressAdapterInterface; -use Magento\Payment\Gateway\Data\OrderAdapterInterface; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Gateway\Request\CustomerDataBuilder. - */ -class CustomerDataBuilderTest extends TestCase -{ - /** - * @var PaymentDataObjectInterface|MockObject - */ - private $paymentDOMock; - - /** - * @var OrderAdapterInterface|MockObject - */ - private $orderMock; - - /** - * @var CustomerDataBuilder - */ - private $builder; - - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - protected function setUp(): void - { - $this->paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - $this->orderMock = $this->getMockForAbstractClass(OrderAdapterInterface::class); - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->builder = new CustomerDataBuilder($this->subjectReaderMock); - } - - public function testBuildReadPaymentException() - { - $this->expectException(\InvalidArgumentException::class); - $buildSubject = [ - 'payment' => null, - ]; - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willThrowException(new \InvalidArgumentException()); - - $this->builder->build($buildSubject); - } - - /** - * @param array $billingData - * @param array $expectedResult - * - * @dataProvider dataProviderBuild - */ - public function testBuild($billingData, $expectedResult) - { - $billingMock = $this->getBillingMock($billingData); - - $this->paymentDOMock->expects(static::once()) - ->method('getOrder') - ->willReturn($this->orderMock); - $this->orderMock->expects(static::once()) - ->method('getBillingAddress') - ->willReturn($billingMock); - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - ]; - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willReturn($this->paymentDOMock); - - self::assertEquals($expectedResult, $this->builder->build($buildSubject)); - } - - /** - * @return array - */ - public function dataProviderBuild() - { - return [ - [ - [ - 'first_name' => 'John', - 'last_name' => 'Smith', - 'company' => 'Magento', - 'phone' => '555-555-555', - 'email' => 'john@magento.com', - ], - [ - CustomerDataBuilder::CUSTOMER => [ - CustomerDataBuilder::FIRST_NAME => 'John', - CustomerDataBuilder::LAST_NAME => 'Smith', - CustomerDataBuilder::COMPANY => 'Magento', - CustomerDataBuilder::PHONE => '555-555-555', - CustomerDataBuilder::EMAIL => 'john@magento.com', - ], - ], - ], - ]; - } - - /** - * @param array $billingData - * @return AddressAdapterInterface|MockObject - */ - private function getBillingMock($billingData) - { - $addressMock = $this->getMockForAbstractClass(AddressAdapterInterface::class); - - $addressMock->expects(static::once()) - ->method('getFirstname') - ->willReturn($billingData['first_name']); - $addressMock->expects(static::once()) - ->method('getLastname') - ->willReturn($billingData['last_name']); - $addressMock->expects(static::once()) - ->method('getCompany') - ->willReturn($billingData['company']); - $addressMock->expects(static::once()) - ->method('getTelephone') - ->willReturn($billingData['phone']); - $addressMock->expects(static::once()) - ->method('getEmail') - ->willReturn($billingData['email']); - - return $addressMock; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/DescriptorDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/DescriptorDataBuilderTest.php deleted file mode 100644 index 0e30977773659..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/DescriptorDataBuilderTest.php +++ /dev/null @@ -1,127 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Request; - -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\Request\DescriptorDataBuilder; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\OrderAdapterInterface; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class DescriptorDataBuilderTest extends TestCase -{ - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - /** - * @var Config|MockObject - */ - private $configMock; - - /** - * @var DescriptorDataBuilder - */ - private $builder; - - protected function setUp(): void - { - $this->configMock = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->setMethods(['getDynamicDescriptors']) - ->getMock(); - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->builder = new DescriptorDataBuilder($this->configMock, $this->subjectReaderMock); - } - - /** - * @param array $descriptors - * @param array $expected - * @dataProvider buildDataProvider - */ - public function testBuild(array $descriptors, array $expected) - { - $paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - $buildSubject = [ - 'payment' => $paymentDOMock, - ]; - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willReturn($paymentDOMock); - - $order = $this->getMockForAbstractClass(OrderAdapterInterface::class); - $order->expects(self::once())->method('getStoreId')->willReturn('1'); - - $paymentDOMock->expects(self::once())->method('getOrder')->willReturn($order); - - $this->configMock->method('getDynamicDescriptors')->willReturn($descriptors); - - $actual = $this->builder->build(['payment' => $paymentDOMock]); - static::assertEquals($expected, $actual); - } - - /** - * Get variations for build method testing - * @return array - */ - public function buildDataProvider() - { - $name = 'company * product'; - $phone = '333-22-22-333'; - $url = 'https://test.url.mage.com'; - return [ - [ - 'descriptors' => [ - 'name' => $name, - 'phone' => $phone, - 'url' => $url, - ], - 'expected' => [ - 'descriptor' => [ - 'name' => $name, - 'phone' => $phone, - 'url' => $url, - ], - ], - ], - [ - 'descriptors' => [ - 'name' => $name, - 'phone' => $phone, - ], - 'expected' => [ - 'descriptor' => [ - 'name' => $name, - 'phone' => $phone, - ], - ], - ], - [ - 'descriptors' => [ - 'name' => $name, - ], - 'expected' => [ - 'descriptor' => [ - 'name' => $name, - ], - ], - ], - [ - 'descriptors' => [], - 'expected' => [], - ], - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/KountPaymentDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/KountPaymentDataBuilderTest.php deleted file mode 100644 index 6fe0dc8e4e67a..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/KountPaymentDataBuilderTest.php +++ /dev/null @@ -1,122 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Request; - -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\Request\KountPaymentDataBuilder; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Braintree\Observer\DataAssignObserver; -use Magento\Payment\Gateway\Data\OrderAdapterInterface; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Sales\Model\Order\Payment; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Gateway\Request\KountPaymentDataBuilder. - */ -class KountPaymentDataBuilderTest extends TestCase -{ - const DEVICE_DATA = '{"test": "test"}'; - - /** - * @var KountPaymentDataBuilder - */ - private $builder; - - /** - * @var Config|MockObject - */ - private $configMock; - - /** - * @var Payment|MockObject - */ - private $paymentMock; - - /** - * @var PaymentDataObjectInterface|MockObject - */ - private $paymentDOMock; - - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - protected function setUp(): void - { - $this->paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - $this->configMock = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); - $this->paymentMock = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->getMock(); - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->builder = new KountPaymentDataBuilder($this->configMock, $this->subjectReaderMock); - } - - public function testBuildReadPaymentException() - { - $this->expectException(\InvalidArgumentException::class); - $buildSubject = []; - - $this->configMock->expects(self::never()) - ->method('hasFraudProtection') - ->willReturn(true); - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willThrowException(new \InvalidArgumentException()); - - $this->builder->build($buildSubject); - } - - public function testBuild() - { - $additionalData = [ - DataAssignObserver::DEVICE_DATA => self::DEVICE_DATA, - ]; - - $expectedResult = [ - KountPaymentDataBuilder::DEVICE_DATA => self::DEVICE_DATA, - ]; - - $order = $this->getMockForAbstractClass(OrderAdapterInterface::class); - $this->paymentDOMock->expects(self::once())->method('getOrder')->willReturn($order); - - $buildSubject = ['payment' => $this->paymentDOMock]; - - $this->paymentMock->expects(self::exactly(count($additionalData))) - ->method('getAdditionalInformation') - ->willReturn($additionalData); - - $this->configMock->expects(self::once()) - ->method('hasFraudProtection') - ->willReturn(true); - - $this->paymentDOMock->expects(self::once()) - ->method('getPayment') - ->willReturn($this->paymentMock); - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willReturn($this->paymentDOMock); - - static::assertEquals( - $expectedResult, - $this->builder->build($buildSubject) - ); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/DeviceDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/DeviceDataBuilderTest.php deleted file mode 100644 index 0203fcb789332..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/DeviceDataBuilderTest.php +++ /dev/null @@ -1,118 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Request\PayPal; - -use Magento\Braintree\Gateway\Request\PayPal\DeviceDataBuilder; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Payment\Model\InfoInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Gateway\Request\PayPal\DeviceDataBuilder. - */ -class DeviceDataBuilderTest extends TestCase -{ - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - /** - * @var PaymentDataObjectInterface|MockObject - */ - private $paymentDataObjectMock; - - /** - * @var InfoInterface|MockObject - */ - private $paymentInfoMock; - - /** - * @var DeviceDataBuilder - */ - private $builder; - - protected function setUp(): void - { - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->setMethods(['readPayment']) - ->getMock(); - - $this->paymentDataObjectMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - - $this->paymentInfoMock = $this->getMockForAbstractClass(InfoInterface::class); - - $this->builder = new DeviceDataBuilder($this->subjectReaderMock); - } - - /** - * @covers \Magento\Braintree\Gateway\Request\PayPal\DeviceDataBuilder::build - * @param array $paymentData - * @param array $expected - * @dataProvider buildDataProvider - */ - public function testBuild(array $paymentData, array $expected) - { - $subject = [ - 'payment' => $this->paymentDataObjectMock, - ]; - - $this->subjectReaderMock->expects(static::once()) - ->method('readPayment') - ->with($subject) - ->willReturn($this->paymentDataObjectMock); - - $this->paymentDataObjectMock->expects(static::once()) - ->method('getPayment') - ->willReturn($this->paymentInfoMock); - - $this->paymentInfoMock->expects(static::once()) - ->method('getAdditionalInformation') - ->willReturn($paymentData); - - $actual = $this->builder->build($subject); - static::assertEquals($expected, $actual); - } - - /** - * Get variations for build method testing - * @return array - */ - public function buildDataProvider() - { - return [ - [ - 'paymentData' => [ - 'device_data' => '{correlation_id: 12s3jf9as}' - ], - 'expected' => [ - 'deviceData' => '{correlation_id: 12s3jf9as}' - ] - ], - [ - 'paymentData' => [ - 'device_data' => null, - ], - 'expected' => [] - ], - [ - 'paymentData' => [ - 'deviceData' => '{correlation_id: 12s3jf9as}', - ], - 'expected' => [] - ], - [ - 'paymentData' => [], - 'expected' => [] - ] - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/VaultDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/VaultDataBuilderTest.php deleted file mode 100644 index e996882540707..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PayPal/VaultDataBuilderTest.php +++ /dev/null @@ -1,115 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Request\PayPal; - -use Magento\Braintree\Gateway\Request\PayPal\VaultDataBuilder; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Payment\Model\InfoInterface; -use Magento\Vault\Model\Ui\VaultConfigProvider; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Gateway\Request\PayPal\VaultDataBuilder. - */ -class VaultDataBuilderTest extends TestCase -{ - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - /** - * @var PaymentDataObjectInterface|MockObject - */ - private $paymentDataObjectMock; - - /** - * @var InfoInterface|MockObject - */ - private $paymentInfoMock; - - /** - * @var VaultDataBuilder - */ - private $builder; - - protected function setUp(): void - { - $this->paymentDataObjectMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - - $this->paymentInfoMock = $this->getMockForAbstractClass(InfoInterface::class); - - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->setMethods(['readPayment']) - ->getMock(); - - $this->builder = new VaultDataBuilder($this->subjectReaderMock); - } - - /** - * @covers \Magento\Braintree\Gateway\Request\PayPal\VaultDataBuilder::build - * @param array $additionalInfo - * @param array $expected - * @dataProvider buildDataProvider - */ - public function testBuild(array $additionalInfo, array $expected) - { - $subject = [ - 'payment' => $this->paymentDataObjectMock, - ]; - - $this->subjectReaderMock->expects(static::once()) - ->method('readPayment') - ->with($subject) - ->willReturn($this->paymentDataObjectMock); - - $this->paymentDataObjectMock->expects(static::once()) - ->method('getPayment') - ->willReturn($this->paymentInfoMock); - - $this->paymentInfoMock->expects(static::once()) - ->method('getAdditionalInformation') - ->willReturn($additionalInfo); - - $actual = $this->builder->build($subject); - static::assertEquals($expected, $actual); - } - - /** - * Get variations to test build method - * @return array - */ - public function buildDataProvider() - { - return [ - [ - 'additionalInfo' => [ - VaultConfigProvider::IS_ACTIVE_CODE => true - ], - 'expected' => [ - 'options' => [ - 'storeInVaultOnSuccess' => true - ] - ] - ], - [ - 'additionalInfo' => [ - VaultConfigProvider::IS_ACTIVE_CODE => false - ], - 'expected' => [] - ], - [ - 'additionalInfo' => [], - 'expected' => [] - ], - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PaymentDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PaymentDataBuilderTest.php deleted file mode 100644 index bde20d50ab659..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/PaymentDataBuilderTest.php +++ /dev/null @@ -1,166 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Request; - -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\Request\PaymentDataBuilder; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Braintree\Observer\DataAssignObserver; -use Magento\Payment\Gateway\Data\OrderAdapterInterface; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Sales\Model\Order\Payment; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Gateway\Request\PaymentDataBuilder. - */ -class PaymentDataBuilderTest extends TestCase -{ - const PAYMENT_METHOD_NONCE = 'nonce'; - - /** - * @var PaymentDataBuilder - */ - private $builder; - - /** - * @var Payment|MockObject - */ - private $paymentMock; - - /** - * @var PaymentDataObjectInterface|MockObject - */ - private $paymentDOMock; - - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - /** - * @var OrderAdapterInterface|MockObject - */ - private $orderMock; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - $this->paymentMock = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->getMock(); - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - $this->orderMock = $this->getMockForAbstractClass(OrderAdapterInterface::class); - - /** @var Config $config */ - $config = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->builder = new PaymentDataBuilder($config, $this->subjectReaderMock); - } - - /** - * @return void - */ - public function testBuildReadPaymentException(): void - { - $this->expectException(\InvalidArgumentException::class); - $buildSubject = []; - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willThrowException(new \InvalidArgumentException()); - - $this->builder->build($buildSubject); - } - - /** - * @return void - */ - public function testBuildReadAmountException(): void - { - $this->expectException(\InvalidArgumentException::class); - $buildSubject = [ - 'payment' => $this->paymentDOMock, - 'amount' => null, - ]; - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willReturn($this->paymentDOMock); - $this->subjectReaderMock->expects(self::once()) - ->method('readAmount') - ->with($buildSubject) - ->willThrowException(new \InvalidArgumentException()); - - $this->builder->build($buildSubject); - } - - /** - * @return void - */ - public function testBuild(): void - { - $additionalData = [ - [ - DataAssignObserver::PAYMENT_METHOD_NONCE, - self::PAYMENT_METHOD_NONCE, - ], - ]; - - $expectedResult = [ - PaymentDataBuilder::AMOUNT => 10.00, - PaymentDataBuilder::PAYMENT_METHOD_NONCE => self::PAYMENT_METHOD_NONCE, - PaymentDataBuilder::ORDER_ID => '000000101' - ]; - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - 'amount' => 10.00, - ]; - - $this->paymentMock->expects(self::exactly(count($additionalData))) - ->method('getAdditionalInformation') - ->willReturnMap($additionalData); - - $this->paymentDOMock->expects(self::once()) - ->method('getPayment') - ->willReturn($this->paymentMock); - - $this->paymentDOMock->expects(self::once()) - ->method('getOrder') - ->willReturn($this->orderMock); - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willReturn($this->paymentDOMock); - $this->subjectReaderMock->expects(self::once()) - ->method('readAmount') - ->with($buildSubject) - ->willReturn(10.00); - - $this->orderMock->expects(self::once()) - ->method('getOrderIncrementId') - ->willReturn('000000101'); - - self::assertEquals( - $expectedResult, - $this->builder->build($buildSubject) - ); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/RefundDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/RefundDataBuilderTest.php deleted file mode 100644 index f0ab7056d69a4..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/RefundDataBuilderTest.php +++ /dev/null @@ -1,153 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Request; - -use Magento\Braintree\Gateway\Request\PaymentDataBuilder; -use Magento\Braintree\Gateway\Request\RefundDataBuilder; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Sales\Api\Data\TransactionInterface; -use Magento\Sales\Model\Order\Payment; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Gateway\Request\RefundDataBuilder. - */ -class RefundDataBuilderTest extends TestCase -{ - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - /** - * @var PaymentDataObjectInterface|MockObject - */ - private $paymentDOMock; - - /** - * @var Payment|MockObject - */ - private $paymentModelMock; - - /** - * @var RefundDataBuilder - */ - private $dataBuilder; - - /** - * @var string - */ - private $transactionId = 'xsd7n'; - - protected function setUp(): void - { - $this->paymentModelMock = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->dataBuilder = new RefundDataBuilder($this->subjectReaderMock); - } - - public function testBuild() - { - $this->initPaymentDOMock(); - $buildSubject = ['payment' => $this->paymentDOMock, 'amount' => 12.358]; - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willReturn($this->paymentDOMock); - $this->paymentModelMock->expects(self::once()) - ->method('getParentTransactionId') - ->willReturn($this->transactionId); - $this->subjectReaderMock->expects(self::once()) - ->method('readAmount') - ->with($buildSubject) - ->willReturn($buildSubject['amount']); - - static::assertEquals( - [ - 'transaction_id' => $this->transactionId, - PaymentDataBuilder::AMOUNT => '12.36', - ], - $this->dataBuilder->build($buildSubject) - ); - } - - public function testBuildNullAmount() - { - $this->initPaymentDOMock(); - $buildSubject = ['payment' => $this->paymentDOMock]; - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willReturn($this->paymentDOMock); - $this->paymentModelMock->expects(self::once()) - ->method('getParentTransactionId') - ->willReturn($this->transactionId); - $this->subjectReaderMock->expects(self::once()) - ->method('readAmount') - ->with($buildSubject) - ->willThrowException(new \InvalidArgumentException()); - - static::assertEquals( - [ - 'transaction_id' => $this->transactionId, - PaymentDataBuilder::AMOUNT => null, - ], - $this->dataBuilder->build($buildSubject) - ); - } - - public function testBuildCutOffLegacyTransactionIdPostfix() - { - $this->initPaymentDOMock(); - $buildSubject = ['payment' => $this->paymentDOMock]; - $legacyTxnId = 'xsd7n-' . TransactionInterface::TYPE_CAPTURE; - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willReturn($this->paymentDOMock); - $this->paymentModelMock->expects(self::once()) - ->method('getParentTransactionId') - ->willReturn($legacyTxnId); - $this->subjectReaderMock->expects(self::once()) - ->method('readAmount') - ->with($buildSubject) - ->willThrowException(new \InvalidArgumentException()); - - static::assertEquals( - [ - 'transaction_id' => $this->transactionId, - PaymentDataBuilder::AMOUNT => null, - ], - $this->dataBuilder->build($buildSubject) - ); - } - - /** - * Creates mock object for PaymentDataObjectInterface - * - * @return void - */ - private function initPaymentDOMock(): void - { - $this->paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - $this->paymentDOMock->expects(self::once()) - ->method('getPayment') - ->willReturn($this->paymentModelMock); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/SettlementDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/SettlementDataBuilderTest.php deleted file mode 100644 index e1daec1f29f7c..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/SettlementDataBuilderTest.php +++ /dev/null @@ -1,26 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Request; - -use Magento\Braintree\Gateway\Request\SettlementDataBuilder; -use PHPUnit\Framework\TestCase; - -class SettlementDataBuilderTest extends TestCase -{ - public function testBuild() - { - $this->assertEquals( - [ - 'options' => [ - SettlementDataBuilder::SUBMIT_FOR_SETTLEMENT => true - ] - ], - (new SettlementDataBuilder())->build([]) - ); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/ThreeDSecureDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/ThreeDSecureDataBuilderTest.php deleted file mode 100644 index a65941ff30d1f..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/ThreeDSecureDataBuilderTest.php +++ /dev/null @@ -1,185 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Request; - -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\Request\ThreeDSecureDataBuilder; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\Order\AddressAdapter; -use Magento\Payment\Gateway\Data\Order\OrderAdapter; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Gateway\Request\ThreeDSecureDataBuilder. - */ -class ThreeDSecureDataBuilderTest extends TestCase -{ - /** - * @var ThreeDSecureDataBuilder - */ - private $builder; - - /** - * @var Config|MockObject - */ - private $configMock; - - /** - * @var PaymentDataObjectInterface|MockObject - */ - private $paymentDOMock; - - /** - * @var OrderAdapter|MockObject - */ - private $orderMock; - - /** - * @var AddressAdapter|MockObject - */ - private $billingAddressMock; - - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - /** - * @var int - */ - private $storeId = 1; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->initOrderMock(); - - $this->paymentDOMock = $this->getMockBuilder(PaymentDataObjectInterface::class) - ->disableOriginalConstructor() - ->setMethods(['getOrder', 'getPayment']) - ->getMockForAbstractClass(); - $this->paymentDOMock->expects(static::once()) - ->method('getOrder') - ->willReturn($this->orderMock); - - $this->configMock = $this->getMockBuilder(Config::class) - ->setMethods(['isVerify3DSecure', 'getThresholdAmount', 'get3DSecureSpecificCountries']) - ->disableOriginalConstructor() - ->getMock(); - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->builder = new ThreeDSecureDataBuilder($this->configMock, $this->subjectReaderMock); - } - - /** - * @param bool $verify - * @param float $thresholdAmount - * @param string $countryId - * @param array $countries - * @param array $expected - * @covers \Magento\Braintree\Gateway\Request\ThreeDSecureDataBuilder::build - * @dataProvider buildDataProvider - */ - public function testBuild($verify, $thresholdAmount, $countryId, array $countries, array $expected) - { - $buildSubject = [ - 'payment' => $this->paymentDOMock, - 'amount' => 25, - ]; - - $this->configMock->expects(static::once()) - ->method('isVerify3DSecure') - ->with(self::equalTo($this->storeId)) - ->willReturn($verify); - - $this->configMock->expects(static::any()) - ->method('getThresholdAmount') - ->with(self::equalTo($this->storeId)) - ->willReturn($thresholdAmount); - - $this->configMock->expects(static::any()) - ->method('get3DSecureSpecificCountries') - ->with(self::equalTo($this->storeId)) - ->willReturn($countries); - - $this->billingAddressMock->expects(static::any()) - ->method('getCountryId') - ->willReturn($countryId); - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willReturn($this->paymentDOMock); - $this->subjectReaderMock->expects(self::once()) - ->method('readAmount') - ->with($buildSubject) - ->willReturn(25); - - $result = $this->builder->build($buildSubject); - self::assertEquals($expected, $result); - } - - /** - * Gets list of variations to build request data. - * - * @return array - */ - public function buildDataProvider() - { - return [ - ['verify' => true, 'amount' => 20, 'countryId' => 'US', 'countries' => [], 'result' => [ - 'options' => [ - 'three_d_secure' => [ - 'required' => true - ] - ] - ]], - ['verify' => true, 'amount' => 0, 'countryId' => 'US', 'countries' => ['US', 'GB'], 'result' => [ - 'options' => [ - 'three_d_secure' => [ - 'required' => true - ] - ] - ]], - ['verify' => true, 'amount' => 40, 'countryId' => 'US', 'countries' => [], 'result' => []], - ['verify' => false, 'amount' => 40, 'countryId' => 'US', 'countries' => [], 'result' => []], - ['verify' => false, 'amount' => 20, 'countryId' => 'US', 'countries' => [], 'result' => []], - ['verify' => true, 'amount' => 20, 'countryId' => 'CA', 'countries' => ['US', 'GB'], 'result' => []], - ]; - } - - /** - * Creates mock object for order adapter. - * - * @return void - */ - private function initOrderMock() - { - $this->billingAddressMock = $this->getMockBuilder(AddressAdapter::class) - ->disableOriginalConstructor() - ->setMethods(['getCountryId']) - ->getMock(); - - $this->orderMock = $this->getMockBuilder(OrderAdapter::class) - ->disableOriginalConstructor() - ->setMethods(['getBillingAddress', 'getStoreId']) - ->getMock(); - - $this->orderMock->expects(static::any()) - ->method('getBillingAddress') - ->willReturn($this->billingAddressMock); - $this->orderMock->method('getStoreId') - ->willReturn($this->storeId); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultCaptureDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultCaptureDataBuilderTest.php deleted file mode 100644 index 9612beec6a6b2..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultCaptureDataBuilderTest.php +++ /dev/null @@ -1,144 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Request; - -use Magento\Braintree\Gateway\Request\VaultCaptureDataBuilder; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Command\CommandException; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Sales\Api\Data\OrderPaymentExtension; -use Magento\Sales\Model\Order\Payment; -use Magento\Vault\Model\PaymentToken; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Gateway\Request\VaultCaptureDataBuilder. - */ -class VaultCaptureDataBuilderTest extends TestCase -{ - /** - * @var VaultCaptureDataBuilder - */ - private $builder; - - /** - * @var PaymentDataObjectInterface|MockObject - */ - private $paymentDO; - - /** - * @var Payment|MockObject - */ - private $payment; - - /** - * @var SubjectReader|MockObject - */ - private $subjectReader; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->paymentDO = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - $this->payment = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->getMock(); - $this->paymentDO->method('getPayment') - ->willReturn($this->payment); - - $this->subjectReader = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->builder = new VaultCaptureDataBuilder($this->subjectReader); - } - - /** - * Checks the result after builder execution. - */ - public function testBuild(): void - { - $amount = 30.00; - $token = '5tfm4c'; - $buildSubject = [ - 'payment' => $this->paymentDO, - 'amount' => $amount, - ]; - - $expected = [ - 'amount' => $amount, - 'paymentMethodToken' => $token, - ]; - - $this->subjectReader->method('readPayment') - ->with($buildSubject) - ->willReturn($this->paymentDO); - $this->subjectReader->method('readAmount') - ->with($buildSubject) - ->willReturn($amount); - - /** @var OrderPaymentExtension|MockObject $paymentExtension */ - $paymentExtension = $this->getMockBuilder(OrderPaymentExtension::class) - ->setMethods(['getVaultPaymentToken']) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - - /** @var PaymentToken|MockObject $paymentToken */ - $paymentToken = $this->getMockBuilder(PaymentToken::class) - ->disableOriginalConstructor() - ->getMock(); - - $paymentExtension->method('getVaultPaymentToken') - ->willReturn($paymentToken); - $this->payment->method('getExtensionAttributes') - ->willReturn($paymentExtension); - - $paymentToken->method('getGatewayToken') - ->willReturn($token); - - $result = $this->builder->build($buildSubject); - self::assertEquals($expected, $result); - } - - /** - * Checks a builder execution if Payment Token doesn't exist. - */ - public function testBuildWithoutPaymentToken(): void - { - $this->expectException(CommandException::class); - $this->expectExceptionMessage('The Payment Token is not available to perform the request.'); - $amount = 30.00; - $buildSubject = [ - 'payment' => $this->paymentDO, - 'amount' => $amount, - ]; - - $this->subjectReader->method('readPayment') - ->with($buildSubject) - ->willReturn($this->paymentDO); - $this->subjectReader->method('readAmount') - ->with($buildSubject) - ->willReturn($amount); - - /** @var OrderPaymentExtension|MockObject $paymentExtension */ - $paymentExtension = $this->getMockBuilder(OrderPaymentExtension::class) - ->setMethods(['getVaultPaymentToken']) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - - $this->payment->method('getExtensionAttributes') - ->willReturn($paymentExtension); - $paymentExtension->method('getVaultPaymentToken') - ->willReturn(null); - - $this->builder->build($buildSubject); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultDataBuilderTest.php deleted file mode 100644 index b8b5960a34ebd..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VaultDataBuilderTest.php +++ /dev/null @@ -1,31 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Request; - -use Magento\Braintree\Gateway\Request\VaultDataBuilder; -use PHPUnit\Framework\TestCase; - -class VaultDataBuilderTest extends TestCase -{ - public function testBuild() - { - $expectedResult = [ - VaultDataBuilder::OPTIONS => [ - VaultDataBuilder::STORE_IN_VAULT_ON_SUCCESS => true - ] - ]; - - $buildSubject = []; - - $builder = new VaultDataBuilder(); - static::assertEquals( - $expectedResult, - $builder->build($buildSubject) - ); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VoidDataBuilderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VoidDataBuilderTest.php deleted file mode 100644 index 6b816eadd074e..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Request/VoidDataBuilderTest.php +++ /dev/null @@ -1,118 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Request; - -use Magento\Braintree\Gateway\Request\VoidDataBuilder; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Sales\Model\Order\Payment; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Gateway\Request\VaultCaptureDataBuilder. - */ -class VoidDataBuilderTest extends TestCase -{ - /** - * @var VoidDataBuilder - */ - private $builder; - - /** - * @var PaymentDataObjectInterface|MockObject - */ - private $paymentDOMock; - - /** - * @var Payment|MockObject - */ - private $paymentMock; - - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->paymentDOMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - $this->paymentMock = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->getMock(); - $this->paymentDOMock->expects(static::once()) - ->method('getPayment') - ->willReturn($this->paymentMock); - - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->builder = new VoidDataBuilder($this->subjectReaderMock); - } - - /** - * @param string|null $parentTransactionId - * @param string $callLastTransId - * @param string $lastTransId - * @param string $expected - * @return void - * @dataProvider buildDataProvider - */ - public function testBuild($parentTransactionId, $callLastTransId, $lastTransId, $expected) - { - $amount = 30.00; - - $buildSubject = [ - 'payment' => $this->paymentDOMock, - 'amount' => $amount, - ]; - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($buildSubject) - ->willReturn($this->paymentDOMock); - - $this->paymentMock->expects(self::once()) - ->method('getParentTransactionId') - ->willReturn($parentTransactionId); - $this->paymentMock->expects(self::$callLastTransId()) - ->method('getLastTransId') - ->willReturn($lastTransId); - - $result = $this->builder->build($buildSubject); - self::assertEquals( - ['transaction_id' => $expected], - $result - ); - } - - /** - * @return array - */ - public function buildDataProvider() - { - return [ - [ - 'parentTransactionId' => 'b3b99d', - 'callLastTransId' => 'never', - 'lastTransId' => 'd45d22', - 'expected' => 'b3b99d', - ], - [ - 'parentTransactionId' => null, - 'callLastTransId' => 'once', - 'expected' => 'd45d22', - 'lastTransId' => 'd45d22', - ], - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/CancelDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/CancelDetailsHandlerTest.php deleted file mode 100644 index b9cd0d901e7fe..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/CancelDetailsHandlerTest.php +++ /dev/null @@ -1,61 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Response; - -use Magento\Braintree\Gateway\Response\CancelDetailsHandler; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\OrderAdapterInterface; -use Magento\Payment\Gateway\Data\PaymentDataObject; -use Magento\Sales\Model\Order\Payment; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Gateway\Response\CancelDetailsHandler. - */ -class CancelDetailsHandlerTest extends TestCase -{ - /** - * @var CancelDetailsHandler - */ - private $handler; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->handler = new CancelDetailsHandler(new SubjectReader()); - } - - /** - * Checks a case when cancel handler closes the current and parent transactions. - * - * @return void - */ - public function testHandle(): void - { - /** @var OrderAdapterInterface|MockObject $order */ - $order = $this->getMockForAbstractClass(OrderAdapterInterface::class); - /** @var Payment|MockObject $payment */ - $payment = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->setMethods(['setOrder']) - ->getMock(); - - $paymentDO = new PaymentDataObject($order, $payment); - $response = [ - 'payment' => $paymentDO, - ]; - - $this->handler->handle($response, []); - - self::assertTrue($payment->getIsTransactionClosed(), 'The current transaction should be closed.'); - self::assertTrue($payment->getShouldCloseParentTransaction(), 'The parent transaction should be closed.'); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/CardDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/CardDetailsHandlerTest.php deleted file mode 100644 index f39b65f3c8e85..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/CardDetailsHandlerTest.php +++ /dev/null @@ -1,158 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Response; - -use Braintree\Transaction; -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\Response\CardDetailsHandler; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\PaymentDataObject; -use Magento\Sales\Model\Order\Payment; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Gateway\Response\CardDetailsHandler. - */ -class CardDetailsHandlerTest extends TestCase -{ - /** - * @var CardDetailsHandler - */ - private $cardHandler; - - /** - * @var Payment|MockObject - */ - private $paymentMock; - - /** - * @var Config|MockObject - */ - private $configMock; - - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - protected function setUp(): void - { - $this->initConfigMock(); - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->cardHandler = new CardDetailsHandler($this->configMock, $this->subjectReaderMock); - } - - /** - * @covers \Magento\Braintree\Gateway\Response\CardDetailsHandler::handle - */ - public function testHandle() - { - $paymentDataMock = $this->getPaymentDataObjectMock(); - $transaction = $this->getBraintreeTransaction(); - - $subject = ['payment' => $paymentDataMock]; - $response = ['object' => $transaction]; - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($subject) - ->willReturn($paymentDataMock); - $this->subjectReaderMock->expects(self::once()) - ->method('readTransaction') - ->with($response) - ->willReturn($transaction); - - $this->paymentMock->expects(static::once()) - ->method('setCcLast4'); - $this->paymentMock->expects(static::once()) - ->method('setCcExpMonth'); - $this->paymentMock->expects(static::once()) - ->method('setCcExpYear'); - $this->paymentMock->expects(static::once()) - ->method('setCcType'); - $this->paymentMock->expects(static::exactly(2)) - ->method('setAdditionalInformation'); - - $this->cardHandler->handle($subject, $response); - } - - /** - * Create mock for gateway config - */ - private function initConfigMock() - { - $this->configMock = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->setMethods(['getCctypesMapper']) - ->getMock(); - - $this->configMock->expects(static::once()) - ->method('getCctypesMapper') - ->willReturn([ - 'american-express' => 'AE', - 'discover' => 'DI', - 'jcb' => 'JCB', - 'mastercard' => 'MC', - 'master-card' => 'MC', - 'visa' => 'VI' - ]); - } - - /** - * Create mock for payment data object and order payment - * @return MockObject - */ - private function getPaymentDataObjectMock() - { - $this->paymentMock = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->setMethods([ - 'setCcLast4', - 'setCcExpMonth', - 'setCcExpYear', - 'setCcType', - 'setAdditionalInformation', - ]) - ->getMock(); - - $mock = $this->getMockBuilder(PaymentDataObject::class) - ->setMethods(['getPayment']) - ->disableOriginalConstructor() - ->getMock(); - - $mock->expects(static::once()) - ->method('getPayment') - ->willReturn($this->paymentMock); - - return $mock; - } - - /** - * Create Braintree transaction - * @return Transaction - */ - private function getBraintreeTransaction() - { - $attributes = [ - 'creditCard' => [ - 'bin' => '5421', - 'cardType' => 'American Express', - 'expirationMonth' => 12, - 'expirationYear' => 21, - 'last4' => 1231 - ] - ]; - $transaction = Transaction::factory($attributes); - - return $transaction; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPal/VaultDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPal/VaultDetailsHandlerTest.php deleted file mode 100644 index a8621b1b83e67..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPal/VaultDetailsHandlerTest.php +++ /dev/null @@ -1,235 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Response\PayPal; - -use Braintree\Result\Successful; -use Braintree\Transaction; -use Braintree\Transaction\PayPalDetails; -use Magento\Braintree\Gateway\Response\PayPal\VaultDetailsHandler; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Framework\Intl\DateTimeFactory; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Sales\Api\Data\OrderPaymentExtensionInterface; -use Magento\Sales\Api\Data\OrderPaymentExtensionInterfaceFactory; -use Magento\Sales\Model\Order\Payment; -use Magento\Vault\Api\Data\PaymentTokenFactoryInterface; -use Magento\Vault\Api\Data\PaymentTokenInterface; -use Magento\Vault\Model\PaymentToken; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Gateway\Response\PayPal\VaultDetailsHandler. - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class VaultDetailsHandlerTest extends TestCase -{ - private static $transactionId = '1n2suy'; - - private static $token = 'rc39al'; - - private static $payerEmail = 'john.doe@example.com'; - - /** - * @var PaymentDataObjectInterface|MockObject - */ - private $paymentDataObjectMock; - - /** - * @var Payment|MockObject - */ - private $paymentInfoMock; - - /** - * @var PaymentTokenFactoryInterface|MockObject - */ - private $paymentTokenFactoryMock; - - /** - * @var PaymentTokenInterface|MockObject - */ - protected $paymentTokenMock; - - /** - * @var OrderPaymentExtension|MockObject - */ - private $paymentExtensionMock; - - /** - * @var OrderPaymentExtensionInterfaceFactory|MockObject - */ - private $paymentExtensionFactoryMock; - - /** - * @var VaultDetailsHandler - */ - private $handler; - - /** - * @var DateTimeFactory|MockObject - */ - private $dateTimeFactoryMock; - - /** - * @var array - */ - private $subject = []; - - protected function setUp(): void - { - $objectManager = new ObjectManager($this); - - $this->paymentDataObjectMock = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - - $this->paymentInfoMock = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->setMethods(['__wakeup', 'getExtensionAttributes']) - ->getMock(); - - $this->paymentTokenMock = $objectManager->getObject(PaymentToken::class); - - $this->paymentTokenFactoryMock = $this->getMockBuilder(PaymentTokenFactoryInterface::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - - $this->paymentExtensionMock = $this->getMockBuilder(OrderPaymentExtensionInterface::class) - ->setMethods([ - 'setVaultPaymentToken', - 'getVaultPaymentToken', - 'setNotificationMessage', - 'getNotificationMessage' - ]) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - $this->paymentExtensionFactoryMock = $this->getMockBuilder(OrderPaymentExtensionInterfaceFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $this->paymentInfoMock->expects(self::any()) - ->method('getExtensionAttributes') - ->willReturn($this->paymentExtensionMock); - - $this->subject = [ - 'payment' => $this->paymentDataObjectMock, - ]; - - $this->dateTimeFactoryMock = $this->getMockBuilder(DateTimeFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $this->handler = new VaultDetailsHandler( - $this->paymentTokenFactoryMock, - $this->paymentExtensionFactoryMock, - new SubjectReader(), - $this->dateTimeFactoryMock - ); - } - - public function testHandle() - { - $transaction = $this->getTransaction(); - $response = [ - 'object' => $transaction - ]; - - $this->paymentExtensionMock->method('setVaultPaymentToken') - ->with($this->paymentTokenMock); - $this->paymentExtensionMock->method('getVaultPaymentToken') - ->willReturn($this->paymentTokenMock); - - $this->paymentDataObjectMock->method('getPayment') - ->willReturn($this->paymentInfoMock); - - $this->paymentTokenFactoryMock->method('create') - ->with(PaymentTokenFactoryInterface::TOKEN_TYPE_ACCOUNT) - ->willReturn($this->paymentTokenMock); - - $this->paymentExtensionFactoryMock->method('create') - ->willReturn($this->paymentExtensionMock); - - $dateTime = new \DateTime('2016-07-05 00:00:00', new \DateTimeZone('UTC')); - $expirationDate = '2017-07-05 00:00:00'; - $this->dateTimeFactoryMock->method('create') - ->willReturn($dateTime); - - $this->handler->handle($this->subject, $response); - - $extensionAttributes = $this->paymentInfoMock->getExtensionAttributes(); - $paymentToken = $extensionAttributes->getVaultPaymentToken(); - self::assertNotNull($paymentToken); - - $tokenDetails = json_decode($paymentToken->getTokenDetails(), true); - - self::assertSame($this->paymentTokenMock, $paymentToken); - self::assertEquals(self::$token, $paymentToken->getGatewayToken()); - self::assertEquals(self::$payerEmail, $tokenDetails['payerEmail']); - self::assertEquals($expirationDate, $paymentToken->getExpiresAt()); - } - - public function testHandleWithoutToken() - { - $transaction = $this->getTransaction(); - $transaction->transaction->paypalDetails->token = null; - - $response = [ - 'object' => $transaction - ]; - - $this->paymentDataObjectMock->method('getPayment') - ->willReturn($this->paymentInfoMock); - - $this->paymentTokenFactoryMock->expects(self::never()) - ->method('create'); - - $this->dateTimeFactoryMock->expects(self::never()) - ->method('create'); - - $this->handler->handle($this->subject, $response); - self::assertNotNull($this->paymentInfoMock->getExtensionAttributes()); - } - - /** - * Creates Braintree transaction. - * - * @return Successful - */ - private function getTransaction(): Successful - { - $attributes = [ - 'id' => self::$transactionId, - 'paypalDetails' => $this->getPayPalDetails() - ]; - - $transaction = Transaction::factory($attributes); - $result = new Successful(['transaction' => $transaction]); - - return $result; - } - - /** - * Gets PayPal transaction details. - * - * @return PayPalDetails - */ - private function getPayPalDetails(): PayPalDetails - { - $attributes = [ - 'token' => self::$token, - 'payerEmail' => self::$payerEmail - ]; - - $details = new PayPalDetails($attributes); - - return $details; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPalDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPalDetailsHandlerTest.php deleted file mode 100644 index 8ade35ac37937..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PayPalDetailsHandlerTest.php +++ /dev/null @@ -1,116 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Response; - -use Braintree\Transaction; -use Magento\Braintree\Gateway\Response\PayPalDetailsHandler; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\PaymentDataObject; -use Magento\Sales\Model\Order\Payment; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class PayPalDetailsHandlerTest extends TestCase -{ - /** - * @var PayPalDetailsHandler|MockObject - */ - private $payPalHandler; - - /** - * @var Payment|MockObject - */ - private $paymentMock; - - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - protected function setUp(): void - { - $this->paymentMock = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->setMethods([ - 'setAdditionalInformation', - ]) - ->getMock(); - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->payPalHandler = new PayPalDetailsHandler($this->subjectReaderMock); - } - - /** - * @covers \Magento\Braintree\Gateway\Response\PayPalDetailsHandler::handle - */ - public function testHandle() - { - $paymentDataMock = $this->getPaymentDataObjectMock(); - $transaction = $this->getBraintreeTransaction(); - - $subject = ['payment' => $paymentDataMock]; - $response = ['object' => $transaction]; - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($subject) - ->willReturn($paymentDataMock); - $this->subjectReaderMock->expects(self::once()) - ->method('readTransaction') - ->with($response) - ->willReturn($transaction); - $this->subjectReaderMock->expects(static::once()) - ->method('readPayPal') - ->with($transaction) - ->willReturn($transaction->paypal); - - $this->paymentMock->expects(static::exactly(2)) - ->method('setAdditionalInformation'); - - $this->payPalHandler->handle($subject, $response); - } - - /** - * Create mock for payment data object and order payment - * @return MockObject - */ - private function getPaymentDataObjectMock() - { - $mock = $this->getMockBuilder(PaymentDataObject::class) - ->setMethods(['getPayment']) - ->disableOriginalConstructor() - ->getMock(); - - $mock->expects(static::once()) - ->method('getPayment') - ->willReturn($this->paymentMock); - - return $mock; - } - - /** - * Create Braintree transaction - * @return Transaction - */ - private function getBraintreeTransaction() - { - $attributes = [ - 'id' => '23ui8be', - 'paypal' => [ - 'paymentId' => 'u239dkv6n2lds', - 'payerEmail' => 'example@test.com' - ] - ]; - - $transaction = Transaction::factory($attributes); - - return $transaction; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PaymentDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PaymentDetailsHandlerTest.php deleted file mode 100644 index 081abc536b0eb..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/PaymentDetailsHandlerTest.php +++ /dev/null @@ -1,123 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Response; - -use Braintree\Transaction; -use Magento\Braintree\Gateway\Response\PaymentDetailsHandler; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\PaymentDataObject; -use Magento\Sales\Model\Order\Payment; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \\Magento\Braintree\Gateway\Response\PaymentDetailsHandler. - */ -class PaymentDetailsHandlerTest extends TestCase -{ - const TRANSACTION_ID = '432erwwe'; - - /** - * @var PaymentDetailsHandler - */ - private $paymentHandler; - - /** - * @var Payment|MockObject - */ - private $paymentMock; - - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - protected function setUp(): void - { - $this->paymentMock = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->setMethods([ - 'setCcTransId', - 'setLastTransId', - 'setAdditionalInformation', - ]) - ->getMock(); - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->paymentMock->expects(static::once()) - ->method('setCcTransId'); - $this->paymentMock->expects(static::once()) - ->method('setLastTransId'); - $this->paymentMock->expects(static::any()) - ->method('setAdditionalInformation'); - - $this->paymentHandler = new PaymentDetailsHandler($this->subjectReaderMock); - } - - /** - * @covers \Magento\Braintree\Gateway\Response\PaymentDetailsHandler::handle - */ - public function testHandle() - { - $paymentDataMock = $this->getPaymentDataObjectMock(); - $transaction = $this->getBraintreeTransaction(); - - $subject = ['payment' => $paymentDataMock]; - $response = ['object' => $transaction]; - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($subject) - ->willReturn($paymentDataMock); - $this->subjectReaderMock->expects(self::once()) - ->method('readTransaction') - ->with($response) - ->willReturn($transaction); - - $this->paymentHandler->handle($subject, $response); - } - - /** - * Create mock for payment data object and order payment - * @return MockObject - */ - private function getPaymentDataObjectMock() - { - $mock = $this->getMockBuilder(PaymentDataObject::class) - ->setMethods(['getPayment']) - ->disableOriginalConstructor() - ->getMock(); - - $mock->expects(static::once()) - ->method('getPayment') - ->willReturn($this->paymentMock); - - return $mock; - } - - /** - * Create Braintree transaction - * @return Transaction - */ - private function getBraintreeTransaction() - { - $attributes = [ - 'id' => self::TRANSACTION_ID, - 'avsPostalCodeResponseCode' => 'M', - 'avsStreetAddressResponseCode' => 'M', - 'cvvResponseCode' => 'M', - 'processorAuthorizationCode' => 'W1V8XK', - 'processorResponseCode' => '1000', - 'processorResponseText' => 'Approved', - ]; - - return Transaction::factory($attributes); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/RiskDataHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/RiskDataHandlerTest.php deleted file mode 100644 index d3a0ec3a93798..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/RiskDataHandlerTest.php +++ /dev/null @@ -1,120 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Response; - -use Braintree\Transaction; -use Magento\Braintree\Gateway\Response\RiskDataHandler; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Sales\Model\Order\Payment; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @see \Magento\Braintree\Gateway\Response\RiskDataHandler - */ -class RiskDataHandlerTest extends TestCase -{ - /** - * @var RiskDataHandler - */ - private $riskDataHandler; - - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->setMethods(['readPayment', 'readTransaction']) - ->getMock(); - - $this->riskDataHandler = new RiskDataHandler($this->subjectReaderMock); - } - - /** - * Test for handle method - * @covers \Magento\Braintree\Gateway\Response\RiskDataHandler::handle - * @param string $riskDecision - * @param boolean $isFraud - * @dataProvider riskDataProvider - */ - public function testHandle($riskDecision, $isFraud) - { - /** @var Payment|MockObject $payment */ - $payment = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->setMethods(['setAdditionalInformation', 'setIsFraudDetected']) - ->getMock(); - /** @var PaymentDataObjectInterface|MockObject $paymentDO */ - $paymentDO = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - $paymentDO->expects(self::once()) - ->method('getPayment') - ->willReturn($payment); - - $transaction = Transaction::factory([ - 'riskData' => [ - 'id' => 'test-id', - 'decision' => $riskDecision - ] - ]); - - $response = [ - 'object' => $transaction - ]; - $handlingSubject = [ - 'payment' => $paymentDO, - ]; - - $this->subjectReaderMock->expects(static::once()) - ->method('readPayment') - ->with($handlingSubject) - ->willReturn($paymentDO); - $this->subjectReaderMock->expects(static::once()) - ->method('readTransaction') - ->with($response) - ->willReturn($transaction); - - $payment->expects(static::at(0)) - ->method('setAdditionalInformation') - ->with(RiskDataHandler::RISK_DATA_ID, 'test-id'); - $payment->expects(static::at(1)) - ->method('setAdditionalInformation') - ->with(RiskDataHandler::RISK_DATA_DECISION, $riskDecision); - - if (!$isFraud) { - $payment->expects(static::never()) - ->method('setIsFraudDetected'); - } else { - $payment->expects(static::once()) - ->method('setIsFraudDetected') - ->with(true); - } - - $this->riskDataHandler->handle($handlingSubject, $response); - } - - /** - * Get list of variations to test fraud - * @return array - */ - public function riskDataProvider() - { - return [ - ['decision' => 'Not Evaluated', 'isFraud' => false], - ['decision' => 'Approve', 'isFraud' => false], - ['decision' => 'Review', 'isFraud' => true], - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/ThreeDSecureDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/ThreeDSecureDetailsHandlerTest.php deleted file mode 100644 index d7f3a714f8158..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/ThreeDSecureDetailsHandlerTest.php +++ /dev/null @@ -1,132 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Response; - -use Braintree\Transaction; -use Magento\Braintree\Gateway\Response\ThreeDSecureDetailsHandler; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\PaymentDataObject; -use Magento\Sales\Model\Order\Payment; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class ThreeDSecureDetailsHandlerTest extends TestCase -{ - const TRANSACTION_ID = '432er5ww3e'; - - /** - * @var ThreeDSecureDetailsHandler - */ - private $handler; - - /** - * @var Payment|MockObject - */ - private $paymentMock; - - /** - * @var SubjectReader|MockObject - */ - private $subjectReaderMock; - - protected function setUp(): void - { - $this->paymentMock = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->setMethods([ - 'unsAdditionalInformation', - 'hasAdditionalInformation', - 'setAdditionalInformation', - ]) - ->getMock(); - - $this->subjectReaderMock = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->handler = new ThreeDSecureDetailsHandler($this->subjectReaderMock); - } - - /** - * @covers \Magento\Braintree\Gateway\Response\ThreeDSecureDetailsHandler::handle - */ - public function testHandle() - { - $paymentData = $this->getPaymentDataObjectMock(); - $transaction = $this->getBraintreeTransaction(); - - $subject = ['payment' => $paymentData]; - $response = ['object' => $transaction]; - - $this->subjectReaderMock->expects(self::once()) - ->method('readPayment') - ->with($subject) - ->willReturn($paymentData); - $this->subjectReaderMock->expects(self::once()) - ->method('readTransaction') - ->with($response) - ->willReturn($transaction); - - $this->paymentMock->expects(static::at(1)) - ->method('setAdditionalInformation') - ->with('liabilityShifted', 'Yes'); - $this->paymentMock->expects(static::at(2)) - ->method('setAdditionalInformation') - ->with('liabilityShiftPossible', 'Yes'); - - $this->handler->handle($subject, $response); - } - - /** - * Create mock for payment data object and order payment - * @return MockObject - */ - private function getPaymentDataObjectMock() - { - $mock = $this->getMockBuilder(PaymentDataObject::class) - ->setMethods(['getPayment']) - ->disableOriginalConstructor() - ->getMock(); - - $mock->expects(static::once()) - ->method('getPayment') - ->willReturn($this->paymentMock); - - return $mock; - } - - /** - * Create Braintree transaction - * @return MockObject - */ - private function getBraintreeTransaction() - { - $attributes = [ - 'id' => self::TRANSACTION_ID, - 'threeDSecureInfo' => $this->getThreeDSecureInfo() - ]; - - $transaction = Transaction::factory($attributes); - - return $transaction; - } - - /** - * Get 3d secure details - * @return array - */ - private function getThreeDSecureInfo() - { - $attributes = [ - 'liabilityShifted' => 'Yes', - 'liabilityShiftPossible' => 'Yes' - ]; - - return $attributes; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/TransactionIdHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/TransactionIdHandlerTest.php deleted file mode 100644 index a9a924c437c45..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/TransactionIdHandlerTest.php +++ /dev/null @@ -1,65 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Response; - -use Braintree\Result\Successful; -use Braintree\Transaction; -use Magento\Braintree\Gateway\Response\TransactionIdHandler; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Sales\Model\Order\Payment; -use PHPUnit\Framework\TestCase; - -class TransactionIdHandlerTest extends TestCase -{ - public function testHandle() - { - $paymentDO = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - $paymentInfo = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->getMock(); - $handlingSubject = [ - 'payment' => $paymentDO - ]; - - $transaction = Transaction::factory(['id' => 1]); - $response = [ - 'object' => new Successful($transaction, 'transaction') - ]; - - $subjectReader = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $subjectReader->expects(static::once()) - ->method('readPayment') - ->with($handlingSubject) - ->willReturn($paymentDO); - $paymentDO->expects(static::atLeastOnce()) - ->method('getPayment') - ->willReturn($paymentInfo); - $subjectReader->expects(static::once()) - ->method('readTransaction') - ->with($response) - ->willReturn($transaction); - - $paymentInfo->expects(static::once()) - ->method('setTransactionId') - ->with(1); - - $paymentInfo->expects(static::once()) - ->method('setIsTransactionClosed') - ->with(false); - $paymentInfo->expects(static::once()) - ->method('setShouldCloseParentTransaction') - ->with(false); - - $handler = new TransactionIdHandler($subjectReader); - $handler->handle($handlingSubject, $response); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VaultDetailsHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VaultDetailsHandlerTest.php deleted file mode 100644 index 8408fe55811b8..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VaultDetailsHandlerTest.php +++ /dev/null @@ -1,237 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Response; - -use Braintree\Result\Successful; -use Braintree\Transaction; -use Braintree\Transaction\CreditCardDetails; -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Gateway\Response\PaymentDetailsHandler; -use Magento\Braintree\Gateway\Response\VaultDetailsHandler; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Framework\Serialize\Serializer\Json; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Payment\Gateway\Data\PaymentDataObject; -use Magento\Sales\Api\Data\OrderPaymentExtension; -use Magento\Sales\Api\Data\OrderPaymentExtensionInterface; -use Magento\Sales\Api\Data\OrderPaymentExtensionInterfaceFactory; -use Magento\Sales\Model\Order\Payment; -use Magento\Vault\Api\Data\PaymentTokenFactoryInterface; -use Magento\Vault\Model\PaymentToken; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Verify class VaultDetailsHandler - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class VaultDetailsHandlerTest extends TestCase -{ - private static $transactionId = '432erwwe'; - - private static $token = 'rh3gd4'; - - /** - * @var PaymentDetailsHandler - */ - private $paymentHandler; - - /** - * @var Payment|MockObject - */ - private $payment; - - /** - * @var PaymentTokenFactoryInterface|MockObject - */ - private $paymentTokenFactory; - - /** - * @var OrderPaymentExtension|MockObject - */ - private $paymentExtension; - - /** - * @var OrderPaymentExtensionInterfaceFactory|MockObject - */ - private $paymentExtensionFactory; - - protected function setUp(): void - { - $objectManager = new ObjectManager($this); - $paymentToken = $objectManager->getObject(PaymentToken::class); - $this->paymentTokenFactory = $this->getMockBuilder(PaymentTokenFactoryInterface::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - $this->paymentTokenFactory->method('create') - ->with(PaymentTokenFactoryInterface::TOKEN_TYPE_CREDIT_CARD) - ->willReturn($paymentToken); - - $this->initPaymentExtensionAttributesMock(); - $this->paymentExtension->method('setVaultPaymentToken') - ->with($paymentToken); - $this->paymentExtension->method('getVaultPaymentToken') - ->willReturn($paymentToken); - - $this->payment = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->setMethods(['__wakeup', 'getExtensionAttributes']) - ->getMock(); - - $this->payment->expects(self::any())->method('getExtensionAttributes')->willReturn($this->paymentExtension); - - $config = $this->getConfigMock(); - - $this->paymentHandler = new VaultDetailsHandler( - $this->paymentTokenFactory, - $this->paymentExtensionFactory, - $config, - new SubjectReader(), - new Json() - ); - } - - public function testHandle() - { - $paymentData = $this->getPaymentDataObjectMock(); - - $subject = ['payment' => $paymentData]; - $response = ['object' => $this->getBraintreeTransaction()]; - - $this->paymentHandler->handle($subject, $response); - $paymentToken = $this->payment->getExtensionAttributes() - ->getVaultPaymentToken(); - - self::assertEquals(self::$token, $paymentToken->getGatewayToken()); - self::assertEquals('2022-01-01 00:00:00', $paymentToken->getExpiresAt()); - - $details = json_decode($paymentToken->getTokenDetails(), true); - self::assertEquals( - [ - 'type' => 'AE', - 'maskedCC' => 1231, - 'expirationDate' => '12/2021' - ], - $details - ); - } - - /** - * Creates mock for payment data object and order payment. - * - * @return PaymentDataObject|MockObject - */ - private function getPaymentDataObjectMock(): PaymentDataObject - { - $mock = $this->getMockBuilder(PaymentDataObject::class) - ->setMethods(['getPayment']) - ->disableOriginalConstructor() - ->getMock(); - - $mock->method('getPayment') - ->willReturn($this->payment); - - return $mock; - } - - /** - * Creates Braintree transaction. - * - * @return Successful - */ - private function getBraintreeTransaction() - { - $attributes = [ - 'id' => self::$transactionId, - 'creditCardDetails' => $this->getCreditCardDetails() - ]; - - $transaction = Transaction::factory($attributes); - $result = new Successful(['transaction' => $transaction]); - - return $result; - } - - /** - * Creates Braintree transaction. - * - * @return CreditCardDetails - */ - private function getCreditCardDetails(): CreditCardDetails - { - $attributes = [ - 'token' => self::$token, - 'bin' => '5421', - 'cardType' => 'American Express', - 'expirationMonth' => 12, - 'expirationYear' => 2021, - 'last4' => 1231 - ]; - - $creditCardDetails = new CreditCardDetails($attributes); - - return $creditCardDetails; - } - - /** - * Creates mock of config class. - * - * @return Config|MockObject - */ - private function getConfigMock(): Config - { - $mapperArray = [ - 'american-express' => 'AE', - 'discover' => 'DI', - 'jcb' => 'JCB', - 'mastercard' => 'MC', - 'master-card' => 'MC', - 'visa' => 'VI', - 'maestro' => 'MI', - 'diners-club' => 'DN', - 'unionpay' => 'CUP' - ]; - - $config = $this->getMockBuilder(Config::class) - ->setMethods(['getCctypesMapper']) - ->disableOriginalConstructor() - ->getMock(); - - $config->method('getCctypesMapper') - ->willReturn($mapperArray); - - return $config; - } - - /** - * Initializes payment extension attributes mocks. - * - * @return void - */ - private function initPaymentExtensionAttributesMock() - { - $this->paymentExtension = $this->getMockBuilder(OrderPaymentExtensionInterface::class) - ->setMethods([ - 'setVaultPaymentToken', - 'getVaultPaymentToken', - 'setNotificationMessage', - 'getNotificationMessage' - ]) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - - $this->paymentExtensionFactory = $this->getMockBuilder(OrderPaymentExtensionInterfaceFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - $this->paymentExtensionFactory->method('create') - ->willReturn($this->paymentExtension); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VoidHandlerTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VoidHandlerTest.php deleted file mode 100644 index 11a0eec6c14db..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Response/VoidHandlerTest.php +++ /dev/null @@ -1,64 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Response; - -use Braintree\Result\Successful; -use Braintree\Transaction; -use Magento\Braintree\Gateway\Response\VoidHandler; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Payment\Gateway\Data\PaymentDataObjectInterface; -use Magento\Sales\Model\Order\Payment; -use PHPUnit\Framework\TestCase; - -class VoidHandlerTest extends TestCase -{ - public function testHandle() - { - $paymentDO = $this->getMockForAbstractClass(PaymentDataObjectInterface::class); - $paymentInfo = $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->getMock(); - $handlingSubject = [ - 'payment' => $paymentDO - ]; - - $transaction = Transaction::factory(['id' => 1]); - $response = [ - 'object' => new Successful($transaction, 'transaction') - ]; - - $subjectReader = $this->getMockBuilder(SubjectReader::class) - ->disableOriginalConstructor() - ->getMock(); - - $subjectReader->expects(static::once()) - ->method('readPayment') - ->with($handlingSubject) - ->willReturn($paymentDO); - $paymentDO->expects(static::atLeastOnce()) - ->method('getPayment') - ->willReturn($paymentInfo); - $subjectReader->expects(static::once()) - ->method('readTransaction') - ->with($response) - ->willReturn($transaction); - - $paymentInfo->expects(static::never()) - ->method('setTransactionId'); - - $paymentInfo->expects(static::once()) - ->method('setIsTransactionClosed') - ->with(true); - $paymentInfo->expects(static::once()) - ->method('setShouldCloseParentTransaction') - ->with(true); - - $handler = new VoidHandler($subjectReader); - $handler->handle($handlingSubject, $response); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/SubjectReaderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/SubjectReaderTest.php deleted file mode 100644 index 18961fac74e47..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/SubjectReaderTest.php +++ /dev/null @@ -1,167 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway; - -use Braintree\Result\Successful; -use Braintree\Transaction; -use Magento\Braintree\Gateway\SubjectReader; -use PHPUnit\Framework\TestCase; - -class SubjectReaderTest extends TestCase -{ - /** - * @var SubjectReader - */ - private $subjectReader; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->subjectReader = new SubjectReader(); - } - - /** - * @covers \Magento\Braintree\Gateway\SubjectReader::readCustomerId - * @return void - */ - public function testReadCustomerIdWithException(): void - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The "customerId" field does not exists'); - $this->subjectReader->readCustomerId([]); - } - - /** - * @covers \Magento\Braintree\Gateway\SubjectReader::readCustomerId - * @return void - */ - public function testReadCustomerId(): void - { - $customerId = 1; - $this->assertEquals($customerId, $this->subjectReader->readCustomerId(['customer_id' => $customerId])); - } - - /** - * @covers \Magento\Braintree\Gateway\SubjectReader::readPublicHash - * @return void - */ - public function testReadPublicHashWithException(): void - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The "public_hash" field does not exists'); - $this->subjectReader->readPublicHash([]); - } - - /** - * @covers \Magento\Braintree\Gateway\SubjectReader::readPublicHash - * @return void - */ - public function testReadPublicHash(): void - { - $hash = 'fj23djf2o1fd'; - $this->assertEquals($hash, $this->subjectReader->readPublicHash(['public_hash' => $hash])); - } - - /** - * @covers \Magento\Braintree\Gateway\SubjectReader::readPayPal - * @return void - */ - public function testReadPayPalWithException(): void - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('Transaction has\'t paypal attribute'); - $transaction = Transaction::factory([ - 'id' => 'u38rf8kg6vn', - ]); - $this->subjectReader->readPayPal($transaction); - } - - /** - * @covers \Magento\Braintree\Gateway\SubjectReader::readPayPal - * @return void - */ - public function testReadPayPal(): void - { - $paypal = [ - 'paymentId' => '3ek7dk7fn0vi1', - 'payerEmail' => 'payer@example.com', - ]; - $transaction = Transaction::factory([ - 'id' => '4yr95vb', - 'paypal' => $paypal, - ]); - - $this->assertEquals($paypal, $this->subjectReader->readPayPal($transaction)); - } - - /** - * Checks a case when subject reader retrieves successful Braintree transaction. - * - * @return void - */ - public function testReadTransaction(): void - { - $transaction = Transaction::factory(['id' => 1]); - $response = [ - 'object' => new Successful($transaction, 'transaction'), - ]; - $actual = $this->subjectReader->readTransaction($response); - - $this->assertSame($transaction, $actual); - } - - /** - * Checks a case when subject reader retrieves invalid data instead transaction details. - * - * @param array $response - * @param string $expectedMessage - * @dataProvider invalidTransactionResponseDataProvider - * @return void - */ - public function testReadTransactionWithInvalidResponse(array $response, string $expectedMessage): void - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage($expectedMessage); - $this->subjectReader->readTransaction($response); - } - - /** - * Gets list of variations with invalid subject data. - * - * @return array - */ - public function invalidTransactionResponseDataProvider(): array - { - $transaction = new \stdClass(); - $response = new \stdClass(); - $response->transaction = $transaction; - - return [ - [ - 'response' => [ - 'object' => [], - ], - 'expectedMessage' => 'Response object does not exist.', - ], - [ - 'response' => [ - 'object' => new \stdClass(), - ], - 'expectedMessage' => 'The object is not a class \Braintree\Transaction.', - ], - [ - 'response' => [ - 'object' => $response, - ], - 'expectedMessage' => 'The object is not a class \Braintree\Transaction.', - ], - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/CancelResponseValidatorTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/CancelResponseValidatorTest.php deleted file mode 100644 index f49a6467d1194..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/CancelResponseValidatorTest.php +++ /dev/null @@ -1,179 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Validator; - -use Braintree\Result\Error; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Braintree\Gateway\Validator\CancelResponseValidator; -use Magento\Braintree\Gateway\Validator\GeneralResponseValidator; -use Magento\Payment\Gateway\Validator\ResultInterface; -use Magento\Payment\Gateway\Validator\ResultInterfaceFactory; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests \Magento\Braintree\Gateway\Validator\CancelResponseValidator class. - */ -class CancelResponseValidatorTest extends TestCase -{ - /** - * @var CancelResponseValidator - */ - private $validator; - - /** - * @var GeneralResponseValidator|MockObject - */ - private $generalValidator; - - /** - * @var ResultInterfaceFactory|MockObject - */ - private $resultFactory; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->generalValidator = $this->getMockBuilder(GeneralResponseValidator::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->resultFactory = $this->getMockBuilder(ResultInterfaceFactory::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->validator = new CancelResponseValidator( - $this->resultFactory, - $this->generalValidator, - new SubjectReader() - ); - } - - /** - * Checks a case when response is successful and additional validation doesn't needed. - * - * @return void - */ - public function testValidateSuccessfulTransaction(): void - { - /** @var ResultInterface|MockObject $result */ - $result = $this->getMockForAbstractClass(ResultInterface::class); - $result->method('isValid')->willReturn(true); - $this->generalValidator->method('validate')->willReturn($result); - $actual = $this->validator->validate([]); - - $this->assertSame($result, $actual); - } - - /** - * Checks a case when response contains error related to expired authorization transaction and - * validator should return positive result. - * - * @return void - */ - public function testValidateExpiredTransaction(): void - { - /** @var ResultInterface|MockObject $result */ - $result = $this->getMockForAbstractClass(ResultInterface::class); - $result->method('isValid')->willReturn(false); - $this->generalValidator->method('validate')->willReturn($result); - - $expected = $this->getMockForAbstractClass(ResultInterface::class); - $expected->method('isValid')->willReturn(true); - $this->resultFactory->method('create') - ->with( - [ - 'isValid' => true, - 'failsDescription' => ['Transaction is cancelled offline.'], - 'errorCodes' => [] - ] - )->willReturn($expected); - - $errors = [ - 'errors' => [ - [ - 'code' => 91504, - 'message' => 'Transaction can only be voided if status is authorized.', - ], - ], - ]; - $buildSubject = [ - 'response' => [ - 'object' => new Error(['errors' => $errors]), - ], - ]; - - $actual = $this->validator->validate($buildSubject); - - $this->assertSame($expected, $actual); - } - - /** - * Checks a case when response contains multiple errors and validator should return negative result. - * - * @param array $responseErrors - * @return void - * @dataProvider getErrorsDataProvider - */ - public function testValidateWithMultipleErrors(array $responseErrors): void - { - /** @var ResultInterface|MockObject $result */ - $result = $this->getMockForAbstractClass(ResultInterface::class); - $result->method('isValid')->willReturn(false); - - $this->generalValidator->method('validate')->willReturn($result); - - $this->resultFactory->expects($this->never())->method('create'); - - $errors = [ - 'errors' => $responseErrors, - ]; - $buildSubject = [ - 'response' => [ - 'object' => new Error(['errors' => $errors]), - ] - ]; - - $actual = $this->validator->validate($buildSubject); - - $this->assertSame($result, $actual); - } - - /** - * Gets list of errors variations. - * - * @return array - */ - public function getErrorsDataProvider(): array - { - return [ - [ - 'errors' => [ - [ - 'code' => 91734, - 'message' => 'Credit card type is not accepted by this merchant account.', - ], - [ - 'code' => 91504, - 'message' => 'Transaction can only be voided if status is authorized.', - ], - ], - ], - [ - 'errors' => [ - [ - 'code' => 91734, - 'message' => 'Credit card type is not accepted by this merchant account.', - ], - ], - ], - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ErrorCodeProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ErrorCodeProviderTest.php deleted file mode 100644 index 173488e6eaca4..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ErrorCodeProviderTest.php +++ /dev/null @@ -1,91 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Validator; - -use Braintree\Result\Error; -use Magento\Braintree\Gateway\Validator\ErrorCodeProvider; -use PHPUnit\Framework\TestCase; - -class ErrorCodeProviderTest extends TestCase -{ - /** - * @var ErrorCodeProvider - */ - private $model; - - /** - * Checks a extracting error codes from response. - * - * @param array $errors - * @param array $transaction - * @param array $expectedResult - * @return void - * @dataProvider getErrorCodeDataProvider - */ - public function testGetErrorCodes(array $errors, array $transaction, array $expectedResult): void - { - $response = new Error( - [ - 'errors' => ['errors' => $errors], - 'transaction' => $transaction, - ] - ); - $this->model = new ErrorCodeProvider(); - $actual = $this->model->getErrorCodes($response); - - $this->assertSame($expectedResult, $actual); - } - - /** - * Gets list of errors variations. - * - * @return array - */ - public function getErrorCodeDataProvider(): array - { - return [ - [ - 'errors' => [ - ['code' => 91734], - ['code' => 91504] - ], - 'transaction' => [ - 'status' => 'success', - ], - 'expectedResult' => ['91734', '91504'] - ], - [ - 'errors' => [], - 'transaction' => [ - 'status' => 'processor_declined', - 'processorResponseCode' => '1000' - ], - 'expectedResult' => ['1000'] - ], - [ - 'errors' => [], - 'transaction' => [ - 'status' => 'processor_declined', - 'processorResponseCode' => '2059' - ], - 'expectedResult' => ['2059'] - ], - [ - 'errors' => [ - ['code' => 91734], - ['code' => 91504] - ], - 'transaction' => [ - 'status' => 'processor_declined', - 'processorResponseCode' => '1000' - ], - 'expectedResult' => ['91734', '91504', '1000'] - ], - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/GeneralResponseValidatorTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/GeneralResponseValidatorTest.php deleted file mode 100644 index e6fafcf86c577..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/GeneralResponseValidatorTest.php +++ /dev/null @@ -1,145 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Validator; - -use Braintree\Result\Error; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Braintree\Gateway\Validator\ErrorCodeProvider; -use Magento\Braintree\Gateway\Validator\GeneralResponseValidator; -use Magento\Framework\Phrase; -use Magento\Payment\Gateway\Validator\Result; -use Magento\Payment\Gateway\Validator\ResultInterfaceFactory; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class GeneralResponseValidatorTest extends TestCase -{ - /** - * @var GeneralResponseValidator - */ - private $responseValidator; - - /** - * @var ResultInterfaceFactory|MockObject - */ - private $resultInterfaceFactory; - - /** - * Set up - * - * @return void - */ - protected function setUp(): void - { - $this->resultInterfaceFactory = $this->getMockBuilder(ResultInterfaceFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $this->responseValidator = new GeneralResponseValidator( - $this->resultInterfaceFactory, - new SubjectReader(), - new ErrorCodeProvider() - ); - } - - /** - * Checks a case when the validator processes successful and failed transactions. - * - * @param array $validationSubject - * @param bool $isValid - * @param Phrase[] $messages - * @param array $errorCodes - * @return void - * - * @dataProvider dataProviderTestValidate - */ - public function testValidate(array $validationSubject, bool $isValid, $messages, array $errorCodes) - { - $result = new Result($isValid, $messages); - - $this->resultInterfaceFactory->method('create') - ->with( - [ - 'isValid' => $isValid, - 'failsDescription' => $messages, - 'errorCodes' => $errorCodes - ] - ) - ->willReturn($result); - - $actual = $this->responseValidator->validate($validationSubject); - - self::assertEquals($result, $actual); - } - - /** - * Gets variations for different type of response. - * - * @return array - */ - public function dataProviderTestValidate() - { - $successTransaction = new \stdClass(); - $successTransaction->success = true; - $successTransaction->status = 'authorized'; - - $failureTransaction = new \stdClass(); - $failureTransaction->success = false; - $failureTransaction->status = 'declined'; - $failureTransaction->message = 'Transaction was failed.'; - - $errors = [ - 'errors' => [ - [ - 'code' => 81804, - 'attribute' => 'base', - 'message' => 'Cannot process transaction.' - ], - ] - ]; - $errorTransaction = new Error(['errors' => $errors, 'transaction' => ['status' => 'declined']]); - - return [ - [ - 'validationSubject' => [ - 'response' => [ - 'object' => $successTransaction - ], - ], - 'isValid' => true, - [], - 'errorCodes' => [] - ], - [ - 'validationSubject' => [ - 'response' => [ - 'object' => $failureTransaction - ] - ], - 'isValid' => false, - [ - __('Transaction was failed.') - ], - 'errorCodes' => [] - ], - [ - 'validationSubject' => [ - 'response' => [ - 'object' => $errorTransaction - ] - ], - 'isValid' => false, - [ - __('Braintree error response.') - ], - 'errorCodes' => ['81804'] - ] - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/PaymentNonceResponseValidatorTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/PaymentNonceResponseValidatorTest.php deleted file mode 100644 index 153ffa9719a46..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/PaymentNonceResponseValidatorTest.php +++ /dev/null @@ -1,82 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Validator; - -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Braintree\Gateway\Validator\ErrorCodeProvider; -use Magento\Braintree\Gateway\Validator\PaymentNonceResponseValidator; -use Magento\Payment\Gateway\Validator\Result; -use Magento\Payment\Gateway\Validator\ResultInterfaceFactory; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class PaymentNonceResponseValidatorTest extends TestCase -{ - /** - * @var PaymentNonceResponseValidator - */ - private $validator; - - /** - * @var ResultInterfaceFactory|MockObject - */ - private $resultInterfaceFactory; - - protected function setUp(): void - { - $this->resultInterfaceFactory = $this->getMockBuilder(ResultInterfaceFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $this->validator = new PaymentNonceResponseValidator( - $this->resultInterfaceFactory, - new SubjectReader(), - new ErrorCodeProvider() - ); - } - - public function testFailedValidate() - { - $obj = new \stdClass(); - $obj->success = true; - $subject = [ - 'response' => [ - 'object' => $obj - ] - ]; - - $result = new Result(false, [__('Payment method nonce can\'t be retrieved.')]); - $this->resultInterfaceFactory->method('create') - ->willReturn($result); - - $actual = $this->validator->validate($subject); - self::assertEquals($result, $actual); - } - - public function testValidateSuccess() - { - $obj = new \stdClass(); - $obj->success = true; - $obj->paymentMethodNonce = new \stdClass(); - $obj->paymentMethodNonce->nonce = 'fj2hd9239kd1kq9'; - - $subject = [ - 'response' => [ - 'object' => $obj - ] - ]; - - $result = new Result(true); - $this->resultInterfaceFactory->method('create') - ->willReturn($result); - - $actual = $this->validator->validate($subject); - self::assertEquals($result, $actual); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ResponseValidatorTest.php b/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ResponseValidatorTest.php deleted file mode 100644 index 21dc8eebe1845..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Gateway/Validator/ResponseValidatorTest.php +++ /dev/null @@ -1,149 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Gateway\Validator; - -use Braintree\Result\Successful; -use Braintree\Transaction; -use Magento\Braintree\Gateway\SubjectReader; -use Magento\Braintree\Gateway\Validator\ErrorCodeProvider; -use Magento\Braintree\Gateway\Validator\ResponseValidator; -use Magento\Framework\Phrase; -use Magento\Payment\Gateway\Validator\Result; -use Magento\Payment\Gateway\Validator\ResultInterface; -use Magento\Payment\Gateway\Validator\ResultInterfaceFactory; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class ResponseValidatorTest extends TestCase -{ - /** - * @var ResponseValidator - */ - private $responseValidator; - - /** - * @var ResultInterfaceFactory|MockObject - */ - private $resultInterfaceFactory; - - /** - * Set up - * - * @return void - */ - protected function setUp(): void - { - $this->resultInterfaceFactory = $this->getMockBuilder(ResultInterfaceFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $this->responseValidator = new ResponseValidator( - $this->resultInterfaceFactory, - new SubjectReader(), - new ErrorCodeProvider() - ); - } - - public function testValidateReadResponseException() - { - $this->expectException(\InvalidArgumentException::class); - $validationSubject = [ - 'response' => null - ]; - - $this->responseValidator->validate($validationSubject); - } - - public function testValidateReadResponseObjectException() - { - $this->expectException(\InvalidArgumentException::class); - $validationSubject = [ - 'response' => ['object' => null] - ]; - - $this->responseValidator->validate($validationSubject); - } - - /** - * Run test for validate method - * - * @param array $validationSubject - * @param bool $isValid - * @param Phrase[] $messages - * @return void - * - * @dataProvider dataProviderTestValidate - */ - public function testValidate(array $validationSubject, $isValid, $messages) - { - /** @var ResultInterface|MockObject $result */ - $result = new Result($isValid, $messages); - - $this->resultInterfaceFactory->method('create') - ->willReturn($result); - - $actual = $this->responseValidator->validate($validationSubject); - - self::assertEquals($result, $actual); - } - - /** - * @return array - */ - public function dataProviderTestValidate() - { - $successTrue = new Successful(); - $successTrue->success = true; - $successTrue->transaction = new \stdClass(); - $successTrue->transaction->status = Transaction::AUTHORIZED; - - $successFalse = new Successful(); - $successFalse->success = false; - - $transactionDeclined = new Successful(); - $transactionDeclined->success = true; - $transactionDeclined->transaction = new \stdClass(); - $transactionDeclined->transaction->status = Transaction::SETTLEMENT_DECLINED; - - return [ - [ - 'validationSubject' => [ - 'response' => [ - 'object' => $successTrue - ], - ], - 'isValid' => true, - [] - ], - [ - 'validationSubject' => [ - 'response' => [ - 'object' => $successFalse - ] - ], - 'isValid' => false, - [ - __('Braintree error response.'), - __('Wrong transaction status') - ] - ], - [ - 'validationSubject' => [ - 'response' => [ - 'object' => $transactionDeclined - ] - ], - 'isValid' => false, - [ - __('Wrong transaction status') - ] - ] - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Helper/CcTypeTest.php b/app/code/Magento/Braintree/Test/Unit/Helper/CcTypeTest.php deleted file mode 100644 index 78761999a2e38..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Helper/CcTypeTest.php +++ /dev/null @@ -1,64 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Helper; - -use Magento\Braintree\Helper\CcType; -use Magento\Braintree\Model\Adminhtml\Source\CcType as CcTypeSource; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class CcTypeTest extends TestCase -{ - - /** - * @var ObjectManager - */ - private $objectManager; - - /** - * @var \Magento\Braintree\Helper\CcType - */ - private $helper; - - /** @var \Magento\Braintree\Model\Adminhtml\Source\CcType|MockObject */ - private $ccTypeSource; - - protected function setUp(): void - { - $this->objectManager = new ObjectManager($this); - - $this->ccTypeSource = $this->getMockBuilder(CcTypeSource::class) - ->disableOriginalConstructor() - ->setMethods(['toOptionArray']) - ->getMock(); - - $this->helper = $this->objectManager->getObject(CcType::class, [ - 'ccTypeSource' => $this->ccTypeSource - ]); - } - - /** - * @covers \Magento\Braintree\Helper\CcType::getCcTypes - */ - public function testGetCcTypes() - { - $this->ccTypeSource->expects(static::once()) - ->method('toOptionArray') - ->willReturn([ - 'label' => 'VISA', 'value' => 'VI' - ]); - - $this->helper->getCcTypes(); - - $this->ccTypeSource->expects(static::never()) - ->method('toOptionArray'); - - $this->helper->getCcTypes(); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Helper/CountryTest.php b/app/code/Magento/Braintree/Test/Unit/Helper/CountryTest.php deleted file mode 100644 index fb2875b7e73fd..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Helper/CountryTest.php +++ /dev/null @@ -1,94 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Helper; - -use Magento\Braintree\Helper\Country; -use Magento\Directory\Model\ResourceModel\Country\Collection; -use Magento\Directory\Model\ResourceModel\Country\CollectionFactory; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class CountryTest extends TestCase -{ - /** - * @var Collection|MockObject - */ - private $collection; - - /** - * @var Country - */ - private $helper; - - /** - * @var ObjectManager - */ - private $objectManager; - - protected function setUp(): void - { - $this->objectManager = new ObjectManager($this); - - $collectionFactory = $this->getCollectionFactoryMock(); - - $this->helper = $this->objectManager->getObject(Country::class, [ - 'factory' => $collectionFactory - ]); - } - - /** - * @covers \Magento\Braintree\Helper\Country::getCountries - */ - public function testGetCountries() - { - $this->collection->expects(static::once()) - ->method('toOptionArray') - ->willReturn([ - ['value' => 'US', 'label' => 'United States'], - ['value' => 'UK', 'label' => 'United Kingdom'], - ]); - - $this->helper->getCountries(); - - $this->collection->expects(static::never()) - ->method('toOptionArray'); - - $this->helper->getCountries(); - } - - /** - * Create mock for country collection factory - */ - protected function getCollectionFactoryMock() - { - $this->collection = $this->getMockBuilder(Collection::class) - ->disableOriginalConstructor() - ->setMethods(['addFieldToFilter', 'loadData', 'toOptionArray', '__wakeup']) - ->getMock(); - - $this->collection->expects(static::any()) - ->method('addFieldToFilter') - ->willReturnSelf(); - - $this->collection->expects(static::any()) - ->method('loadData') - ->willReturnSelf(); - - $collectionFactory = $this->getMockBuilder(CollectionFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $collectionFactory->expects(static::once()) - ->method('create') - ->willReturn($this->collection); - - return $collectionFactory; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Adminhtml/System/Config/CountryCreditCardTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Adminhtml/System/Config/CountryCreditCardTest.php deleted file mode 100644 index 68a099b168fb4..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/Adminhtml/System/Config/CountryCreditCardTest.php +++ /dev/null @@ -1,227 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\Adminhtml\System\Config; - -use Magento\Braintree\Model\Adminhtml\System\Config\CountryCreditCard; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\Math\Random; -use Magento\Framework\Model\ResourceModel\AbstractResource; -use Magento\Framework\Serialize\Serializer\Json; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class CountryCreditCardTest extends TestCase -{ - /** - * @var CountryCreditCard - */ - protected $model; - - /** - * @var ObjectManager - */ - protected $objectManager; - - /** - * @var ScopeConfigInterface|MockObject - */ - protected $resourceMock; - - /** - * @var Random|MockObject - */ - protected $mathRandomMock; - - /** - * @var Json|MockObject - */ - private $serializerMock; - - protected function setUp(): void - { - $this->resourceMock = $this->getMockForAbstractClass(AbstractResource::class); - $this->mathRandomMock = $this->getMockBuilder(Random::class) - ->disableOriginalConstructor() - ->getMock(); - $this->serializerMock = $this->createMock(Json::class); - - $this->objectManager = new ObjectManager($this); - $this->model = $this->objectManager->getObject( - CountryCreditCard::class, - [ - 'mathRandom' => $this->mathRandomMock, - 'resource' => $this->resourceMock, - 'serializer' => $this->serializerMock - ] - ); - } - - /** - * @dataProvider beforeSaveDataProvider - * @param array $value - * @param array $expectedValue - * @param string $encodedValue - */ - public function testBeforeSave(array $value, array $expectedValue, $encodedValue) - { - $this->model->setValue($value); - - $this->serializerMock->expects($this->once()) - ->method('serialize') - ->with($expectedValue) - ->willReturn($encodedValue); - - $this->model->beforeSave(); - $this->assertEquals($encodedValue, $this->model->getValue()); - } - - /** - * Get data for testing credit card types - * @return array - */ - public function beforeSaveDataProvider() - { - return [ - 'empty_value' => [ - 'value' => [], - 'expected' => [], - 'encoded' => '[]' - ], - 'not_array' => [ - 'value' => ['US'], - 'expected' => [], - 'encoded' => '[]' - ], - 'array_with_invalid_format' => [ - 'value' => [ - [ - 'country_id' => 'US', - ], - ], - 'expected' => [], - 'encoded' => '[]' - ], - 'array_with_two_countries' => [ - 'value' => [ - [ - 'country_id' => 'AF', - 'cc_types' => ['AE', 'VI'] - ], - [ - 'country_id' => 'US', - 'cc_types' => ['AE', 'VI', 'MA'] - ], - '__empty' => "", - ], - 'expected' => [ - 'AF' => ['AE', 'VI'], - 'US' => ['AE', 'VI', 'MA'], - ], - 'encoded' => '{"AF":["AE","VI"],"US":["AE","VI","MA"]}' - ], - 'array_with_two_same_countries' => [ - 'value' => [ - [ - 'country_id' => 'AF', - 'cc_types' => ['AE', 'VI'] - ], - [ - 'country_id' => 'US', - 'cc_types' => ['AE', 'VI', 'MA'] - ], - [ - 'country_id' => 'US', - 'cc_types' => ['VI', 'OT'] - ], - '__empty' => "", - ], - 'expected' => [ - 'AF' => ['AE', 'VI'], - 'US' => ['AE', 'VI', 'MA', 'OT'], - ], - 'encoded' => '{"AF":["AE","VI"],"US":["AE","VI","MA","OT"]}' - ], - ]; - } - - /** - * @param string $encodedValue - * @param array|null $value - * @param array $hashData - * @param array|null $expected - * @param int $unserializeCalledNum - * @dataProvider afterLoadDataProvider - */ - public function testAfterLoad( - $encodedValue, - $value, - array $hashData, - $expected, - $unserializeCalledNum = 1 - ) { - $this->model->setValue($encodedValue); - $index = 0; - foreach ($hashData as $hash) { - $this->mathRandomMock->expects($this->at($index)) - ->method('getUniqueHash') - ->willReturn($hash); - $index++; - } - - $this->serializerMock->expects($this->exactly($unserializeCalledNum)) - ->method('unserialize') - ->with($encodedValue) - ->willReturn($value); - - $this->model->afterLoad(); - $this->assertEquals($expected, $this->model->getValue()); - } - - /** - * Get data to test saved credit cards types - * - * @return array - */ - public function afterLoadDataProvider() - { - return [ - 'empty' => [ - 'encoded' => '[]', - 'value' => [], - 'randomHash' => [], - 'expected' => [] - ], - 'null' => [ - 'encoded' => '', - 'value' => null, - 'randomHash' => [], - 'expected' => null, - 0 - ], - 'valid data' => [ - 'encoded' => '{"US":["AE","VI","MA"],"AF":["AE","MA"]}', - 'value' => [ - 'US' => ['AE', 'VI', 'MA'], - 'AF' => ['AE', 'MA'] - ], - 'randomHash' => ['hash_1', 'hash_2'], - 'expected' => [ - 'hash_1' => [ - 'country_id' => 'US', - 'cc_types' => ['AE', 'VI', 'MA'] - ], - 'hash_2' => [ - 'country_id' => 'AF', - 'cc_types' => ['AE', 'MA'] - ] - ] - ] - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Adminhtml/System/Config/CountryTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Adminhtml/System/Config/CountryTest.php deleted file mode 100644 index 5d4f88b1a11da..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/Adminhtml/System/Config/CountryTest.php +++ /dev/null @@ -1,147 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\Adminhtml\System\Config; - -use Magento\Braintree\Model\Adminhtml\System\Config\Country; -use Magento\Directory\Model\ResourceModel\Country\Collection; -use Magento\Framework\Phrase; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class CountryTest extends TestCase -{ - /** - * @var Country - */ - protected $model; - - /** - * @var Collection|MockObject - */ - protected $countryCollectionMock; - - /** - * @var ObjectManager - */ - protected $objectManager; - - protected function setUp(): void - { - $this->countryCollectionMock = $this->getMockBuilder(Collection::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->objectManager = new ObjectManager($this); - $this->model = $this->objectManager->getObject( - Country::class, - [ - 'countryCollection' => $this->countryCollectionMock, - ] - ); - } - - /** - * @covers \Magento\Braintree\Model\Adminhtml\System\Config\Country::toOptionArray - */ - public function testToOptionArrayMultiSelect() - { - $countries = [ - [ - 'value' => 'US', - 'label' => 'United States', - ], - [ - 'value' => 'UK', - 'label' => 'United Kingdom', - ], - ]; - $this->initCountryCollectionMock($countries); - - $this->assertEquals($countries, $this->model->toOptionArray(true)); - } - - /** - * @covers \Magento\Braintree\Model\Adminhtml\System\Config\Country::toOptionArray - */ - public function testToOptionArray() - { - $countries = [ - [ - 'value' => 'US', - 'label' => 'United States', - ], - [ - 'value' => 'UK', - 'label' => 'United Kingdom', - ], - ]; - $this->initCountryCollectionMock($countries); - - $header = ['value' => '', 'label' => new Phrase('--Please Select--')]; - array_unshift($countries, $header); - - $this->assertEquals($countries, $this->model->toOptionArray()); - } - - /** - * @covers \Magento\Braintree\Model\Adminhtml\System\Config\Country::isCountryRestricted - * @param string $countryId - * @dataProvider countryDataProvider - */ - public function testIsCountryRestricted($countryId) - { - static::assertTrue($this->model->isCountryRestricted($countryId)); - } - - /** - * Get simple list of not available braintree countries - * @return array - */ - public function countryDataProvider() - { - return [ - ['MM'], - ['IR'], - ['SD'], - ['BY'], - ['CI'], - ['CD'], - ['CG'], - ['IQ'], - ['LR'], - ['LB'], - ['KP'], - ['SL'], - ['SY'], - ['ZW'], - ['AL'], - ['BA'], - ['MK'], - ['ME'], - ['RS'] - ]; - } - - /** - * Init country collection mock - * @param array $countries - */ - protected function initCountryCollectionMock(array $countries) - { - $this->countryCollectionMock->expects(static::once()) - ->method('addFieldToFilter') - ->willReturnSelf(); - $this->countryCollectionMock->expects(static::once()) - ->method('loadData') - ->willReturnSelf(); - $this->countryCollectionMock->expects(static::once()) - ->method('toOptionArray') - ->willReturn($countries); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/AvsEmsCodeMapperTest.php b/app/code/Magento/Braintree/Test/Unit/Model/AvsEmsCodeMapperTest.php deleted file mode 100644 index 5952324d583ed..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/AvsEmsCodeMapperTest.php +++ /dev/null @@ -1,104 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model; - -use Magento\Braintree\Model\AvsEmsCodeMapper; -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Sales\Api\Data\OrderPaymentInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class AvsEmsCodeMapperTest extends TestCase -{ - /** - * @var AvsEmsCodeMapper - */ - private $mapper; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->mapper = new AvsEmsCodeMapper(); - } - - /** - * Checks different variations for AVS codes mapping. - * - * @covers \Magento\Braintree\Model\AvsEmsCodeMapper::getCode - * @param string $avsZip - * @param string $avsStreet - * @param string $expected - * @dataProvider getCodeDataProvider - */ - public function testGetCode($avsZip, $avsStreet, $expected) - { - /** @var OrderPaymentInterface|MockObject $orderPayment */ - $orderPayment = $this->getMockBuilder(OrderPaymentInterface::class) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - - $orderPayment->expects(self::once()) - ->method('getMethod') - ->willReturn(ConfigProvider::CODE); - - $orderPayment->expects(self::once()) - ->method('getAdditionalInformation') - ->willReturn([ - 'avsPostalCodeResponseCode' => $avsZip, - 'avsStreetAddressResponseCode' => $avsStreet - ]); - - self::assertEquals($expected, $this->mapper->getCode($orderPayment)); - } - - /** - * Checks a test case, when payment order is not Braintree payment method. - * - * @covers \Magento\Braintree\Model\AvsEmsCodeMapper::getCode - */ - public function testGetCodeWithException() - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The "some_payment" does not supported by Braintree AVS mapper.'); - /** @var OrderPaymentInterface|MockObject $orderPayment */ - $orderPayment = $this->getMockBuilder(OrderPaymentInterface::class) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - - $orderPayment->expects(self::exactly(2)) - ->method('getMethod') - ->willReturn('some_payment'); - - $this->mapper->getCode($orderPayment); - } - - /** - * Gets list of AVS codes. - * - * @return array - */ - public function getCodeDataProvider() - { - return [ - ['avsZip' => null, 'avsStreet' => null, 'expected' => ''], - ['avsZip' => null, 'avsStreet' => 'M', 'expected' => ''], - ['avsZip' => 'M', 'avsStreet' => null, 'expected' => ''], - ['avsZip' => 'M', 'avsStreet' => 'Unknown', 'expected' => ''], - ['avsZip' => 'I', 'avsStreet' => 'A', 'expected' => ''], - ['avsZip' => 'M', 'avsStreet' => 'M', 'expected' => 'Y'], - ['avsZip' => 'N', 'avsStreet' => 'M', 'expected' => 'A'], - ['avsZip' => 'M', 'avsStreet' => 'N', 'expected' => 'Z'], - ['avsZip' => 'N', 'avsStreet' => 'N', 'expected' => 'N'], - ['avsZip' => 'U', 'avsStreet' => 'U', 'expected' => 'U'], - ['avsZip' => 'I', 'avsStreet' => 'I', 'expected' => 'U'], - ['avsZip' => 'A', 'avsStreet' => 'A', 'expected' => 'E'], - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/CvvEmsCodeMapperTest.php b/app/code/Magento/Braintree/Test/Unit/Model/CvvEmsCodeMapperTest.php deleted file mode 100644 index 3b09babbc16fd..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/CvvEmsCodeMapperTest.php +++ /dev/null @@ -1,97 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model; - -use Magento\Braintree\Model\CvvEmsCodeMapper; -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Sales\Api\Data\OrderPaymentInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class CvvEmsCodeMapperTest extends TestCase -{ - /** - * @var CvvEmsCodeMapper - */ - private $mapper; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->mapper = new CvvEmsCodeMapper(); - } - - /** - * Checks different variations for cvv codes mapping. - * - * @covers \Magento\Braintree\Model\CvvEmsCodeMapper::getCode - * @param string $cvvCode - * @param string $expected - * @dataProvider getCodeDataProvider - */ - public function testGetCode($cvvCode, $expected) - { - /** @var OrderPaymentInterface|MockObject $orderPayment */ - $orderPayment = $this->getMockBuilder(OrderPaymentInterface::class) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - - $orderPayment->expects(self::once()) - ->method('getMethod') - ->willReturn(ConfigProvider::CODE); - - $orderPayment->expects(self::once()) - ->method('getAdditionalInformation') - ->willReturn(['cvvResponseCode' => $cvvCode]); - - self::assertEquals($expected, $this->mapper->getCode($orderPayment)); - } - - /** - * Checks a test case, when payment order is not Braintree payment method. - * - * @covers \Magento\Braintree\Model\CvvEmsCodeMapper::getCode - */ - public function testGetCodeWithException() - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The "some_payment" does not supported by Braintree CVV mapper.'); - /** @var OrderPaymentInterface|MockObject $orderPayment */ - $orderPayment = $this->getMockBuilder(OrderPaymentInterface::class) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - - $orderPayment->expects(self::exactly(2)) - ->method('getMethod') - ->willReturn('some_payment'); - - $this->mapper->getCode($orderPayment); - } - - /** - * Gets variations of cvv codes and expected mapping result. - * - * @return array - */ - public function getCodeDataProvider() - { - return [ - ['cvvCode' => '', 'expected' => 'P'], - ['cvvCode' => null, 'expected' => 'P'], - ['cvvCode' => 'Unknown', 'expected' => 'P'], - ['cvvCode' => 'M', 'expected' => 'M'], - ['cvvCode' => 'N', 'expected' => 'N'], - ['cvvCode' => 'U', 'expected' => 'P'], - ['cvvCode' => 'I', 'expected' => 'P'], - ['cvvCode' => 'S', 'expected' => 'S'], - ['cvvCode' => 'A', 'expected' => ''], - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/CreditCard/AvailabilityCheckerTest.php b/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/CreditCard/AvailabilityCheckerTest.php deleted file mode 100644 index 419e07fc3b9f5..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/CreditCard/AvailabilityCheckerTest.php +++ /dev/null @@ -1,72 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\InstantPurchase\CreditCard; - -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Model\InstantPurchase\CreditCard\AvailabilityChecker; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @covers \Magento\Braintree\Model\InstantPurchase\CreditCard\AvailabilityChecker - */ -class AvailabilityCheckerTest extends TestCase -{ - /** - * Testable Object - * - * @var AvailabilityChecker - */ - private $availabilityChecker; - - /** - * @var Config|MockObject - */ - private $configMock; - - /** - * Set Up - * - * @return void - */ - protected function setUp(): void - { - $this->configMock = $this->createMock(Config::class); - $this->availabilityChecker = new AvailabilityChecker($this->configMock); - } - - /** - * Test isAvailable method - * - * @dataProvider isAvailableDataProvider - * - * @param bool $isVerify3DSecure - * @param bool $expected - * - * @return void - */ - public function testIsAvailable(bool $isVerify3DSecure, bool $expected) - { - $this->configMock->expects($this->once())->method('isVerify3DSecure')->willReturn($isVerify3DSecure); - $actual = $this->availabilityChecker->isAvailable(); - self::assertEquals($expected, $actual); - } - - /** - * Data provider for isAvailable method test - * - * @return array - */ - public function isAvailableDataProvider() - { - return [ - [true, false], - [false, true], - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/CreditCard/TokenFormatterTest.php b/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/CreditCard/TokenFormatterTest.php deleted file mode 100644 index 9a074ddfba9e2..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/CreditCard/TokenFormatterTest.php +++ /dev/null @@ -1,119 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\InstantPurchase\CreditCard; - -use Magento\Braintree\Model\InstantPurchase\CreditCard\TokenFormatter as CreditCardTokenFormatter; -use Magento\Vault\Api\Data\PaymentTokenInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class TokenFormatterTest extends TestCase -{ - /** - * @var PaymentTokenInterface|MockObject - */ - private $paymentTokenMock; - - /** - * @var CreditCardTokenFormatter - */ - private $creditCardTokenFormatter; - - /** - * @var array - */ - private $tokenDetails = [ - 'type' => 'visa', - 'maskedCC' => '1111************9999', - 'expirationDate' => '01-01-2020' - ]; - - /** - * Set Up - * - * @return void - */ - protected function setUp(): void - { - $this->paymentTokenMock = $this->getMockBuilder(PaymentTokenInterface::class) - ->getMockForAbstractClass(); - - $this->creditCardTokenFormatter = new CreditCardTokenFormatter(); - } - - /** - * Testing the payment format with a known credit card type - * - * @return void - */ - public function testFormatPaymentTokenWithKnownCardType() - { - $this->tokenDetails['type'] = key(CreditCardTokenFormatter::$baseCardTypes); - $this->paymentTokenMock->expects($this->once()) - ->method('getTokenDetails') - ->willReturn(json_encode($this->tokenDetails)); - - $formattedString = sprintf( - '%s: %s, %s: %s (%s: %s)', - __('Credit Card'), - reset(CreditCardTokenFormatter::$baseCardTypes), - __('ending'), - $this->tokenDetails['maskedCC'], - __('expires'), - $this->tokenDetails['expirationDate'] - ); - - self::assertEquals( - $formattedString, - $this->creditCardTokenFormatter->formatPaymentToken($this->paymentTokenMock) - ); - } - - /** - * Testing the payment format with a unknown credit card type - * - * @return void - */ - public function testFormatPaymentTokenWithUnknownCardType() - { - $this->paymentTokenMock->expects($this->once()) - ->method('getTokenDetails') - ->willReturn(json_encode($this->tokenDetails)); - - $formattedString = sprintf( - '%s: %s, %s: %s (%s: %s)', - __('Credit Card'), - $this->tokenDetails['type'], - __('ending'), - $this->tokenDetails['maskedCC'], - __('expires'), - $this->tokenDetails['expirationDate'] - ); - - self::assertEquals( - $formattedString, - $this->creditCardTokenFormatter->formatPaymentToken($this->paymentTokenMock) - ); - } - - /** - * Testing the payment format with wrong card data - * - * @return void - */ - public function testFormatPaymentTokenWithWrongData() - { - unset($this->tokenDetails['type']); - $this->paymentTokenMock->expects($this->once()) - ->method('getTokenDetails') - ->willReturn(json_encode($this->tokenDetails)); - self::expectException('\InvalidArgumentException'); - - $this->creditCardTokenFormatter->formatPaymentToken($this->paymentTokenMock); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/PayPal/TokenFormatterTest.php b/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/PayPal/TokenFormatterTest.php deleted file mode 100644 index 3c300dce71ca0..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/PayPal/TokenFormatterTest.php +++ /dev/null @@ -1,106 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\InstantPurchase\PayPal; - -use Magento\Braintree\Model\InstantPurchase\CreditCard\TokenFormatter as PaypalTokenFormatter; -use Magento\Vault\Api\Data\PaymentTokenInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class TokenFormatterTest extends TestCase -{ - /** - * @var PaymentTokenInterface|MockObject - */ - private $paymentTokenMock; - - /** - * @var PaypalTokenFormatter - */ - private $paypalTokenFormatter; - - /** - * @var array - */ - private $tokenDetails = [ - 'type' => 'visa', - 'maskedCC' => '4444************9999', - 'expirationDate' => '07-07-2025' - ]; - - /** - * Test setup - */ - protected function setUp(): void - { - $this->paymentTokenMock = $this->getMockBuilder(PaymentTokenInterface::class) - ->getMockForAbstractClass(); - - $this->paypalTokenFormatter = new PaypalTokenFormatter(); - } - - /** - * testFormatPaymentTokenWithKnownCardType - */ - public function testFormatPaymentTokenWithKnownCardType() - { - $this->tokenDetails['type'] = key(PaypalTokenFormatter::$baseCardTypes); - $this->paymentTokenMock->expects($this->once()) - ->method('getTokenDetails') - ->willReturn(json_encode($this->tokenDetails)); - - $formattedString = sprintf( - '%s: %s, %s: %s (%s: %s)', - __('Credit Card'), - reset(PaypalTokenFormatter::$baseCardTypes), - __('ending'), - $this->tokenDetails['maskedCC'], - __('expires'), - $this->tokenDetails['expirationDate'] - ); - - self::assertEquals($formattedString, $this->paypalTokenFormatter->formatPaymentToken($this->paymentTokenMock)); - } - - /** - * testFormatPaymentTokenWithUnknownCardType - */ - public function testFormatPaymentTokenWithUnknownCardType() - { - $this->paymentTokenMock->expects($this->once()) - ->method('getTokenDetails') - ->willReturn(json_encode($this->tokenDetails)); - - $formattedString = sprintf( - '%s: %s, %s: %s (%s: %s)', - __('Credit Card'), - $this->tokenDetails['type'], - __('ending'), - $this->tokenDetails['maskedCC'], - __('expires'), - $this->tokenDetails['expirationDate'] - ); - - self::assertEquals($formattedString, $this->paypalTokenFormatter->formatPaymentToken($this->paymentTokenMock)); - } - - /** - * testFormatPaymentTokenWithWrongData - */ - public function testFormatPaymentTokenWithWrongData() - { - unset($this->tokenDetails['type']); - - $this->paymentTokenMock->expects($this->once()) - ->method('getTokenDetails') - ->willReturn(json_encode($this->tokenDetails)); - self::expectException('\InvalidArgumentException'); - - $this->paypalTokenFormatter->formatPaymentToken($this->paymentTokenMock); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/PaymentAdditionalInformationProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/PaymentAdditionalInformationProviderTest.php deleted file mode 100644 index f51488c8adc7f..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/InstantPurchase/PaymentAdditionalInformationProviderTest.php +++ /dev/null @@ -1,85 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\InstantPurchase; - -use Magento\Braintree\Gateway\Command\GetPaymentNonceCommand; -use Magento\Braintree\Model\InstantPurchase\PaymentAdditionalInformationProvider; -use Magento\Payment\Gateway\Command\Result\ArrayResult; -use Magento\Vault\Api\Data\PaymentTokenInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @covers \Magento\Braintree\Model\InstantPurchase\PaymentAdditionalInformationProvider - */ -class PaymentAdditionalInformationProviderTest extends TestCase -{ - /** - * Testable Object - * - * @var PaymentAdditionalInformationProvider - */ - private $paymentAdditionalInformationProvider; - - /** - * @var GetPaymentNonceCommand|MockObject - */ - private $getPaymentNonceCommandMock; - - /** - * @var PaymentTokenInterface|MockObject - */ - private $paymentTokenMock; - - /** - * @var ArrayResult|MockObject - */ - private $arrayResultMock; - - /** - * Set Up - * - * @return void - */ - protected function setUp(): void - { - $this->getPaymentNonceCommandMock = $this->createMock(GetPaymentNonceCommand::class); - $this->paymentTokenMock = $this->getMockForAbstractClass(PaymentTokenInterface::class); - $this->arrayResultMock = $this->createMock(ArrayResult::class); - $this->paymentAdditionalInformationProvider = new PaymentAdditionalInformationProvider( - $this->getPaymentNonceCommandMock - ); - } - - /** - * Test getAdditionalInformation method - * - * @return void - */ - public function testGetAdditionalInformation() - { - $customerId = 15; - $publicHash = '3n4b7sn48g'; - $paymentMethodNonce = 'test'; - - $this->paymentTokenMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); - $this->paymentTokenMock->expects($this->once())->method('getPublicHash')->willReturn($publicHash); - $this->getPaymentNonceCommandMock->expects($this->once())->method('execute')->with([ - PaymentTokenInterface::CUSTOMER_ID => $customerId, - PaymentTokenInterface::PUBLIC_HASH => $publicHash, - ])->willReturn($this->arrayResultMock); - $this->arrayResultMock->expects($this->once())->method('get') - ->willReturn(['paymentMethodNonce' => $paymentMethodNonce]); - - $expected = [ - 'payment_method_nonce' => $paymentMethodNonce, - ]; - $actual = $this->paymentAdditionalInformationProvider->getAdditionalInformation($this->paymentTokenMock); - self::assertEquals($expected, $actual); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/LocaleResolverTest.php b/app/code/Magento/Braintree/Test/Unit/Model/LocaleResolverTest.php deleted file mode 100644 index 693a7c4d3fe1f..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/LocaleResolverTest.php +++ /dev/null @@ -1,156 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model; - -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Model\LocaleResolver; -use Magento\Framework\Locale\ResolverInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @covers \Magento\Braintree\Model\LocaleResolver - */ -class LocaleResolverTest extends TestCase -{ - /** - * Testable Object - * - * @var LocaleResolver - */ - private $localeResolver; - - /** - * @var Config|MockObject - */ - private $configMock; - - /** - * @var ResolverInterface|MockObject - */ - private $resolverMock; - - /** - * Set Up - * - * @return void - */ - protected function setUp(): void - { - $this->configMock = $this->createMock(Config::class); - $this->resolverMock = $this->getMockForAbstractClass(ResolverInterface::class); - $this->localeResolver = new LocaleResolver($this->resolverMock, $this->configMock); - } - - /** - * Test getDefaultLocalePath method - * - * @return void - */ - public function testGetDefaultLocalePath() - { - $expected = 'general/locale/code'; - $this->resolverMock->expects($this->once())->method('getDefaultLocalePath')->willReturn($expected); - $actual = $this->localeResolver->getDefaultLocalePath(); - self::assertEquals($expected, $actual); - } - - /** - * Test setDefaultLocale method - * - * @return void - */ - public function testSetDefaultLocale() - { - $defaultLocale = 'en_US'; - $this->resolverMock->expects($this->once())->method('setDefaultLocale')->with($defaultLocale); - $this->localeResolver->setDefaultLocale($defaultLocale); - } - - /** - * Test getDefaultLocale method - * - * @return void - */ - public function testGetDefaultLocale() - { - $expected = 'fr_FR'; - $this->resolverMock->expects($this->once())->method('getDefaultLocale')->willReturn($expected); - $actual = $this->localeResolver->getDefaultLocale(); - self::assertEquals($expected, $actual); - } - - /** - * Test setLocale method - * - * @return void - */ - public function testSetLocale() - { - $locale = 'en_GB'; - $this->resolverMock->expects($this->once())->method('setLocale')->with($locale); - $this->localeResolver->setLocale($locale); - } - - /** - * Test getLocale method - * - * @param string $locale - * @param string $expectedLocale - * @dataProvider getLocaleDataProvider - */ - public function testGetLocale(string $locale, string $expectedLocale) - { - $allowedLocales = 'en_US,en_GB,en_AU,da_DK,fr_FR,fr_CA,de_DE,zh_HK,it_IT,zh_CN,zh_TW,nl_NL'; - $this->resolverMock->method('getLocale') - ->willReturn($locale); - $this->configMock->method('getValue') - ->with('supported_locales') - ->willReturn($allowedLocales); - $actual = $this->localeResolver->getLocale(); - - self::assertEquals($expectedLocale, $actual); - } - - /** - * @return array - */ - public function getLocaleDataProvider(): array - { - return [ - ['locale' => 'zh_Hans_CN', 'expectedLocale' => 'zh_CN'], - ['locale' => 'zh_Hant_HK', 'expectedLocale' => 'zh_HK'], - ['locale' => 'zh_Hant_TW', 'expectedLocale' => 'zh_TW'], - ['locale' => 'fr_FR', 'expectedLocale' => 'fr_FR'], - ['locale' => 'unknown', 'expectedLocale' => 'en_US'], - ]; - } - - /** - * Test emulate method - * - * @return void - */ - public function testEmulate() - { - $scopeId = 12; - $this->resolverMock->expects($this->once())->method('emulate')->with($scopeId); - $this->localeResolver->emulate($scopeId); - } - - /** - * Test revert method - * - * @return void - */ - public function testRevert() - { - $this->resolverMock->expects($this->once())->method('revert'); - $this->localeResolver->revert(); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/OrderPlaceTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/OrderPlaceTest.php deleted file mode 100644 index 19813e9bf7173..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/OrderPlaceTest.php +++ /dev/null @@ -1,265 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\Paypal\Helper; - -use Magento\Braintree\Model\Paypal\Helper\OrderPlace; -use Magento\Braintree\Model\Paypal\OrderCancellationService; -use Magento\Checkout\Api\AgreementsValidatorInterface; -use Magento\Checkout\Helper\Data; -use Magento\Checkout\Model\Type\Onepage; -use Magento\Customer\Model\Group; -use Magento\Customer\Model\Session; -use Magento\Quote\Api\CartManagementInterface; -use Magento\Quote\Model\Quote; -use Magento\Quote\Model\Quote\Address; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @see \Magento\Braintree\Model\Paypal\Helper\OrderPlace - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class OrderPlaceTest extends TestCase -{ - const TEST_EMAIL = 'test@test.loc'; - - /** - * @var CartManagementInterface|MockObject - */ - private $cartManagement; - - /** - * @var AgreementsValidatorInterface|MockObject - */ - private $agreementsValidator; - - /** - * @var Session|MockObject - */ - private $customerSession; - - /** - * @var Data|MockObject - */ - private $checkoutHelper; - - /** - * @var Address|MockObject - */ - private $billingAddress; - - /** - * @var OrderPlace - */ - private $orderPlace; - - /** - * @var OrderCancellationService|MockObject - */ - private $orderCancellation; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->cartManagement = $this->getMockBuilder(CartManagementInterface::class) - ->getMockForAbstractClass(); - $this->agreementsValidator = $this->getMockBuilder(AgreementsValidatorInterface::class) - ->getMockForAbstractClass(); - $this->customerSession = $this->getMockBuilder(Session::class) - ->disableOriginalConstructor() - ->getMock(); - $this->checkoutHelper = $this->getMockBuilder(Data::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->orderCancellation = $this->getMockBuilder(OrderCancellationService::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->orderPlace = new OrderPlace( - $this->cartManagement, - $this->agreementsValidator, - $this->customerSession, - $this->checkoutHelper, - $this->orderCancellation - ); - } - - /** - * Checks a scenario for a guest customer. - * - * @throws \Exception - */ - public function testExecuteGuest() - { - $agreement = ['test', 'test']; - $quoteMock = $this->getQuoteMock(); - - $this->agreementsValidator->expects(self::once()) - ->method('isValid') - ->willReturn(true); - - $this->getCheckoutMethodStep($quoteMock); - $this->prepareGuestQuoteStep($quoteMock); - $this->disabledQuoteAddressValidationStep($quoteMock); - - $quoteMock->expects(self::once()) - ->method('collectTotals'); - - $quoteMock->expects(self::once()) - ->method('getId') - ->willReturn(10); - - $this->cartManagement->expects(self::once()) - ->method('placeOrder') - ->with(10); - - $this->orderPlace->execute($quoteMock, $agreement); - } - - /** - * Disables address validation. - * - * @param MockObject $quoteMock - */ - private function disabledQuoteAddressValidationStep(MockObject $quoteMock) - { - $billingAddressMock = $this->getBillingAddressMock($quoteMock); - $shippingAddressMock = $this->getMockBuilder(Address::class) - ->setMethods(['setShouldIgnoreValidation']) - ->disableOriginalConstructor() - ->getMock(); - - $quoteMock->method('getShippingAddress') - ->willReturn($shippingAddressMock); - - $billingAddressMock->method('setShouldIgnoreValidation') - ->with(true) - ->willReturnSelf(); - - $quoteMock->method('getIsVirtual') - ->willReturn(false); - - $shippingAddressMock->method('setShouldIgnoreValidation') - ->with(true) - ->willReturnSelf(); - - $billingAddressMock->method('getEmail') - ->willReturn(self::TEST_EMAIL); - - $billingAddressMock->expects(self::never()) - ->method('setSameAsBilling'); - } - - /** - * Prepares checkout step. - * - * @param MockObject $quoteMock - */ - private function getCheckoutMethodStep(MockObject $quoteMock) - { - $this->customerSession->method('isLoggedIn') - ->willReturn(false); - - $quoteMock->expects(self::at(1)) - ->method('getCheckoutMethod') - ->willReturn(null); - - $this->checkoutHelper->method('isAllowedGuestCheckout') - ->with($quoteMock) - ->willReturn(true); - - $quoteMock->method('setCheckoutMethod') - ->with(Onepage::METHOD_GUEST); - - $quoteMock->expects(self::at(2)) - ->method('getCheckoutMethod') - ->willReturn(Onepage::METHOD_GUEST); - } - - /** - * Prepares quote. - * - * @param MockObject $quoteMock - */ - private function prepareGuestQuoteStep(MockObject $quoteMock) - { - $billingAddressMock = $this->getBillingAddressMock($quoteMock); - - $quoteMock->expects(self::once()) - ->method('setCustomerId') - ->with(null) - ->willReturnSelf(); - - $billingAddressMock->expects(self::at(0)) - ->method('getEmail') - ->willReturn(self::TEST_EMAIL); - - $quoteMock->method('setCustomerEmail') - ->with(self::TEST_EMAIL) - ->willReturnSelf(); - - $quoteMock->method('setCustomerIsGuest') - ->with(true) - ->willReturnSelf(); - - $quoteMock->method('setCustomerGroupId') - ->with(Group::NOT_LOGGED_IN_ID) - ->willReturnSelf(); - } - - /** - * Gets a mock object for a billing address entity. - * - * @param MockObject $quoteMock - * @return Address|MockObject - */ - private function getBillingAddressMock(MockObject $quoteMock) - { - if (!isset($this->billingAddress)) { - $this->billingAddress = $this->getMockBuilder(Address::class) - ->setMethods(['setShouldIgnoreValidation', 'getEmail', 'setSameAsBilling']) - ->disableOriginalConstructor() - ->getMock(); - } - - $quoteMock->method('getBillingAddress') - ->willReturn($this->billingAddress); - - return $this->billingAddress; - } - - /** - * Gets a mock object for a quote. - * - * @return Quote|MockObject - */ - private function getQuoteMock() - { - return $this->getMockBuilder(Quote::class) - ->setMethods( - [ - 'setCustomerId', - 'setCustomerEmail', - 'setCustomerIsGuest', - 'setCustomerGroupId', - 'getCheckoutMethod', - 'setCheckoutMethod', - 'collectTotals', - 'getId', - 'getBillingAddress', - 'getShippingAddress', - 'getIsVirtual' - ] - )->disableOriginalConstructor() - ->getMock(); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/QuoteUpdaterTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/QuoteUpdaterTest.php deleted file mode 100644 index a11e0713ade6f..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/QuoteUpdaterTest.php +++ /dev/null @@ -1,329 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\Paypal\Helper; - -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Model\Paypal\Helper\QuoteUpdater; -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider; -use Magento\Braintree\Observer\DataAssignObserver; -use Magento\Framework\Exception\LocalizedException; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Quote\Api\Data\CartExtensionInterface; -use Magento\Quote\Model\Quote; -use Magento\Quote\Model\Quote\Address; -use Magento\Quote\Model\Quote\Payment; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class QuoteUpdaterTest extends TestCase -{ - const TEST_NONCE = '3ede7045-2aea-463e-9754-cd658ffeeb48'; - - /** - * @var Config|MockObject - */ - private $config; - - /** - * @var CartRepositoryInterface|MockObject - */ - private $quoteRepository; - - /** - * @var Address|MockObject - */ - private $billingAddress; - - /** - * @var Address|MockObject - */ - private $shippingAddress; - - /** - * @var QuoteUpdater - */ - private $quoteUpdater; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->config = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); - $this->quoteRepository = $this->getMockBuilder(CartRepositoryInterface::class) - ->getMockForAbstractClass(); - - $this->billingAddress = $this->getMockBuilder(Address::class) - ->setMethods( - [ - 'setLastname', - 'setFirstname', - 'setEmail', - 'setCollectShippingRates', - 'setStreet', - 'setCity', - 'setRegionCode', - 'setCountryId', - 'setPostcode', - 'setShouldIgnoreValidation', - 'getEmail' - ] - ) - ->disableOriginalConstructor() - ->getMock(); - $this->shippingAddress = $this->getMockBuilder(Address::class) - ->setMethods( - [ - 'setLastname', - 'setFirstname', - 'setEmail', - 'setCollectShippingRates', - 'setStreet', - 'setCity', - 'setRegionCode', - 'setCountryId', - 'setPostcode', - 'setShouldIgnoreValidation' - ] - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->quoteUpdater = new QuoteUpdater( - $this->config, - $this->quoteRepository - ); - } - - /** - * Checks if quote details can be update by the response from Braintree. - * - * @throws LocalizedException - */ - public function testExecute(): void - { - $details = $this->getDetails(); - $quote = $this->getQuoteMock(); - $payment = $this->getPaymentMock(); - - $quote->method('getPayment') - ->willReturn($payment); - - $payment->method('setMethod') - ->with(ConfigProvider::PAYPAL_CODE); - $payment->method('setAdditionalInformation') - ->with(DataAssignObserver::PAYMENT_METHOD_NONCE, self::TEST_NONCE); - - $this->updateQuoteStep($quote, $details); - - $this->quoteUpdater->execute(self::TEST_NONCE, $details, $quote); - } - - /** - * Disables quote's addresses validation. - * - * @return void - */ - private function disabledQuoteAddressValidationStep(): void - { - $this->billingAddress->method('setShouldIgnoreValidation') - ->with(true); - $this->shippingAddress->method('setShouldIgnoreValidation') - ->with(true); - $this->billingAddress->method('getEmail') - ->willReturn('bt_buyer_us@paypal.com'); - } - - /** - * Gets quote's details. - * - * @return array - */ - private function getDetails(): array - { - return [ - 'email' => 'bt_buyer_us@paypal.com', - 'payerId' => 'FAKE_PAYER_ID', - 'firstName' => 'John', - 'lastName' => 'Doe', - 'phone' => '312-123-4567', - 'countryCode' => 'US', - 'shippingAddress' => [ - 'line1' => '123 Division Street', - 'line2' => 'Apt. #1', - 'city' => 'Chicago', - 'state' => 'IL', - 'postalCode' => '60618', - 'countryCode' => 'US', - 'recipientName' => 'Jane Smith', - ], - 'billingAddress' => [ - 'line1' => '123 Billing Street', - 'line2' => 'Apt. #1', - 'city' => 'Chicago', - 'state' => 'IL', - 'postalCode' => '60618', - 'countryCode' => 'US', - ], - ]; - } - - /** - * Updates shipping address details. - * - * @param array $details - */ - private function updateShippingAddressStep(array $details): void - { - $this->shippingAddress->method('setLastname') - ->with('Smith'); - $this->shippingAddress->method('setFirstname') - ->with('Jane'); - $this->shippingAddress->method('setEmail') - ->with($details['email']); - $this->shippingAddress->method('setCollectShippingRates') - ->with(true); - - $this->updateAddressDataStep($this->shippingAddress, $details['shippingAddress']); - } - - /** - * Updates address details. - * - * @param MockObject $address - * @param array $addressData - */ - private function updateAddressDataStep(MockObject $address, array $addressData): void - { - $address->method('setStreet') - ->with([$addressData['line1'], $addressData['line2']]); - $address->method('setCity') - ->with($addressData['city']); - $address->method('setRegionCode') - ->with($addressData['state']); - $address->method('setCountryId') - ->with($addressData['countryCode']); - $address->method('setPostcode') - ->with($addressData['postalCode']); - } - - /** - * Updates quote's address details. - * - * @param MockObject $quoteMock - * @param array $details - */ - private function updateQuoteAddressStep(MockObject $quoteMock, array $details): void - { - $quoteMock->expects(self::exactly(2)) - ->method('getIsVirtual') - ->willReturn(false); - - $this->updateShippingAddressStep($details); - $this->updateBillingAddressStep($details); - } - - /** - * Updates billing address details. - * - * @param array $details - */ - private function updateBillingAddressStep(array $details): void - { - $this->config->method('isRequiredBillingAddress') - ->willReturn(true); - - $this->updateAddressDataStep($this->billingAddress, $details['billingAddress']); - - $this->billingAddress->method('setLastname') - ->with($details['lastName']); - $this->billingAddress->method('setFirstname') - ->with($details['firstName']); - $this->billingAddress->method('setEmail') - ->with($details['email']); - } - - /** - * Updates quote details. - * - * @param MockObject $quote - * @param array $details - */ - private function updateQuoteStep(MockObject $quote, array $details): void - { - $quote->method('setMayEditShippingAddress') - ->with(false); - $quote->method('setMayEditShippingMethod') - ->with(true); - - $quote->method('getShippingAddress') - ->willReturn($this->shippingAddress); - $quote->expects(self::exactly(2)) - ->method('getBillingAddress') - ->willReturn($this->billingAddress); - - $this->updateQuoteAddressStep($quote, $details); - $this->disabledQuoteAddressValidationStep(); - - $quote->method('collectTotals'); - - $this->quoteRepository->method('save') - ->with($quote); - } - - /** - * Creates a mock for Quote object. - * - * @return Quote|MockObject - */ - private function getQuoteMock(): MockObject - { - $quote = $this->getMockBuilder(Quote::class) - ->setMethods( - [ - 'getIsVirtual', - 'getPayment', - 'setMayEditShippingAddress', - 'setMayEditShippingMethod', - 'collectTotals', - 'getShippingAddress', - 'getBillingAddress', - 'getExtensionAttributes' - ] - ) - ->disableOriginalConstructor() - ->getMock(); - - $cartExtension = $this->getMockBuilder(CartExtensionInterface::class) - ->setMethods(['setShippingAssignments']) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - - $quote->method('getExtensionAttributes') - ->willReturn($cartExtension); - - return $quote; - } - - /** - * Creates a mock for Payment object. - * - * @return Payment|MockObject - */ - private function getPaymentMock(): MockObject - { - return $this->getMockBuilder(Payment::class) - ->disableOriginalConstructor() - ->getMock(); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/ShippingMethodUpdaterTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/ShippingMethodUpdaterTest.php deleted file mode 100644 index cf3753fb40e6b..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/Paypal/Helper/ShippingMethodUpdaterTest.php +++ /dev/null @@ -1,175 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\Paypal\Helper; - -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Model\Paypal\Helper\ShippingMethodUpdater; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Quote\Model\Quote; -use Magento\Quote\Model\Quote\Address; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @see \Magento\Braintree\Model\Paypal\Helper\ShippingMethodUpdater - */ -class ShippingMethodUpdaterTest extends TestCase -{ - const TEST_SHIPPING_METHOD = 'test-shipping-method'; - - const TEST_EMAIL = 'test@test.loc'; - - /** - * @var Config|MockObject - */ - private $configMock; - - /** - * @var CartRepositoryInterface|MockObject - */ - private $quoteRepositoryMock; - - /** - * @var Address|MockObject - */ - private $shippingAddressMock; - - /** - * @var ShippingMethodUpdater - */ - private $shippingMethodUpdater; - - protected function setUp(): void - { - $this->configMock = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); - $this->quoteRepositoryMock = $this->getMockBuilder(CartRepositoryInterface::class) - ->getMockForAbstractClass(); - - $this->shippingAddressMock = $this->getMockBuilder(Address::class) - ->setMethods( - [ - 'setShouldIgnoreValidation', - 'getShippingMethod', - 'setShippingMethod', - 'setCollectShippingRates' - ] - )->disableOriginalConstructor() - ->getMock(); - - $this->shippingMethodUpdater = new ShippingMethodUpdater( - $this->configMock, - $this->quoteRepositoryMock - ); - } - - public function testExecuteException() - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The "shippingMethod" field does not exists.'); - $quoteMock = $this->getQuoteMock(); - - $this->shippingMethodUpdater->execute('', $quoteMock); - } - - public function testExecute() - { - $quoteMock = $this->getQuoteMock(); - - $quoteMock->expects(self::exactly(2)) - ->method('getIsVirtual') - ->willReturn(false); - - $quoteMock->expects(self::exactly(2)) - ->method('getShippingAddress') - ->willReturn($this->shippingAddressMock); - - $this->shippingAddressMock->expects(self::once()) - ->method('getShippingMethod') - ->willReturn(self::TEST_SHIPPING_METHOD . '-bad'); - - $this->disabledQuoteAddressValidationStep($quoteMock); - - $this->shippingAddressMock->expects(self::once()) - ->method('setShippingMethod') - ->willReturn(self::TEST_SHIPPING_METHOD); - $this->shippingAddressMock->expects(self::once()) - ->method('setCollectShippingRates') - ->willReturn(true); - - $quoteMock->expects(self::once()) - ->method('collectTotals'); - - $this->quoteRepositoryMock->expects(self::once()) - ->method('save') - ->with($quoteMock); - - $this->shippingMethodUpdater->execute(self::TEST_SHIPPING_METHOD, $quoteMock); - } - - /** - * @param MockObject $quoteMock - */ - private function disabledQuoteAddressValidationStep(MockObject $quoteMock) - { - $billingAddressMock = $this->getBillingAddressMock($quoteMock); - - $billingAddressMock->expects(self::once()) - ->method('setShouldIgnoreValidation') - ->with(true) - ->willReturnSelf(); - - $this->shippingAddressMock->expects(self::once()) - ->method('setShouldIgnoreValidation') - ->with(true) - ->willReturnSelf(); - - $billingAddressMock->expects(self::at(1)) - ->method('getEmail') - ->willReturn(self::TEST_EMAIL); - - $billingAddressMock->expects(self::never()) - ->method('setSameAsBilling'); - } - - /** - * @param MockObject $quoteMock - * @return Address|MockObject - */ - private function getBillingAddressMock(MockObject $quoteMock) - { - $billingAddressMock = $this->getMockBuilder(Address::class) - ->setMethods(['setShouldIgnoreValidation', 'getEmail', 'setSameAsBilling']) - ->disableOriginalConstructor() - ->getMock(); - - $quoteMock->expects(self::any()) - ->method('getBillingAddress') - ->willReturn($billingAddressMock); - - return $billingAddressMock; - } - - /** - * @return Quote|MockObject - */ - private function getQuoteMock() - { - return $this->getMockBuilder(Quote::class) - ->setMethods( - [ - 'collectTotals', - 'getBillingAddress', - 'getShippingAddress', - 'getIsVirtual' - ] - )->disableOriginalConstructor() - ->getMock(); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Report/BraintreeSearchNodeStub.php b/app/code/Magento/Braintree/Test/Unit/Model/Report/BraintreeSearchNodeStub.php deleted file mode 100644 index 1223afb4ad3a5..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/Report/BraintreeSearchNodeStub.php +++ /dev/null @@ -1,12 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\Report; - -class BraintreeSearchNodeStub -{ -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Report/BraintreeTransactionStub.php b/app/code/Magento/Braintree/Test/Unit/Model/Report/BraintreeTransactionStub.php deleted file mode 100644 index d3a680d8c1bc9..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/Report/BraintreeTransactionStub.php +++ /dev/null @@ -1,64 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\Report; - -class BraintreeTransactionStub -{ - protected $_attributes = []; - - /** - * Set attributes array - * - * @param $attrs - * @return void - */ - public function setAttributes($attrs) - { - $this->_attributes = $attrs; - } - - /** - * Accessor for instance properties stored in the private $_attributes property - * - * @ignore - * @param string $name - * @return mixed - */ - public function __get($name) - { - if (array_key_exists($name, $this->_attributes)) { - return $this->_attributes[$name]; - } - trigger_error('Undefined property on ' . get_class($this) . ': ' . $name, E_USER_NOTICE); - return null; - } - - /** - * Checks for the existence of a property stored in the private $_attributes property - * - * @ignore - * @param string $name - * @return boolean - */ - public function __isset($name) - { - return array_key_exists($name, $this->_attributes); - } - - /** - * Mutator for instance properties stored in the private $_attributes property - * - * @ignore - * @param string $key - * @param mixed $value - */ - public function _set($key, $value) - { - $this->_attributes[$key] = $value; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Report/FilterMapperTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Report/FilterMapperTest.php deleted file mode 100644 index 8897b103d518b..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/Report/FilterMapperTest.php +++ /dev/null @@ -1,117 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\Report; - -use Magento\Braintree\Model\Adapter\BraintreeSearchAdapter; -use Magento\Braintree\Model\Report\ConditionAppliers\ApplierInterface; -use Magento\Braintree\Model\Report\ConditionAppliers\AppliersPool; -use Magento\Braintree\Model\Report\FilterMapper; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Test for class \Magento\Braintree\Model\Report\FilterMapper - */ -class FilterMapperTest extends TestCase -{ - /** - * @var BraintreeSearchAdapter|MockObject - */ - private $braintreeSearchAdapterMock; - - /** - * @var AppliersPool|MockObject - */ - private $appliersPoolMock; - - /** - * @var ApplierInterface|MockObject - */ - private $applierMock; - - /** - * Setup - */ - protected function setUp(): void - { - $methods = [ - 'id', - 'merchantAccountId', - 'orderId', - 'paypalPaymentId', - 'createdUsing', - 'type', - 'createdAt', - 'amount', - 'status', - 'settlementBatchId', - 'paymentInstrumentType', - ]; - $this->braintreeSearchAdapterMock = $this->getMockBuilder(BraintreeSearchAdapter::class) - ->setMethods($methods) - ->disableOriginalConstructor() - ->getMock(); - foreach ($methods as $method) { - $this->braintreeSearchAdapterMock->expects($this->once())->method($method) - ->willReturn(new BraintreeSearchNodeStub()); - } - - $this->appliersPoolMock = $this->getMockBuilder(AppliersPool::class) - ->setMethods(['getApplier']) - ->disableOriginalConstructor() - ->getMock(); - - $this->applierMock = $this->getMockBuilder(ApplierInterface::class) - ->setMethods(['apply']) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - } - - /** - * Positive test - */ - public function testGetFilterPositiveApply() - { - $this->applierMock->expects($this->exactly(3)) - ->method('apply') - ->willReturn(true); - - $this->appliersPoolMock->expects($this->exactly(3)) - ->method('getApplier') - ->willReturn($this->applierMock); - - $mapper = new FilterMapper($this->appliersPoolMock, $this->braintreeSearchAdapterMock); - - $result = $mapper->getFilter('id', ['eq' => 'value']); - $this->assertInstanceOf(BraintreeSearchNodeStub::class, $result); - - $result = $mapper->getFilter('orderId', ['eq' => 'value']); - $this->assertInstanceOf(BraintreeSearchNodeStub::class, $result); - - $result = $mapper->getFilter('amount', ['eq' => 'value']); - $this->assertInstanceOf(BraintreeSearchNodeStub::class, $result); - } - - /** - * Negative test - */ - public function testGetFilterNegativeApply() - { - $this->applierMock->expects($this->never()) - ->method('apply') - ->willReturn(true); - - $this->appliersPoolMock->expects($this->once()) - ->method('getApplier') - ->willReturn($this->applierMock); - - $mapper = new FilterMapper($this->appliersPoolMock, $this->braintreeSearchAdapterMock); - $result = $mapper->getFilter('orderId', []); - $this->assertNull($result); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionMapTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionMapTest.php deleted file mode 100644 index 8361eecaa2775..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionMapTest.php +++ /dev/null @@ -1,158 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\Report; - -use Braintree\Transaction; -use Braintree\Transaction\PayPalDetails; -use Magento\Braintree\Model\Report\Row\TransactionMap; -use Magento\Framework\Api\AttributeValue; -use Magento\Framework\Api\AttributeValueFactory; -use Magento\Framework\Phrase; -use Magento\Framework\Phrase\RendererInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Test for class \Magento\Braintree\Model\Report\\Row\TransactionMap - */ -class TransactionMapTest extends TestCase -{ - /** - * @var Transaction|MockObject - */ - private $transactionStub; - - /** - * @var AttributeValueFactory|MockObject - */ - private $attributeValueFactoryMock; - - /** - * @var RendererInterface|MockObject - */ - private $defaultRenderer; - - /** - * @var RendererInterface|MockObject - */ - private $rendererMock; - - /** - * Setup - */ - protected function setUp(): void - { - $this->attributeValueFactoryMock = $this->getMockBuilder(AttributeValueFactory::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMock(); - $this->defaultRenderer = Phrase::getRenderer(); - $this->rendererMock = $this->getMockBuilder(RendererInterface::class) - ->getMock(); - } - - /** - * Get items - * - * @param array $transaction - * @dataProvider getConfigDataProvider - */ - public function testGetCustomAttributes($transaction) - { - $this->transactionStub = Transaction::factory($transaction); - - $fields = TransactionMap::$simpleFieldsMap; - $fieldsQty = count($fields); - - $this->attributeValueFactoryMock->expects($this->exactly($fieldsQty)) - ->method('create') - ->willReturnCallback(function () { - return new AttributeValue(); - }); - - $map = new TransactionMap( - $this->attributeValueFactoryMock, - $this->transactionStub - ); - - Phrase::setRenderer($this->rendererMock); - - /** @var AttributeValue[] $result */ - $result = $map->getCustomAttributes(); - - $this->assertCount($fieldsQty, $result); - $this->assertInstanceOf(AttributeValue::class, $result[1]); - $this->assertEquals($transaction['id'], $result[0]->getValue()); - $this->assertEquals($transaction['paypalDetails']->paymentId, $result[4]->getValue()); - $this->assertEquals( - $transaction['createdAt']->format(\Magento\Framework\Stdlib\DateTime::DATETIME_PHP_FORMAT), - $result[6]->getValue() - ); - $this->assertEquals(implode(', ', $transaction['refundIds']), $result[11]->getValue()); - $this->assertEquals($transaction['merchantAccountId'], $result[1]->getValue()); - $this->assertEquals($transaction['orderId'], $result[2]->getValue()); - $this->assertEquals($transaction['amount'], $result[7]->getValue()); - $this->assertEquals($transaction['processorSettlementResponseCode'], $result[8]->getValue()); - $this->assertEquals($transaction['processorSettlementResponseText'], $result[10]->getValue()); - $this->assertEquals($transaction['settlementBatchId'], $result[12]->getValue()); - $this->assertEquals($transaction['currencyIsoCode'], $result[13]->getValue()); - - $this->rendererMock->expects($this->at(0)) - ->method('render') - ->with([$transaction['paymentInstrumentType']]) - ->willReturn('Credit card'); - $this->assertEquals('Credit card', $result[3]->getValue()->render()); - - $this->rendererMock->expects($this->at(0)) - ->method('render') - ->with([$transaction['type']]) - ->willReturn('Sale'); - $this->assertEquals('Sale', $result[5]->getValue()->render()); - - $this->rendererMock->expects($this->at(0)) - ->method('render') - ->with([$transaction['status']]) - ->willReturn('Pending for settlement'); - $this->assertEquals('Pending for settlement', $result[9]->getValue()->render()); - } - - /** - * @return array - */ - public function getConfigDataProvider() - { - return [ - [ - 'transaction' => [ - 'id' => 1, - 'createdAt' => new \DateTime(), - 'paypalDetails' => new PayPalDetails(['paymentId' => 10]), - 'refundIds' => [1, 2, 3, 4, 5], - 'merchantAccountId' => 'MerchantId', - 'orderId' => 1, - 'paymentInstrumentType' => 'credit_card', - 'type' => 'sale', - 'amount' => '$19.99', - 'processorSettlementResponseCode' => 1, - 'status' => 'pending_for_settlement', - 'processorSettlementResponseText' => 'sample text', - 'settlementBatchId' => 2, - 'currencyIsoCode' => 'USD' - ] - ] - ]; - } - - /** - * @return void - */ - protected function tearDown(): void - { - Phrase::setRenderer($this->defaultRenderer); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionsCollectionTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionsCollectionTest.php deleted file mode 100644 index 5bd25d5851c12..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/Report/TransactionsCollectionTest.php +++ /dev/null @@ -1,237 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\Report; - -use Magento\Braintree\Model\Adapter\BraintreeAdapter; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Braintree\Model\Report\FilterMapper; -use Magento\Braintree\Model\Report\TransactionsCollection; -use Magento\Framework\Api\Search\DocumentInterface; -use Magento\Framework\Data\Collection\EntityFactoryInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Test for class \Magento\Braintree\Model\Report\TransactionsCollection - */ -class TransactionsCollectionTest extends TestCase -{ - /** - * @var BraintreeAdapter|MockObject - */ - private $braintreeAdapterMock; - - /** - * @var BraintreeAdapterFactory|MockObject - */ - private $adapterFactoryMock; - - /** - * @var EntityFactoryInterface|MockObject - */ - private $entityFactoryMock; - - /** - * @var FilterMapper|MockObject - */ - private $filterMapperMock; - - /** - * @var DocumentInterface|MockObject - */ - private $transactionMapMock; - - /** - * Setup - */ - protected function setUp(): void - { - $this->transactionMapMock = $this->getMockBuilder(DocumentInterface::class) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - - $this->entityFactoryMock = $this->getMockBuilder(EntityFactoryInterface::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - - $this->filterMapperMock = $this->getMockBuilder(FilterMapper::class) - ->setMethods(['getFilter']) - ->disableOriginalConstructor() - ->getMock(); - - $this->braintreeAdapterMock = $this->getMockBuilder(BraintreeAdapter::class) - ->setMethods(['search']) - ->disableOriginalConstructor() - ->getMock(); - $this->adapterFactoryMock = $this->getMockBuilder(BraintreeAdapterFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->adapterFactoryMock->method('create') - ->willReturn($this->braintreeAdapterMock); - } - - /** - * Get items - */ - public function testGetItems() - { - $this->filterMapperMock->expects($this->once()) - ->method('getFilter') - ->willReturn(new BraintreeSearchNodeStub()); - - $this->braintreeAdapterMock->expects($this->once()) - ->method('search') - ->willReturn(['transaction1', 'transaction2']); - - $this->entityFactoryMock->expects($this->exactly(2)) - ->method('create') - ->willReturn($this->transactionMapMock); - - $collection = new TransactionsCollection( - $this->entityFactoryMock, - $this->adapterFactoryMock, - $this->filterMapperMock - ); - - $collection->addFieldToFilter('orderId', ['like' => '0']); - $items = $collection->getItems(); - $this->assertCount(2, $items); - $this->assertInstanceOf(DocumentInterface::class, $items[1]); - } - - /** - * Get empty result - */ - public function testGetItemsEmptyCollection() - { - $this->filterMapperMock->expects($this->once()) - ->method('getFilter') - ->willReturn(new BraintreeSearchNodeStub()); - - $this->braintreeAdapterMock->expects($this->once()) - ->method('search') - ->willReturn(null); - - $this->entityFactoryMock->expects($this->never()) - ->method('create') - ->willReturn($this->transactionMapMock); - - $collection = new TransactionsCollection( - $this->entityFactoryMock, - $this->adapterFactoryMock, - $this->filterMapperMock - ); - - $collection->addFieldToFilter('orderId', ['like' => '0']); - $items = $collection->getItems(); - $this->assertCount(0, $items); - } - - /** - * Get items with limit - */ - public function testGetItemsWithLimit() - { - $transactions = range(1, TransactionsCollection::TRANSACTION_MAXIMUM_COUNT + 10); - - $this->filterMapperMock->expects($this->once()) - ->method('getFilter') - ->willReturn(new BraintreeSearchNodeStub()); - - $this->braintreeAdapterMock->expects($this->once()) - ->method('search') - ->willReturn($transactions); - - $this->entityFactoryMock->expects($this->exactly(TransactionsCollection::TRANSACTION_MAXIMUM_COUNT)) - ->method('create') - ->willReturn($this->transactionMapMock); - - $collection = new TransactionsCollection( - $this->entityFactoryMock, - $this->adapterFactoryMock, - $this->filterMapperMock - ); - $collection->setPageSize(TransactionsCollection::TRANSACTION_MAXIMUM_COUNT); - - $collection->addFieldToFilter('orderId', ['like' => '0']); - $items = $collection->getItems(); - $this->assertCount(TransactionsCollection::TRANSACTION_MAXIMUM_COUNT, $items); - $this->assertInstanceOf(DocumentInterface::class, $items[1]); - } - - /** - * Get items with limit - */ - public function testGetItemsWithNullLimit() - { - $transactions = range(1, TransactionsCollection::TRANSACTION_MAXIMUM_COUNT + 10); - - $this->filterMapperMock->expects($this->once()) - ->method('getFilter') - ->willReturn(new BraintreeSearchNodeStub()); - - $this->braintreeAdapterMock->expects($this->once()) - ->method('search') - ->willReturn($transactions); - - $this->entityFactoryMock->expects($this->exactly(TransactionsCollection::TRANSACTION_MAXIMUM_COUNT)) - ->method('create') - ->willReturn($this->transactionMapMock); - - $collection = new TransactionsCollection( - $this->entityFactoryMock, - $this->adapterFactoryMock, - $this->filterMapperMock - ); - $collection->setPageSize(null); - - $collection->addFieldToFilter('orderId', ['like' => '0']); - $items = $collection->getItems(); - $this->assertCount(TransactionsCollection::TRANSACTION_MAXIMUM_COUNT, $items); - $this->assertInstanceOf(DocumentInterface::class, $items[1]); - } - - /** - * Add fields to filter - * - * @dataProvider addToFilterDataProvider - */ - public function testAddToFilter($field, $condition, $filterMapperCall, $expectedCondition) - { - $this->filterMapperMock->expects(static::exactly($filterMapperCall)) - ->method('getFilter') - ->with($field, $expectedCondition) - ->willReturn(new BraintreeSearchNodeStub()); - - $collection = new TransactionsCollection( - $this->entityFactoryMock, - $this->adapterFactoryMock, - $this->filterMapperMock - ); - - static::assertInstanceOf( - TransactionsCollection::class, - $collection->addFieldToFilter($field, $condition) - ); - } - - /** - * addToFilter DataProvider - * - * @return array - */ - public function addToFilterDataProvider() - { - return [ - ['orderId', ['like' => 1], 1, ['like' => 1]], - ['type', 'sale', 1, ['eq' => 'sale']], - [['type', 'orderId'], [], 0, []], - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php deleted file mode 100644 index ca98c3b27c0f5..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php +++ /dev/null @@ -1,117 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\Ui\Adminhtml\PayPal; - -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Model\Ui\Adminhtml\PayPal\TokenUiComponentProvider; -use Magento\Framework\UrlInterface; -use Magento\Vault\Api\Data\PaymentTokenInterface; -use Magento\Vault\Model\Ui\TokenUiComponentInterface; -use Magento\Vault\Model\Ui\TokenUiComponentInterfaceFactory; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Contains methods to test PayPal token Ui component provider - */ -class TokenUiComponentProviderTest extends TestCase -{ - /** - * @var TokenUiComponentInterfaceFactory|MockObject - */ - private $componentFactory; - - /** - * @var UrlInterface|MockObject - */ - private $urlBuilder; - - /** - * @var Config|MockObject - */ - private $config; - - /** - * @var TokenUiComponentProvider - */ - private $tokenUiComponentProvider; - - protected function setUp(): void - { - $this->componentFactory = $this->getMockBuilder(TokenUiComponentInterfaceFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); - - $this->config = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->setMethods(['getPayPalIcon']) - ->getMock(); - - $this->tokenUiComponentProvider = new TokenUiComponentProvider( - $this->componentFactory, - $this->urlBuilder, - $this->config - ); - } - - /** - * @covers \Magento\Braintree\Model\Ui\Adminhtml\PayPal\TokenUiComponentProvider::getComponentForToken - */ - public function testGetComponentForToken() - { - $nonceUrl = 'https://payment/adminhtml/nonce/url'; - $payerEmail = 'john.doe@test.com'; - $icon = [ - 'url' => 'https://payment/adminhtml/icon.png', - 'width' => 48, - 'height' => 32 - ]; - - $expected = [ - 'code' => 'vault', - 'nonceUrl' => $nonceUrl, - 'details' => [ - 'payerEmail' => $payerEmail, - 'icon' => $icon - ], - 'template' => 'vault.phtml' - ]; - - $this->config->expects(static::once()) - ->method('getPayPalIcon') - ->willReturn($icon); - - $paymentToken = $this->getMockForAbstractClass(PaymentTokenInterface::class); - $paymentToken->expects(static::once()) - ->method('getTokenDetails') - ->willReturn('{"payerEmail":" ' . $payerEmail . '"}'); - $paymentToken->expects(static::once()) - ->method('getPublicHash') - ->willReturn('cmk32dl21l'); - - $this->urlBuilder->expects(static::once()) - ->method('getUrl') - ->willReturn($nonceUrl); - - $tokenComponent = $this->getMockForAbstractClass(TokenUiComponentInterface::class); - $tokenComponent->expects(static::once()) - ->method('getConfig') - ->willReturn($expected); - - $this->componentFactory->expects(static::once()) - ->method('create') - ->willReturn($tokenComponent); - - $component = $this->tokenUiComponentProvider->getComponentForToken($paymentToken); - static::assertEquals($tokenComponent, $component); - static::assertEquals($expected, $component->getConfig()); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/TokenUiComponentProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/TokenUiComponentProviderTest.php deleted file mode 100644 index 288115e219591..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/Ui/Adminhtml/TokenUiComponentProviderTest.php +++ /dev/null @@ -1,97 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\Ui\Adminhtml; - -use Magento\Braintree\Model\Ui\Adminhtml\TokenUiComponentProvider; -use Magento\Framework\UrlInterface; -use Magento\Vault\Api\Data\PaymentTokenInterface; -use Magento\Vault\Model\Ui\TokenUiComponentInterface; -use Magento\Vault\Model\Ui\TokenUiComponentInterfaceFactory; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class TokenUiComponentProviderTest extends TestCase -{ - - /** - * @var TokenUiComponentInterfaceFactory|MockObject - */ - private $componentFactory; - - /** - * @var UrlInterface|MockObject - */ - private $urlBuilder; - - /** - * @var TokenUiComponentProvider - */ - private $tokenUiComponentProvider; - - protected function setUp(): void - { - $this->componentFactory = $this->getMockBuilder(TokenUiComponentInterfaceFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); - - $this->tokenUiComponentProvider = new TokenUiComponentProvider( - $this->componentFactory, - $this->urlBuilder - ); - } - - /** - * @covers \Magento\Braintree\Model\Ui\Adminhtml\TokenUiComponentProvider::getComponentForToken - */ - public function testGetComponentForToken() - { - $nonceUrl = 'https://payment/adminhtml/nonce/url'; - $type = 'VI'; - $maskedCC = '1111'; - $expirationDate = '12/2015'; - - $expected = [ - 'code' => 'vault', - 'nonceUrl' => $nonceUrl, - 'details' => [ - 'type' => $type, - 'maskedCC' => $maskedCC, - 'expirationDate' => $expirationDate - ], - 'template' => 'vault.phtml' - ]; - - $paymentToken = $this->getMockForAbstractClass(PaymentTokenInterface::class); - $paymentToken->expects(static::once()) - ->method('getTokenDetails') - ->willReturn('{"type":"VI","maskedCC":"1111","expirationDate":"12\/2015"}'); - $paymentToken->expects(static::once()) - ->method('getPublicHash') - ->willReturn('37du7ir5ed'); - - $this->urlBuilder->expects(static::once()) - ->method('getUrl') - ->willReturn($nonceUrl); - - $tokenComponent = $this->getMockForAbstractClass(TokenUiComponentInterface::class); - $tokenComponent->expects(static::once()) - ->method('getConfig') - ->willReturn($expected); - - $this->componentFactory->expects(static::once()) - ->method('create') - ->willReturn($tokenComponent); - - $component = $this->tokenUiComponentProvider->getComponentForToken($paymentToken); - static::assertEquals($tokenComponent, $component); - static::assertEquals($expected, $component->getConfig()); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Ui/ConfigProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Ui/ConfigProviderTest.php deleted file mode 100644 index 95d235d36e3a5..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/Ui/ConfigProviderTest.php +++ /dev/null @@ -1,216 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\Ui; - -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Model\Adapter\BraintreeAdapter; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Customer\Model\Session; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Test for class \Magento\Braintree\Model\Ui\ConfigProvider - */ -class ConfigProviderTest extends TestCase -{ - const SDK_URL = 'https://js.braintreegateway.com/v2/braintree.js'; - const CLIENT_TOKEN = 'token'; - const MERCHANT_ACCOUNT_ID = '245345'; - - /** - * @var Config|MockObject - */ - private $config; - - /** - * @var BraintreeAdapter|MockObject - */ - private $braintreeAdapter; - - /** - * @var Session|MockObject - */ - private $session; - - /** - * @var ConfigProvider - */ - private $configProvider; - - protected function setUp(): void - { - $this->config = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->braintreeAdapter = $this->getMockBuilder(BraintreeAdapter::class) - ->disableOriginalConstructor() - ->getMock(); - /** @var BraintreeAdapterFactory|MockObject $adapterFactoryMock */ - $adapterFactoryMock = $this->getMockBuilder(BraintreeAdapterFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $adapterFactoryMock->method('create') - ->willReturn($this->braintreeAdapter); - - $this->session = $this->getMockBuilder(Session::class) - ->disableOriginalConstructor() - ->setMethods(['getStoreId']) - ->getMock(); - $this->session->method('getStoreId') - ->willReturn(null); - - $this->configProvider = new ConfigProvider( - $this->config, - $adapterFactoryMock, - $this->session - ); - } - - /** - * Ensure that get config returns correct data if payment is active or not - * - * @param array $config - * @param array $expected - * @dataProvider getConfigDataProvider - */ - public function testGetConfig($config, $expected) - { - if ($config['isActive']) { - $this->braintreeAdapter->expects($this->once()) - ->method('generate') - ->willReturn(self::CLIENT_TOKEN); - } else { - $config = array_replace_recursive( - $this->getConfigDataProvider()[0]['config'], - $config - ); - $expected = array_replace_recursive( - $this->getConfigDataProvider()[0]['expected'], - $expected - ); - $this->braintreeAdapter->expects($this->never()) - ->method('generate'); - } - - foreach ($config as $method => $value) { - $this->config->expects($this->once()) - ->method($method) - ->willReturn($value); - } - - $this->assertEquals($expected, $this->configProvider->getConfig()); - } - - /** - * @covers \Magento\Braintree\Model\Ui\ConfigProvider::getClientToken - * @dataProvider getClientTokenDataProvider - * @param $merchantAccountId - * @param $params - */ - public function testGetClientToken($merchantAccountId, $params) - { - $this->config->expects(static::once()) - ->method('getMerchantAccountId') - ->willReturn($merchantAccountId); - - $this->braintreeAdapter->expects(static::once()) - ->method('generate') - ->with($params) - ->willReturn(self::CLIENT_TOKEN); - - static::assertEquals(self::CLIENT_TOKEN, $this->configProvider->getClientToken()); - } - - /** - * @return array - */ - public function getConfigDataProvider() - { - return [ - [ - 'config' => [ - 'isActive' => true, - 'getCcTypesMapper' => ['visa' => 'VI', 'american-express' => 'AE'], - 'getSdkUrl' => self::SDK_URL, - 'getHostedFieldsSdkUrl' => 'https://sdk.com/test.js', - 'getCountrySpecificCardTypeConfig' => [ - 'GB' => ['VI', 'AE'], - 'US' => ['DI', 'JCB'] - ], - 'getAvailableCardTypes' => ['AE', 'VI', 'MC', 'DI', 'JCB'], - 'isCvvEnabled' => true, - 'isVerify3DSecure' => true, - 'getThresholdAmount' => 20, - 'get3DSecureSpecificCountries' => ['GB', 'US', 'CA'], - 'getEnvironment' => 'test-environment', - 'getMerchantId' => 'test-merchant-id', - 'hasFraudProtection' => true, - ], - 'expected' => [ - 'payment' => [ - ConfigProvider::CODE => [ - 'isActive' => true, - 'clientToken' => self::CLIENT_TOKEN, - 'ccTypesMapper' => ['visa' => 'VI', 'american-express' => 'AE'], - 'sdkUrl' => self::SDK_URL, - 'hostedFieldsSdkUrl' => 'https://sdk.com/test.js', - 'countrySpecificCardTypes' => [ - 'GB' => ['VI', 'AE'], - 'US' => ['DI', 'JCB'] - ], - 'availableCardTypes' => ['AE', 'VI', 'MC', 'DI', 'JCB'], - 'useCvv' => true, - 'environment' => 'test-environment', - 'merchantId' => 'test-merchant-id', - 'hasFraudProtection' => true, - 'ccVaultCode' => ConfigProvider::CC_VAULT_CODE - ], - Config::CODE_3DSECURE => [ - 'enabled' => true, - 'thresholdAmount' => 20, - 'specificCountries' => ['GB', 'US', 'CA'] - ] - ] - ] - ], - [ - 'config' => [ - 'isActive' => false, - ], - 'expected' => [ - 'payment' => [ - ConfigProvider::CODE => [ - 'isActive' => false, - 'clientToken' => null, - ] - ] - ] - ] - ]; - } - - /** - * @return array - */ - public function getClientTokenDataProvider() - { - return [ - [ - 'merchantAccountId' => '', - 'params' => [] - ], - [ - 'merchantAccountId' => self::MERCHANT_ACCOUNT_ID, - 'params' => ['merchantAccountId' => self::MERCHANT_ACCOUNT_ID] - ] - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/ConfigProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/ConfigProviderTest.php deleted file mode 100644 index 0c290c5d31523..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/ConfigProviderTest.php +++ /dev/null @@ -1,111 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\Ui\PayPal; - -use Magento\Braintree\Gateway\Config\PayPal\Config; -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider; -use Magento\Framework\Locale\ResolverInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Test for class \Magento\Braintree\Model\Ui\PayPal\ConfigProvider - */ -class ConfigProviderTest extends TestCase -{ - private const STUB_IMAGE_SRC = 'https://www.paypalobjects.com/webstatic/en_US/i/buttons/pp-acceptance-medium.png'; - - /** @var Config|MockObject */ - private $config; - - /** @var ResolverInterface|MockObject */ - private $localeResolver; - - /** @var ConfigProvider */ - private $configProvider; - - protected function setUp(): void - { - $this->config = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->localeResolver = $this->getMockForAbstractClass(ResolverInterface::class); - - $this->configProvider = new ConfigProvider( - $this->config, - $this->localeResolver - ); - } - - /** - * Run test getConfig method - * - * @param array $expected - * @dataProvider getConfigDataProvider - */ - public function testGetConfig($expected) - { - $this->config->method('isActive') - ->willReturn(true); - - $this->config->method('isAllowToEditShippingAddress') - ->willReturn(true); - - $this->config->method('getMerchantName') - ->willReturn('Test'); - - $this->config->method('getTitle') - ->willReturn('Payment Title'); - - $this->localeResolver->method('getLocale') - ->willReturn('en_US'); - - $this->config->method('isSkipOrderReview') - ->willReturn(false); - - $this->config->method('getPayPalIcon') - ->willReturn([ - 'width' => 30, 'height' => 26, 'url' => 'https://icon.test.url' - ]); - - $this->config->method('isRequiredBillingAddress') - ->willReturn(1); - - self::assertEquals($expected, $this->configProvider->getConfig()); - } - - /** - * @return array - */ - public function getConfigDataProvider() - { - return [ - [ - 'expected' => [ - 'payment' => [ - ConfigProvider::PAYPAL_CODE => [ - 'isActive' => true, - 'title' => 'Payment Title', - 'isAllowShippingAddressOverride' => true, - 'merchantName' => 'Test', - 'locale' => 'en_US', - 'paymentAcceptanceMarkSrc' => self::STUB_IMAGE_SRC, - 'vaultCode' => ConfigProvider::PAYPAL_VAULT_CODE, - 'skipOrderReview' => false, - 'paymentIcon' => [ - 'width' => 30, 'height' => 26, 'url' => 'https://icon.test.url' - ], - 'isRequiredBillingAddress' => true - ] - ] - ] - ] - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/TokenUiComponentProviderTest.php b/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/TokenUiComponentProviderTest.php deleted file mode 100644 index d637c3cbac27c..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Model/Ui/PayPal/TokenUiComponentProviderTest.php +++ /dev/null @@ -1,92 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Model\Ui\PayPal; - -use Magento\Braintree\Model\Ui\PayPal\TokenUiComponentProvider; -use Magento\Framework\UrlInterface; -use Magento\Vault\Api\Data\PaymentTokenInterface; -use Magento\Vault\Model\Ui\TokenUiComponentInterface; -use Magento\Vault\Model\Ui\TokenUiComponentInterfaceFactory; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class TokenUiComponentProviderTest extends TestCase -{ - /** - * @var UrlInterface|MockObject - */ - private $urlBuilder; - - /** - * @var PaymentTokenInterface|MockObject - */ - private $paymentToken; - - /** - * @var TokenUiComponentInterface|MockObject - */ - private $tokenComponent; - - /** - * @var TokenUiComponentInterfaceFactory|MockObject - */ - private $componentFactory; - - /** - * @var TokenUiComponentProvider - */ - private $componentProvider; - - protected function setUp(): void - { - $this->componentFactory = $this->getMockBuilder(TokenUiComponentInterfaceFactory::class) - ->disableOriginalConstructor() - ->setMethods(['create']) - ->getMock(); - - $this->tokenComponent = $this->getMockForAbstractClass(TokenUiComponentInterface::class); - - $this->urlBuilder = $this->getMockForAbstractClass(UrlInterface::class); - - $this->paymentToken = $this->getMockForAbstractClass(PaymentTokenInterface::class); - - $this->componentProvider = new TokenUiComponentProvider( - $this->componentFactory, - $this->urlBuilder - ); - } - - /** - * @covers \Magento\Braintree\Model\Ui\PayPal\TokenUiComponentProvider::getComponentForToken - */ - public function testGetComponentForToken() - { - $tokenDetails = [ - 'payerEmail' => 'john.doe@example.com' - ]; - $hash = '4g1mn4ew0vj23n2jf'; - - $this->paymentToken->expects(static::once()) - ->method('getTokenDetails') - ->willReturn(json_encode($tokenDetails)); - - $this->componentFactory->expects(static::once()) - ->method('create') - ->willReturn($this->tokenComponent); - - $this->paymentToken->expects(static::once()) - ->method('getPublicHash') - ->willReturn($hash); - - $this->urlBuilder->expects(static::once()) - ->method('getUrl'); - - $actual = $this->componentProvider->getComponentForToken($this->paymentToken); - static::assertEquals($this->tokenComponent, $actual); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Observer/AddPaypalShortcutsTest.php b/app/code/Magento/Braintree/Test/Unit/Observer/AddPaypalShortcutsTest.php deleted file mode 100644 index 3b577aed505ad..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Observer/AddPaypalShortcutsTest.php +++ /dev/null @@ -1,82 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Observer; - -use Magento\Braintree\Block\Paypal\Button; -use Magento\Braintree\Observer\AddPaypalShortcuts; -use Magento\Catalog\Block\ShortcutButtons; -use Magento\Framework\Event; -use Magento\Framework\Event\Observer; -use Magento\Framework\View\LayoutInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @see \Magento\Braintree\Observer\AddPaypalShortcuts - */ -class AddPaypalShortcutsTest extends TestCase -{ - /** - * Tests PayPal shortcuts observer. - */ - public function testExecute() - { - $addPaypalShortcuts = new AddPaypalShortcuts( - [ - 'mini_cart' => 'Minicart-block', - 'shopping_cart' => 'Shoppingcart-block' - ] - ); - - /** @var Observer|MockObject $observerMock */ - $observerMock = $this->getMockBuilder(Observer::class) - ->disableOriginalConstructor() - ->getMock(); - - /** @var Event|MockObject $eventMock */ - $eventMock = $this->getMockBuilder(Event::class) - ->setMethods(['getContainer']) - ->disableOriginalConstructor() - ->getMock(); - - /** @var ShortcutButtons|MockObject $shortcutButtonsMock */ - $shortcutButtonsMock = $this->getMockBuilder(ShortcutButtons::class) - ->disableOriginalConstructor() - ->getMock(); - - $layoutMock = $this->getMockBuilder(LayoutInterface::class) - ->getMockForAbstractClass(); - - $blockMock = $this->getMockBuilder(Button::class) - ->disableOriginalConstructor() - ->getMock(); - - $observerMock->expects(self::once()) - ->method('getEvent') - ->willReturn($eventMock); - - $eventMock->expects(self::once()) - ->method('getContainer') - ->willReturn($shortcutButtonsMock); - - $shortcutButtonsMock->expects(self::once()) - ->method('getLayout') - ->willReturn($layoutMock); - - $layoutMock->expects(self::once()) - ->method('createBlock') - ->with('Minicart-block') - ->willReturn($blockMock); - - $shortcutButtonsMock->expects(self::once()) - ->method('addShortcut') - ->with($blockMock); - - $addPaypalShortcuts->execute($observerMock); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Observer/DataAssignObserverTest.php b/app/code/Magento/Braintree/Test/Unit/Observer/DataAssignObserverTest.php deleted file mode 100644 index 848e7f35d488f..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Observer/DataAssignObserverTest.php +++ /dev/null @@ -1,62 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Observer; - -use Magento\Braintree\Observer\DataAssignObserver; -use Magento\Framework\DataObject; -use Magento\Framework\Event; -use Magento\Framework\Event\Observer; -use Magento\Payment\Model\InfoInterface; -use Magento\Payment\Observer\AbstractDataAssignObserver; -use Magento\Quote\Api\Data\PaymentInterface; -use PHPUnit\Framework\TestCase; - -class DataAssignObserverTest extends TestCase -{ - const PAYMENT_METHOD_NONCE = 'nonce'; - const DEVICE_DATA = '{"test": "test"}'; - - public function testExecute() - { - $observerContainer = $this->getMockBuilder(Observer::class) - ->disableOriginalConstructor() - ->getMock(); - $event = $this->getMockBuilder(Event::class) - ->disableOriginalConstructor() - ->getMock(); - $paymentInfoModel = $this->getMockForAbstractClass(InfoInterface::class); - $dataObject = new DataObject( - [ - PaymentInterface::KEY_ADDITIONAL_DATA => [ - 'payment_method_nonce' => self::PAYMENT_METHOD_NONCE, - 'device_data' => self::DEVICE_DATA - ] - ] - ); - $observerContainer->expects(static::atLeastOnce()) - ->method('getEvent') - ->willReturn($event); - $event->expects(static::exactly(2)) - ->method('getDataByKey') - ->willReturnMap( - [ - [AbstractDataAssignObserver::MODEL_CODE, $paymentInfoModel], - [AbstractDataAssignObserver::DATA_CODE, $dataObject] - ] - ); - $paymentInfoModel->expects(static::at(0)) - ->method('setAdditionalInformation') - ->with('payment_method_nonce', self::PAYMENT_METHOD_NONCE); - $paymentInfoModel->expects(static::at(1)) - ->method('setAdditionalInformation') - ->with('device_data', self::DEVICE_DATA); - - $observer = new DataAssignObserver(); - $observer->execute($observerContainer); - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Filters/Type/DateRangeTest.php b/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Filters/Type/DateRangeTest.php deleted file mode 100644 index cd49b1e373105..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Filters/Type/DateRangeTest.php +++ /dev/null @@ -1,260 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Ui\Component\Report\Filters\Type; - -use Magento\Braintree\Ui\Component\Report\Filters\Type\DateRange; -use Magento\Framework\Api\Filter; -use Magento\Framework\Api\FilterBuilder; -use Magento\Framework\View\Element\UiComponent\ContextInterface; -use Magento\Framework\View\Element\UiComponent\DataProvider\DataProviderInterface; -use Magento\Framework\View\Element\UiComponent\Processor; -use Magento\Framework\View\Element\UiComponentFactory; -use Magento\Ui\Component\Filters\FilterModifier; -use Magento\Ui\Component\Form\Element\DataType\Date as FormDate; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class DateRangeTest extends TestCase -{ - /** - * @var ContextInterface|MockObject - */ - private $contextMock; - - /** - * @var UiComponentFactory|MockObject - */ - private $uiComponentFactory; - - /** - * @var FilterBuilder|MockObject - */ - private $filterBuilderMock; - - /** - * @var FilterModifier|MockObject - */ - private $filterModifierMock; - - /** - * @var DataProviderInterface|MockObject - */ - private $dataProviderMock; - - /** - * Set up - */ - protected function setUp(): void - { - $this->contextMock = $this->getMockForAbstractClass(ContextInterface::class); - $processor = $this->getMockBuilder(Processor::class) - ->disableOriginalConstructor() - ->getMock(); - $this->contextMock->expects(static::atLeastOnce()) - ->method('getProcessor') - ->willReturn($processor); - $this->uiComponentFactory = $this->getMockBuilder(UiComponentFactory::class) - ->setMethods(['create']) - ->disableOriginalConstructor() - ->getMock(); - $this->filterBuilderMock = $this->getMockBuilder(FilterBuilder::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->filterModifierMock = $this->getMockBuilder(FilterModifier::class) - ->setMethods(['applyFilterModifier']) - ->disableOriginalConstructor() - ->getMock(); - - $this->contextMock->expects($this->any()) - ->method('getNamespace') - ->willReturn(DateRange::NAME); - $this->contextMock->expects($this->any()) - ->method('addComponentDefinition') - ->with(DateRange::NAME, ['extends' => DateRange::NAME]); - - $this->dataProviderMock = $this->getMockForAbstractClass(DataProviderInterface::class); - } - - /** - * Run test prepare method - * - * @param string $name - * @param array $filterData - * @param array|null $expectedCondition - * @dataProvider getPrepareDataProvider - * @return void - * @SuppressWarnings(PHPMD.CyclomaticComplexity) - */ - public function testPrepare($name, $filterData, $expectedCondition) - { - /** @var FormDate|MockObject $uiComponent */ - $uiComponent = $this->getMockBuilder(FormDate::class) - ->disableOriginalConstructor() - ->getMock(); - - $uiComponent->expects($this->any()) - ->method('getContext') - ->willReturn($this->contextMock); - - $this->contextMock->expects($this->any()) - ->method('getFiltersParams') - ->willReturn($filterData); - - $this->contextMock->expects($this->any()) - ->method('getDataProvider') - ->willReturn($this->dataProviderMock); - - if ($expectedCondition !== null) { - if (is_string($filterData[$name])) { - $uiComponent->expects(static::once()) - ->method('convertDate') - ->with($filterData[$name]) - ->willReturn(new \DateTime($filterData[$name], new \DateTimeZone('UTC'))); - } else { - $uiComponent->method('convertDate') - ->willReturnMap([ - [ - $filterData[$name]['from'], 0, 0, 0, true, - new \DateTime($filterData[$name]['from'] ?? 'now', new \DateTimeZone('UTC')) - ], - [ - $filterData[$name]['to'], - 23, - 59, - 59, - true, - new \DateTime( - $filterData[$name]['to'] ? $filterData[$name]['to'] . ' 23:59:00' : 'now', - new \DateTimeZone('UTC') - ) - ], - ]); - } - - $i=0; - switch (true) { - case is_string($filterData[$name]): - case isset($filterData[$name]['from']) && !isset($filterData[$name]['to']): - case !isset($filterData[$name]['from']) && isset($filterData[$name]['to']): - $filterMock = $this->getFilterMock( - $name, - $expectedCondition['type'], - $expectedCondition['date'], - $i - ); - $this->dataProviderMock->expects(static::once()) - ->method('addFilter') - ->with($filterMock); - break; - case isset($filterData[$name]['from']) && isset($filterData[$name]['to']): - $this->getFilterMock( - $name, - $expectedCondition['type_from'], - $expectedCondition['date_from'], - $i - ); - $filterMock = $this->getFilterMock( - $name, - $expectedCondition['type_to'], - $expectedCondition['date_to'], - $i - ); - $this->dataProviderMock->expects(static::exactly(2)) - ->method('addFilter') - ->with($filterMock); - break; - } - } - - $this->uiComponentFactory->expects($this->any()) - ->method('create') - ->with($name, DateRange::COMPONENT, ['context' => $this->contextMock]) - ->willReturn($uiComponent); - - $date = new DateRange( - $this->contextMock, - $this->uiComponentFactory, - $this->filterBuilderMock, - $this->filterModifierMock, - [], - ['name' => $name] - ); - $date->prepare(); - } - - /** - * Gets Filter mock - * - * @param string $name - * @param string $expectedType - * @param string $expectedDate - * @param int $i - * - * @return Filter|MockObject - */ - private function getFilterMock($name, $expectedType, $expectedDate, &$i) - { - $this->filterBuilderMock->expects(static::at($i++)) - ->method('setConditionType') - ->with($expectedType) - ->willReturnSelf(); - $this->filterBuilderMock->expects(static::at($i++)) - ->method('setField') - ->with($name) - ->willReturnSelf(); - $this->filterBuilderMock->expects(static::at($i++)) - ->method('setValue') - ->with($expectedDate) - ->willReturnSelf(); - - $filterMock = $this->createMock(Filter::class); - $this->filterBuilderMock->expects(static::at($i++)) - ->method('create') - ->willReturn($filterMock); - - return $filterMock; - } - - /** - * @return array - */ - public function getPrepareDataProvider() - { - return [ - [ - 'test_date', - ['test_date' => ['from' => '11-05-2015', 'to' => null]], - ['date' => '2015-05-11T00:00:00+0000', 'type' => 'gteq'], - ], - [ - 'test_date', - ['test_date' => ['from' => null, 'to' => '11-05-2015']], - ['date' => '2015-05-11T23:59:00+0000', 'type' => 'lteq'], - ], - [ - 'test_date', - ['test_date' => ['from' => '11-05-2015', 'to' => '11-05-2015']], - [ - 'date_from' => '2015-05-11T00:00:00+0000', 'type_from' => 'gteq', - 'date_to' => '2015-05-11T23:59:00+0000', 'type_to' => 'lteq' - ], - ], - [ - 'test_date', - ['test_date' => '11-05-2015'], - ['date' => '2015-05-11T00:00:00+0000', 'type' => 'eq'], - ], - [ - 'test_date', - ['test_date' => ['from' => '', 'to' => '']], - null, - ] - ]; - } -} diff --git a/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Listing/Column/CheckColumnOptionSourceTest.php b/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Listing/Column/CheckColumnOptionSourceTest.php deleted file mode 100644 index fe6e5e9802db1..0000000000000 --- a/app/code/Magento/Braintree/Test/Unit/Ui/Component/Report/Listing/Column/CheckColumnOptionSourceTest.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Test\Unit\Ui\Component\Report\Listing\Column; - -use Magento\Braintree\Ui\Component\Report\Listing\Column\PaymentType; -use Magento\Braintree\Ui\Component\Report\Listing\Column\Status; -use Magento\Braintree\Ui\Component\Report\Listing\Column\TransactionType; -use PHPUnit\Framework\TestCase; - -class CheckColumnOptionSourceTest extends TestCase -{ - public function testPaymentTypeSource() - { - $source = new PaymentType(); - $options = $source->toOptionArray(); - - static::assertCount(6, $options); - } - - public function testStatusSource() - { - $source = new Status(); - $options = $source->toOptionArray(); - - static::assertCount(14, $options); - } - - public function testTransactionTypeSource() - { - $source = new TransactionType(); - $options = $source->toOptionArray(); - - static::assertCount(2, $options); - } -} diff --git a/app/code/Magento/Braintree/Ui/Component/Report/Filters/Type/DateRange.php b/app/code/Magento/Braintree/Ui/Component/Report/Filters/Type/DateRange.php deleted file mode 100644 index 9ec154a7c6ed2..0000000000000 --- a/app/code/Magento/Braintree/Ui/Component/Report/Filters/Type/DateRange.php +++ /dev/null @@ -1,19 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Ui\Component\Report\Filters\Type; - -/** - * Class DateRange - */ -class DateRange extends \Magento\Ui\Component\Filters\Type\Date -{ - /** - * Braintree date format - * - * @var string - */ - protected static $dateFormat = 'Y-m-d\TH:i:00O'; -} diff --git a/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/PaymentType.php b/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/PaymentType.php deleted file mode 100644 index 4621dbc79fb6f..0000000000000 --- a/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/PaymentType.php +++ /dev/null @@ -1,57 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Ui\Component\Report\Listing\Column; - -use Braintree\PaymentInstrumentType; -use Magento\Framework\Data\OptionSourceInterface; - -/** - * Class PaymentType - */ -class PaymentType implements OptionSourceInterface -{ - /** - * @var array - */ - protected $options; - - /** - * Get options - * - * @return array - */ - public function toOptionArray() - { - if ($this->options !== null) { - return $this->options; - } - - $types = $this->getAvailablePaymentTypes(); - foreach ($types as $typeCode => $typeName) { - $this->options[$typeCode]['label'] = $typeName; - $this->options[$typeCode]['value'] = $typeCode; - } - - return $this->options; - } - - /** - * @return array - */ - private function getAvailablePaymentTypes() - { - // @codingStandardsIgnoreStart - return [ - PaymentInstrumentType::PAYPAL_ACCOUNT => __(PaymentInstrumentType::PAYPAL_ACCOUNT), - PaymentInstrumentType::COINBASE_ACCOUNT => __(PaymentInstrumentType::COINBASE_ACCOUNT), - PaymentInstrumentType::EUROPE_BANK_ACCOUNT => __(PaymentInstrumentType::EUROPE_BANK_ACCOUNT), - PaymentInstrumentType::CREDIT_CARD => __(PaymentInstrumentType::CREDIT_CARD), - PaymentInstrumentType::APPLE_PAY_CARD => __(PaymentInstrumentType::APPLE_PAY_CARD), - PaymentInstrumentType::ANDROID_PAY_CARD => __(PaymentInstrumentType::ANDROID_PAY_CARD) - ]; - // @codingStandardsIgnoreEnd - } -} diff --git a/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/Status.php b/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/Status.php deleted file mode 100644 index bf5187ddd319c..0000000000000 --- a/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/Status.php +++ /dev/null @@ -1,65 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Ui\Component\Report\Listing\Column; - -use Braintree\Transaction; -use Magento\Framework\Data\OptionSourceInterface; - -/** - * Class Status - */ -class Status implements OptionSourceInterface -{ - /** - * @var array - */ - protected $options; - - /** - * Get options - * - * @return array - */ - public function toOptionArray() - { - if ($this->options !== null) { - return $this->options; - } - - $statuses = $this->getAvailableStatuses(); - foreach ($statuses as $statusCode => $statusName) { - $this->options[$statusCode]['label'] = $statusName; - $this->options[$statusCode]['value'] = $statusCode; - } - - return $this->options; - } - - /** - * @return array - */ - private function getAvailableStatuses() - { - // @codingStandardsIgnoreStart - return [ - Transaction::AUTHORIZATION_EXPIRED => __(Transaction::AUTHORIZATION_EXPIRED), - Transaction::AUTHORIZING => __(Transaction::AUTHORIZING), - Transaction::AUTHORIZED => __(Transaction::AUTHORIZED), - Transaction::GATEWAY_REJECTED => __(Transaction::GATEWAY_REJECTED), - Transaction::FAILED => __(Transaction::FAILED), - Transaction::PROCESSOR_DECLINED => __(Transaction::PROCESSOR_DECLINED), - Transaction::SETTLED => __(Transaction::SETTLED), - Transaction::SETTLING => __(Transaction::SETTLING), - Transaction::SUBMITTED_FOR_SETTLEMENT => __(Transaction::SUBMITTED_FOR_SETTLEMENT), - Transaction::VOIDED => __(Transaction::VOIDED), - Transaction::UNRECOGNIZED => __(Transaction::UNRECOGNIZED), - Transaction::SETTLEMENT_DECLINED => __(Transaction::SETTLEMENT_DECLINED), - Transaction::SETTLEMENT_PENDING => __(Transaction::SETTLEMENT_PENDING), - Transaction::SETTLEMENT_CONFIRMED => __(Transaction::SETTLEMENT_CONFIRMED) - ]; - // @codingStandardsIgnoreEnd - } -} diff --git a/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/TransactionType.php b/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/TransactionType.php deleted file mode 100644 index 5b4d0ce794ef0..0000000000000 --- a/app/code/Magento/Braintree/Ui/Component/Report/Listing/Column/TransactionType.php +++ /dev/null @@ -1,53 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Ui\Component\Report\Listing\Column; - -use Braintree\Transaction; -use Magento\Framework\Data\OptionSourceInterface; - -/** - * Class Type - */ -class TransactionType implements OptionSourceInterface -{ - /** - * @var array - */ - protected $options; - - /** - * Get options - * - * @return array - */ - public function toOptionArray() - { - if ($this->options !== null) { - return $this->options; - } - - $types = $this->getAvailableTransactionTypes(); - foreach ($types as $typeCode => $typeName) { - $this->options[$typeCode]['label'] = $typeName; - $this->options[$typeCode]['value'] = $typeCode; - } - - return $this->options; - } - - /** - * @return array - */ - private function getAvailableTransactionTypes() - { - // @codingStandardsIgnoreStart - return [ - Transaction::SALE => __(Transaction::SALE), - Transaction::CREDIT => __(Transaction::CREDIT) - ]; - // @codingStandardsIgnoreEnd - } -} diff --git a/app/code/Magento/Braintree/composer.json b/app/code/Magento/Braintree/composer.json deleted file mode 100644 index 7627959c5d330..0000000000000 --- a/app/code/Magento/Braintree/composer.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "magento/module-braintree", - "description": "N/A", - "config": { - "sort-packages": true - }, - "require": { - "php": "~7.3.0||~7.4.0", - "braintree/braintree_php": "3.35.0", - "magento/framework": "*", - "magento/magento-composer-installer": "*", - "magento/module-catalog": "*", - "magento/module-backend": "*", - "magento/module-checkout": "*", - "magento/module-config": "*", - "magento/module-customer": "*", - "magento/module-directory": "*", - "magento/module-instant-purchase": "*", - "magento/module-payment": "*", - "magento/module-paypal": "*", - "magento/module-quote": "*", - "magento/module-sales": "*", - "magento/module-ui": "*", - "magento/module-vault": "*", - "magento/module-multishipping": "*", - "magento/module-theme": "*" - }, - "suggest": { - "magento/module-checkout-agreements": "*" - }, - "type": "magento2-module", - "license": [ - "OSL-3.0", - "AFL-3.0" - ], - "autoload": { - "files": [ - "registration.php" - ], - "psr-4": { - "Magento\\Braintree\\": "" - } - } -} diff --git a/app/code/Magento/Braintree/etc/acl.xml b/app/code/Magento/Braintree/etc/acl.xml deleted file mode 100644 index 066ccc818d4e6..0000000000000 --- a/app/code/Magento/Braintree/etc/acl.xml +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd"> - <acl> - <resources> - <resource id="Magento_Backend::admin"> - <resource id="Magento_Reports::report"> - <resource id="Magento_Reports::salesroot"> - <resource id="Magento_Braintree::settlement_report" title="Braintree Settlement" translate="title" sortOrder="80" /> - </resource> - </resource> - <resource id="Magento_Sales::sales"> - <resource id="Magento_Sales::sales_operation"> - <resource id="Magento_Sales::sales_order"> - <resource id="Magento_Sales::actions"> - <resource id="Magento_Braintree::get_client_token" title="Get Client Token Braintree" sortOrder="170" /> - </resource> - </resource> - </resource> - </resource> - </resource> - </resources> - </acl> -</config> diff --git a/app/code/Magento/Braintree/etc/adminhtml/braintree_error_mapping.xml b/app/code/Magento/Braintree/etc/adminhtml/braintree_error_mapping.xml deleted file mode 100644 index 611f9372518fc..0000000000000 --- a/app/code/Magento/Braintree/etc/adminhtml/braintree_error_mapping.xml +++ /dev/null @@ -1,32 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<mapping xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Payment:etc/error_mapping.xsd"> - <message_list> - <message code="81509" translate="true">Credit card type is not accepted by this merchant account.</message> - <message code="91504" translate="true">Transaction can only be voided if status is authorized, submitted_for_settlement, or - for PayPal - settlement_pending.</message> - <message code="91505" translate="true">Credit transactions cannot be refunded.</message> - <message code="91506" translate="true">Cannot refund a transaction unless it is settled.</message> - <message code="91507" translate="true">Cannot submit for settlement unless status is authorized.</message> - <message code="91511" translate="true">Customer does not have any credit cards.</message> - <message code="91512" translate="true">Transaction has already been completely refunded.</message> - <message code="91517" translate="true">Payment instrument type is not accepted by this merchant account.</message> - <message code="91519" translate="true">Processor authorization code cannot be set unless for a voice authorization.</message> - <message code="91521" translate="true">Refund amount is too large.</message> - <message code="91522" translate="true">Settlement amount is too large.</message> - <message code="91530" translate="true">Cannot provide a billing address unless also providing a credit card.</message> - <message code="91538" translate="true">Cannot refund a transaction with a suspended merchant account.</message> - <message code="91547" translate="true">Merchant account does not support refunds.</message> - <message code="91574" translate="true">Cannot refund a transaction transaction in settling status on this merchant account. Try again after the transaction has settled.</message> - <message code="91576" translate="true">PayPal is not enabled for your merchant account.</message> - <message code="915102" translate="true">Partial settlements are not supported by this processor.</message> - <message code="915103" translate="true">Cannot submit for partial settlement.</message> - <message code="915148" translate="true">Transaction can not be voided if status of a PayPal partial settlement child transaction is settlement_pending.</message> - <message code="915149" translate="true">Too many concurrent attempts to refund this transaction. Try again later.</message> - <message code="915151" translate="true">Too many concurrent attempts to void this transaction. Try again later.</message> - </message_list> -</mapping> diff --git a/app/code/Magento/Braintree/etc/adminhtml/di.xml b/app/code/Magento/Braintree/etc/adminhtml/di.xml deleted file mode 100644 index 9de1ad48d2261..0000000000000 --- a/app/code/Magento/Braintree/etc/adminhtml/di.xml +++ /dev/null @@ -1,77 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> - <type name="Magento\Braintree\Block\Payment"> - <arguments> - <argument name="config" xsi:type="object">Magento\Braintree\Model\Ui\ConfigProvider</argument> - </arguments> - </type> - <type name="Magento\Braintree\Block\Info"> - <arguments> - <argument name="data" xsi:type="array"> - <item xsi:type="string" name="is_secure_mode">0</item> - </argument> - </arguments> - </type> - - <virtualType name="BraintreeAuthorizeRequest" type="Magento\Payment\Gateway\Request\BuilderComposite"> - <arguments> - <argument name="builders" xsi:type="array"> - <item name="customer" xsi:type="string">Magento\Braintree\Gateway\Request\CustomerDataBuilder</item> - <item name="payment" xsi:type="string">Magento\Braintree\Gateway\Request\PaymentDataBuilder</item> - <item name="channel" xsi:type="string">Magento\Braintree\Gateway\Request\ChannelDataBuilder</item> - <item name="address" xsi:type="string">Magento\Braintree\Gateway\Request\AddressDataBuilder</item> - <item name="vault" xsi:type="string">Magento\Braintree\Gateway\Request\VaultDataBuilder</item> - <item name="dynamic_descriptor" xsi:type="string">Magento\Braintree\Gateway\Request\DescriptorDataBuilder</item> - <item name="store" xsi:type="string">Magento\Braintree\Gateway\Request\StoreConfigBuilder</item> - <item name="merchant_account" xsi:type="string">Magento\Braintree\Gateway\Request\MerchantAccountDataBuilder</item> - </argument> - </arguments> - </virtualType> - <virtualType name="BraintreeVaultAuthorizeRequest" type="Magento\Payment\Gateway\Request\BuilderComposite"> - <arguments> - <argument name="builders" xsi:type="array"> - <item name="customer" xsi:type="string">Magento\Braintree\Gateway\Request\CustomerDataBuilder</item> - <item name="payment" xsi:type="string">Magento\Braintree\Gateway\Request\PaymentDataBuilder</item> - <item name="channel" xsi:type="string">Magento\Braintree\Gateway\Request\ChannelDataBuilder</item> - <item name="address" xsi:type="string">Magento\Braintree\Gateway\Request\AddressDataBuilder</item> - <item name="dynamic_descriptor" xsi:type="string">Magento\Braintree\Gateway\Request\DescriptorDataBuilder</item> - <item name="store" xsi:type="string">Magento\Braintree\Gateway\Request\StoreConfigBuilder</item> - <item name="merchant_account" xsi:type="string">Magento\Braintree\Gateway\Request\MerchantAccountDataBuilder</item> - </argument> - </arguments> - </virtualType> - - <!-- Braintree commands --> - <type name="BraintreeVoidCommand"> - <arguments> - <argument name="errorMessageMapper" xsi:type="object">Magento\Braintree\Gateway\ErrorMapper\VirtualErrorMessageMapper</argument> - </arguments> - </type> - <type name="BraintreeRefundCommand"> - <arguments> - <argument name="errorMessageMapper" xsi:type="object">Magento\Braintree\Gateway\ErrorMapper\VirtualErrorMessageMapper</argument> - </arguments> - </type> - <!-- END Braintree commands --> - - <type name="Magento\Vault\Model\Ui\Adminhtml\TokensConfigProvider"> - <arguments> - <argument name="tokenUiComponentProviders" xsi:type="array"> - <item name="braintree" xsi:type="object">Magento\Braintree\Model\Ui\Adminhtml\TokenUiComponentProvider</item> - <item name="braintree_paypal" xsi:type="object">Magento\Braintree\Model\Ui\Adminhtml\PayPal\TokenUiComponentProvider</item> - </argument> - </arguments> - </type> - - <type name="Magento\Braintree\Controller\Adminhtml\Payment\GetNonce"> - <arguments> - <argument name="session" xsi:type="object">Magento\Backend\Model\Session\Quote</argument> - </arguments> - </type> -</config> diff --git a/app/code/Magento/Braintree/etc/adminhtml/menu.xml b/app/code/Magento/Braintree/etc/adminhtml/menu.xml deleted file mode 100644 index ce4dd4844f3bc..0000000000000 --- a/app/code/Magento/Braintree/etc/adminhtml/menu.xml +++ /dev/null @@ -1,20 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd"> - <menu> - <add - id="Magento_Braintree::settlement_report" - title="Braintree Settlement" - translate="title" - module="Magento_Braintree" - sortOrder="80" - parent="Magento_Reports::report_salesroot" - action="braintree/report" - resource="Magento_Braintree::settlement_report"/> - </menu> -</config> diff --git a/app/code/Magento/Braintree/etc/adminhtml/routes.xml b/app/code/Magento/Braintree/etc/adminhtml/routes.xml deleted file mode 100644 index 5349d540598ce..0000000000000 --- a/app/code/Magento/Braintree/etc/adminhtml/routes.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> - <router id="admin"> - <route id="braintree" frontName="braintree"> - <module name="Magento_Braintree" before="Magento_Backend" /> - </route> - </router> -</config> diff --git a/app/code/Magento/Braintree/etc/adminhtml/system.xml b/app/code/Magento/Braintree/etc/adminhtml/system.xml deleted file mode 100644 index 06268536e880e..0000000000000 --- a/app/code/Magento/Braintree/etc/adminhtml/system.xml +++ /dev/null @@ -1,268 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd"> - <system> - <section id="payment"> - <group id="braintree_section" sortOrder="6"> - <group id="braintree" translate="label comment" type="text" showInDefault="1" showInWebsite="1" showInStore="1"> - <label>Braintree</label> - <comment><![CDATA[Accept credit/debit cards and PayPal in your Magento store.<br/>No setup or monthly fees and your customers never leave your store to complete the purchase.]]></comment> - <fieldset_css>complex braintree-section</fieldset_css> - <frontend_model>Magento\Paypal\Block\Adminhtml\System\Config\Fieldset\Payment</frontend_model> - <attribute type="activity_path">payment/braintree/active</attribute> - <attribute type="displayIn">recommended_solutions</attribute> - <field id="active" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1"> - <label>Enable this Solution</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <config_path>payment/braintree/active</config_path> - <requires> - <group id="braintree_required"/> - </requires> - </field> - <field id="active_braintree_paypal" translate="label" type="select" sortOrder="11" showInDefault="1" showInWebsite="1"> - <label>Enable PayPal through Braintree</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <config_path>payment/braintree_paypal/active</config_path> - <requires> - <group id="braintree_required"/> - </requires> - </field> - <field id="braintree_cc_vault_active" translate="label" type="select" sortOrder="12" showInDefault="1" showInWebsite="1"> - <label>Vault Enabled</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <config_path>payment/braintree_cc_vault/active</config_path> - <requires> - <group id="braintree_required"/> - </requires> - </field> - <group id="configuration_details" showInDefault="1" showInWebsite="1" showInStore="1" sortOrder="4"> - <comment>https://docs.magento.com/m2/ce/user_guide/payment/braintree.html</comment> - <frontend_model>Magento\Paypal\Block\Adminhtml\System\Config\Fieldset\Hint</frontend_model> - </group> - <group id="braintree_required" translate="label" showInDefault="1" showInWebsite="1" showInStore="1" sortOrder="5"> - <label>Basic Braintree Settings</label> - <attribute type="expanded">1</attribute> - <frontend_model>Magento\Config\Block\System\Config\Form\Fieldset</frontend_model> - <field id="title" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1"> - <label>Title</label> - <config_path>payment/braintree/title</config_path> - </field> - <field id="environment" translate="label" type="select" sortOrder="30" showInDefault="1" showInWebsite="1"> - <label>Environment</label> - <source_model>Magento\Braintree\Model\Adminhtml\Source\Environment</source_model> - <config_path>payment/braintree/environment</config_path> - </field> - <field id="payment_action" translate="label" type="select" sortOrder="50" showInDefault="1" showInWebsite="1"> - <label>Payment Action</label> - <source_model>Magento\Braintree\Model\Adminhtml\Source\PaymentAction</source_model> - <config_path>payment/braintree/payment_action</config_path> - </field> - <field id="merchant_id" translate="label" sortOrder="90" showInDefault="1" showInWebsite="1"> - <label>Merchant ID</label> - <config_path>payment/braintree/merchant_id</config_path> - </field> - <field id="public_key" translate="label" type="obscure" sortOrder="100" showInDefault="1" showInWebsite="1"> - <label>Public Key</label> - <config_path>payment/braintree/public_key</config_path> - <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model> - </field> - <field id="private_key" translate="label" type="obscure" sortOrder="110" showInDefault="1" showInWebsite="1"> - <label>Private Key</label> - <config_path>payment/braintree/private_key</config_path> - <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model> - </field> - </group> - <group id="braintree_advanced" translate="label" showInDefault="1" showInWebsite="1" sortOrder="20"> - <label>Advanced Braintree Settings</label> - <frontend_model>Magento\Config\Block\System\Config\Form\Fieldset</frontend_model> - <field id="braintree_cc_vault_title" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1"> - <label>Vault Title</label> - <config_path>payment/braintree_cc_vault/title</config_path> - </field> - <field id="merchant_account_id" translate="label comment" sortOrder="30" showInDefault="1" showInWebsite="1"> - <label>Merchant Account ID</label> - <comment>If you don't specify the merchant account to use to process a transaction, Braintree will process it using your default merchant account.</comment> - <config_path>payment/braintree/merchant_account_id</config_path> - </field> - <field id="fraudprotection" translate="label comment" type="select" sortOrder="34" showInDefault="1" showInWebsite="1"> - <label>Advanced Fraud Protection</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <comment>Be sure to Enable Advanced Fraud Protection in Your Braintree Account in Settings/Processing Section</comment> - <config_path>payment/braintree/fraudprotection</config_path> - </field> - <field id="debug" translate="label" type="select" sortOrder="40" showInDefault="1" showInWebsite="1"> - <label>Debug</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <config_path>payment/braintree/debug</config_path> - </field> - <field id="useccv" translate="label comment" type="select" sortOrder="150" showInDefault="1" showInWebsite="1"> - <label>CVV Verification</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <comment>Be sure to Enable AVS and/or CVV in Your Braintree Account in Settings/Processing Section.</comment> - <config_path>payment/braintree/useccv</config_path> - </field> - <field id="cctypes" translate="label" type="multiselect" sortOrder="160" showInDefault="1" showInWebsite="1"> - <label>Credit Card Types</label> - <source_model>Magento\Braintree\Model\Adminhtml\Source\CcType</source_model> - <config_path>payment/braintree/cctypes</config_path> - </field> - <field id="sort_order" translate="label" type="text" sortOrder="230" showInDefault="1" showInWebsite="1"> - <label>Sort Order</label> - <frontend_class>validate-number</frontend_class> - <config_path>payment/braintree/sort_order</config_path> - </field> - </group> - <group id="braintree_country_specific" translate="label" showInDefault="1" showInWebsite="1" sortOrder="30"> - <label>Country Specific Settings</label> - <frontend_model>Magento\Config\Block\System\Config\Form\Fieldset</frontend_model> - <field id="allowspecific" translate="label" type="allowspecific" sortOrder="200" showInDefault="1" showInWebsite="1"> - <label>Payment from Applicable Countries</label> - <source_model>Magento\Payment\Model\Config\Source\Allspecificcountries</source_model> - <config_path>payment/braintree/allowspecific</config_path> - </field> - <field id="specificcountry" translate="label" type="multiselect" sortOrder="210" showInDefault="1" showInWebsite="1"> - <label>Payment from Specific Countries</label> - <source_model>Magento\Braintree\Model\Adminhtml\System\Config\Country</source_model> - <can_be_empty>1</can_be_empty> - <config_path>payment/braintree/specificcountry</config_path> - </field> - <field id="countrycreditcard" translate="label" sortOrder="220" showInDefault="1" showInWebsite="1"> - <label>Country Specific Credit Card Types</label> - <frontend_model>Magento\Braintree\Block\Adminhtml\Form\Field\CountryCreditCard</frontend_model> - <backend_model>Magento\Braintree\Model\Adminhtml\System\Config\CountryCreditCard</backend_model> - <config_path>payment/braintree/countrycreditcard</config_path> - </field> - </group> - <group id="braintree_paypal" translate="label" showInDefault="1" showInWebsite="1" showInStore="1" sortOrder="40"> - <label>PayPal through Braintree</label> - <frontend_model>Magento\Config\Block\System\Config\Form\Fieldset</frontend_model> - <field id="title" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1"> - <label>Title</label> - <config_path>payment/braintree_paypal/title</config_path> - <comment>It is recommended to set this value to "PayPal" per store views.</comment> - </field> - <field id="braintree_paypal_vault_active" translate="label" type="select" sortOrder="21" showInDefault="1" showInWebsite="1"> - <label>Vault Enabled</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <config_path>payment/braintree_paypal_vault/active</config_path> - <requires> - <group id="braintree_required"/> - </requires> - </field> - <field id="sort_order" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1"> - <label>Sort Order</label> - <frontend_class>validate-number</frontend_class> - <config_path>payment/braintree_paypal/sort_order</config_path> - </field> - <field id="merchant_name_override" translate="label" type="text" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1"> - <label>Override Merchant Name</label> - <config_path>payment/braintree_paypal/merchant_name_override</config_path> - </field> - <field id="payment_action" translate="label" type="select" sortOrder="50" showInDefault="1" showInWebsite="1"> - <label>Payment Action</label> - <source_model>Magento\Braintree\Model\Adminhtml\Source\PaymentAction</source_model> - <config_path>payment/braintree_paypal/payment_action</config_path> - </field> - <field id="allowspecific" translate="label" type="allowspecific" sortOrder="70" showInDefault="1" showInWebsite="1"> - <label>Payment from Applicable Countries</label> - <source_model>Magento\Payment\Model\Config\Source\Allspecificcountries</source_model> - <config_path>payment/braintree_paypal/allowspecific</config_path> - </field> - <field id="specificcountry" translate="label" type="multiselect" sortOrder="80" showInDefault="1" showInWebsite="1"> - <label>Payment from Specific Countries</label> - <source_model>Magento\Braintree\Model\Adminhtml\System\Config\Country</source_model> - <can_be_empty>1</can_be_empty> - <config_path>payment/braintree_paypal/specificcountry</config_path> - </field> - <field id="require_billing_address" translate="label comment" type="select" sortOrder="90" showInDefault="1" showInWebsite="1"> - <label>Require Customer's Billing Address</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <config_path>payment/braintree_paypal/require_billing_address</config_path> - <comment>This feature needs be enabled first for the merchant account through PayPal technical support.</comment> - </field> - <field id="allow_shipping_address_override" translate="label" type="select" sortOrder="100" showInDefault="1" showInWebsite="1"> - <label>Allow to Edit Shipping Address Entered During Checkout on PayPal Side</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <config_path>payment/braintree_paypal/allow_shipping_address_override</config_path> - </field> - <field id="debug" translate="label" type="select" sortOrder="110" showInDefault="1" showInWebsite="1"> - <label>Debug</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <config_path>payment/braintree_paypal/debug</config_path> - </field> - <field id="display_on_shopping_cart" translate="label comment" type="select" sortOrder="120" showInDefault="1" showInWebsite="1"> - <label>Display on Shopping Cart</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <config_path>payment/braintree_paypal/display_on_shopping_cart</config_path> - <comment>Also affects mini-shopping cart.</comment> - </field> - <field id="skip_order_review" translate="label" type="select" sortOrder="120" showInDefault="1" showInWebsite="1"> - <label>Skip Order Review</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <config_path>payment/braintree_paypal/skip_order_review</config_path> - </field> - </group> - <group id="braintree_3dsecure" translate="label" showInDefault="1" showInWebsite="1" sortOrder="41"> - <label>3D Secure Verification Settings</label> - <frontend_model>Magento\Config\Block\System\Config\Form\Fieldset</frontend_model> - <field id="verify_3dsecure" translate="label" type="select" sortOrder="150" showInDefault="1" showInWebsite="1"> - <label>3D Secure Verification</label> - <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> - <config_path>payment/braintree/verify_3dsecure</config_path> - </field> - <field id="threshold_amount" translate="label" type="text" sortOrder="151" showInDefault="1" showInWebsite="1"> - <label>Threshold Amount</label> - <config_path>payment/braintree/threshold_amount</config_path> - </field> - <field id="allowspecific" translate="label" type="allowspecific" sortOrder="152" showInDefault="1" showInWebsite="1"> - <label>Verify for Applicable Countries</label> - <source_model>Magento\Payment\Model\Config\Source\Allspecificcountries</source_model> - <config_path>payment/braintree/verify_all_countries</config_path> - </field> - <field id="specificcountry" translate="label" type="multiselect" sortOrder="153" showInDefault="1" showInWebsite="1"> - <label>Verify for Specific Countries</label> - <source_model>Magento\Braintree\Model\Adminhtml\System\Config\Country</source_model> - <can_be_empty>1</can_be_empty> - <config_path>payment/braintree/verify_specific_countries</config_path> - </field> - </group> - <group id="braintree_dynamic_descriptor" translate="label comment" showInDefault="1" showInWebsite="1" showInStore="1" sortOrder="50"> - <label>Dynamic Descriptors</label> - <comment><![CDATA[Dynamic descriptors are sent on a per-transaction basis and define what will appear on your customers credit card statements for a specific purchase. - The clearer the description of your product, the less likely customers will issue chargebacks due to confusion or non-recognition. - Dynamic descriptors are not enabled on all accounts by default. If you receive a validation error of 92203 or if your dynamic descriptors are not displaying as expected, - please <a href="mailto:support@getbraintree.com">Braintree Support</a>.]]></comment> - <frontend_model>Magento\Config\Block\System\Config\Form\Fieldset</frontend_model> - <field id="name" translate="label comment" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1"> - <label>Name</label> - <config_path>payment/braintree/descriptor_name</config_path> - <comment> - The value in the business name field of a customer's statement. Company name/DBA section must be either 3, 7 or 12 characters - and the product descriptor can be up to 18, 14, or 9 characters respectively (with an * in between for a total descriptor name of 22 characters). - </comment> - </field> - <field id="phone" translate="label comment" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1"> - <label>Phone</label> - <config_path>payment/braintree/descriptor_phone</config_path> - <comment> - The value in the phone number field of a customer's statement. Phone must be 10-14 characters and can only contain numbers, dashes, parentheses and periods. - </comment> - </field> - <field id="url" translate="label comment" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1"> - <label>URL</label> - <config_path>payment/braintree/descriptor_url</config_path> - <comment> - The value in the URL/web address field of a customer's statement. The URL must be 13 characters or shorter. - </comment> - </field> - </group> - </group> - </group> - </section> - </system> -</config> diff --git a/app/code/Magento/Braintree/etc/braintree_error_mapping.xml b/app/code/Magento/Braintree/etc/braintree_error_mapping.xml deleted file mode 100644 index bffcc75705938..0000000000000 --- a/app/code/Magento/Braintree/etc/braintree_error_mapping.xml +++ /dev/null @@ -1,66 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<mapping xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Payment:etc/error_mapping.xsd"> - <message_list> - <message code="81703" translate="true">Credit card type is not accepted by this merchant account.</message> - <message code="81706" translate="true">CVV is required.</message> - <message code="81707" translate="true">CVV must be 4 digits for American Express and 3 digits for other card types.</message> - <message code="81709" translate="true">Expiration date is required.</message> - <message code="81710" translate="true">Expiration date is invalid.</message> - <message code="81711" translate="true">Expiration year is invalid. It must be between 1975 and 2201.</message> - <message code="81712" translate="true">Expiration month is invalid.</message> - <message code="81713" translate="true">Expiration year is invalid.</message> - <message code="81714" translate="true">Credit card number is required.</message> - <message code="81715" translate="true">Credit card number is invalid.</message> - <message code="81716" translate="true">Credit card number must be 12-19 digits.</message> - <message code="81723" translate="true">Cardholder name is too long.</message> - <message code="81736" translate="true">CVV verification failed.</message> - <message code="cvv" translate="true">CVV verification failed.</message> - <message code="2059" translate="true">Address Verification Failed.</message> - <message code="81737" translate="true">Postal code verification failed.</message> - <message code="81750" translate="true">Credit card number is prohibited.</message> - <message code="81801" translate="true">Addresses must have at least one field filled in.</message> - <message code="81802" translate="true">Company is too long.</message> - <message code="81804" translate="true">Extended address is too long.</message> - <message code="81805" translate="true">First name is too long.</message> - <message code="81806" translate="true">Last name is too long.</message> - <message code="81807" translate="true">Locality is too long.</message> - <message code="81808" translate="true">Postal code is required.</message> - <message code="81809" translate="true">Postal code may contain no more than 9 letter or number characters.</message> - <message code="81810" translate="true">Region is too long.</message> - <message code="81811" translate="true">Street address is required.</message> - <message code="81812" translate="true">Street address is too long.</message> - <message code="81813" translate="true">Postal code can only contain letters, numbers, spaces, and hyphens.</message> - <message code="81827" translate="true">US state codes must be two characters to meet PayPal Seller Protection requirements.</message> - <message code="82901" translate="true">Incomplete PayPal account information.</message> - <message code="82903" translate="true">Invalid PayPal account information.</message> - <message code="82904" translate="true">PayPal Accounts are not accepted by this merchant account.</message> - <message code="91726" translate="true">Credit card type is not accepted by this merchant account.</message> - <message code="91734" translate="true">Credit card type is not accepted by this merchant account.</message> - <message code="91744" translate="true">Billing address format is invalid.</message> - <message code="91803" translate="true">Country name is not an accepted country.</message> - <message code="91814" translate="true">Country code is not accepted. Please contact the store administrator.</message> - <message code="91815" translate="true">Provided country information is inconsistent.</message> - <message code="91816" translate="true">Country code is not accepted. Please contact the store administrator.</message> - <message code="91817" translate="true">Country code is not accepted. Please contact the store administrator.</message> - <message code="91818" translate="true">Customer has already reached the maximum of 50 addresses.</message> - <message code="91819" translate="true">Address is invalid. Please contact the store administrator.</message> - <message code="91820" translate="true">Address is invalid. Please contact the store administrator.</message> - <message code="91821" translate="true">Address is invalid. Please contact the store administrator.</message> - <message code="91822" translate="true">Address is invalid. Please contact the store administrator.</message> - <message code="91823" translate="true">Address is invalid. Please contact the store administrator.</message> - <message code="91824" translate="true">Address is invalid. Please contact the store administrator.</message> - <message code="91825" translate="true">Address is invalid. Please contact the store administrator.</message> - <message code="91826" translate="true">Address is invalid. Please contact the store administrator.</message> - <message code="91828" translate="true">Address is invalid. Please contact the store administrator.</message> - <message code="92910" translate="true">Error communicating with PayPal.</message> - <message code="92911" translate="true">PayPal authentication expired.</message> - <message code="92916" translate="true">Error executing PayPal order.</message> - <message code="92917" translate="true">Error executing PayPal billing agreement.</message> - </message_list> -</mapping> diff --git a/app/code/Magento/Braintree/etc/config.xml b/app/code/Magento/Braintree/etc/config.xml deleted file mode 100644 index b681100dc4dd0..0000000000000 --- a/app/code/Magento/Braintree/etc/config.xml +++ /dev/null @@ -1,97 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd"> - <default> - <payment> - <braintree> - <model>BraintreeFacade</model> - <title>Credit Card (Braintree) - authorize - 0 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - AE,VI,MC,DI,JCB,CUP,DN,MI - 1 - - processing - sandbox - 0 - - - - - cvv,number - avsPostalCodeResponseCode,avsStreetAddressResponseCode,cvvResponseCode,processorAuthorizationCode,processorResponseCode,processorResponseText,liabilityShifted,liabilityShiftPossible,riskDataId,riskDataDecision - cc_type,cc_number,avsPostalCodeResponseCode,avsStreetAddressResponseCode,cvvResponseCode,processorAuthorizationCode,processorResponseCode,processorResponseText,liabilityShifted,liabilityShiftPossible,riskDataId,riskDataDecision - Magento\Braintree\Model\AvsEmsCodeMapper - Magento\Braintree\Model\CvvEmsCodeMapper - braintree_group - - - BraintreePayPalFacade - PayPal (Braintree) - 0 - authorize - 0 - 0 - 1 - 1 - processing - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - processorResponseCode,processorResponseText,paymentId - processorResponseCode,processorResponseText,paymentId,payerEmail - en_US,en_GB,en_AU,da_DK,fr_FR,fr_CA,de_DE,zh_HK,it_IT,nl_NL,no_NO,pl_PL,es_ES,sv_SE,tr_TR,pt_BR,ja_JP,id_ID,ko_KR,pt_PT,ru_RU,th_TH,zh_CN,zh_TW - braintree_group - - - BraintreeCreditCardVaultFacade - Stored Cards (Braintree) - - Magento\Braintree\Model\InstantPurchase\CreditCard\AvailabilityChecker - Magento\Braintree\Model\InstantPurchase\CreditCard\TokenFormatter - Magento\Braintree\Model\InstantPurchase\PaymentAdditionalInformationProvider - - braintree_group - - - BraintreePayPalVaultFacade - Stored Accounts (Braintree PayPal) - 1 - - Magento\Braintree\Model\InstantPurchase\PayPal\TokenFormatter - Magento\Braintree\Model\InstantPurchase\PaymentAdditionalInformationProvider - - braintree_group - - - - diff --git a/app/code/Magento/Braintree/etc/di.xml b/app/code/Magento/Braintree/etc/di.xml deleted file mode 100644 index ef12b5eae6835..0000000000000 --- a/app/code/Magento/Braintree/etc/di.xml +++ /dev/null @@ -1,633 +0,0 @@ - - - - - - - Magento\Braintree\Model\Ui\ConfigProvider::CODE - Magento\Braintree\Block\Form - Magento\Braintree\Block\Info - BraintreeValueHandlerPool - BraintreeValidatorPool - BraintreeCommandPool - - - - - Magento\Braintree\Model\Ui\PayPal\ConfigProvider::PAYPAL_CODE - BraintreePayPalInfo - BraintreePayPalValueHandlerPool - BraintreePayPalValidatorPool - BraintreePayPalCommandPool - - - - - - - Magento\Braintree\Model\Ui\ConfigProvider::CC_VAULT_CODE - - - - - BraintreeVaultPaymentConfig - - - - - - BraintreeVaultPaymentValueHandler - - - - - - BraintreeVaultPaymentConfig - BraintreeVaultPaymentValueHandlerPool - BraintreeFacade - Magento\Braintree\Model\Ui\ConfigProvider::CC_VAULT_CODE - - - - - Magento\Braintree\Model\Ui\PayPal\ConfigProvider::PAYPAL_VAULT_CODE - - - - - BraintreePayPalVaultPaymentConfig - - - - - - BraintreePayPalVaultPaymentValueHandler - - - - - - BraintreePayPalVaultPaymentConfig - BraintreePayPalVaultPaymentValueHandlerPool - BraintreePayPalFacade - Magento\Braintree\Model\Ui\PayPal\ConfigProvider::PAYPAL_VAULT_CODE - - - - - - - - Magento\Braintree\Model\Ui\ConfigProvider::CODE - - - - - Magento\Braintree\Model\Ui\PayPal\ConfigProvider::PAYPAL_CODE - - - - - - - Magento\Braintree\Gateway\Config\Config - - - - - BraintreeLoggerForTransactionSale - - - - - BraintreeLoggerForTransactionSale - - - - - BraintreeLoggerForTransactionSale - - - - - BraintreeLoggerForTransactionSale - - - - - - - - - BraintreeAuthorizeCommand - BraintreeSaleCommand - BraintreeCaptureStrategyCommand - BraintreeCaptureCommand - BraintreeVaultAuthorizeCommand - BraintreeVaultSaleCommand - BraintreeVaultCaptureCommand - BraintreeVoidCommand - BraintreeRefundCommand - Magento\Braintree\Gateway\CancelCommand - Magento\Braintree\Gateway\CancelCommand - - - - - - - BraintreePayPalAuthorizeCommand - BraintreePayPalSaleCommand - BraintreePayPalCaptureStrategyCommand - BraintreeCaptureCommand - BraintreePayPalVaultAuthorizeCommand - BraintreePayPalVaultSaleCommand - BraintreeVaultCaptureCommand - BraintreeVoidCommand - BraintreeRefundCommand - Magento\Braintree\Gateway\CancelCommand - - - - - - BraintreeCommandPool - - - - - BraintreePayPalCommandPool - - - - - - - - BraintreeCommandPool - - - - - BraintreePayPalCommandPool - - - - - - BraintreeCommandManager - BraintreePayPalCommandManager - - - - - - - - Magento\Braintree\Gateway\Config\Config - - - - - - braintree_error_mapping.xml - - - - - Magento\Braintree\Gateway\ErrorMapper\VirtualConfigReader - braintree_error_mapper - - - - - Magento\Braintree\Gateway\ErrorMapper\VirtualMappingData - - - - - - - BraintreeAuthorizeRequest - Magento\Braintree\Gateway\Http\TransferFactory - Magento\Braintree\Gateway\Http\Client\TransactionSale - BraintreeAuthorizationHandler - Magento\Braintree\Gateway\Validator\ResponseValidator - Magento\Braintree\Gateway\ErrorMapper\VirtualErrorMessageMapper - - - - - - Magento\Braintree\Gateway\Request\CustomerDataBuilder - Magento\Braintree\Gateway\Request\PaymentDataBuilder - Magento\Braintree\Gateway\Request\ChannelDataBuilder - Magento\Braintree\Gateway\Request\AddressDataBuilder - Magento\Braintree\Gateway\Request\VaultDataBuilder - Magento\Braintree\Gateway\Request\ThreeDSecureDataBuilder - Magento\Braintree\Gateway\Request\KountPaymentDataBuilder - Magento\Braintree\Gateway\Request\DescriptorDataBuilder - Magento\Braintree\Gateway\Request\StoreConfigBuilder - Magento\Braintree\Gateway\Request\MerchantAccountDataBuilder - - - - - - - BraintreeSaleRequest - - - - - - BraintreeAuthorizeRequest - Magento\Braintree\Gateway\Request\SettlementDataBuilder - - - - - - - BraintreeCaptureRequest - Magento\Braintree\Gateway\Http\TransferFactory - Magento\Braintree\Gateway\Http\Client\TransactionSubmitForSettlement - Magento\Braintree\Gateway\Response\TransactionIdHandler - Magento\Braintree\Gateway\Validator\ResponseValidator - Magento\Braintree\Gateway\ErrorMapper\VirtualErrorMessageMapper - - - - - - Magento\Braintree\Gateway\Request\CaptureDataBuilder - Magento\Braintree\Gateway\Request\StoreConfigBuilder - - - - - - - BraintreeVaultAuthorizeRequest - Magento\Braintree\Gateway\Http\TransferFactory - Magento\Braintree\Gateway\Http\Client\TransactionSale - BraintreeVaultResponseHandler - Magento\Braintree\Gateway\Validator\ResponseValidator - Magento\Braintree\Gateway\ErrorMapper\VirtualErrorMessageMapper - - - - - - Magento\Braintree\Gateway\Request\CustomerDataBuilder - Magento\Braintree\Gateway\Request\PaymentDataBuilder - Magento\Braintree\Gateway\Request\ChannelDataBuilder - Magento\Braintree\Gateway\Request\AddressDataBuilder - Magento\Braintree\Gateway\Request\VaultThreeDSecureDataBuilder - Magento\Braintree\Gateway\Request\KountPaymentDataBuilder - Magento\Braintree\Gateway\Request\DescriptorDataBuilder - Magento\Braintree\Gateway\Request\StoreConfigBuilder - Magento\Braintree\Gateway\Request\MerchantAccountDataBuilder - - - - - - - BraintreeVaultSaleRequest - - - - - - BraintreeVaultAuthorizeRequest - Magento\Braintree\Gateway\Request\SettlementDataBuilder - - - - - - - BraintreeVaultCaptureRequest - Magento\Braintree\Gateway\Http\TransferFactory - Magento\Braintree\Gateway\Http\Client\TransactionSale - Magento\Braintree\Gateway\Response\TransactionIdHandler - Magento\Braintree\Gateway\Validator\ResponseValidator - Magento\Braintree\Gateway\ErrorMapper\VirtualErrorMessageMapper - - - - - - Magento\Braintree\Gateway\Request\VaultCaptureDataBuilder - Magento\Braintree\Gateway\Request\SettlementDataBuilder - Magento\Braintree\Gateway\Request\StoreConfigBuilder - Magento\Braintree\Gateway\Request\MerchantAccountDataBuilder - - - - - - - - - BraintreePayPalAuthorizeRequest - BraintreePayPalResponseHandler - - - - - - Magento\Braintree\Gateway\Request\CustomerDataBuilder - Magento\Braintree\Gateway\Request\PaymentDataBuilder - Magento\Braintree\Gateway\Request\ChannelDataBuilder - Magento\Braintree\Gateway\Request\PayPal\VaultDataBuilder - Magento\Braintree\Gateway\Request\PayPal\DeviceDataBuilder - Magento\Braintree\Gateway\Request\DescriptorDataBuilder - Magento\Braintree\Gateway\Request\StoreConfigBuilder - Magento\Braintree\Gateway\Request\MerchantAccountDataBuilder - - - - - - - BraintreePayPalSaleRequest - - - - - - BraintreePayPalAuthorizeRequest - Magento\Braintree\Gateway\Request\SettlementDataBuilder - - - - - - - BraintreePayPalVaultAuthorizeRequest - BraintreePayPalVaultResponseHandler - - - - - - Magento\Braintree\Gateway\Request\CustomerDataBuilder - Magento\Braintree\Gateway\Request\PaymentDataBuilder - Magento\Braintree\Gateway\Request\ChannelDataBuilder - Magento\Braintree\Gateway\Request\BillingAddressDataBuilder - Magento\Braintree\Gateway\Request\DescriptorDataBuilder - Magento\Braintree\Gateway\Request\StoreConfigBuilder - Magento\Braintree\Gateway\Request\MerchantAccountDataBuilder - - - - - - - BraintreePayPalVaultSaleRequest - - - - - - BraintreePayPalVaultAuthorizeRequest - Magento\Braintree\Gateway\Request\SettlementDataBuilder - - - - - - - - - Magento\Vault\Api\Data\PaymentTokenFactoryInterface - - - - - - BraintreeConfigValueHandler - Magento\Braintree\Gateway\Config\CanVoidHandler - Magento\Braintree\Gateway\Config\CanVoidHandler - - - - - - Magento\Braintree\Gateway\Config\Config - - - - - - Magento\Braintree\Gateway\Response\PaymentDetailsHandler - Magento\Braintree\Gateway\Response\TransactionIdHandler - Magento\Braintree\Gateway\Response\CardDetailsHandler - Magento\Braintree\Gateway\Response\RiskDataHandler - Magento\Braintree\Gateway\Response\VaultDetailsHandler - Magento\Braintree\Gateway\Response\ThreeDSecureDetailsHandler - - - - - - - Magento\Braintree\Gateway\Response\PaymentDetailsHandler - Magento\Braintree\Gateway\Response\TransactionIdHandler - Magento\Braintree\Gateway\Response\CardDetailsHandler - Magento\Braintree\Gateway\Response\RiskDataHandler - Magento\Braintree\Gateway\Response\ThreeDSecureDetailsHandler - - - - - - - - - Magento\Vault\Api\Data\PaymentTokenFactoryInterface - - - - - - BraintreePayPalConfigValueHandler - Magento\Braintree\Gateway\Config\CanVoidHandler - Magento\Braintree\Gateway\Config\CanVoidHandler - Magento\Braintree\Gateway\Config\CanVoidHandler - - - - - - Magento\Braintree\Gateway\Config\PayPal\Config - - - - - - Magento\Braintree\Gateway\Response\PaymentDetailsHandler - Magento\Braintree\Gateway\Response\TransactionIdHandler - Magento\Braintree\Gateway\Response\PayPalDetailsHandler - Magento\Braintree\Gateway\Response\PayPal\VaultDetailsHandler - - - - - - - Magento\Braintree\Gateway\Response\PaymentDetailsHandler - Magento\Braintree\Gateway\Response\TransactionIdHandler - Magento\Braintree\Gateway\Response\PayPalDetailsHandler - - - - - - - - - Magento\Braintree\Gateway\Http\Client\TransactionVoid - BraintreeVoidRequestBuilder - Magento\Braintree\Gateway\Response\VoidHandler - Magento\Braintree\Gateway\Validator\GeneralResponseValidator - Magento\Braintree\Gateway\Http\TransferFactory - - - - - - Magento\Braintree\Gateway\Request\VoidDataBuilder - Magento\Braintree\Gateway\Request\StoreConfigBuilder - - - - - - - - Magento\Braintree\Gateway\Response\CancelDetailsHandler - Magento\Braintree\Gateway\Validator\CancelResponseValidator - - - - - - - - Magento\Braintree\Gateway\Http\Client\TransactionRefund - BraintreeRefundBuilder - Magento\Braintree\Gateway\Validator\GeneralResponseValidator - Magento\Braintree\Gateway\Response\RefundHandler - Magento\Braintree\Gateway\Http\TransferFactory - - - - - - Magento\Braintree\Gateway\Request\RefundDataBuilder - Magento\Braintree\Gateway\Request\StoreConfigBuilder - - - - - - - - - Magento\Braintree\Gateway\Config\Config - - - - - - BraintreeCountryValidator - - - - - - - - - Magento\Braintree\Gateway\Config\PayPal\Config - - - - - - BraintreePayPalCountryValidator - - - - - - - - Magento\Braintree\Gateway\Config\Config - - - - - Magento\Braintree\Gateway\Config\PayPal\Config - - - - - - - - Magento\Braintree\Model\Report\TransactionsCollection - - - - - - BraintreeTransactionsCollectionFactoryForReporting - - - - - BraintreeTransactionsReporting - - - - - - Magento\Braintree\Model\Report\ConditionAppliers\Text - Magento\Braintree\Model\Report\ConditionAppliers\Range - Magento\Braintree\Model\Report\ConditionAppliers\MultipleValue - - - - - - - - 1 - 1 - 1 - 1 - 1 - 1 - - - 1 - - - - - - - - - - - diff --git a/app/code/Magento/Braintree/etc/events.xml b/app/code/Magento/Braintree/etc/events.xml deleted file mode 100644 index a87d518a85a36..0000000000000 --- a/app/code/Magento/Braintree/etc/events.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - diff --git a/app/code/Magento/Braintree/etc/frontend/di.xml b/app/code/Magento/Braintree/etc/frontend/di.xml deleted file mode 100644 index 330fa51258c44..0000000000000 --- a/app/code/Magento/Braintree/etc/frontend/di.xml +++ /dev/null @@ -1,89 +0,0 @@ - - - - - - - Magento\Braintree\Model\Ui\ConfigProvider - Magento\Braintree\Model\Ui\PayPal\ConfigProvider - - - - - - - Magento\Braintree\Model\Ui\ConfigProvider::CODE - - - - - - - 1 - - - - - - - - Magento\Braintree\Model\Ui\TokenUiComponentProvider - Magento\Braintree\Model\Ui\PayPal\TokenUiComponentProvider - - - - - - - Magento\Customer\Model\Session - - - - - - Magento\Braintree\Model\LocaleResolver - - Magento_Braintree::paypal/button.phtml - braintree.paypal.mini-cart - braintree-paypal-mini-cart - - BraintreePayPalFacade - - - - - - Magento_Braintree::paypal/button_shopping_cart.phtml - braintree.paypal.mini-cart - braintree-paypal-mini-cart - - - - - - - Magento\Braintree\Block\Paypal\Button - Magento\Braintree\Block\Paypal\ButtonShoppingCartVirtual - - - - - - - Magento\Braintree\Model\LocaleResolver - - - - - - Magento\Braintree\Model\Multishipping\PlaceOrder - Magento\Braintree\Model\Multishipping\PlaceOrder - - - - diff --git a/app/code/Magento/Braintree/etc/frontend/events.xml b/app/code/Magento/Braintree/etc/frontend/events.xml deleted file mode 100644 index 77bc1a45e65ee..0000000000000 --- a/app/code/Magento/Braintree/etc/frontend/events.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - diff --git a/app/code/Magento/Braintree/etc/frontend/routes.xml b/app/code/Magento/Braintree/etc/frontend/routes.xml deleted file mode 100644 index 5dbe389ac84f8..0000000000000 --- a/app/code/Magento/Braintree/etc/frontend/routes.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - diff --git a/app/code/Magento/Braintree/etc/frontend/sections.xml b/app/code/Magento/Braintree/etc/frontend/sections.xml deleted file mode 100644 index e44fb38aaef4b..0000000000000 --- a/app/code/Magento/Braintree/etc/frontend/sections.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - -
-
- - diff --git a/app/code/Magento/Braintree/etc/module.xml b/app/code/Magento/Braintree/etc/module.xml deleted file mode 100644 index 8be79268e7b58..0000000000000 --- a/app/code/Magento/Braintree/etc/module.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/app/code/Magento/Braintree/etc/payment.xml b/app/code/Magento/Braintree/etc/payment.xml deleted file mode 100644 index 4cae049aaf5a9..0000000000000 --- a/app/code/Magento/Braintree/etc/payment.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - 1 - - - 1 - - - diff --git a/app/code/Magento/Braintree/i18n/en_US.csv b/app/code/Magento/Braintree/i18n/en_US.csv deleted file mode 100644 index e9145b35b56ef..0000000000000 --- a/app/code/Magento/Braintree/i18n/en_US.csv +++ /dev/null @@ -1,196 +0,0 @@ -cc_type,"Credit Card Type" -cc_number,"Credit Card Number" -avsPostalCodeResponseCode,"AVS Postal Code Response Code" -avsStreetAddressResponseCode,"AVS Street Address Response Code" -cvvResponseCode,"CVV Response Code" -processorAuthorizationCode,"Processor Authorization Code" -processorResponseCode,"Processor Response Code" -processorResponseText,"Processor Response Text" -braintree,Braintree -liabilityShifted,"Liability Shifted" -liabilityShiftPossible,"Liability Shift Possible" -riskDataId,"Risk ID" -riskDataDecision,"Risk Decision" -paymentId,"Payment Id" -payerEmail,"Payer Email" -sale,Sale -credit,Credit -authorization_expired,"Authorization expired" -authorizing,Authorizing -authorized,Authorized -gateway_rejected,"Gateway rejected" -failed,Failed -processor_declined,"Processor declined" -settled,Settled -settling,Settling -submitted_for_settlement,"Submitted for settlement" -voided,Voided -unrecognized,Unrecognized -settlement_declined,"Settlement declined" -settlement_pending,"Settlement pending" -settlement_confirmed,"Settlement confirmed" -paypal_account,"Paypal account" -coinbase_account,"Coinbase account" -europe_bank_accout,"Europe bank account" -credit_card,"Credit card" -apple_pay_card,"Apple pay card" -android_pay_card,"Android pay card" -Country,Country -"Allowed Credit Card Types","Allowed Credit Card Types" -"Add Rule","Add Rule" -"Braintree Settlement Report","Braintree Settlement Report" -"Sorry, but something went wrong","Sorry, but something went wrong" -"We can't initialize checkout.","We can't initialize checkout." -"No authorization transaction to proceed capture.","No authorization transaction to proceed capture." -"Braintree error response.","Braintree error response." -"Payment method nonce can't be retrieved.","Payment method nonce can't be retrieved." -"Wrong transaction status","Wrong transaction status" -Authorize,Authorize -"Authorize and Capture","Authorize and Capture" -"--Please Select--","--Please Select--" -"Please agree to all the terms and conditions before placing the order.","Please agree to all the terms and conditions before placing the order." -"Credit Card Type","Credit Card Type" -"Credit Card Number","Credit Card Number" -"Please, enter valid Credit Card Number","Please, enter valid Credit Card Number" -"Expiration Date","Expiration Date" -"Please, enter valid Expiration Date","Please, enter valid Expiration Date" -"Card Verification Number","Card Verification Number" -"Please, enter valid Card Verification Number","Please, enter valid Card Verification Number" -ending,ending -expires,expires -"Are you sure you want to delete this PayPal account","Are you sure you want to delete this PayPal account" -"PayPal Account","PayPal Account" -"PayPal Logo","PayPal Logo" -Actions,Actions -Delete,Delete -"Credit Card Information","Credit Card Information" -"What is this?","What is this?" -"Save for later use.","Save for later use." -"Place Order","Place Order" -"This payment is not available","This payment is not available" -MM,MM -YY,YY -"Please try again with another form of payment.","Please try again with another form of payment." -"Sorry, but something went wrong.","Sorry, but something went wrong." -"Payment ","Payment " -Braintree,Braintree -"Accept credit/debit cards and PayPal in your Magento store.
No setup or monthly fees and your customers never leave your store to complete the purchase.","Accept credit/debit cards and PayPal in your Magento store.
No setup or monthly fees and your customers never leave your store to complete the purchase." -"Enable this Solution","Enable this Solution" -"Enable PayPal through Braintree","Enable PayPal through Braintree" -"Vault Enabled","Vault Enabled" -"Basic Braintree Settings","Basic Braintree Settings" -Title,Title -Environment,Environment -"Payment Action","Payment Action" -"Merchant ID","Merchant ID" -"Public Key","Public Key" -"Private Key","Private Key" -"Advanced Braintree Settings","Advanced Braintree Settings" -"Vault Title","Vault Title" -"Merchant Account ID","Merchant Account ID" -"Advanced Fraud Protection","Advanced Fraud Protection" -"Kount Merchant ID","Kount Merchant ID" -Debug,Debug -"CVV Verification","CVV Verification" -"Credit Card Types","Credit Card Types" -"Sort Order","Sort Order" -"Country Specific Settings","Country Specific Settings" -"Payment from Applicable Countries","Payment from Applicable Countries" -"Payment from Specific Countries","Payment from Specific Countries" -"Country Specific Credit Card Types","Country Specific Credit Card Types" -"PayPal through Braintree","PayPal through Braintree" -"Override Merchant Name","Override Merchant Name" -"Require Customer's Billing Address","Require Customer's Billing Address" -"Allow to Edit Shipping Address Entered During Checkout on PayPal Side","Allow to Edit Shipping Address Entered During Checkout on PayPal Side" -"Display on Shopping Cart","Display on Shopping Cart" -"Skip Order Review","Skip Order Review" -"3D Secure Verification Settings","3D Secure Verification Settings" -"3D Secure Verification","3D Secure Verification" -"Threshold Amount","Threshold Amount" -"Verify for Applicable Countries","Verify for Applicable Countries" -"Verify for Specific Countries","Verify for Specific Countries" -"Dynamic Descriptors","Dynamic Descriptors" -Name,Name -Phone,Phone -URL,URL -"Apply filters in order to get results. Only first 100 records will be displayed in the grid, you will be able to download full version of the report in .csv format.","Apply filters in order to get results. Only first 100 records will be displayed in the grid, you will be able to download full version of the report in .csv format." -Select...,Select... -Status,Status -"Transaction Type","Transaction Type" -"Payment Type","Payment Type" -"PayPal Payment ID","PayPal Payment ID" -"Created At","Created At" -"Transaction ID","Transaction ID" -"Order ID","Order ID" -Type,Type -Amount,Amount -"Settlement Code","Settlement Code" -"Settlement Response Text","Settlement Response Text" -"Refund Ids","Refund Ids" -"Settlement Batch ID","Settlement Batch ID" -Currency,Currency -"Addresses must have at least one field filled in.","Addresses must have at least one field filled in." -"Company is too long.","Company is too long." -"Extended address is too long.","Extended address is too long." -"First name is too long.","First name is too long." -"Last name is too long.","Last name is too long." -"Locality is too long.","Locality is too long." -"Postal code can only contain letters, numbers, spaces, and hyphens.","Postal code can only contain letters, numbers, spaces, and hyphens." -"Postal code is required.","Postal code is required." -"Postal code may contain no more than 9 letter or number characters.","Postal code may contain no more than 9 letter or number characters." -"Region is too long.","Region is too long." -"Street address is required.","Street address is required." -"Street address is too long.","Street address is too long." -"US state codes must be two characters to meet PayPal Seller Protection requirements.","US state codes must be two characters to meet PayPal Seller Protection requirements." -"Country name is not an accepted country.","Country name is not an accepted country." -"Provided country information is inconsistent.","Provided country information is inconsistent." -"Country code is not accepted. Please contact the store administrator.","Country code is not accepted. Please contact the store administrator." -"Customer has already reached the maximum of 50 addresses.","Customer has already reached the maximum of 50 addresses." -"Address is invalid. Please contact the store administrator.","Address is invalid. Please contact the store administrator." -"Address is invalid.","Address is invalid." -"Billing address format is invalid.","Billing address format is invalid." -"Cardholder name is too long.","Cardholder name is too long." -"Credit card type is not accepted by this merchant account.","Credit card type is not accepted by this merchant account." -"CVV is required.","CVV is required." -"CVV must be 4 digits for American Express and 3 digits for other card types.","CVV must be 4 digits for American Express and 3 digits for other card types." -"Expiration date is required.","Expiration date is required." -"Expiration date is invalid.","Expiration date is invalid." -"Expiration year is invalid. It must be between 1975 and 2201.","Expiration year is invalid. It must be between 1975 and 2201." -"Expiration month is invalid.","Expiration month is invalid." -"Expiration year is invalid.","Expiration year is invalid." -"Credit card number is required.","Credit card number is required." -"Credit card number is invalid.","Credit card number is invalid." -"Credit card number must be 12-19 digits.","Credit card number must be 12-19 digits." -"CVV verification failed.","CVV verification failed." -"Postal code verification failed.","Postal code verification failed." -"Credit card number is prohibited.","Credit card number is prohibited." -"Incomplete PayPal account information.","Incomplete PayPal account information." -"Invalid PayPal account information.","Invalid PayPal account information." -"PayPal Accounts are not accepted by this merchant account.","PayPal Accounts are not accepted by this merchant account." -"Error communicating with PayPal.","Error communicating with PayPal." -"PayPal authentication expired.","PayPal authentication expired." -"Error executing PayPal order.","Error executing PayPal order." -"Error executing PayPal billing agreement.","Error executing PayPal billing agreement." -"Cannot provide a billing address unless also providing a credit card.","Cannot provide a billing address unless also providing a credit card." -"Transaction can only be voided if status is authorized, submitted_for_settlement, or - for PayPal - settlement_pending.","Transaction can only be voided if status is authorized, submitted_for_settlement, or - for PayPal - settlement_pending." -"Credit transactions cannot be refunded.","Credit transactions cannot be refunded." -"Cannot refund a transaction unless it is settled.","Cannot refund a transaction unless it is settled." -"Cannot submit for settlement unless status is authorized.","Cannot submit for settlement unless status is authorized." -"Customer does not have any credit cards.","Customer does not have any credit cards." -"Transaction has already been completely refunded.","Transaction has already been completely refunded." -"Payment instrument type is not accepted by this merchant account.","Payment instrument type is not accepted by this merchant account." -"Processor authorization code cannot be set unless for a voice authorization.","Processor authorization code cannot be set unless for a voice authorization." -"Refund amount is too large.","Refund amount is too large." -"Settlement amount is too large.","Settlement amount is too large." -"Cannot refund a transaction with a suspended merchant account.","Cannot refund a transaction with a suspended merchant account." -"Merchant account does not support refunds.","Merchant account does not support refunds." -"PayPal is not enabled for your merchant account.","PayPal is not enabled for your merchant account." -"Cannot refund a transaction transaction in settling status on this merchant account. Try again after the transaction has settled.","Cannot refund a transaction transaction in settling status on this merchant account. Try again after the transaction has settled." -"Cannot submit for partial settlement.","Cannot submit for partial settlement." -"Partial settlements are not supported by this processor.","Partial settlements are not supported by this processor." -"Transaction can not be voided if status of a PayPal partial settlement child transaction is settlement_pending.","Transaction can not be voided if status of a PayPal partial settlement child transaction is settlement_pending." -"Too many concurrent attempts to refund this transaction. Try again later.","Too many concurrent attempts to refund this transaction. Try again later." -"Too many concurrent attempts to void this transaction. Try again later.","Too many concurrent attempts to void this transaction. Try again later." -"Braintree Settlement","Braintree Settlement" -"The Payment Token is not available to perform the request.","The Payment Token is not available to perform the request." -"The order #%1 cannot be processed.","The order #%1 cannot be processed." diff --git a/app/code/Magento/Braintree/registration.php b/app/code/Magento/Braintree/registration.php deleted file mode 100644 index 1a0d00ec6557d..0000000000000 --- a/app/code/Magento/Braintree/registration.php +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - diff --git a/app/code/Magento/Braintree/view/adminhtml/layout/braintree_report_index.xml b/app/code/Magento/Braintree/view/adminhtml/layout/braintree_report_index.xml deleted file mode 100644 index fef51cff62fc5..0000000000000 --- a/app/code/Magento/Braintree/view/adminhtml/layout/braintree_report_index.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - Apply filters in order to get results. Only first 100 records will be displayed in the grid, you will be able to download full version of the report in .csv format. - - - - - - - - diff --git a/app/code/Magento/Braintree/view/adminhtml/layout/sales_order_create_index.xml b/app/code/Magento/Braintree/view/adminhtml/layout/sales_order_create_index.xml deleted file mode 100644 index 5394f0b7370a6..0000000000000 --- a/app/code/Magento/Braintree/view/adminhtml/layout/sales_order_create_index.xml +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - braintree - Magento_Braintree::form/cc.phtml - - - - - braintree_cc_vault - Magento_Vault::form/vault.phtml - - - braintree_paypal_vault - Magento_Vault::form/vault.phtml - - - - - - - diff --git a/app/code/Magento/Braintree/view/adminhtml/layout/sales_order_create_load_block_billing_method.xml b/app/code/Magento/Braintree/view/adminhtml/layout/sales_order_create_load_block_billing_method.xml deleted file mode 100644 index ca1b1980d0365..0000000000000 --- a/app/code/Magento/Braintree/view/adminhtml/layout/sales_order_create_load_block_billing_method.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - braintree - Magento_Braintree::form/cc.phtml - - - - - braintree_cc_vault - Magento_Vault::form/vault.phtml - - - braintree_paypal_vault - Magento_Vault::form/vault.phtml - - - - diff --git a/app/code/Magento/Braintree/view/adminhtml/templates/form/cc.phtml b/app/code/Magento/Braintree/view/adminhtml/templates/form/cc.phtml deleted file mode 100644 index 0d2599ff45f25..0000000000000 --- a/app/code/Magento/Braintree/view/adminhtml/templates/form/cc.phtml +++ /dev/null @@ -1,93 +0,0 @@ -escapeHtml($block->getMethodCode()); -$ccType = $block->getInfoData('cc_type'); -?> - diff --git a/app/code/Magento/Braintree/view/adminhtml/templates/form/paypal/vault.phtml b/app/code/Magento/Braintree/view/adminhtml/templates/form/paypal/vault.phtml deleted file mode 100644 index 132f053d3bf89..0000000000000 --- a/app/code/Magento/Braintree/view/adminhtml/templates/form/paypal/vault.phtml +++ /dev/null @@ -1,30 +0,0 @@ -getData(TokenUiComponentProviderInterface::COMPONENT_DETAILS); -$icon = $details['icon']; -$id = $block->escapeHtml($block->getData('id')); -?> -
", - "nonceUrl": "escapeUrl($block->getData('nonceUrl')) ?>" - } - }' id="payment_" class="admin__field"> -
- - - escapeHtml($details['payerEmail']) ?> -
-
diff --git a/app/code/Magento/Braintree/view/adminhtml/templates/form/vault.phtml b/app/code/Magento/Braintree/view/adminhtml/templates/form/vault.phtml deleted file mode 100644 index 49ce2cc7c065c..0000000000000 --- a/app/code/Magento/Braintree/view/adminhtml/templates/form/vault.phtml +++ /dev/null @@ -1,33 +0,0 @@ -getData(TokenUiComponentProviderInterface::COMPONENT_DETAILS); -$icon = $block->getData('icons')[$details['type']]; -$id = $block->escapeHtml($block->getData('id')); -?> -
", - "nonceUrl": "escapeUrl($block->getData('nonceUrl')) ?>" - } - }' id="payment_" class="admin__field"> -
- - - escapeHtml(__('ending')) ?> - escapeHtml($details['maskedCC']) ?> - (escapeHtml(__('expires')) ?>: - escapeHtml($details['expirationDate']) ?>) -
-
diff --git a/app/code/Magento/Braintree/view/adminhtml/templates/grid/tooltip.phtml b/app/code/Magento/Braintree/view/adminhtml/templates/grid/tooltip.phtml deleted file mode 100644 index 1a852222b8b3d..0000000000000 --- a/app/code/Magento/Braintree/view/adminhtml/templates/grid/tooltip.phtml +++ /dev/null @@ -1,11 +0,0 @@ - -escapeHtml($block->getData('tooltip_content')); diff --git a/app/code/Magento/Braintree/view/adminhtml/templates/payment/script.phtml b/app/code/Magento/Braintree/view/adminhtml/templates/payment/script.phtml deleted file mode 100644 index 1b188b68948bf..0000000000000 --- a/app/code/Magento/Braintree/view/adminhtml/templates/payment/script.phtml +++ /dev/null @@ -1,28 +0,0 @@ -escapeHtml($block->getCode()); - -?> - diff --git a/app/code/Magento/Braintree/view/adminhtml/ui_component/braintree_report.xml b/app/code/Magento/Braintree/view/adminhtml/ui_component/braintree_report.xml deleted file mode 100644 index f039fe51a4ee0..0000000000000 --- a/app/code/Magento/Braintree/view/adminhtml/ui_component/braintree_report.xml +++ /dev/null @@ -1,244 +0,0 @@ - - -- - - braintree_report.braintree_report_data_source - - - - braintree_report_columns - - braintree_report.braintree_report_data_source - - - - - - Magento_Braintree/js/grid/provider - - - - - - Magento_Braintree::settlement_report - - - id - page_id - - - - - - - - - localStorage - - - - - - - - - braintree_report.braintree_report.braintree_report_columns - - - - - - - - filters - - - braintree_report.braintree_report.listing_top.bookmarks:current.columns.${ $.index }.visible - - braintree_report.braintree_report.listing_top.listing_filters - - - current.filters - braintree_report.braintree_report.listing_top.bookmarks - - - - - -
- - status - - componentType = column, index = ${ $.index }:visible - - - - - - - - - type - - componentType = column, index = ${ $.index }:visible - - - - - - - - - paymentInstrumentType - - componentType = column, index = ${ $.index }:visible - - - - - - - paypalDetails_paymentId - - - - - - braintree_report.braintree_report.listing_top.listing_filters - - - - date - - createdAt - - componentType = column, index = ${ $.index }:visible - - - - - - - - - - braintree_report.braintree_report.listing_top.bookmarks - columns.${ $.index } - current.${ $.storageConfig.root} - - true - - braintree_report.braintree_report.braintree_report_columns_editor - startEdit - - ${ $.$data.rowIndex } - true - - - - - current - braintree_report.braintree_report.listing_top.bookmarks - - - - - id - - - - - text - text - - - - - - text - text - - - - - - text - text - - - - - - text - - - - - - text - - - - - - date - - desc - - - - - textRange - - - - - - text - - - - - - text - - - - - - text - - - - - - text - - - - - - text - - - - - - text - - - - - - text - - - - - diff --git a/app/code/Magento/Braintree/view/adminhtml/web/images/braintree_allinone.png b/app/code/Magento/Braintree/view/adminhtml/web/images/braintree_allinone.png deleted file mode 100644 index 377490cc51123..0000000000000 Binary files a/app/code/Magento/Braintree/view/adminhtml/web/images/braintree_allinone.png and /dev/null differ diff --git a/app/code/Magento/Braintree/view/adminhtml/web/images/braintree_logo.png b/app/code/Magento/Braintree/view/adminhtml/web/images/braintree_logo.png deleted file mode 100644 index 791fe3f3391c0..0000000000000 Binary files a/app/code/Magento/Braintree/view/adminhtml/web/images/braintree_logo.png and /dev/null differ diff --git a/app/code/Magento/Braintree/view/adminhtml/web/js/braintree.js b/app/code/Magento/Braintree/view/adminhtml/web/js/braintree.js deleted file mode 100644 index 393b07fc30403..0000000000000 --- a/app/code/Magento/Braintree/view/adminhtml/web/js/braintree.js +++ /dev/null @@ -1,393 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -/*browser:true*/ -/*global define*/ -define([ - 'jquery', - 'uiComponent', - 'Magento_Ui/js/modal/alert', - 'Magento_Ui/js/lib/view/utils/dom-observer', - 'mage/translate', - 'Magento_Braintree/js/validator' -], function ($, Class, alert, domObserver, $t, validator) { - 'use strict'; - - return Class.extend({ - - defaults: { - $selector: null, - selector: 'edit_form', - container: 'payment_form_braintree', - active: false, - scriptLoaded: false, - braintreeClient: null, - braintreeHostedFields: null, - hostedFieldsInstance: null, - selectedCardType: null, - selectorsMapper: { - 'expirationMonth': 'expirationMonth', - 'expirationYear': 'expirationYear', - 'number': 'cc_number', - 'cvv': 'cc_cid' - }, - imports: { - onActiveChange: 'active' - } - }, - - /** - * Set list of observable attributes - * @returns {exports.initObservable} - */ - initObservable: function () { - var self = this; - - validator.setConfig(this); - - self.$selector = $('#' + self.selector); - this._super() - .observe([ - 'active', - 'scriptLoaded', - 'selectedCardType' - ]); - - // re-init payment method events - self.$selector.off('changePaymentMethod.' + this.code) - .on('changePaymentMethod.' + this.code, this.changePaymentMethod.bind(this)); - - // listen block changes - domObserver.get('#' + self.container, function () { - if (self.scriptLoaded()) { - self.$selector.off('submit'); - self.initBraintree(); - } - }); - - return this; - }, - - /** - * Enable/disable current payment method - * @param {Object} event - * @param {String} method - * @returns {exports.changePaymentMethod} - */ - changePaymentMethod: function (event, method) { - this.active(method === this.code); - - return this; - }, - - /** - * Triggered when payment changed - * @param {Boolean} isActive - */ - onActiveChange: function (isActive) { - if (!isActive) { - this.$selector.off('submitOrder.braintree'); - - return; - } - this.disableEventListeners(); - window.order.addExcludedPaymentMethod(this.code); - - if (!this.clientToken) { - this.error($.mage.__('This payment is not available')); - - return; - } - - this.enableEventListeners(); - - if (!this.scriptLoaded()) { - this.loadScript(); - } - }, - - /** - * Load external Braintree SDK - */ - loadScript: function () { - var self = this, - state = self.scriptLoaded; - - $('body').trigger('processStart'); - require([this.sdkUrl, this.hostedFieldsSdkUrl], function (client, hostedFields) { - state(true); - self.braintreeClient = client; - self.braintreeHostedFields = hostedFields; - self.initBraintree(); - $('body').trigger('processStop'); - }); - }, - - /** - * Retrieves client token and setup Braintree SDK - */ - initBraintree: function () { - var self = this; - - try { - $('body').trigger('processStart'); - - $.getJSON(self.clientTokenUrl).done(function (response) { - self.clientToken = response.clientToken; - self._initBraintree(); - }).fail(function (response) { - var failed = JSON.parse(response.responseText); - - $('body').trigger('processStop'); - self.error(failed.message); - }); - } catch (e) { - $('body').trigger('processStop'); - self.error(e.message); - } - }, - - /** - * Setup Braintree SDK - */ - _initBraintree: function () { - var self = this; - - self.disableEventListeners(); - - self.braintreeClient.create({ - authorization: self.clientToken - }) - .then(function (clientInstance) { - return self.braintreeHostedFields.create({ - client: clientInstance, - fields: self.getHostedFields() - }); - }) - .then(function (hostedFieldsInstance) { - self.hostedFieldsInstance = hostedFieldsInstance; - self.enableEventListeners(); - self.fieldEventHandler(hostedFieldsInstance); - $('body').trigger('processStop'); - }) - .catch(function () { - self.error($t('Braintree can\'t be initialized.')); - }); - }, - - /** - * Get hosted fields configuration - * @returns {Object} - */ - getHostedFields: function () { - var self = this, - fields = { - number: { - selector: self.getSelector('cc_number') - }, - expirationMonth: { - selector: self.getSelector('cc_exp_month'), - placeholder: $t('MM') - }, - expirationYear: { - selector: self.getSelector('cc_exp_year'), - placeholder: $t('YY') - } - }; - - if (self.useCvv) { - fields.cvv = { - selector: self.getSelector('cc_cid') - }; - } - - return fields; - }, - - /** - * Function to handle hosted fields events - * @param {Object} hostedFieldsInstance - */ - fieldEventHandler: function (hostedFieldsInstance) { - var self = this, - $cardType = $('#' + self.container).find('.icon-type'); - - hostedFieldsInstance.on('empty', function (event) { - if (event.emittedBy === 'number') { - $cardType.attr('class', 'icon-type'); - self.selectedCardType(null); - } - - }); - - hostedFieldsInstance.on('validityChange', function (event) { - var field = event.fields[event.emittedBy], - fieldKey = event.emittedBy; - - if (fieldKey === 'number') { - $cardType.addClass('icon-type-' + event.cards[0].type); - } - - if (fieldKey in self.selectorsMapper && field.isValid === false) { - self.addInvalidClass(self.selectorsMapper[fieldKey]); - } - }); - - hostedFieldsInstance.on('blur', function (event) { - if (event.emittedBy === 'number') { - self.validateCardType(); - } - }); - - hostedFieldsInstance.on('cardTypeChange', function (event) { - if (event.cards.length !== 1) { - return; - } - - $cardType.addClass('icon-type-' + event.cards[0].type); - self.selectedCardType( - validator.getMageCardType(event.cards[0].type, self.getCcAvailableTypes()) - ); - }); - }, - - /** - * Show alert message - * @param {String} message - */ - error: function (message) { - alert({ - content: message - }); - }, - - /** - * Enable form event listeners - */ - enableEventListeners: function () { - this.$selector.on('submitOrder.braintree', this.submitOrder.bind(this)); - }, - - /** - * Disable form event listeners - */ - disableEventListeners: function () { - this.$selector.off('submitOrder'); - this.$selector.off('submit'); - }, - - /** - * Store payment details - * @param {String} nonce - */ - setPaymentDetails: function (nonce) { - var $container = $('#' + this.container); - - $container.find('[name="payment[payment_method_nonce]"]').val(nonce); - }, - - /** - * Trigger order submit - */ - submitOrder: function () { - var self = this; - - self.$selector.validate().form(); - self.$selector.trigger('afterValidate.beforeSubmit'); - - // validate parent form - if (self.$selector.validate().errorList.length) { - $('body').trigger('processStop'); - - return false; - } - - if (!self.validateCardType()) { - return false; - } - - self.hostedFieldsInstance.tokenize(function (err, payload) { - if (err) { - $('body').trigger('processStop'); - self.error($t('Some payment input fields are invalid.')); - - return false; - } - - self.setPaymentDetails(payload.nonce); - $('#' + self.container).find('[type="submit"]').trigger('click'); - }); - }, - - /** - * Place order - */ - placeOrder: function () { - $('#' + this.selector).trigger('realOrder'); - }, - - /** - * Get list of currently available card types - * @returns {Array} - */ - getCcAvailableTypes: function () { - var types = [], - $options = $(this.getSelector('cc_type')).find('option'); - - $.map($options, function (option) { - types.push($(option).val()); - }); - - return types; - }, - - /** - * Validate current entered card type - * @returns {Boolean} - */ - validateCardType: function () { - this.removeInvalidClass('cc_number'); - - if (!this.selectedCardType()) { - this.addInvalidClass('cc_number'); - - return false; - } - $(this.getSelector('cc_type')).val(this.selectedCardType()); - - return true; - }, - - /** - * Get jQuery selector - * @param {String} field - * @returns {String} - */ - getSelector: function (field) { - return '#' + this.code + '_' + field; - }, - - /** - * Add invalid class to field. - * - * @param {String} field - * @returns void - * @private - */ - addInvalidClass: function (field) { - $(this.getSelector(field)).addClass('braintree-hosted-fields-invalid'); - }, - - /** - * Remove invalid class from field. - * - * @param {String} field - * @returns void - * @private - */ - removeInvalidClass: function (field) { - $(this.getSelector(field)).removeClass('braintree-hosted-fields-invalid'); - } - }); -}); diff --git a/app/code/Magento/Braintree/view/adminhtml/web/js/grid/filters/status.html b/app/code/Magento/Braintree/view/adminhtml/web/js/grid/filters/status.html deleted file mode 100644 index 63fa308beee48..0000000000000 --- a/app/code/Magento/Braintree/view/adminhtml/web/js/grid/filters/status.html +++ /dev/null @@ -1,10 +0,0 @@ - - -
diff --git a/app/code/Magento/Braintree/view/adminhtml/web/js/grid/provider.js b/app/code/Magento/Braintree/view/adminhtml/web/js/grid/provider.js deleted file mode 100644 index 373b01d5eaa7e..0000000000000 --- a/app/code/Magento/Braintree/view/adminhtml/web/js/grid/provider.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -define([ - 'underscore', - 'Magento_Ui/js/grid/provider' -], function (_, Provider) { - 'use strict'; - - return Provider.extend({ - - /** - * Reload grid - * @returns {exports} - */ - reload: function () { - if (this.hasFilters()) { - this._super(); - - return this; - } - - this.trigger('reload'); - - this.onReload({ - items: [], - totalRecords: 0 - }); - - return this; - }, - - /** - * Has filters checker - * @returns {Boolean} - */ - hasFilters: function () { - var params = this.params, - filters = params.filters || {}; - - return _.keys(filters).length > 1; - } - }); -}); diff --git a/app/code/Magento/Braintree/view/adminhtml/web/js/vault.js b/app/code/Magento/Braintree/view/adminhtml/web/js/vault.js deleted file mode 100644 index a1a1c81d27c3d..0000000000000 --- a/app/code/Magento/Braintree/view/adminhtml/web/js/vault.js +++ /dev/null @@ -1,175 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -/*browser:true*/ -/*global define*/ -define([ - 'jquery', - 'uiComponent', - 'Magento_Ui/js/modal/alert' -], function ($, Class, alert) { - 'use strict'; - - return Class.extend({ - defaults: { - $selector: null, - selector: 'edit_form', - $container: null - }, - - /** - * Set list of observable attributes - * @returns {exports.initObservable} - */ - initObservable: function () { - var self = this; - - self.$selector = $('#' + self.selector); - self.$container = $('#' + self.container); - self.$selector.on( - 'setVaultNotActive.' + self.getCode(), - function () { - self.$selector.off('submitOrder.' + self.getCode()); - } - ); - self._super(); - - self.initEventHandlers(); - - return self; - }, - - /** - * Get payment code - * @returns {String} - */ - getCode: function () { - return this.code; - }, - - /** - * Init event handlers - */ - initEventHandlers: function () { - $(this.$container).find('[name="payment[token_switcher]"]') - .on('click', this.selectPaymentMethod.bind(this)); - }, - - /** - * Select current payment token - */ - selectPaymentMethod: function () { - this.disableEventListeners(); - this.enableEventListeners(); - }, - - /** - * Enable form event listeners - */ - enableEventListeners: function () { - this.$selector.on('submitOrder.' + this.getCode(), this.submitOrder.bind(this)); - }, - - /** - * Disable form event listeners - */ - disableEventListeners: function () { - this.$selector.off('submitOrder'); - }, - - /** - * Pre submit for order - * @returns {Boolean} - */ - submitOrder: function () { - this.$selector.validate().form(); - this.$selector.trigger('afterValidate.beforeSubmit'); - $('body').trigger('processStop'); - - // validate parent form - if (this.$selector.validate().errorList.length) { - return false; - } - this.getPaymentMethodNonce(); - }, - - /** - * Place order - */ - placeOrder: function () { - this.$selector.trigger('realOrder'); - }, - - /** - * Send request to get payment method nonce - */ - getPaymentMethodNonce: function () { - var self = this; - - $('body').trigger('processStart'); - - $.getJSON(self.nonceUrl, { - 'public_hash': self.publicHash - }).done(function (response) { - self.setPaymentDetails(response.paymentMethodNonce); - self.placeOrder(); - }).fail(function (response) { - var failed = JSON.parse(response.responseText); - - self.error(failed.message); - }).always(function () { - $('body').trigger('processStop'); - }); - }, - - /** - * Store payment details - * @param {String} nonce - */ - setPaymentDetails: function (nonce) { - this.createPublicHashSelector(); - - this.$selector.find('[name="payment[public_hash]"]').val(this.publicHash); - this.$container.find('#' + this.getNonceSelectorName()).val(nonce); - }, - - /** - * Creates public hash selector - */ - createPublicHashSelector: function () { - var $input; - - if (this.$container.find('#' + this.getNonceSelectorName()).size() === 0) { - $input = $('').attr( - { - type: 'hidden', - id: this.getNonceSelectorName(), - name: 'payment[payment_method_nonce]' - } - ); - - $input.appendTo(this.$container); - $input.prop('disabled', false); - } - }, - - /** - * Show alert message - * @param {String} message - */ - error: function (message) { - alert({ - content: message - }); - }, - - /** - * Get selector name for nonce input - * @returns {String} - */ - getNonceSelectorName: function () { - return 'nonce_' + this.getCode(); - } - }); -}); diff --git a/app/code/Magento/Braintree/view/adminhtml/web/styles.css b/app/code/Magento/Braintree/view/adminhtml/web/styles.css deleted file mode 100644 index 3c9daaaee72f7..0000000000000 --- a/app/code/Magento/Braintree/view/adminhtml/web/styles.css +++ /dev/null @@ -1,8 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -.braintree-section .heading {background: url("images/braintree_logo.png") no-repeat 0 50% / 18rem auto; padding-left: 20rem;} -.braintree-section .button-container {float: right;} -.braintree-section .config-alt {background: url("images/braintree_allinone.png") no-repeat scroll 0 0 / 100% auto; height: 28px; margin: 0.5rem 0 0; width: 230px;} diff --git a/app/code/Magento/Braintree/view/base/web/images/paypal-small.png b/app/code/Magento/Braintree/view/base/web/images/paypal-small.png deleted file mode 100644 index 912cd1fb20cb1..0000000000000 Binary files a/app/code/Magento/Braintree/view/base/web/images/paypal-small.png and /dev/null differ diff --git a/app/code/Magento/Braintree/view/base/web/images/paypal.png b/app/code/Magento/Braintree/view/base/web/images/paypal.png deleted file mode 100644 index 2da695608d4b7..0000000000000 Binary files a/app/code/Magento/Braintree/view/base/web/images/paypal.png and /dev/null differ diff --git a/app/code/Magento/Braintree/view/base/web/js/validator.js b/app/code/Magento/Braintree/view/base/web/js/validator.js deleted file mode 100644 index d4ba1ec86bbb5..0000000000000 --- a/app/code/Magento/Braintree/view/base/web/js/validator.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -/*browser:true*/ -/*global define*/ -define([ - 'underscore' -], function (_) { - 'use strict'; - - return { - config: {}, - - /** - * Set configuration - * @param {Object} config - */ - setConfig: function (config) { - this.config = config; - }, - - /** - * Get List of available card types - * @returns {*|exports.defaults.availableCardTypes|{}} - */ - getAvailableCardTypes: function () { - return this.config.availableCardTypes; - }, - - /** - * Get list of card types - * @returns {Object} - */ - getCcTypesMapper: function () { - return this.config.ccTypesMapper; - }, - - /** - * Find mage card type by Braintree type - * @param {String} type - * @param {Object} availableTypes - * @returns {*} - */ - getMageCardType: function (type, availableTypes) { - var storedCardType = null, - mapper = this.getCcTypesMapper(); - - if (type && typeof mapper[type] !== 'undefined') { - storedCardType = mapper[type]; - - if (_.indexOf(availableTypes, storedCardType) !== -1) { - return storedCardType; - } - } - - return null; - }, - - /** - * Filter list of available card types - * @param {Object} availableTypes - * @param {Object} countrySpecificCardTypes - * @returns {Object} - */ - collectTypes: function (availableTypes, countrySpecificCardTypes) { - var key, - filteredTypes = []; - - for (key in availableTypes) { - if (_.indexOf(countrySpecificCardTypes, availableTypes[key]) !== -1) { - filteredTypes.push(availableTypes[key]); - } - } - - return filteredTypes; - }, - - /** - * Get list of card types for country - * @param {String} countryId - * @returns {*} - */ - getCountrySpecificCardTypes: function (countryId) { - if (typeof this.config.countrySpecificCardTypes[countryId] !== 'undefined') { - return this.config.countrySpecificCardTypes[countryId]; - } - - return false; - } - }; -}); diff --git a/app/code/Magento/Braintree/view/frontend/layout/braintree_paypal_review.xml b/app/code/Magento/Braintree/view/frontend/layout/braintree_paypal_review.xml deleted file mode 100644 index cc9fb25cd8a7b..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/layout/braintree_paypal_review.xml +++ /dev/null @@ -1,36 +0,0 @@ - - - - - Review Order - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/code/Magento/Braintree/view/frontend/layout/checkout_index_index.xml b/app/code/Magento/Braintree/view/frontend/layout/checkout_index_index.xml deleted file mode 100644 index c4152e1c3ebf9..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/layout/checkout_index_index.xml +++ /dev/null @@ -1,58 +0,0 @@ - - - - - - - - - - - - - - - - - uiComponent - - - - - - - - Magento_Braintree/js/view/payment/braintree - - - true - - - false - - - true - - - - - - - - - - - - - - - - - - - diff --git a/app/code/Magento/Braintree/view/frontend/layout/multishipping_checkout_billing.xml b/app/code/Magento/Braintree/view/frontend/layout/multishipping_checkout_billing.xml deleted file mode 100644 index 06390d403e63d..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/layout/multishipping_checkout_billing.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - Magento_Braintree::multishipping/form.phtml - Magento_Braintree::multishipping/form_paypal.phtml - - - - - diff --git a/app/code/Magento/Braintree/view/frontend/layout/vault_cards_listaction.xml b/app/code/Magento/Braintree/view/frontend/layout/vault_cards_listaction.xml deleted file mode 100644 index 03e5324d4c869..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/layout/vault_cards_listaction.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - diff --git a/app/code/Magento/Braintree/view/frontend/requirejs-config.js b/app/code/Magento/Braintree/view/frontend/requirejs-config.js deleted file mode 100644 index 5c9bcd88de730..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/requirejs-config.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -var config = { - map: { - '*': { - braintreeClient: 'https://js.braintreegateway.com/web/3.48.0/js/client.min.js', - braintreeHostedFields: 'https://js.braintreegateway.com/web/3.48.0/js/hosted-fields.min.js', - braintreePayPal: 'https://js.braintreegateway.com/web/3.48.0/js/paypal-checkout.min.js', - braintree3DSecure: 'https://js.braintreegateway.com/web/3.48.0/js/three-d-secure.min.js', - braintreeDataCollector: 'https://js.braintreegateway.com/web/3.48.0/js/data-collector.min.js' - } - }, - paths: { - braintreePayPalCheckout: 'https://www.paypalobjects.com/api/checkout.min' - }, - shim: { - braintreePayPalCheckout: { - exports: 'paypal' - } - } -}; diff --git a/app/code/Magento/Braintree/view/frontend/templates/multishipping/form.phtml b/app/code/Magento/Braintree/view/frontend/templates/multishipping/form.phtml deleted file mode 100644 index fc3030b6a4b36..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/templates/multishipping/form.phtml +++ /dev/null @@ -1,29 +0,0 @@ - - - diff --git a/app/code/Magento/Braintree/view/frontend/templates/multishipping/form_paypal.phtml b/app/code/Magento/Braintree/view/frontend/templates/multishipping/form_paypal.phtml deleted file mode 100644 index ea3eb2214c2d8..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/templates/multishipping/form_paypal.phtml +++ /dev/null @@ -1,29 +0,0 @@ - - - diff --git a/app/code/Magento/Braintree/view/frontend/templates/paypal/button.phtml b/app/code/Magento/Braintree/view/frontend/templates/paypal/button.phtml deleted file mode 100644 index 19dfed0255085..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/templates/paypal/button.phtml +++ /dev/null @@ -1,29 +0,0 @@ -getContainerId() . random_int(0, PHP_INT_MAX); - -$config = [ - 'id' => $id, - 'clientToken' => $block->getClientToken(), - 'displayName' => $block->getMerchantName(), - 'actionSuccess' => $block->getActionSuccess(), - 'environment' => $block->getEnvironment() -]; -?> - diff --git a/app/code/Magento/Braintree/view/frontend/templates/paypal/button_shopping_cart.phtml b/app/code/Magento/Braintree/view/frontend/templates/paypal/button_shopping_cart.phtml deleted file mode 100644 index 913e1035b910f..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/templates/paypal/button_shopping_cart.phtml +++ /dev/null @@ -1,32 +0,0 @@ -getContainerId() . random_int(0, PHP_INT_MAX); - -$config = [ - 'Magento_Braintree/js/paypal/button_shopping_cart' => [ - 'id' => $id, - 'clientToken' => $block->getClientToken(), - 'displayName' => $block->getMerchantName(), - 'actionSuccess' => $block->getActionSuccess(), - 'environment' => $block->getEnvironment() - ] -]; - -?> - diff --git a/app/code/Magento/Braintree/view/frontend/templates/paypal/vault_token.phtml b/app/code/Magento/Braintree/view/frontend/templates/paypal/vault_token.phtml deleted file mode 100644 index e12ffddfe09e2..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/templates/paypal/vault_token.phtml +++ /dev/null @@ -1,48 +0,0 @@ -getPayerEmail(); -$confirmDeleteMessage = sprintf('%s: %s?', __('Are you sure you want to delete this PayPal account'), $payerEmail); -?> -
- - - diff --git a/app/code/Magento/Braintree/view/frontend/web/js/paypal/button.js b/app/code/Magento/Braintree/view/frontend/web/js/paypal/button.js deleted file mode 100644 index aacd3016d7367..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/js/paypal/button.js +++ /dev/null @@ -1,143 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -define( - [ - 'rjsResolver', - 'uiRegistry', - 'uiComponent', - 'underscore', - 'jquery', - 'braintreeClient', - 'braintreePayPal', - 'braintreePayPalCheckout', - 'Magento_Braintree/js/paypal/form-builder', - 'domReady!' - ], - function ( - resolver, - registry, - Component, - _, - $, - braintreeClient, - braintreePayPal, - braintreePayPalCheckout, - formBuilder - ) { - 'use strict'; - - return Component.extend({ - - defaults: { - displayName: null, - clientToken: null, - paypalCheckoutInstance: null - }, - - /** - * @returns {Object} - */ - initialize: function () { - var self = this; - - self._super(); - - braintreeClient.create({ - authorization: self.clientToken - }) - .then(function (clientInstance) { - return braintreePayPal.create({ - client: clientInstance - }); - }) - .then(function (paypalCheckoutInstance) { - self.paypalCheckoutInstance = paypalCheckoutInstance; - - return self.paypalCheckoutInstance; - }); - - self.initComponent(); - - return this; - }, - - /** - * @returns {Object} - */ - initComponent: function () { - var self = this, - selector = '#' + self.id, - $this = $(selector), - data = { - amount: $this.data('amount'), - locale: $this.data('locale'), - currency: $this.data('currency') - }; - - $this.html(''); - braintreePayPalCheckout.Button.render({ - env: self.environment, - style: { - color: 'blue', - shape: 'rect', - size: 'medium', - label: 'pay', - tagline: false - }, - - /** - * Payment setup - */ - payment: function () { - return self.paypalCheckoutInstance.createPayment(self.getClientConfig(data)); - }, - - /** - * Triggers on `onAuthorize` event - * - * @param {Object} response - */ - onAuthorize: function (response) { - return self.paypalCheckoutInstance.tokenizePayment(response) - .then(function (payload) { - $('body').trigger('processStart'); - - formBuilder.build( - { - action: self.actionSuccess, - fields: { - result: JSON.stringify(payload) - } - } - ).submit(); - }); - } - }, selector); - - return this; - }, - - /** - * @returns {Object} - * @private - */ - getClientConfig: function (data) { - var config = { - flow: 'checkout', - amount: data.amount, - currency: data.currency, - locale: data.locale, - enableShippingAddress: true - }; - - if (this.displayName) { - config.displayName = this.displayName; - } - - return config; - } - }); - } -); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/paypal/button_shopping_cart.js b/app/code/Magento/Braintree/view/frontend/web/js/paypal/button_shopping_cart.js deleted file mode 100644 index 9dd249998c152..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/js/paypal/button_shopping_cart.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -define( - [ - 'Magento_Braintree/js/paypal/button', - 'Magento_Checkout/js/model/quote', - 'domReady!' - ], - function ( - Component, - quote - ) { - 'use strict'; - - return Component.extend({ - - /** - * Overrides amount with a value from quote. - * - * @returns {Object} - * @private - */ - getClientConfig: function (data) { - var config = this._super(data); - - if (config.amount !== quote.totals()['base_grand_total']) { - config.amount = quote.totals()['base_grand_total']; - } - - return config; - } - }); - } -); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/paypal/form-builder.js b/app/code/Magento/Braintree/view/frontend/web/js/paypal/form-builder.js deleted file mode 100644 index 83bf770c81806..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/js/paypal/form-builder.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -define( - [ - 'jquery', - 'underscore', - 'mage/template' - ], - function ($, _, mageTemplate) { - 'use strict'; - - return { - - /** - * @param {Object} formData - * @returns {*|jQuery} - */ - build: function (formData) { - var formTmpl = mageTemplate('' + - '<% _.each(data.fields, function(val, key){ %>' + - '\' name="<%= key %>" type="hidden">' + - '<% }); %>' + - ''); - - return $(formTmpl({ - data: { - action: formData.action, - fields: formData.fields - } - })).appendTo($('[data-container="body"]')); - } - }; - } -); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/3d-secure.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/3d-secure.js deleted file mode 100644 index b66725c063414..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/3d-secure.js +++ /dev/null @@ -1,230 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -/*browser:true*/ -/*global define*/ - -define([ - 'jquery', - 'braintree3DSecure', - 'Magento_Braintree/js/view/payment/adapter', - 'Magento_Checkout/js/model/quote', - 'mage/translate', - 'Magento_Ui/js/modal/modal', - 'Magento_Checkout/js/model/full-screen-loader' -], function ( - $, - braintree3DSecure, - braintreeAdapter, - quote, - $t, - Modal, - fullScreenLoader -) { - 'use strict'; - - return { - config: null, - modal: null, - threeDSecureInstance: null, - state: null, - - /** - * Initializes component - */ - initialize: function () { - var self = this, - promise = $.Deferred(); - - self.state = $.Deferred(); - braintreeAdapter.getApiClient() - .then(function (clientInstance) { - return braintree3DSecure.create({ - version: 2, // Will use 3DS 2 whenever possible - client: clientInstance - }); - }) - .then(function (threeDSecureInstance) { - self.threeDSecureInstance = threeDSecureInstance; - promise.resolve(self.threeDSecureInstance); - }) - .catch(function (err) { - fullScreenLoader.stopLoader(); - promise.reject(err); - }); - - return promise.promise(); - }, - - /** - * Sets 3D Secure config - * - * @param {Object} config - */ - setConfig: function (config) { - this.config = config; - this.config.thresholdAmount = parseFloat(config.thresholdAmount); - }, - - /** - * Gets code - * - * @returns {String} - */ - getCode: function () { - return 'three_d_secure'; - }, - - /** - * Validates 3D Secure - * - * @param {Object} context - * @returns {Object} - */ - validate: function (context) { - var self = this, - totalAmount = quote.totals()['base_grand_total'], - billingAddress = quote.billingAddress(), - shippingAddress = quote.shippingAddress(), - options = { - amount: totalAmount, - nonce: context.paymentPayload.nonce, - billingAddress: { - givenName: billingAddress.firstname, - surname: billingAddress.lastname, - phoneNumber: billingAddress.telephone, - streetAddress: billingAddress.street[0], - extendedAddress: billingAddress.street[1], - locality: billingAddress.city, - region: billingAddress.regionCode, - postalCode: billingAddress.postcode, - countryCodeAlpha2: billingAddress.countryId - }, - - /** - * Will be called after receiving ThreeDSecure response, before completing the flow. - * - * @param {Object} data - ThreeDSecure data to consume before continuing - * @param {Function} next - callback to continue flow - */ - onLookupComplete: function (data, next) { - next(); - } - }; - - if (context.paymentPayload.details) { - options.bin = context.paymentPayload.details.bin; - } - - if (shippingAddress && this.isValidShippingAddress(shippingAddress)) { - options.additionalInformation = { - shippingGivenName: shippingAddress.firstname, - shippingSurname: shippingAddress.lastname, - shippingPhone: shippingAddress.telephone, - shippingAddress: { - streetAddress: shippingAddress.street[0], - extendedAddress: shippingAddress.street[1], - locality: shippingAddress.city, - region: shippingAddress.regionCode, - postalCode: shippingAddress.postcode, - countryCodeAlpha2: shippingAddress.countryId - } - }; - } - - if (!this.isAmountAvailable(totalAmount) || !this.isCountryAvailable(billingAddress.countryId)) { - self.state = $.Deferred(); - self.state.resolve(); - - return self.state.promise(); - } - - fullScreenLoader.startLoader(); - this.initialize() - .then(function () { - self.threeDSecureInstance.verifyCard(options, function (err, payload) { - if (err) { - fullScreenLoader.stopLoader(); - self.state.reject(err.message); - - return; - } - - // `liabilityShifted` indicates that 3DS worked and authentication succeeded - // if `liabilityShifted` and `liabilityShiftPossible` are false - card is ineligible for 3DS - if (payload.liabilityShifted || !payload.liabilityShifted && !payload.liabilityShiftPossible) { - context.paymentPayload.nonce = payload.nonce; - self.state.resolve(); - } else { - fullScreenLoader.stopLoader(); - self.state.reject($t('Please try again with another form of payment.')); - } - }); - }) - .fail(function () { - fullScreenLoader.stopLoader(); - self.state.reject($t('Please try again with another form of payment.')); - }); - - return self.state.promise(); - }, - - /** - * Checks minimal amount for 3D Secure activation - * - * @param {Number} amount - * @returns {Boolean} - * @private - */ - isAmountAvailable: function (amount) { - amount = parseFloat(amount); - - return amount >= this.config.thresholdAmount; - }, - - /** - * Checks if current country is available for 3D Secure - * - * @param {String} countryId - * @returns {Boolean} - * @private - */ - isCountryAvailable: function (countryId) { - var key, - specificCountries = this.config.specificCountries; - - // all countries are available - if (!specificCountries.length) { - return true; - } - - for (key in specificCountries) { - if (countryId === specificCountries[key]) { - return true; - } - } - - return false; - }, - - /** - * Validate shipping address - * - * @param {Object} shippingAddress - * @return {Boolean} - */ - isValidShippingAddress: function (shippingAddress) { - var isValid = false; - - // check that required fields are not empty - if (shippingAddress.firstname && shippingAddress.lastname && shippingAddress.telephone && - shippingAddress.street && shippingAddress.city && shippingAddress.regionCode && - shippingAddress.postcode && shippingAddress.countryId) { - isValid = true; - } - - return isValid; - } - }; -}); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/adapter.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/adapter.js deleted file mode 100644 index 9cd6aa688674e..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/adapter.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -/*browser:true*/ -/*global define*/ -define([ - 'jquery', - 'braintreeClient' -], function ($, braintreeClient) { - 'use strict'; - - return { - apiClient: null, - checkout: null, - code: 'braintree', - - /** - * Returns Braintree API client - * @returns {Object} - */ - getApiClient: function () { - return braintreeClient.create({ - authorization: this.getClientToken() - }); - }, - - /** - * Returns payment code - * - * @returns {String} - */ - getCode: function () { - return this.code; - }, - - /** - * Returns client token - * - * @returns {String} - * @private - */ - getClientToken: function () { - return window.checkoutConfig.payment[this.code].clientToken; - } - }; -}); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/braintree.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/braintree.js deleted file mode 100644 index 132fcd6b3b06c..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/braintree.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -/*browser:true*/ -/*global define*/ -define( - [ - 'uiComponent', - 'Magento_Checkout/js/model/payment/renderer-list' - ], - function ( - Component, - rendererList - ) { - 'use strict'; - - var config = window.checkoutConfig.payment, - braintreeType = 'braintree', - payPalType = 'braintree_paypal'; - - if (config[braintreeType].isActive) { - rendererList.push( - { - type: braintreeType, - component: 'Magento_Braintree/js/view/payment/method-renderer/cc-form' - } - ); - } - - if (config[payPalType].isActive) { - rendererList.push( - { - type: payPalType, - component: 'Magento_Braintree/js/view/payment/method-renderer/paypal' - } - ); - } - - /** Add view logic here if needed */ - return Component.extend({}); - } -); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/kount.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/kount.js deleted file mode 100644 index cd0d024387b8c..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/kount.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -/*browser:true*/ -/*global define*/ - -define([ - 'jquery', - 'braintreeDataCollector', - 'Magento_Braintree/js/view/payment/adapter' -], function ( - $, - braintreeDataCollector, - braintreeAdapter -) { - 'use strict'; - - return { - paymentCode: 'braintree', - - /** - * Returns information about a customer's device on checkout page for passing to Kount for review. - * - * @returns {Object} - */ - getDeviceData: function () { - var state = $.Deferred(); - - if (this.hasFraudProtection()) { - braintreeAdapter.getApiClient() - .then(function (clientInstance) { - return braintreeDataCollector.create({ - client: clientInstance, - kount: true - }); - }) - .then(function (dataCollectorInstance) { - var deviceData = dataCollectorInstance.deviceData; - - state.resolve(deviceData); - }) - .catch(function (err) { - state.reject(err); - }); - } - - return state.promise(); - }, - - /** - * Returns setting value. - * - * @returns {Boolean} - * @private - */ - hasFraudProtection: function () { - return window.checkoutConfig.payment[this.paymentCode].hasFraudProtection; - } - }; -}); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/cc-form.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/cc-form.js deleted file mode 100644 index 21809f186d252..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/cc-form.js +++ /dev/null @@ -1,427 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -/*browser:true*/ -/*global define*/ -define( - [ - 'underscore', - 'jquery', - 'Magento_Payment/js/view/payment/cc-form', - 'Magento_Braintree/js/view/payment/adapter', - 'braintreeHostedFields', - 'Magento_Checkout/js/model/quote', - 'Magento_Braintree/js/validator', - 'Magento_Ui/js/model/messageList', - 'Magento_Braintree/js/view/payment/validator-handler', - 'Magento_Vault/js/view/payment/vault-enabler', - 'Magento_Braintree/js/view/payment/kount', - 'mage/translate', - 'domReady!' - ], - function ( - _, - $, - Component, - braintreeAdapter, - hostedFields, - quote, - validator, - globalMessageList, - validatorManager, - VaultEnabler, - kount, - $t - ) { - 'use strict'; - - return Component.extend({ - defaults: { - template: 'Magento_Braintree/payment/form', - active: false, - code: 'braintree', - lastBillingAddress: null, - hostedFieldsInstance: null, - selectorsMapper: { - 'expirationMonth': 'expirationMonth', - 'expirationYear': 'expirationYear', - 'number': 'cc_number', - 'cvv': 'cc_cid' - }, - paymentPayload: { - nonce: null - }, - additionalData: {} - }, - - /** - * @returns {exports.initialize} - */ - initialize: function () { - var self = this; - - self._super(); - self.vaultEnabler = new VaultEnabler(); - self.vaultEnabler.setPaymentCode(self.getVaultCode()); - - kount.getDeviceData() - .then(function (deviceData) { - self.additionalData['device_data'] = deviceData; - }); - - return self; - }, - - /** - * Init hosted fields. - * - * Is called after knockout finishes input fields bindings. - */ - initHostedFields: function () { - var self = this; - - braintreeAdapter.getApiClient() - .then(function (clientInstance) { - - return hostedFields.create({ - client: clientInstance, - fields: self.getFieldsConfiguration() - }); - }) - .then(function (hostedFieldsInstance) { - self.hostedFieldsInstance = hostedFieldsInstance; - self.isPlaceOrderActionAllowed(false); - self.initFormValidationEvents(hostedFieldsInstance); - - return self.hostedFieldsInstance; - }) - .catch(function () { - self.showError($t('Payment ' + self.getTitle() + ' can\'t be initialized')); - }); - }, - - /** - * Set list of observable attributes - * - * @returns {exports.initObservable} - */ - initObservable: function () { - validator.setConfig(window.checkoutConfig.payment[this.getCode()]); - this._super() - .observe(['active']); - - return this; - }, - - /** - * Get payment name - * - * @returns {String} - */ - getCode: function () { - return this.code; - }, - - /** - * Check if payment is active - * - * @returns {Boolean} - */ - isActive: function () { - var active = this.getCode() === this.isChecked(); - - this.active(active); - - return active; - }, - - /** - * Get data - * - * @returns {Object} - */ - getData: function () { - var data = { - 'method': this.getCode(), - 'additional_data': { - 'payment_method_nonce': this.paymentPayload.nonce - } - }; - - data['additional_data'] = _.extend(data['additional_data'], this.additionalData); - this.vaultEnabler.visitAdditionalData(data); - - return data; - }, - - /** - * Get list of available CC types - * - * @returns {Object} - */ - getCcAvailableTypes: function () { - var availableTypes = validator.getAvailableCardTypes(), - billingAddress = quote.billingAddress(), - billingCountryId; - - this.lastBillingAddress = quote.shippingAddress(); - - if (!billingAddress) { - billingAddress = this.lastBillingAddress; - } - - billingCountryId = billingAddress.countryId; - - if (billingCountryId && validator.getCountrySpecificCardTypes(billingCountryId)) { - return validator.collectTypes( - availableTypes, - validator.getCountrySpecificCardTypes(billingCountryId) - ); - } - - return availableTypes; - }, - - /** - * @returns {Boolean} - */ - isVaultEnabled: function () { - return this.vaultEnabler.isVaultEnabled(); - }, - - /** - * Returns vault code. - * - * @returns {String} - */ - getVaultCode: function () { - return window.checkoutConfig.payment[this.getCode()].ccVaultCode; - }, - - /** - * Action to place order - * @param {String} key - */ - placeOrder: function (key) { - var self = this; - - if (key) { - return self._super(); - } - // place order on success validation - validatorManager.validate(self, function () { - return self.placeOrder('parent'); - }, function (err) { - - if (err) { - self.showError(err); - } - }); - - return false; - }, - - /** - * Returns state of place order button - * - * @returns {Boolean} - */ - isButtonActive: function () { - return this.isActive() && this.isPlaceOrderActionAllowed(); - }, - - /** - * Trigger order placing - */ - placeOrderClick: function () { - var self = this; - - if (this.isFormValid(this.hostedFieldsInstance)) { - self.hostedFieldsInstance.tokenize(function (err, payload) { - if (err) { - self.showError($t('Some payment input fields are invalid.')); - - return; - } - - if (self.validateCardType()) { - self.setPaymentPayload(payload); - self.placeOrder(); - } - }); - } - }, - - /** - * Validates credit card form. - * - * @param {Object} hostedFieldsInstance - * @returns {Boolean} - * @private - */ - isFormValid: function (hostedFieldsInstance) { - var self = this, - state = hostedFieldsInstance.getState(); - - return Object.keys(state.fields).every(function (fieldKey) { - if (fieldKey in self.selectorsMapper && state.fields[fieldKey].isValid === false) { - self.addInvalidClass(self.selectorsMapper[fieldKey]); - } - - return state.fields[fieldKey].isValid; - }); - }, - - /** - * Init form validation events. - * - * @param {Object} hostedFieldsInstance - * @private - */ - initFormValidationEvents: function (hostedFieldsInstance) { - var self = this; - - hostedFieldsInstance.on('empty', function (event) { - if (event.emittedBy === 'number') { - self.selectedCardType(null); - } - - }); - - hostedFieldsInstance.on('blur', function (event) { - if (event.emittedBy === 'number') { - self.validateCardType(); - } - }); - - hostedFieldsInstance.on('validityChange', function (event) { - var field = event.fields[event.emittedBy], - fieldKey = event.emittedBy; - - if (fieldKey === 'number') { - self.isValidCardNumber = field.isValid; - } - - if (fieldKey in self.selectorsMapper && field.isValid === false) { - self.addInvalidClass(self.selectorsMapper[fieldKey]); - } - }); - - hostedFieldsInstance.on('cardTypeChange', function (event) { - if (event.cards.length === 1) { - self.selectedCardType( - validator.getMageCardType(event.cards[0].type, self.getCcAvailableTypes()) - ); - } - }); - }, - - /** - * Get full selector name - * - * @param {String} field - * @returns {String} - * @private - */ - getSelector: function (field) { - return '#' + this.getCode() + '_' + field; - }, - - /** - * Add invalid class to field. - * - * @param {String} field - * @returns void - * @private - */ - addInvalidClass: function (field) { - $(this.getSelector(field)).addClass('braintree-hosted-fields-invalid'); - }, - - /** - * Remove invalid class from field. - * - * @param {String} field - * @returns void - * @private - */ - removeInvalidClass: function (field) { - $(this.getSelector(field)).removeClass('braintree-hosted-fields-invalid'); - }, - - /** - * Get Braintree Hosted Fields - * - * @returns {Object} - * @private - */ - getFieldsConfiguration: function () { - var self = this, - fields = { - number: { - selector: self.getSelector('cc_number') - }, - expirationMonth: { - selector: self.getSelector('expirationMonth'), - placeholder: $t('MM') - }, - expirationYear: { - selector: self.getSelector('expirationYear'), - placeholder: $t('YY') - } - }; - - if (self.hasVerification()) { - fields.cvv = { - selector: self.getSelector('cc_cid') - }; - } - - return fields; - }, - - /** - * Validate current credit card type. - * - * @returns {Boolean} - * @private - */ - validateCardType: function () { - var cardFieldName = 'cc_number'; - - this.removeInvalidClass(cardFieldName); - - if (this.selectedCardType() === null || !this.isValidCardNumber) { - this.addInvalidClass(cardFieldName); - - return false; - } - - return true; - }, - - /** - * Sets payment payload - * - * @param {Object} paymentPayload - * @private - */ - setPaymentPayload: function (paymentPayload) { - this.paymentPayload = paymentPayload; - }, - - /** - * Show error message - * - * @param {String} errorMessage - * @private - */ - showError: function (errorMessage) { - globalMessageList.addErrorMessage({ - message: errorMessage - }); - } - }); - } -); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/multishipping/cc-form.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/multishipping/cc-form.js deleted file mode 100644 index 868fe174ae482..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/multishipping/cc-form.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -/*browser:true*/ -/*global define*/ - -define([ - 'jquery', - 'Magento_Braintree/js/view/payment/method-renderer/cc-form', - 'Magento_Braintree/js/validator', - 'Magento_Ui/js/model/messageList', - 'mage/translate', - 'Magento_Checkout/js/model/full-screen-loader', - 'Magento_Checkout/js/action/set-payment-information-extended', - 'Magento_Checkout/js/model/payment/additional-validators', - 'Magento_Braintree/js/view/payment/validator-handler' -], function ( - $, - Component, - validator, - messageList, - $t, - fullScreenLoader, - setPaymentInformationExtended, - additionalValidators, - validatorManager -) { - 'use strict'; - - return Component.extend({ - defaults: { - template: 'Magento_Braintree/payment/multishipping/form' - }, - - /** - * @override - */ - placeOrder: function () { - var self = this; - - validatorManager.validate(self, function () { - return self.setPaymentInformation(); - }); - }, - - /** - * @override - */ - setPaymentInformation: function () { - if (additionalValidators.validate()) { - fullScreenLoader.startLoader(); - $.when( - setPaymentInformationExtended( - this.messageContainer, - this.getData(), - true - ) - ).done(this.done.bind(this)) - .fail(this.fail.bind(this)); - } - }, - - /** - * {Function} - */ - fail: function () { - fullScreenLoader.stopLoader(); - - return this; - }, - - /** - * {Function} - */ - done: function () { - fullScreenLoader.stopLoader(); - $('#multishipping-billing-form').submit(); - - return this; - } - }); -}); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/multishipping/paypal.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/multishipping/paypal.js deleted file mode 100644 index b3837103148cc..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/multishipping/paypal.js +++ /dev/null @@ -1,162 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -/*browser:true*/ -/*global define*/ -define([ - 'jquery', - 'underscore', - 'Magento_Braintree/js/view/payment/method-renderer/paypal', - 'Magento_Checkout/js/action/set-payment-information-extended', - 'Magento_Checkout/js/model/payment/additional-validators', - 'Magento_Checkout/js/model/full-screen-loader' -], function ( - $, - _, - Component, - setPaymentInformationExtended, - additionalValidators, - fullScreenLoader -) { - 'use strict'; - - return Component.extend({ - defaults: { - template: 'Magento_Braintree/payment/multishipping/paypal', - submitButtonSelector: '#payment-continue span', - paypalButtonSelector: '[id="parent-payment-continue"]', - reviewButtonHtml: '' - }, - - /** - * @override - */ - initObservable: function () { - this.reviewButtonHtml = $(this.paypalButtonSelector).html(); - - return this._super(); - }, - - /** - * Get configuration for PayPal. - * - * @returns {Object} - */ - getPayPalConfig: function () { - var config; - - config = this._super(); - config.flow = 'vault'; - config.enableShippingAddress = false; - config.shippingAddressEditable = false; - - return config; - }, - - /** - * @override - */ - onActiveChange: function (isActive) { - this._super(isActive); - this.updateSubmitButton(isActive); - }, - - /** - * @override - */ - beforePlaceOrder: function (data) { - this._super(data); - - this.updateSubmitButton(true); - }, - - /** - * @override - */ - getShippingAddress: function () { - return {}; - }, - - /** - * @override - */ - getData: function () { - var data = this._super(); - - data['additional_data']['is_active_payment_token_enabler'] = true; - - return data; - }, - - /** - * @override - */ - isActiveVault: function () { - return true; - }, - - /** - * Skipping order review step on checkout with multiple addresses is not allowed. - * - * @returns {Boolean} - */ - isSkipOrderReview: function () { - return false; - }, - - /** - * Checks if payment method nonce is already received. - * - * @returns {Boolean} - */ - isPaymentMethodNonceReceived: function () { - return this.paymentPayload.nonce !== null; - }, - - /** - * Updates submit button on multi-addresses checkout billing form. - * - * @param {Boolean} isActive - */ - updateSubmitButton: function (isActive) { - if (this.isPaymentMethodNonceReceived() || !isActive) { - $(this.paypalButtonSelector).html(this.reviewButtonHtml); - } - }, - - /** - * @override - */ - placeOrder: function () { - fullScreenLoader.startLoader(); - $.when( - setPaymentInformationExtended( - this.messageContainer, - this.getData(), - true - ) - ).done(this.done.bind(this)) - .fail(this.fail.bind(this)); - }, - - /** - * {Function} - */ - fail: function () { - fullScreenLoader.stopLoader(); - - return this; - }, - - /** - * {Function} - */ - done: function () { - fullScreenLoader.stopLoader(); - $('#multishipping-billing-form').submit(); - - return this; - } - }); -}); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/paypal-vault.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/paypal-vault.js deleted file mode 100644 index 933f20867168c..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/paypal-vault.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -/*browser:true*/ -/*global define*/ -define([ - 'jquery', - 'underscore', - 'Magento_Vault/js/view/payment/method-renderer/vault', - 'Magento_Ui/js/model/messageList', - 'Magento_Checkout/js/model/full-screen-loader' -], function ($, _, VaultComponent, globalMessageList, fullScreenLoader) { - 'use strict'; - - return VaultComponent.extend({ - defaults: { - template: 'Magento_Braintree/payment/paypal/vault', - additionalData: {} - }, - - /** - * Get PayPal payer email - * @returns {String} - */ - getPayerEmail: function () { - return this.details.payerEmail; - }, - - /** - * Get type of payment - * @returns {String} - */ - getPaymentIcon: function () { - return window.checkoutConfig.payment['braintree_paypal'].paymentIcon; - }, - - /** - * Place order - */ - beforePlaceOrder: function () { - this.getPaymentMethodNonce(); - }, - - /** - * Send request to get payment method nonce - */ - getPaymentMethodNonce: function () { - var self = this; - - fullScreenLoader.startLoader(); - $.getJSON(self.nonceUrl, { - 'public_hash': self.publicHash - }) - .done(function (response) { - fullScreenLoader.stopLoader(); - self.additionalData['payment_method_nonce'] = response.paymentMethodNonce; - self.placeOrder(); - }) - .fail(function (response) { - var error = JSON.parse(response.responseText); - - fullScreenLoader.stopLoader(); - globalMessageList.addErrorMessage({ - message: error.message - }); - }); - }, - - /** - * Get payment method data - * @returns {Object} - */ - getData: function () { - var data = { - 'method': this.code, - 'additional_data': { - 'public_hash': this.publicHash - } - }; - - data['additional_data'] = _.extend(data['additional_data'], this.additionalData); - - return data; - } - }); -}); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/paypal.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/paypal.js deleted file mode 100644 index c0ad38173c52d..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/paypal.js +++ /dev/null @@ -1,435 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -/*browser:true*/ -/*global define*/ -define([ - 'jquery', - 'underscore', - 'Magento_Checkout/js/view/payment/default', - 'Magento_Braintree/js/view/payment/adapter', - 'braintreePayPal', - 'braintreePayPalCheckout', - 'Magento_Checkout/js/model/quote', - 'Magento_Checkout/js/model/full-screen-loader', - 'Magento_Checkout/js/model/payment/additional-validators', - 'Magento_Vault/js/view/payment/vault-enabler', - 'Magento_Checkout/js/action/create-billing-address', - 'Magento_Braintree/js/view/payment/kount', - 'mage/translate', - 'Magento_Ui/js/model/messageList' -], function ( - $, - _, - Component, - BraintreeAdapter, - BraintreePayPal, - BraintreePayPalCheckout, - quote, - fullScreenLoader, - additionalValidators, - VaultEnabler, - createBillingAddress, - kount, - $t, - globalMessageList -) { - 'use strict'; - - return Component.extend({ - defaults: { - template: 'Magento_Braintree/payment/paypal', - code: 'braintree_paypal', - active: false, - grandTotalAmount: null, - isReviewRequired: false, - paypalCheckoutInstance: null, - customerEmail: null, - vaultEnabler: null, - paymentPayload: { - nonce: null - }, - paypalButtonSelector: '[data-container="paypal-button"]', - - /** - * Additional payment data - * - * {Object} - */ - additionalData: {}, - - imports: { - onActiveChange: 'active' - } - }, - - /** - * Initialize view. - * - * @return {exports} - */ - initialize: function () { - var self = this; - - self._super(); - - BraintreeAdapter.getApiClient().then(function (clientInstance) { - return BraintreePayPal.create({ - client: clientInstance - }); - }).then(function (paypalCheckoutInstance) { - self.paypalCheckoutInstance = paypalCheckoutInstance; - - return self.paypalCheckoutInstance; - }); - - kount.getDeviceData() - .then(function (deviceData) { - self.additionalData['device_data'] = deviceData; - }); - - // for each component initialization need update property - this.isReviewRequired(false); - - return self; - }, - - /** - * Set list of observable attributes - * @returns {exports.initObservable} - */ - initObservable: function () { - var self = this; - - this._super() - .observe(['active', 'isReviewRequired', 'customerEmail']); - - this.vaultEnabler = new VaultEnabler(); - this.vaultEnabler.setPaymentCode(this.getVaultCode()); - this.vaultEnabler.isActivePaymentTokenEnabler.subscribe(function () { - self.onVaultPaymentTokenEnablerChange(); - }); - - this.grandTotalAmount = quote.totals()['base_grand_total']; - - quote.totals.subscribe(function () { - if (self.grandTotalAmount !== quote.totals()['base_grand_total']) { - self.grandTotalAmount = quote.totals()['base_grand_total']; - } - }); - - quote.shippingAddress.subscribe(function () { - if (self.isActive()) { - self.reInitPayPal(); - } - }); - - return this; - }, - - /** - * Get payment name - * - * @returns {String} - */ - getCode: function () { - return this.code; - }, - - /** - * Get payment title - * - * @returns {String} - */ - getTitle: function () { - return window.checkoutConfig.payment[this.getCode()].title; - }, - - /** - * Check if payment is active - * - * @returns {Boolean} - */ - isActive: function () { - var active = this.getCode() === this.isChecked(); - - this.active(active); - - return active; - }, - - /** - * Triggers when payment method change - * @param {Boolean} isActive - */ - onActiveChange: function (isActive) { - if (!isActive) { - return; - } - - // need always re-init Braintree with PayPal configuration - this.reInitPayPal(); - }, - - /** - * Sets payment payload - * - * @param {Object} paymentPayload - * @private - */ - setPaymentPayload: function (paymentPayload) { - this.paymentPayload = paymentPayload; - }, - - /** - * Update quote billing address - * @param {Object}customer - * @param {Object}address - */ - setBillingAddress: function (customer, address) { - var billingAddress = { - street: [address.line1], - city: address.city, - postcode: address.postalCode, - countryId: address.countryCode, - email: customer.email, - firstname: customer.firstName, - lastname: customer.lastName, - telephone: customer.phone, - regionCode: address.state - }; - - billingAddress = createBillingAddress(billingAddress); - quote.billingAddress(billingAddress); - }, - - /** - * Prepare data to place order - * @param {Object} payload - */ - beforePlaceOrder: function (payload) { - this.setPaymentPayload(payload); - - if (this.isRequiredBillingAddress() || quote.billingAddress() === null) { - if (typeof payload.details.billingAddress !== 'undefined') { - this.setBillingAddress(payload.details, payload.details.billingAddress); - } else { - this.setBillingAddress(payload.details, payload.details.shippingAddress); - } - } - - if (this.isSkipOrderReview()) { - this.placeOrder(); - } else { - this.customerEmail(payload.details.email); - this.isReviewRequired(true); - } - }, - - /** - * Re-init PayPal Auth Flow - */ - reInitPayPal: function () { - var self = this; - - $(self.paypalButtonSelector).html(''); - - return BraintreePayPalCheckout.Button.render({ - env: this.getEnvironment(), - style: { - color: 'blue', - shape: 'rect', - size: 'medium', - label: 'pay', - tagline: false - }, - - /** - * Creates a PayPal payment - */ - payment: function () { - return self.paypalCheckoutInstance.createPayment( - self.getPayPalConfig() - ); - }, - - /** - * Tokenizes the authorize data - */ - onAuthorize: function (data) { - return self.paypalCheckoutInstance.tokenizePayment(data) - .then(function (payload) { - self.beforePlaceOrder(payload); - }); - }, - - /** - * Triggers on error - */ - onError: function () { - self.showError($t('Payment ' + self.getTitle() + ' can\'t be initialized')); - self.reInitPayPal(); - } - }, self.paypalButtonSelector); - }, - - /** - * Get locale - * @returns {String} - */ - getLocale: function () { - return window.checkoutConfig.payment[this.getCode()].locale; - }, - - /** - * Is shipping address can be editable on PayPal side - * @returns {Boolean} - */ - isAllowOverrideShippingAddress: function () { - return window.checkoutConfig.payment[this.getCode()].isAllowShippingAddressOverride; - }, - - /** - * Is billing address required from PayPal side - * @returns {Boolean} - */ - isRequiredBillingAddress: function () { - return window.checkoutConfig.payment[this.getCode()].isRequiredBillingAddress; - }, - - /** - * Get configuration for PayPal - * @returns {Object} - */ - getPayPalConfig: function () { - var totals = quote.totals(), - config, - isActiveVaultEnabler = this.isActiveVault(); - - config = { - flow: !isActiveVaultEnabler ? 'checkout' : 'vault', - amount: this.grandTotalAmount, - currency: totals['base_currency_code'], - locale: this.getLocale(), - enableShippingAddress: true, - shippingAddressEditable: this.isAllowOverrideShippingAddress() - }; - - config.shippingAddressOverride = this.getShippingAddress(); - - if (this.getMerchantName()) { - config.displayName = this.getMerchantName(); - } - - return config; - }, - - /** - * Get shipping address - * @returns {Object} - */ - getShippingAddress: function () { - var address = quote.shippingAddress(); - - if (_.isNull(address.postcode) || _.isUndefined(address.postcode)) { - return {}; - } - - return { - line1: _.isUndefined(address.street) || _.isUndefined(address.street[0]) ? '' : address.street[0], - city: address.city, - state: address.regionCode, - postalCode: address.postcode, - countryCode: address.countryId, - phone: address.telephone, - recipientName: address.firstname + ' ' + address.lastname - }; - }, - - /** - * Get merchant name - * @returns {String} - */ - getMerchantName: function () { - return window.checkoutConfig.payment[this.getCode()].merchantName; - }, - - /** - * Get data - * @returns {Object} - */ - getData: function () { - var data = { - 'method': this.getCode(), - 'additional_data': { - 'payment_method_nonce': this.paymentPayload.nonce - } - }; - - data['additional_data'] = _.extend(data['additional_data'], this.additionalData); - - this.vaultEnabler.visitAdditionalData(data); - - return data; - }, - - /** - * Returns payment acceptance mark image path - * @returns {String} - */ - getPaymentAcceptanceMarkSrc: function () { - - return window.checkoutConfig.payment[this.getCode()].paymentAcceptanceMarkSrc; - }, - - /** - * @returns {String} - */ - getVaultCode: function () { - return window.checkoutConfig.payment[this.getCode()].vaultCode; - }, - - /** - * @returns {String} - */ - getEnvironment: function () { - return window.checkoutConfig.payment[BraintreeAdapter.getCode()].environment; - }, - - /** - * Check if need to skip order review - * @returns {Boolean} - */ - isSkipOrderReview: function () { - return window.checkoutConfig.payment[this.getCode()].skipOrderReview; - }, - - /** - * Checks if vault is active - * @returns {Boolean} - */ - isActiveVault: function () { - return this.vaultEnabler.isVaultEnabled() && this.vaultEnabler.isActivePaymentTokenEnabler(); - }, - - /** - * Re-init PayPal Auth flow to use Vault - */ - onVaultPaymentTokenEnablerChange: function () { - this.reInitPayPal(); - }, - - /** - * Show error message - * - * @param {String} errorMessage - * @private - */ - showError: function (errorMessage) { - globalMessageList.addErrorMessage({ - message: errorMessage - }); - } - }); -}); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/vault.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/vault.js deleted file mode 100644 index ad8ac02bfb8c6..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/method-renderer/vault.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -/*browser:true*/ -/*global define*/ -define([ - 'jquery', - 'Magento_Vault/js/view/payment/method-renderer/vault', - 'Magento_Braintree/js/view/payment/adapter', - 'Magento_Ui/js/model/messageList', - 'Magento_Checkout/js/model/full-screen-loader' -], function ($, VaultComponent, Braintree, globalMessageList, fullScreenLoader) { - 'use strict'; - - return VaultComponent.extend({ - defaults: { - template: 'Magento_Vault/payment/form', - modules: { - hostedFields: '${ $.parentName }.braintree' - } - }, - - /** - * Get last 4 digits of card - * @returns {String} - */ - getMaskedCard: function () { - return this.details.maskedCC; - }, - - /** - * Get expiration date - * @returns {String} - */ - getExpirationDate: function () { - return this.details.expirationDate; - }, - - /** - * Get card type - * @returns {String} - */ - getCardType: function () { - return this.details.type; - }, - - /** - * Place order - */ - placeOrder: function () { - var self = this; - - self.getPaymentMethodNonce(); - }, - - /** - * Send request to get payment method nonce - */ - getPaymentMethodNonce: function () { - var self = this; - - fullScreenLoader.startLoader(); - $.getJSON(self.nonceUrl, { - 'public_hash': self.publicHash - }) - .done(function (response) { - fullScreenLoader.stopLoader(); - self.hostedFields(function (formComponent) { - formComponent.paymentPayload.nonce = response.paymentMethodNonce; - formComponent.additionalData['public_hash'] = self.publicHash; - formComponent.code = self.code; - formComponent.messageContainer = self.messageContainer; - formComponent.placeOrder(); - }); - }) - .fail(function (response) { - var error = JSON.parse(response.responseText); - - fullScreenLoader.stopLoader(); - globalMessageList.addErrorMessage({ - message: error.message - }); - }); - } - }); -}); diff --git a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/validator-handler.js b/app/code/Magento/Braintree/view/frontend/web/js/view/payment/validator-handler.js deleted file mode 100644 index 992c241fad665..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/js/view/payment/validator-handler.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -/*browser:true*/ -/*global define*/ - -define([ - 'jquery', - 'Magento_Braintree/js/view/payment/3d-secure' -], function ($, verify3DSecure) { - 'use strict'; - - return { - initialized: false, - validators: [], - - /** - * Inits list of validators - */ - initialize: function () { - var config = this.getConfig(); - - if (this.initialized) { - return; - } - - this.initialized = true; - - if (config[verify3DSecure.getCode()].enabled) { - verify3DSecure.setConfig(config[verify3DSecure.getCode()]); - this.add(verify3DSecure); - } - }, - - /** - * Gets payment config - * - * @returns {Object} - */ - getConfig: function () { - return window.checkoutConfig.payment; - }, - - /** - * Adds new validator - * - * @param {Object} validator - */ - add: function (validator) { - this.validators.push(validator); - }, - - /** - * Runs pull of validators - * - * @param {Object} context - * @param {Function} successCallback - * @param {Function} errorCallback - */ - validate: function (context, successCallback, errorCallback) { - var self = this, - deferred; - - self.initialize(); - - // no available validators - if (!self.validators.length) { - successCallback(); - - return; - } - - // get list of deferred validators - deferred = $.map(self.validators, function (current) { - return current.validate(context); - }); - - $.when.apply($, deferred) - .done(function () { - successCallback(); - }).fail(function (error) { - errorCallback(error); - }); - } - }; -}); diff --git a/app/code/Magento/Braintree/view/frontend/web/template/payment/form.html b/app/code/Magento/Braintree/view/frontend/web/template/payment/form.html deleted file mode 100644 index 8da8927a3b247..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/template/payment/form.html +++ /dev/null @@ -1,152 +0,0 @@ - -
-
- - -
-
- - - -
- - - -
-
-
- - - -
-
-
-
    - -
  • - - - -
  • - -
- -
-
-
- -
-
-
-
-
-
- -
-
-
- -
- -
-
-
-
- -
- -
-
-
- -
- - - -
-
-
-
- - -
- - -
- - - -
-
-
- -
- - -
- - - -
-
-
- -
-
-
-
diff --git a/app/code/Magento/Braintree/view/frontend/web/template/payment/multishipping/form.html b/app/code/Magento/Braintree/view/frontend/web/template/payment/multishipping/form.html deleted file mode 100644 index b72ef24b81b63..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/template/payment/multishipping/form.html +++ /dev/null @@ -1,106 +0,0 @@ - - -
-
-
-
- - - -
-
-
-
    - -
  • - - - -
  • - -
- -
-
-
- -
-
-
-
-
-
- -
-
-
- -
- -
-
-
-
- -
- -
-
-
- -
- - - -
-
-
-
- -
- - - -
-
- -
-
-
-
\ No newline at end of file diff --git a/app/code/Magento/Braintree/view/frontend/web/template/payment/multishipping/paypal.html b/app/code/Magento/Braintree/view/frontend/web/template/payment/multishipping/paypal.html deleted file mode 100644 index fcd5320351938..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/template/payment/multishipping/paypal.html +++ /dev/null @@ -1,41 +0,0 @@ - -
-
- -
- -
- -
-
-
-
-
- -
-
- -
-
-
-
-
diff --git a/app/code/Magento/Braintree/view/frontend/web/template/payment/paypal.html b/app/code/Magento/Braintree/view/frontend/web/template/payment/paypal.html deleted file mode 100644 index 0abf3483ac76c..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/template/payment/paypal.html +++ /dev/null @@ -1,71 +0,0 @@ - -
-
- - -
- -
- -
-
-
-
- -
- -
- - -
- - - -
-
-
- -
- -
- -
-
-
-
-
-
-
diff --git a/app/code/Magento/Braintree/view/frontend/web/template/payment/paypal/vault.html b/app/code/Magento/Braintree/view/frontend/web/template/payment/paypal/vault.html deleted file mode 100644 index b9402da02cc8a..0000000000000 --- a/app/code/Magento/Braintree/view/frontend/web/template/payment/paypal/vault.html +++ /dev/null @@ -1,47 +0,0 @@ - -
-
- - -
- -
- -
- - - -
-
-
- -
-
-
-
diff --git a/app/code/Magento/BraintreeGraphQl/Model/BraintreeDataProvider.php b/app/code/Magento/BraintreeGraphQl/Model/BraintreeDataProvider.php deleted file mode 100644 index cb5c4a31837b4..0000000000000 --- a/app/code/Magento/BraintreeGraphQl/Model/BraintreeDataProvider.php +++ /dev/null @@ -1,36 +0,0 @@ -config = $config; - $this->adapterFactory = $adapterFactory; - } - - /** - * @inheritdoc - */ - public function resolve( - Field $field, - $context, - ResolveInfo $info, - array $value = null, - array $args = null - ) { - $storeId = (int)$context->getExtensionAttributes()->getStore()->getId(); - - if (!$this->config->isActive($storeId)) { - throw new GraphQlInputException(__('The Braintree payment method is not active.')); - } - - $params = []; - $merchantAccountId = $this->config->getMerchantAccountId($storeId); - if (!empty($merchantAccountId)) { - $params[PaymentDataBuilder::MERCHANT_ACCOUNT_ID] = $merchantAccountId; - } - - return $this->adapterFactory->create($storeId)->generate($params); - } -} diff --git a/app/code/Magento/BraintreeGraphQl/Plugin/SetVaultPaymentNonce.php b/app/code/Magento/BraintreeGraphQl/Plugin/SetVaultPaymentNonce.php deleted file mode 100644 index 1dea9992c6306..0000000000000 --- a/app/code/Magento/BraintreeGraphQl/Plugin/SetVaultPaymentNonce.php +++ /dev/null @@ -1,79 +0,0 @@ -command = $command; - $this->logger = $logger; - } - - /** - * Set Braintree nonce from public hash - * - * @param \Magento\QuoteGraphQl\Model\Cart\SetPaymentMethodOnCart $subject - * @param \Magento\Quote\Model\Quote $quote - * @param array $paymentData - * @return array - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function beforeExecute( - \Magento\QuoteGraphQl\Model\Cart\SetPaymentMethodOnCart $subject, - \Magento\Quote\Model\Quote $quote, - array $paymentData - ): array { - if ($paymentData['code'] !== ConfigProvider::CC_VAULT_CODE - || !isset($paymentData[ConfigProvider::CC_VAULT_CODE]) - || !isset($paymentData[ConfigProvider::CC_VAULT_CODE]['public_hash']) - ) { - return [$quote, $paymentData]; - } - - $subject = [ - 'public_hash' => $paymentData[ConfigProvider::CC_VAULT_CODE]['public_hash'], - 'customer_id' => $quote->getCustomerId(), - 'store_id' => $quote->getStoreId(), - ]; - - try { - $result = $this->command->execute($subject)->get(); - $paymentData[ConfigProvider::CC_VAULT_CODE]['payment_method_nonce'] = $result['paymentMethodNonce']; - } catch (\Exception $e) { - $this->logger->critical($e); - throw new GraphQlInputException(__('Sorry, but something went wrong')); - } - - return [$quote, $paymentData]; - } -} diff --git a/app/code/Magento/BraintreeGraphQl/README.md b/app/code/Magento/BraintreeGraphQl/README.md deleted file mode 100644 index 4e8eecc93a924..0000000000000 --- a/app/code/Magento/BraintreeGraphQl/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# Magento_BraintreeGraphQl module - -The Magento_BraintreeGraphQl module provides type and resolver information for the GraphQL module to pass payment information data from the client to Magento. - -## Extensibility - -Extension developers can interact with the Magento_BraintreeGraphQl module. For more information about the Magento extension mechanism, see [Magento plug-ins](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html). - -[The Magento dependency injection mechanism](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html) enables you to override the functionality of the Magento_BraintreeGraphQl module. diff --git a/app/code/Magento/BraintreeGraphQl/etc/graphql/di.xml b/app/code/Magento/BraintreeGraphQl/etc/graphql/di.xml deleted file mode 100644 index a310663163771..0000000000000 --- a/app/code/Magento/BraintreeGraphQl/etc/graphql/di.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - Magento\BraintreeGraphQl\Model\BraintreeDataProvider - Magento\BraintreeGraphQl\Model\BraintreeVaultDataProvider - - - - - - - diff --git a/app/code/Magento/BraintreeGraphQl/etc/module.xml b/app/code/Magento/BraintreeGraphQl/etc/module.xml deleted file mode 100644 index 2133e95a69104..0000000000000 --- a/app/code/Magento/BraintreeGraphQl/etc/module.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - diff --git a/app/code/Magento/BraintreeGraphQl/etc/schema.graphqls b/app/code/Magento/BraintreeGraphQl/etc/schema.graphqls deleted file mode 100644 index 08bd10fd4c2dd..0000000000000 --- a/app/code/Magento/BraintreeGraphQl/etc/schema.graphqls +++ /dev/null @@ -1,22 +0,0 @@ -# Copyright © Magento, Inc. All rights reserved. -# See COPYING.txt for license details. - -type Mutation { - createBraintreeClientToken: String! @resolver(class: "\\Magento\\BraintreeGraphQl\\Model\\Resolver\\CreateBraintreeClientToken") @doc(description:"Creates Client Token for Braintree Javascript SDK initialization.") -} - -input PaymentMethodInput { - braintree: BraintreeInput - braintree_cc_vault: BraintreeCcVaultInput -} - -input BraintreeInput { - payment_method_nonce: String! @doc(description:"The one-time payment token generated by Braintree payment gateway based on card details. Required field to make sale transaction.") - is_active_payment_token_enabler: Boolean! @doc(description:"States whether an entered by a customer credit/debit card should be tokenized for later usage. Required only if Vault is enabled for Braintree payment integration.") - device_data: String @doc(description:"Contains a fingerprint provided by Braintree JS SDK and should be sent with sale transaction details to the Braintree payment gateway. Should be specified only in a case if Kount (advanced fraud protection) is enabled for Braintree payment integration.") -} - -input BraintreeCcVaultInput { - public_hash: String! - device_data: String -} diff --git a/app/code/Magento/BraintreeGraphQl/registration.php b/app/code/Magento/BraintreeGraphQl/registration.php deleted file mode 100644 index 37f7ef30864cb..0000000000000 --- a/app/code/Magento/BraintreeGraphQl/registration.php +++ /dev/null @@ -1,10 +0,0 @@ -getOrderItem()->getId()][$item->getOrderItemId()] = $item; foreach ($items as $value) { $parentItem = $value->getOrderItem()->getParentItem(); if ($parentItem) { diff --git a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Sales/Order/Items/RendererTest.php b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Sales/Order/Items/RendererTest.php index 07460549aea18..daf90f9a07af3 100644 --- a/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Sales/Order/Items/RendererTest.php +++ b/app/code/Magento/Bundle/Test/Unit/Block/Adminhtml/Sales/Order/Items/RendererTest.php @@ -17,6 +17,9 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +/** + * Test Renderer order item + */ class RendererTest extends TestCase { /** @var Item|MockObject */ @@ -98,25 +101,27 @@ public function testGetChildren($parentItem) $parentItem = $this->createPartialMock(Item::class, ['getId', '__wakeup']); $parentItem->expects($this->any())->method('getId')->willReturn(1); } - $this->orderItem->expects($this->any())->method('getOrderItem')->willReturnSelf(); - $this->orderItem->expects($this->any())->method('getParentItem')->willReturn($parentItem); - $this->orderItem->expects($this->any())->method('getOrderItemId')->willReturn(2); - $this->orderItem->expects($this->any())->method('getId')->willReturn(1); + $this->orderItem->method('getOrderItem')->willReturnSelf(); + $this->orderItem->method('getParentItem')->willReturn($parentItem); + $this->orderItem->method('getOrderItemId')->willReturn(2); + $this->orderItem->method('getId')->willReturn(1); $salesModel = $this->createPartialMock( Invoice::class, ['getAllItems', '__wakeup'] ); - $salesModel->expects($this->once())->method('getAllItems')->willReturn([$this->orderItem]); + $salesModel->method('getAllItems')->willReturn([$this->orderItem]); $item = $this->createPartialMock( \Magento\Sales\Model\Order\Invoice\Item::class, - ['getInvoice', 'getOrderItem', '__wakeup'] + ['getInvoice', 'getOrderItem', 'getOrderItemId', '__wakeup'] ); - $item->expects($this->once())->method('getInvoice')->willReturn($salesModel); - $item->expects($this->any())->method('getOrderItem')->willReturn($this->orderItem); + $item->method('getInvoice')->willReturn($salesModel); + $item->method('getOrderItem')->willReturn($this->orderItem); + $item->method('getOrderItemId')->willReturn($this->orderItem->getOrderItemId()); - $this->assertSame([2 => $this->orderItem], $this->model->getChildren($item)); + $orderItem = $this->model->getChildren($item); + $this->assertSame([2 => $this->orderItem], $orderItem); } /** diff --git a/app/code/Magento/Bundle/etc/db_schema.xml b/app/code/Magento/Bundle/etc/db_schema.xml index dba9732439065..867e937d6bc83 100644 --- a/app/code/Magento/Bundle/etc/db_schema.xml +++ b/app/code/Magento/Bundle/etc/db_schema.xml @@ -9,13 +9,13 @@ xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
Select...Select...Select...
-
- getBlockHtml('formkey') ?> - - -
-
- - - - @@ -30,14 +30,14 @@
- - - - @@ -53,25 +53,25 @@
- - - - - - - - @@ -91,15 +91,15 @@
- - - - @@ -119,11 +119,11 @@
- - - @@ -152,15 +152,15 @@
- - - - - @@ -171,15 +171,15 @@
- - - - - @@ -205,15 +205,15 @@
- - - - - @@ -239,19 +239,19 @@
- - - - - - - @@ -267,19 +267,19 @@
- - - - - - - @@ -295,13 +295,13 @@
- - - - @@ -322,13 +322,13 @@
- - - - diff --git a/app/code/Magento/Captcha/etc/db_schema.xml b/app/code/Magento/Captcha/etc/db_schema.xml index 158e2f43b9f5d..38e0af72d2756 100644 --- a/app/code/Magento/Captcha/etc/db_schema.xml +++ b/app/code/Magento/Captcha/etc/db_schema.xml @@ -10,7 +10,7 @@
- diff --git a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductAttributeMassUpdateActionGroup.xml b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductAttributeMassUpdateActionGroup.xml index d20b44b0162f0..e4fc000deb9c7 100644 --- a/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductAttributeMassUpdateActionGroup.xml +++ b/app/code/Magento/Catalog/Test/Mftf/ActionGroup/AdminProductAttributeMassUpdateActionGroup.xml @@ -20,6 +20,7 @@ + diff --git a/app/code/Magento/Catalog/Test/Mftf/Data/NewProductData.xml b/app/code/Magento/Catalog/Test/Mftf/Data/NewProductData.xml deleted file mode 100644 index 4479805cb12fb..0000000000000 --- a/app/code/Magento/Catalog/Test/Mftf/Data/NewProductData.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - ProductTest - 100 - 100 - - diff --git a/app/code/Magento/Catalog/etc/db_schema.xml b/app/code/Magento/Catalog/etc/db_schema.xml index d5b318f671726..1c97c920266df 100644 --- a/app/code/Magento/Catalog/etc/db_schema.xml +++ b/app/code/Magento/Catalog/etc/db_schema.xml @@ -8,15 +8,15 @@
- - - - @@ -34,13 +34,13 @@
- - - - @@ -69,13 +69,13 @@
- - - - @@ -105,15 +105,15 @@
- - - - - @@ -141,13 +141,13 @@
- - - - @@ -176,13 +176,13 @@
- - - - @@ -211,15 +211,15 @@
- - - - - @@ -250,22 +250,22 @@
- - - - - - @@ -279,13 +279,13 @@
- - - - @@ -317,13 +317,13 @@
- - - - @@ -356,15 +356,15 @@
- - - - - @@ -395,13 +395,13 @@
- - - - @@ -433,13 +433,13 @@
- - - - @@ -471,13 +471,13 @@
- - - - @@ -500,17 +500,17 @@
- - - - - - @@ -532,15 +532,15 @@
- - - - - @@ -570,9 +570,9 @@
- - @@ -590,7 +590,7 @@
- @@ -599,13 +599,13 @@
- - - - @@ -633,9 +633,9 @@
- - @@ -652,11 +652,11 @@
- - - @@ -680,13 +680,13 @@
- - - - @@ -708,11 +708,11 @@
- - - @@ -735,19 +735,19 @@
- - - - - @@ -779,14 +779,14 @@
- - - @@ -800,18 +800,18 @@
- - - - - - @@ -842,22 +842,22 @@
- - - - - - - @@ -871,11 +871,11 @@
- - - @@ -899,11 +899,11 @@
- - - @@ -925,12 +925,12 @@
- - - @@ -944,11 +944,11 @@
- - - @@ -973,11 +973,11 @@
- - - @@ -999,48 +999,48 @@
- - - - - - - - - - - - - - - - - - - - @@ -1056,9 +1056,9 @@
- - @@ -1076,15 +1076,15 @@
- - - - - @@ -1105,15 +1105,15 @@
- - - - @@ -1134,13 +1134,13 @@
- - - - @@ -1171,11 +1171,11 @@
- - - @@ -1202,9 +1202,9 @@
- - @@ -1219,13 +1219,13 @@
- - - - @@ -1240,13 +1240,13 @@
- - - - @@ -1261,11 +1261,11 @@
- - - @@ -1281,11 +1281,11 @@
- - - @@ -1301,13 +1301,13 @@
- - - - @@ -1329,13 +1329,13 @@
- - - - @@ -1357,11 +1357,11 @@
- - - @@ -1377,11 +1377,11 @@
- - - @@ -1397,13 +1397,13 @@
- - - - @@ -1420,13 +1420,13 @@
- - - - @@ -1443,15 +1443,15 @@
- - - - - @@ -1472,15 +1472,15 @@
- - - - - @@ -1501,15 +1501,15 @@
- - - - @@ -1530,15 +1530,15 @@
- - - - @@ -1559,13 +1559,13 @@
- - - - @@ -1594,13 +1594,13 @@
- - - - @@ -1629,17 +1629,17 @@
- - - - - - @@ -1654,9 +1654,9 @@
- -
- - - - - @@ -1701,15 +1701,15 @@
- - - - @@ -1730,13 +1730,13 @@
- - - - @@ -1767,17 +1767,17 @@
- - - - - - @@ -1800,16 +1800,16 @@
- - - - - diff --git a/app/code/Magento/Catalog/etc/view.xml b/app/code/Magento/Catalog/etc/view.xml index 910a3be8055da..0740ab5b154f6 100644 --- a/app/code/Magento/Catalog/etc/view.xml +++ b/app/code/Magento/Catalog/etc/view.xml @@ -8,5 +8,9 @@ 1 + + 0 diff --git a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/edit/action/inventory.phtml b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/edit/action/inventory.phtml index 792af12494af6..1d22624751b32 100644 --- a/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/edit/action/inventory.phtml +++ b/app/code/Magento/Catalog/view/adminhtml/templates/catalog/product/edit/action/inventory.phtml @@ -33,7 +33,7 @@ $defaultMinSaleQty = $block->getDefaultConfigValue('min_sale_qty'); if (!is_numeric($defaultMinSaleQty)) { $defaultMinSaleQty = json_decode($defaultMinSaleQty, true); - $defaultMinSaleQty = (float) $defaultMinSaleQty[\Magento\Customer\Api\Data\GroupInterface::CUST_GROUP_ALL] ?? 1; + $defaultMinSaleQty = (float) ($defaultMinSaleQty[\Magento\Customer\Api\Data\GroupInterface::CUST_GROUP_ALL] ?? 1); } ?>
@@ -52,17 +52,19 @@ if (!is_numeric($defaultMinSaleQty)) {
-
-
- +
@@ -238,10 +242,12 @@ if (!is_numeric($defaultMinSaleQty)) { name="getFieldSuffix() ?>[backorders]" class="select" disabled="disabled"> - getBackordersOption() as $option) :?> - getDefaultConfigValue('backorders')) ? ' selected="selected"' : '' ?> - + getBackordersOption() as $option):?> + getDefaultConfigValue('backorders')) + ? ' selected="selected"' : '' ?> +
@@ -291,7 +297,9 @@ if (!is_numeric($defaultMinSaleQty)) { class="label">escapeHtml(__('Use Config Settings')) ?>
- +
@@ -314,7 +322,7 @@ if (!is_numeric($defaultMinSaleQty)) { disabled="disabled"> @@ -330,7 +338,9 @@ if (!is_numeric($defaultMinSaleQty)) { class="label">escapeHtml(__('Use Config Settings')) ?>
- +
@@ -364,7 +374,9 @@ if (!is_numeric($defaultMinSaleQty)) { class="label">escapeHtml(__('Use Config Settings')) ?>
- +
@@ -385,11 +397,15 @@ if (!is_numeric($defaultMinSaleQty)) { name="getFieldSuffix() ?>[is_in_stock]" class="select" disabled="disabled"> - +
- +
diff --git a/app/code/Magento/Catalog/view/frontend/templates/product/image.phtml b/app/code/Magento/Catalog/view/frontend/templates/product/image.phtml index 9f8fdfb518408..98d17045a1b2d 100644 --- a/app/code/Magento/Catalog/view/frontend/templates/product/image.phtml +++ b/app/code/Magento/Catalog/view/frontend/templates/product/image.phtml @@ -8,7 +8,7 @@ /** @var $block \Magento\Catalog\Block\Product\Image */ /** @var $escaper \Magento\Framework\Escaper */ ?> - + getCustomAttributes() as $name => $value): ?> escapeHtmlAttr($name) ?>="escapeHtmlAttr($value) ?>" diff --git a/app/code/Magento/Catalog/view/frontend/templates/product/image_with_borders.phtml b/app/code/Magento/Catalog/view/frontend/templates/product/image_with_borders.phtml index 2f352438297d4..020eafcff2442 100644 --- a/app/code/Magento/Catalog/view/frontend/templates/product/image_with_borders.phtml +++ b/app/code/Magento/Catalog/view/frontend/templates/product/image_with_borders.phtml @@ -7,6 +7,16 @@ getVar('product_image_white_borders', 'Magento_Catalog'); +$enableLazyLoadingWithoutBorders = (bool)$block->getVar( + 'enable_lazy_loading_for_images_without_borders', + 'Magento_Catalog' +); ?> src="escapeUrl($block->getImageUrl()) ?>" loading="lazy" - width="escapeHtmlAttr($block->getWidth()) ?>" - height="escapeHtmlAttr($block->getHeight()) ?>" + + width="escapeHtmlAttr($block->getWidth()) ?>" + height="escapeHtmlAttr($block->getHeight()) ?>" + + max-width="escapeHtmlAttr($block->getWidth()) ?>" + max-height="escapeHtmlAttr($block->getHeight()) ?>" + alt="escapeHtmlAttr($block->getLabel()) ?>"/> diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/VirtualTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/VirtualTest.php index 172c2ee8ea2a0..cc17ce12d129d 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/VirtualTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/VirtualTest.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product\Type; use Magento\CatalogImportExport\Model\Import\Product\Type\Virtual; diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_different_type.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_different_type.php index d109d8ffaa525..bf8587ce9719e 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_different_type.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_different_type.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'simple', '_custom_option_type' => 'date_time', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_several_db_rows.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_several_db_rows.php index 97738cd93c4ca..e81fa96ae679e 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_several_db_rows.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_ambiguity_several_db_rows.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'simple', '_custom_option_type' => 'field', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_empty_title.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_empty_title.php index d354e765312e4..c9d73aa651f68 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_empty_title.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_empty_title.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'product-sku', '_custom_option_type' => 'field', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_incorrect_type.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_incorrect_type.php index f91f98619eed0..5c24870a2f154 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_incorrect_type.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_incorrect_type.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'product-sku', '_custom_option_type' => 'incorrect_field', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_max_characters.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_max_characters.php index 5d8c00dd41d7e..8eb299b6c2671 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_max_characters.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_max_characters.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'product-sku', '_custom_option_type' => 'field', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_price.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_price.php index c5f965b15f93b..57c7a6c8ad8b6 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_price.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_price.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'product-sku', '_custom_option_type' => 'field', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_sort_order.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_sort_order.php index c9c4df511c27c..4277222635867 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_sort_order.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_sort_order.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'product-sku', '_custom_option_type' => 'field', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_store.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_store.php index b3630a44e6df0..5e1e6843bdfcc 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_store.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_invalid_store.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'product-sku', '_custom_option_store' => 'incorrect_store', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_max_characters_less_zero.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_max_characters_less_zero.php index 6056d7cb69116..71a2141c0f5a8 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_max_characters_less_zero.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_max_characters_less_zero.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'product-sku', '_custom_option_type' => 'field', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_no_title.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_no_title.php index 99a1f86cc58e5..023f445156ff7 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_no_title.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_no_title.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'product-sku', '_custom_option_type' => 'field', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_sort_order_less_zero.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_sort_order_less_zero.php index 4e2cf6f3ad379..b56aa8691beb1 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_sort_order_less_zero.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_sort_order_less_zero.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'product-sku', '_custom_option_type' => 'field', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_valid.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_valid.php index 4804c9f983889..42365c9dc71c2 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_valid.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_main_valid.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'product-sku', '_custom_option_type' => 'field', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_no_custom_option.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_no_custom_option.php index 6bf5c83e2854d..82ac811875f56 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_no_custom_option.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_no_custom_option.php @@ -5,6 +5,4 @@ */ declare(strict_types=1); -declare(strict_types=1); - return ['sku' => 'product-sku']; diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_price.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_price.php index d0f6656bfe93e..fe9691e963933 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_price.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_price.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'product-sku', '_custom_option_row_title' => 'test row title', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_row_sort.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_row_sort.php index a3cedbc3eec97..a26e399ecedd5 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_row_sort.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_incorrect_row_sort.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'product-sku', '_custom_option_row_title' => 'test row title', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_invalid_store.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_invalid_store.php index ddb4871575e7f..dc931e4418b97 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_invalid_store.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_invalid_store.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'product-sku', '_custom_option_store' => 'incorrect_store', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_row_sort_less_zero.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_row_sort_less_zero.php index dc7f23c180fda..897acf53caa21 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_row_sort_less_zero.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_row_sort_less_zero.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'product-sku', '_custom_option_row_title' => 'test row title', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_valid.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_valid.php index 25c623bb6709f..1da8e2c58be5a 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_valid.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Type/_files/row_data_secondary_valid.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - return [ 'sku' => 'product-sku', '_custom_option_row_title' => 'test row title', diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/MediaTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/MediaTest.php index 5ecaf6e4ca513..824d39ded391f 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/MediaTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/MediaTest.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product\Validator; use Magento\CatalogImportExport\Model\Import\Product; diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/QuantityTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/QuantityTest.php index 7c30d32a6ed68..f54fcd40250e2 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/QuantityTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/QuantityTest.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product\Validator; use Magento\CatalogImportExport\Model\Import\Product; diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/SuperProductsSkuTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/SuperProductsSkuTest.php index 975f7e1dc3bb3..5d4555747f0b6 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/SuperProductsSkuTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/SuperProductsSkuTest.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product\Validator; use Magento\CatalogImportExport\Model\Import\Product\SkuProcessor; diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/TierPriceTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/TierPriceTest.php index 8f611a03f5edc..8a0e4bfb2e4fc 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/TierPriceTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/Validator/TierPriceTest.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product\Validator; use Magento\CatalogImportExport\Model\Import\Product\StoreResolver; @@ -43,9 +41,10 @@ protected function setUp(): void $this->groupRepositoryInterface = $this->createMock( GroupRepository::class ); - $this->searchCriteriaSearch = $this->createMock(SearchCriteria::class); + $searchCriteriaSearch = $this->createMock(SearchCriteria::class); $this->searchCriteriaBuilder = $this->createMock(SearchCriteriaBuilder::class); - $this->searchCriteriaBuilder->expects($this->any())->method('create')->willReturn($this->searchCriteriaSearch); + $this->searchCriteriaBuilder->expects($this->any())->method('create') + ->willReturn($searchCriteriaSearch); $this->storeResolver = $this->createMock( StoreResolver::class ); diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ValidatorTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ValidatorTest.php index 89675de7bf6bf..6c2efb6197db0 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ValidatorTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Import/Product/ValidatorTest.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - namespace Magento\CatalogImportExport\Test\Unit\Model\Import\Product; use Magento\CatalogImportExport\Model\Import\Product; diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Product/Flat/Plugin/ImportTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Product/Flat/Plugin/ImportTest.php index 77f894563550c..71348360fdb55 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Product/Flat/Plugin/ImportTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Product/Flat/Plugin/ImportTest.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - namespace Magento\CatalogImportExport\Test\Unit\Model\Indexer\Product\Flat\Plugin; use Magento\Catalog\Model\Indexer\Product\Flat\Processor; diff --git a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Stock/Plugin/ImportTest.php b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Stock/Plugin/ImportTest.php index 02e7466434949..3659cde191b54 100644 --- a/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Stock/Plugin/ImportTest.php +++ b/app/code/Magento/CatalogImportExport/Test/Unit/Model/Indexer/Stock/Plugin/ImportTest.php @@ -5,8 +5,6 @@ */ declare(strict_types=1); -declare(strict_types=1); - namespace Magento\CatalogImportExport\Test\Unit\Model\Indexer\Stock\Plugin; use Magento\CatalogInventory\Model\Indexer\Stock\Processor; diff --git a/app/code/Magento/CatalogInventory/etc/db_schema.xml b/app/code/Magento/CatalogInventory/etc/db_schema.xml index 3747f3f89633f..bc7ed3c529441 100644 --- a/app/code/Magento/CatalogInventory/etc/db_schema.xml +++ b/app/code/Magento/CatalogInventory/etc/db_schema.xml @@ -8,9 +8,9 @@
- - @@ -21,55 +21,55 @@
- - - - - - - - - - - - - - - - - - - @@ -97,15 +97,15 @@
- - - - @@ -124,15 +124,15 @@
- - - - @@ -148,15 +148,15 @@
- - - - @@ -172,15 +172,15 @@
- - - - diff --git a/app/code/Magento/CatalogRule/Model/Rule/Condition/ConditionsToSearchCriteriaMapper.php b/app/code/Magento/CatalogRule/Model/Rule/Condition/ConditionsToSearchCriteriaMapper.php index fabe504fbe31c..662a2fd6b38fc 100644 --- a/app/code/Magento/CatalogRule/Model/Rule/Condition/ConditionsToSearchCriteriaMapper.php +++ b/app/code/Magento/CatalogRule/Model/Rule/Condition/ConditionsToSearchCriteriaMapper.php @@ -7,13 +7,16 @@ namespace Magento\CatalogRule\Model\Rule\Condition; -use Magento\Framework\Exception\InputException; -use Magento\Rule\Model\Condition\ConditionInterface; use Magento\CatalogRule\Model\Rule\Condition\Combine as CombinedCondition; use Magento\CatalogRule\Model\Rule\Condition\Product as SimpleCondition; use Magento\Framework\Api\CombinedFilterGroup as FilterGroup; +use Magento\Framework\Api\CombinedFilterGroupFactory; use Magento\Framework\Api\Filter; +use Magento\Framework\Api\FilterFactory; use Magento\Framework\Api\SearchCriteria; +use Magento\Framework\Api\SearchCriteriaBuilderFactory; +use Magento\Framework\Exception\InputException; +use Magento\Rule\Model\Condition\ConditionInterface; /** * Maps catalog price rule conditions to search criteria @@ -21,29 +24,29 @@ class ConditionsToSearchCriteriaMapper { /** - * @var \Magento\Framework\Api\SearchCriteriaBuilderFactory + * @var SearchCriteriaBuilderFactory */ private $searchCriteriaBuilderFactory; /** - * @var \Magento\Framework\Api\CombinedFilterGroupFactory + * @var CombinedFilterGroupFactory */ private $combinedFilterGroupFactory; /** - * @var \Magento\Framework\Api\FilterFactory + * @var FilterFactory */ private $filterFactory; /** - * @param \Magento\Framework\Api\SearchCriteriaBuilderFactory $searchCriteriaBuilderFactory - * @param \Magento\Framework\Api\CombinedFilterGroupFactory $combinedFilterGroupFactory - * @param \Magento\Framework\Api\FilterFactory $filterFactory + * @param SearchCriteriaBuilderFactory $searchCriteriaBuilderFactory + * @param CombinedFilterGroupFactory $combinedFilterGroupFactory + * @param FilterFactory $filterFactory */ public function __construct( - \Magento\Framework\Api\SearchCriteriaBuilderFactory $searchCriteriaBuilderFactory, - \Magento\Framework\Api\CombinedFilterGroupFactory $combinedFilterGroupFactory, - \Magento\Framework\Api\FilterFactory $filterFactory + SearchCriteriaBuilderFactory $searchCriteriaBuilderFactory, + CombinedFilterGroupFactory $combinedFilterGroupFactory, + FilterFactory $filterFactory ) { $this->searchCriteriaBuilderFactory = $searchCriteriaBuilderFactory; $this->combinedFilterGroupFactory = $combinedFilterGroupFactory; @@ -74,7 +77,7 @@ public function mapConditionsToSearchCriteria(CombinedCondition $conditions): Se * Convert condition to filter group * * @param ConditionInterface $condition - * @return null|\Magento\Framework\Api\CombinedFilterGroup|\Magento\Framework\Api\Filter + * @return null|FilterGroup|Filter * @throws InputException */ private function mapConditionToFilterGroup(ConditionInterface $condition) @@ -94,7 +97,7 @@ private function mapConditionToFilterGroup(ConditionInterface $condition) * Convert combined condition to filter group * * @param Combine $combinedCondition - * @return null|\Magento\Framework\Api\CombinedFilterGroup + * @return null|FilterGroup * @throws InputException */ private function mapCombinedConditionToFilterGroup(CombinedCondition $combinedCondition) @@ -111,7 +114,7 @@ private function mapCombinedConditionToFilterGroup(CombinedCondition $combinedCo // This required to solve cases when condition is configured like: // "If ALL/ANY of these conditions are FALSE" - we need to reverse SQL operator for this "FALSE" if ((bool)$combinedCondition->getValue() === false) { - $this->reverseSqlOperatorInFilter($filter); + $this->reverseSqlOperatorInFilterRecursively($filter); } $filters[] = $filter; @@ -183,6 +186,24 @@ private function getGlueForArrayValues(string $operator): string return 'any'; } + /** + * Recursively reverse sql conditions to their corresponding negative analog for the entire FilterGroup + * + * @param Filter|FilterGroup $filter + * @return void + * @throws InputException + */ + private function reverseSqlOperatorInFilterRecursively($filter): void + { + if ($filter instanceof FilterGroup) { + foreach ($filter->getFilters() as &$currentFilter) { + $this->reverseSqlOperatorInFilterRecursively($currentFilter); + } + } else { + $this->reverseSqlOperatorInFilter($filter); + } + } + /** * Reverse sql conditions to their corresponding negative analog * diff --git a/app/code/Magento/CatalogRule/etc/db_schema.xml b/app/code/Magento/CatalogRule/etc/db_schema.xml index b3692f280fec5..a2bb4dca4e422 100644 --- a/app/code/Magento/CatalogRule/etc/db_schema.xml +++ b/app/code/Magento/CatalogRule/etc/db_schema.xml @@ -8,19 +8,19 @@
- - - -
- - - - - - + - - - @@ -86,15 +86,15 @@
- - - + - @@ -118,11 +118,11 @@
- - - @@ -137,9 +137,9 @@
- - @@ -157,9 +157,9 @@
- - @@ -176,26 +176,26 @@
- - - - - - + - - - @@ -227,15 +227,15 @@
- - - + - @@ -260,11 +260,11 @@
- - - diff --git a/app/code/Magento/CatalogUrlRewrite/etc/db_schema.xml b/app/code/Magento/CatalogUrlRewrite/etc/db_schema.xml index c8da5b59cf5f5..aaf86e7d4418e 100644 --- a/app/code/Magento/CatalogUrlRewrite/etc/db_schema.xml +++ b/app/code/Magento/CatalogUrlRewrite/etc/db_schema.xml @@ -9,11 +9,11 @@ xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
- - - + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class Crosssell extends \Magento\Catalog\Block\Product\AbstractProduct +class Crosssell extends AbstractProduct { /** * Items quantity will be capped to this value @@ -23,12 +37,12 @@ class Crosssell extends \Magento\Catalog\Block\Product\AbstractProduct protected $_maxItemCount = 4; /** - * @var \Magento\Checkout\Model\Session + * @var Session */ protected $_checkoutSession; /** - * @var \Magento\Catalog\Model\Product\Visibility + * @var Visibility */ protected $_productVisibility; @@ -38,35 +52,53 @@ class Crosssell extends \Magento\Catalog\Block\Product\AbstractProduct protected $stockHelper; /** - * @var \Magento\Catalog\Model\Product\LinkFactory + * @var LinkFactory */ protected $_productLinkFactory; /** - * @var \Magento\Quote\Model\Quote\Item\RelatedProducts + * @var RelatedProducts */ protected $_itemRelationsList; /** - * @param \Magento\Catalog\Block\Product\Context $context - * @param \Magento\Checkout\Model\Session $checkoutSession - * @param \Magento\Catalog\Model\Product\Visibility $productVisibility - * @param \Magento\Catalog\Model\Product\LinkFactory $productLinkFactory - * @param \Magento\Quote\Model\Quote\Item\RelatedProducts $itemRelationsList + * @var CollectionFactory|null + */ + private $productCollectionFactory; + + /** + * @var ProductRepositoryInterface|null + */ + private $productRepository; + + /** + * @var Product[] + */ + private $cartProducts; + + /** + * @param Context $context + * @param Session $checkoutSession + * @param Visibility $productVisibility + * @param LinkFactory $productLinkFactory + * @param RelatedProducts $itemRelationsList * @param StockHelper $stockHelper * @param array $data - * + * @param CollectionFactory|null $productCollectionFactory + * @param ProductRepositoryInterface|null $productRepository * @codeCoverageIgnore * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( - \Magento\Catalog\Block\Product\Context $context, - \Magento\Checkout\Model\Session $checkoutSession, - \Magento\Catalog\Model\Product\Visibility $productVisibility, - \Magento\Catalog\Model\Product\LinkFactory $productLinkFactory, - \Magento\Quote\Model\Quote\Item\RelatedProducts $itemRelationsList, + Context $context, + Session $checkoutSession, + Visibility $productVisibility, + LinkFactory $productLinkFactory, + RelatedProducts $itemRelationsList, StockHelper $stockHelper, - array $data = [] + array $data = [], + ?CollectionFactory $productCollectionFactory = null, + ?ProductRepositoryInterface $productRepository = null ) { $this->_checkoutSession = $checkoutSession; $this->_productVisibility = $productVisibility; @@ -78,6 +110,10 @@ public function __construct( $data ); $this->_isScopePrivate = true; + $this->productCollectionFactory = $productCollectionFactory + ?? ObjectManager::getInstance()->get(CollectionFactory::class); + $this->productRepository = $productRepository + ?? ObjectManager::getInstance()->get(ProductRepositoryInterface::class); } /** @@ -92,9 +128,10 @@ public function getItems() $items = []; $ninProductIds = $this->_getCartProductIds(); if ($ninProductIds) { - $lastAdded = (int)$this->_getLastAddedProductId(); - if ($lastAdded) { - $collection = $this->_getCollection()->addProductFilter($lastAdded); + $lastAddedProduct = $this->getLastAddedProduct(); + if ($lastAddedProduct) { + $collection = $this->_getCollection() + ->addProductFilter($lastAddedProduct->getData($this->getProductLinkField())); if (!empty($ninProductIds)) { $collection->addExcludeProductFilter($ninProductIds); } @@ -108,8 +145,8 @@ public function getItems() if (count($items) < $this->_maxItemCount) { $filterProductIds = array_merge( - $this->_getCartProductIds(), - $this->_itemRelationsList->getRelatedProductIds($this->getQuote()->getAllItems()) + $this->getCartProductLinkIds(), + $this->getCartRelatedProductLinkIds() ); $collection = $this->_getCollection()->addProductFilter( $filterProductIds @@ -150,11 +187,8 @@ protected function _getCartProductIds() $ids = $this->getData('_cart_product_ids'); if ($ids === null) { $ids = []; - foreach ($this->getQuote()->getAllItems() as $item) { - $product = $item->getProduct(); - if ($product) { - $ids[] = $product->getId(); - } + foreach ($this->getCartProducts() as $product) { + $ids[] = $product->getId(); } $this->setData('_cart_product_ids', $ids); } @@ -202,4 +236,93 @@ protected function _getCollection() return $collection; } + + /** + * Get product link ID field + * + * @return string + */ + private function getProductLinkField(): string + { + /* @var $collection Collection */ + $collection = $this->productCollectionFactory->create(); + return $collection->getProductEntityMetadata()->getLinkField(); + } + + /** + * Get cart products link IDs + * + * @return array + */ + private function getCartProductLinkIds(): array + { + $linkField = $this->getProductLinkField(); + $linkIds = []; + foreach ($this->getCartProducts() as $product) { + /** * @var Product $product */ + $linkIds[] = $product->getData($linkField); + } + return $linkIds; + } + + /** + * Get cart related products link IDs + * + * @return array + */ + private function getCartRelatedProductLinkIds(): array + { + $productIds = $this->_itemRelationsList->getRelatedProductIds($this->getQuote()->getAllItems()); + $linkIds = []; + if (!empty($productIds)) { + $linkField = $this->getProductLinkField(); + /* @var $collection Collection */ + $collection = $this->productCollectionFactory->create(); + $collection->addIdFilter($productIds); + foreach ($collection as $product) { + /** * @var Product $product */ + $linkIds[] = $product->getData($linkField); + } + } + return $linkIds; + } + + /** + * Retrieve just added to cart product object + * + * @return ProductInterface|null + */ + private function getLastAddedProduct(): ?ProductInterface + { + $product = null; + $productId = $this->_getLastAddedProductId(); + if ($productId) { + try { + $product = $this->productRepository->getById($productId); + } catch (NoSuchEntityException $e) { + $product = null; + } + } + return $product; + } + + /** + * Retrieve Array of Product instances in Cart + * + * @return array + */ + private function getCartProducts(): array + { + if ($this->cartProducts === null) { + $this->cartProducts = []; + foreach ($this->getQuote()->getAllItems() as $quoteItem) { + /* @var $quoteItem \Magento\Quote\Model\Quote\Item */ + $product = $quoteItem->getProduct(); + if ($product) { + $this->cartProducts[$product->getEntityId()] = $product; + } + } + } + return $this->cartProducts; + } } diff --git a/app/code/Magento/Checkout/Block/Checkout/AttributeMerger.php b/app/code/Magento/Checkout/Block/Checkout/AttributeMerger.php index 1dd1131cde1f1..0e7931146b4c4 100644 --- a/app/code/Magento/Checkout/Block/Checkout/AttributeMerger.php +++ b/app/code/Magento/Checkout/Block/Checkout/AttributeMerger.php @@ -10,6 +10,8 @@ use Magento\Customer\Helper\Address as AddressHelper; use Magento\Customer\Model\Session; use Magento\Directory\Helper\Data as DirectoryHelper; +use Magento\Directory\Model\AllowedCountries; +use Magento\Framework\App\ObjectManager; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; @@ -92,23 +94,32 @@ class AttributeMerger */ private $topCountryCodes; + /** + * @var AllowedCountries|null + */ + private $allowedCountryReader; + /** * @param AddressHelper $addressHelper * @param Session $customerSession * @param CustomerRepository $customerRepository * @param DirectoryHelper $directoryHelper + * @param AllowedCountries $allowedCountryReader */ public function __construct( AddressHelper $addressHelper, Session $customerSession, CustomerRepository $customerRepository, - DirectoryHelper $directoryHelper + DirectoryHelper $directoryHelper, + ?AllowedCountries $allowedCountryReader = null ) { $this->addressHelper = $addressHelper; $this->customerSession = $customerSession; $this->customerRepository = $customerRepository; $this->directoryHelper = $directoryHelper; $this->topCountryCodes = $directoryHelper->getTopCountryCodes(); + $this->allowedCountryReader = + $allowedCountryReader ?: ObjectManager::getInstance()->get(AllowedCountries::class); } /** @@ -289,7 +300,7 @@ protected function getMultilineFieldConfig($attributeCode, array $attributeConfi 'dataScope' => $lineIndex, 'provider' => $providerName, 'validation' => $isFirstLine - //phpcs:ignore Magento2.Performance.ForeachArrayMerge + // phpcs:ignore Magento2.Performance.ForeachArrayMerge ? array_merge( ['required-entry' => (bool)$attributeConfig['required']], $attributeConfig['validation'] @@ -330,7 +341,11 @@ protected function getMultilineFieldConfig($attributeCode, array $attributeConfi protected function getDefaultValue($attributeCode): ?string { if ($attributeCode === 'country_id') { - return $this->directoryHelper->getDefaultCountry(); + $defaultCountryId = $this->directoryHelper->getDefaultCountry(); + if (!in_array($defaultCountryId, $this->allowedCountryReader->getAllowedCountries())) { + $defaultCountryId = null; + } + return $defaultCountryId; } $customer = $this->getCustomer(); diff --git a/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml b/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml index 16fd373d3ae4d..5a9857f6aaa78 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Section/CheckoutPaymentSection.xml @@ -52,7 +52,6 @@ - diff --git a/app/code/Magento/Checkout/Test/Mftf/Test/ConfiguringInstantPurchaseFunctionalityTest.xml b/app/code/Magento/Checkout/Test/Mftf/Test/ConfiguringInstantPurchaseFunctionalityTest.xml index 016616a27a05a..6e3df1c4ed724 100644 --- a/app/code/Magento/Checkout/Test/Mftf/Test/ConfiguringInstantPurchaseFunctionalityTest.xml +++ b/app/code/Magento/Checkout/Test/Mftf/Test/ConfiguringInstantPurchaseFunctionalityTest.xml @@ -22,9 +22,10 @@ - - - + + + + @@ -37,8 +38,8 @@ - - + + @@ -74,16 +75,17 @@ - - - - - - + + + + + + + + - - + @@ -113,7 +115,9 @@ - + + + @@ -149,7 +153,9 @@ - + + + @@ -196,7 +202,9 @@ - + + + @@ -227,7 +235,9 @@ - + + + diff --git a/app/code/Magento/Checkout/Test/Unit/Block/Cart/CrosssellTest.php b/app/code/Magento/Checkout/Test/Unit/Block/Cart/CrosssellTest.php new file mode 100644 index 0000000000000..5eedb42744902 --- /dev/null +++ b/app/code/Magento/Checkout/Test/Unit/Block/Cart/CrosssellTest.php @@ -0,0 +1,348 @@ +storeManager = $this->createMock( + StoreManagerInterface::class + ); + $this->context = $objectManager->getObject( + Context::class, + [ + 'storeManager' => $this->storeManager + ] + ); + $this->checkoutSession = $this->getMockBuilder(Session::class) + ->addMethods(['getLastAddedProductId']) + ->onlyMethods(['getQuote']) + ->disableOriginalConstructor() + ->getMock(); + $this->productRepository = $this->createMock( + ProductRepositoryInterface::class + ); + $this->productLinkFactory = $this->createMock( + LinkFactory::class + ); + $this->productLinkFactory = $this->createMock( + LinkFactory::class + ); + $this->productCollectionFactory = $this->createMock( + CollectionFactory::class + ); + $this->model = $objectManager->getObject( + Crosssell::class, + [ + 'context' => $this->context, + 'checkoutSession' => $this->checkoutSession, + 'productRepository' => $this->productRepository, + 'productLinkFactory' => $this->productLinkFactory, + 'productCollectionFactory' => $this->productCollectionFactory, + ] + ); + } + + /** + * @dataProvider getItemsDataProvider + * @param array $productLinks + * @param array $cartProductIds + * @param int|null $lastAddedProductId + * @param array $expected + */ + public function testGetItems( + array $productLinks, + array $cartProductIds, + ?int $lastAddedProductId, + array $expected + ) { + $this->productLinks = $productLinks; + $cartProducts = array_map( + function ($id) { + return $this->getProduct(['entity_id' => $id]); + }, + $cartProductIds + ); + $cartItems = array_map( + function ($product) { + return new DataObject(['product' => $product]); + }, + $cartProducts + ); + $quote = new DataObject(['all_items' => $cartItems]); + $this->checkoutSession->method('getQuote') + ->willReturn($quote); + $this->checkoutSession->method('getLastAddedProductId') + ->willReturn($lastAddedProductId); + $this->productRepository->method('getById') + ->willReturnCallback( + function ($id) { + return $this->getProduct(['entity_id' => $id]); + } + ); + $link = $this->createMock(Link::class); + $this->productLinkFactory->method('create') + ->willReturn($link); + $link->method('useCrossSellLinks') + ->willReturnSelf(); + $link->method('getProductCollection') + ->willReturnCallback( + function () { + return $this->createLinkCollection(); + } + ); + $this->productCollectionFactory->method('create') + ->willReturnCallback( + function () { + return $this->createProductCollection(); + } + ); + $store = $this->createMock(StoreInterface::class); + $this->storeManager->method('getStore') + ->willReturn($store); + $actual = array_map( + function ($product) { + return $product->getId(); + }, + $this->model->getItems() + ); + $this->assertEquals($expected, $actual); + } + + /** + * @return array + */ + public function getItemsDataProvider(): array + { + $links = [ + 1001 => [ + 1003, + 1005 + ], + 1006 => [ + 1002, + ] + ]; + return [ + [ + 'productLinks' => $links, + 'cartProducts' => [ + 1001, + 1006, + ], + 'lastAddedProduct' => 1006, + 'cross-sells' => [ + 1002, + 1003, + 1005 + ] + ], + [ + 'productLinks' => $links, + 'cartProducts' => [ + 1001, + 1006, + ], + 'lastAddedProduct' => null, + 'cross-sells' => [ + 1003, + 1005, + 1002, + ] + ], + [ + 'productLinks' => $links, + 'cartProducts' => [ + 1001, + 1005, + ], + 'lastAddedProduct' => null, + 'cross-sells' => [ + 1003 + ] + ], + [ + 'productLinks' => $links, + 'cartProducts' => [ + 1002, + 1003, + ], + 'lastAddedProduct' => null, + 'cross-sells' => [ + ] + ] + ]; + } + + /** + * @param array $data + * @return MockObject + */ + private function getProduct(array $data): MockObject + { + $product = $this->createPartialMock(Product::class, []); + $product->setData($data); + return $product; + } + + /** + * @return MockObject + */ + private function createLinkCollection(): MockObject + { + $returnSelfMethods = [ + 'setStoreId', + 'setPageSize', + 'setGroupBy', + 'setVisibility', + 'addMinimalPrice', + 'addFinalPrice', + 'addTaxPercents', + 'addAttributeToSelect', + 'addStoreFilter', + 'setPositionOrder', + 'addUrlRewrite', + 'load', + ]; + $linkCollection = $this->createPartialMock( + Collection::class, + array_merge( + $returnSelfMethods, + [ + 'addProductFilter', + 'addExcludeProductFilter', + 'getSelect', + 'getIterator', + ] + ) + ); + foreach ($returnSelfMethods as $method) { + $linkCollection->method($method) + ->willReturnSelf(); + } + $linkCollection->method('addProductFilter') + ->willReturnCallback( + function ($products) use ($linkCollection) { + if (!is_array($products)) { + $products = [$products]; + } + $linkCollection->setFlag('test_product_ids', $products); + return $linkCollection; + } + ); + $linkCollection->method('addExcludeProductFilter') + ->willReturnCallback( + function ($products) use ($linkCollection) { + if (!is_array($products)) { + $products = [$products]; + } + $linkCollection->setFlag('test_exclude_product_ids', $products); + return $linkCollection; + } + ); + $linkCollection->method('getSelect')->willReturn( + $this->createMock(Select::class) + ); + $linkCollection->method('getIterator') + ->willReturnCallback( + function () use ($linkCollection) { + $productIds = $linkCollection->getFlag('test_product_ids') ?? []; + $excludeProductIds = $linkCollection->getFlag('test_exclude_product_ids') ?? []; + $links = []; + foreach ($productIds as $id) { + if (isset($this->productLinks[$id])) { + array_push($links, ...$this->productLinks[$id]); + } + } + $links = array_values(array_unique(array_diff($links, $excludeProductIds))); + $links = array_combine($links, $links); + $products = array_map( + function ($id) { + return $this->getProduct(['entity_id' => $id]); + }, + $links + ); + return new \ArrayIterator($products); + } + ); + return $linkCollection; + } + + /** + * @return MockObject + */ + private function createProductCollection(): MockObject + { + $productCollection = $this->createMock(\Magento\Catalog\Model\ResourceModel\Product\Collection::class); + $entityMetadataInterface =$this->createMock(EntityMetadataInterface::class); + $entityMetadataInterface->method('getLinkField') + ->willReturn('entity_id'); + $productCollection->method('getProductEntityMetadata') + ->willReturn($entityMetadataInterface); + return $productCollection; + } +} diff --git a/app/code/Magento/CheckoutAgreements/etc/db_schema.xml b/app/code/Magento/CheckoutAgreements/etc/db_schema.xml index 43da8d7d27dd9..6134965a5b5ac 100644 --- a/app/code/Magento/CheckoutAgreements/etc/db_schema.xml +++ b/app/code/Magento/CheckoutAgreements/etc/db_schema.xml @@ -8,26 +8,26 @@
- - - -
- - diff --git a/app/code/Magento/Cms/etc/db_schema.xml b/app/code/Magento/Cms/etc/db_schema.xml index 9ff3153098482..ac49421d31e8e 100644 --- a/app/code/Magento/Cms/etc/db_schema.xml +++ b/app/code/Magento/Cms/etc/db_schema.xml @@ -8,7 +8,7 @@
- @@ -17,7 +17,7 @@ comment="Block Creation Time"/> - @@ -29,8 +29,8 @@
- - + @@ -45,7 +45,7 @@
- @@ -58,9 +58,9 @@ comment="Page Creation Time"/> - - @@ -88,9 +88,9 @@
- - diff --git a/app/code/Magento/Config/etc/db_schema.xml b/app/code/Magento/Config/etc/db_schema.xml index 54680c0be7b06..10338b9f7ef1f 100644 --- a/app/code/Magento/Config/etc/db_schema.xml +++ b/app/code/Magento/Config/etc/db_schema.xml @@ -8,10 +8,10 @@
- - diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/ActionGroup/AdminCreateConfigurationsByAttributeCodeAndNavigateToOptionsQuantityActionGroup.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/ActionGroup/AdminCreateConfigurationsByAttributeCodeAndNavigateToOptionsQuantityActionGroup.xml new file mode 100644 index 0000000000000..581e2f5af10bd --- /dev/null +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/ActionGroup/AdminCreateConfigurationsByAttributeCodeAndNavigateToOptionsQuantityActionGroup.xml @@ -0,0 +1,28 @@ + + + + + + + Selects all Attribute options for the provided Attribute Code and navigates to Options quantity on the Configurable Product creation/edit page. + + + + + + + + + + + + + + + diff --git a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductRemoveConfigurationTest.xml b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductRemoveConfigurationTest.xml index bef7d26c5007f..a4051adfe5d28 100644 --- a/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductRemoveConfigurationTest.xml +++ b/app/code/Magento/ConfigurableProduct/Test/Mftf/Test/AdminConfigurableProductUpdateTest/AdminConfigurableProductRemoveConfigurationTest.xml @@ -25,7 +25,13 @@ + + + + + + diff --git a/app/code/Magento/ConfigurableProduct/etc/db_schema.xml b/app/code/Magento/ConfigurableProduct/etc/db_schema.xml index d6917e8c1845a..2faaba565e9f8 100644 --- a/app/code/Magento/ConfigurableProduct/etc/db_schema.xml +++ b/app/code/Magento/ConfigurableProduct/etc/db_schema.xml @@ -9,13 +9,13 @@ xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
- - - - @@ -30,13 +30,13 @@
- - - - @@ -59,11 +59,11 @@
- - - diff --git a/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/components/dynamic-rows-configurable.js b/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/components/dynamic-rows-configurable.js index 4624f07323d59..68e7d146d33e0 100644 --- a/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/components/dynamic-rows-configurable.js +++ b/app/code/Magento/ConfigurableProduct/view/adminhtml/web/js/components/dynamic-rows-configurable.js @@ -212,7 +212,7 @@ define([ ); tmpData = data.slice(this.pageSize * (this.currentPage() - 1), - this.pageSize * (this.currentPage() - 1) + this.pageSize); + this.pageSize * (this.currentPage() - 1) + parseInt(this.pageSize, 10)); this.source.set(this.dataScope + '.' + this.index, []); diff --git a/app/code/Magento/ConfigurableProduct/view/adminhtml/web/template/variations/steps/summary-grid.html b/app/code/Magento/ConfigurableProduct/view/adminhtml/web/template/variations/steps/summary-grid.html index ff247c14bf52b..bf1e1ad5fe1e1 100644 --- a/app/code/Magento/ConfigurableProduct/view/adminhtml/web/template/variations/steps/summary-grid.html +++ b/app/code/Magento/ConfigurableProduct/view/adminhtml/web/template/variations/steps/summary-grid.html @@ -5,14 +5,14 @@ */ --> -
-
+
+
-
+
diff --git a/app/code/Magento/ConfigurableProduct/view/frontend/web/js/configurable.js b/app/code/Magento/ConfigurableProduct/view/frontend/web/js/configurable.js index 8fd1d761040d7..f705b6a95987c 100644 --- a/app/code/Magento/ConfigurableProduct/view/frontend/web/js/configurable.js +++ b/app/code/Magento/ConfigurableProduct/view/frontend/web/js/configurable.js @@ -33,7 +33,7 @@ define([ mediaGallerySelector: '[data-gallery-role=gallery-placeholder]', mediaGalleryInitial: null, slyOldPriceSelector: '.sly-old-price', - normalPriceLabelSelector: '.normal-price .price-label', + normalPriceLabelSelector: '.product-info-main .normal-price .price-label', /** * Defines the mechanism of how images of a gallery should be diff --git a/app/code/Magento/Cron/etc/db_schema.xml b/app/code/Magento/Cron/etc/db_schema.xml index 206b8f64f3ae7..f26b6feea3b3b 100644 --- a/app/code/Magento/Cron/etc/db_schema.xml +++ b/app/code/Magento/Cron/etc/db_schema.xml @@ -8,7 +8,7 @@
- diff --git a/app/code/Magento/Cron/etc/di.xml b/app/code/Magento/Cron/etc/di.xml index bc321c2a1e2b6..e7286169359bd 100644 --- a/app/code/Magento/Cron/etc/di.xml +++ b/app/code/Magento/Cron/etc/di.xml @@ -68,14 +68,6 @@ {magentoRoot}bin/magento cron:run | grep -v "Ran jobs by schedule" >> {magentoLog}magento.cron.log false - - {magentoRoot}update/cron.php >> {magentoLog}update.cron.log - true - - - {magentoRoot}bin/magento setup:cron:run >> {magentoLog}setup.cron.log - true - diff --git a/app/code/Magento/Customer/Controller/Adminhtml/Index/Save.php b/app/code/Magento/Customer/Controller/Adminhtml/Index/Save.php index a65bfa5d77f9e..977d3753ded65 100644 --- a/app/code/Magento/Customer/Controller/Adminhtml/Index/Save.php +++ b/app/code/Magento/Customer/Controller/Adminhtml/Index/Save.php @@ -248,7 +248,7 @@ protected function _extractData( * @param array $extractedCustomerData * @return array */ - protected function saveDefaultFlags(array $addressIdList, array & $extractedCustomerData) + protected function saveDefaultFlags(array $addressIdList, array &$extractedCustomerData) { $result = []; $extractedCustomerData[CustomerInterface::DEFAULT_BILLING] = null; @@ -290,7 +290,7 @@ protected function saveDefaultFlags(array $addressIdList, array & $extractedCust * @param array $extractedCustomerData * @return array */ - protected function _extractCustomerAddressData(array & $extractedCustomerData) + protected function _extractCustomerAddressData(array &$extractedCustomerData) { $addresses = $this->getRequest()->getPost('address'); $result = []; @@ -380,6 +380,12 @@ public function execute() $this->_coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customerId); $this->messageManager->addSuccessMessage(__('You saved the customer.')); $returnToEdit = (bool)$this->getRequest()->getParam('back', false); + } catch (NoSuchEntityException $exception) { + $this->messageManager->addExceptionMessage( + $exception, + __('Something went wrong while saving the customer.') + ); + $returnToEdit = false; } catch (\Magento\Framework\Validator\Exception $exception) { $messages = $exception->getMessages(); if (empty($messages)) { diff --git a/app/code/Magento/Customer/Model/Customer/DataProviderWithDefaultAddresses.php b/app/code/Magento/Customer/Model/Customer/DataProviderWithDefaultAddresses.php index fbf9cf4cbbf9a..604295cc0c078 100644 --- a/app/code/Magento/Customer/Model/Customer/DataProviderWithDefaultAddresses.php +++ b/app/code/Magento/Customer/Model/Customer/DataProviderWithDefaultAddresses.php @@ -9,17 +9,20 @@ use Magento\Customer\Model\Address; use Magento\Customer\Model\Customer; use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory as CustomerCollectionFactory; +use Magento\Directory\Model\CountryFactory; use Magento\Eav\Model\Config; use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Eav\Model\Entity\Type; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Session\SessionManagerInterface; use Magento\Customer\Model\FileUploaderDataResolver; use Magento\Customer\Model\AttributeMetadataResolver; +use Magento\Ui\DataProvider\AbstractDataProvider; /** * Refactored version of Magento\Customer\Model\Customer\DataProvider with eliminated usage of addresses collection. */ -class DataProviderWithDefaultAddresses extends \Magento\Ui\DataProvider\AbstractDataProvider +class DataProviderWithDefaultAddresses extends AbstractDataProvider { /** * @var array @@ -49,7 +52,7 @@ class DataProviderWithDefaultAddresses extends \Magento\Ui\DataProvider\Abstract private $allowToShowHiddenAttributes; /** - * @var \Magento\Directory\Model\CountryFactory + * @var CountryFactory */ private $countryFactory; @@ -69,14 +72,14 @@ class DataProviderWithDefaultAddresses extends \Magento\Ui\DataProvider\Abstract * @param string $requestFieldName * @param CustomerCollectionFactory $customerCollectionFactory * @param Config $eavConfig - * @param \Magento\Directory\Model\CountryFactory $countryFactory + * @param CountryFactory $countryFactory * @param SessionManagerInterface $session * @param FileUploaderDataResolver $fileUploaderDataResolver * @param AttributeMetadataResolver $attributeMetadataResolver * @param bool $allowToShowHiddenAttributes * @param array $meta * @param array $data - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -85,7 +88,7 @@ public function __construct( string $requestFieldName, CustomerCollectionFactory $customerCollectionFactory, Config $eavConfig, - \Magento\Directory\Model\CountryFactory $countryFactory, + CountryFactory $countryFactory, SessionManagerInterface $session, FileUploaderDataResolver $fileUploaderDataResolver, AttributeMetadataResolver $attributeMetadataResolver, @@ -158,17 +161,21 @@ public function getData(): array */ private function prepareDefaultAddress($address): array { - $addressData = []; - - if (!empty($address)) { - $addressData = $address->getData(); - if (isset($addressData['street']) && !\is_array($address['street'])) { - $addressData['street'] = explode("\n", $addressData['street']); - } - $countryId = $addressData['country_id'] ?? null; - $addressData['country'] = $this->countryFactory->create()->loadByCode($countryId)->getName(); + if (!$address) { + return []; } + $addressData = $address->getData(); + if (isset($addressData['street']) && !is_array($addressData['street'])) { + $addressData['street'] = explode("\n", $addressData['street']); + } + if (!empty($addressData['country_id'])) { + $addressData['country'] = $this->countryFactory->create() + ->loadByCode($addressData['country_id']) + ->getName(); + } + $addressData['region'] = $address->getRegion(); + return $addressData; } @@ -177,7 +184,7 @@ private function prepareDefaultAddress($address): array * * @param Type $entityType * @return array - * @throws \Magento\Framework\Exception\LocalizedException + * @throws LocalizedException */ private function getAttributesMeta(Type $entityType): array { diff --git a/app/code/Magento/Customer/Model/CustomerExtractor.php b/app/code/Magento/Customer/Model/CustomerExtractor.php index 5d6f3245a0439..b9739ce0424a1 100644 --- a/app/code/Magento/Customer/Model/CustomerExtractor.php +++ b/app/code/Magento/Customer/Model/CustomerExtractor.php @@ -93,13 +93,15 @@ public function extract( $customerData, \Magento\Customer\Api\Data\CustomerInterface::class ); - + $store = $this->storeManager->getStore(); $storeId = $store->getId(); - + if ($isGroupIdEmpty) { + $groupId = isset($customerData['group_id']) ? $customerData['group_id'] + : $this->customerGroupManagement->getDefaultGroup($storeId)->getId(); $customerDataObject->setGroupId( - $this->customerGroupManagement->getDefaultGroup($storeId)->getId() + $groupId ); } diff --git a/app/code/Magento/Customer/Model/ResourceModel/Address/Grid/Collection.php b/app/code/Magento/Customer/Model/ResourceModel/Address/Grid/Collection.php index 4e0347059086f..0e2eb3e1d8e65 100644 --- a/app/code/Magento/Customer/Model/ResourceModel/Address/Grid/Collection.php +++ b/app/code/Magento/Customer/Model/ResourceModel/Address/Grid/Collection.php @@ -6,53 +6,84 @@ */ namespace Magento\Customer\Model\ResourceModel\Address\Grid; +use Magento\Framework\Api\ExtensibleDataInterface; use Magento\Framework\Api\Search\SearchResultInterface; use Magento\Framework\Api\Search\AggregationInterface; +use Magento\Framework\Api\SearchCriteriaInterface; +use Magento\Framework\Data\Collection\Db\FetchStrategyInterface; +use Magento\Framework\Data\Collection\EntityFactoryInterface; +use Magento\Framework\DB\Adapter\AdapterInterface; +use Magento\Framework\Event\ManagerInterface; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; +use Magento\Framework\View\Element\UiComponent\DataProvider\Document; +use Psr\Log\LoggerInterface; /** * Class getting collection of addresses assigned to customer */ class Collection extends AbstractCollection implements SearchResultInterface { + /** + * List of fields to fulltext search + */ + private const FIELDS_TO_FULLTEXT_SEARCH = [ + 'firstname', + 'lastname', + 'street', + 'city', + 'region', + 'postcode', + 'telephone', + ]; + /** * @var AggregationInterface */ private $aggregations; /** - * @param \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory - * @param \Psr\Log\LoggerInterface $logger - * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy - * @param \Magento\Framework\Event\ManagerInterface $eventManager + * @var ResolverInterface + */ + private $localeResolver; + + /** + * @param EntityFactoryInterface $entityFactory + * @param LoggerInterface $logger + * @param FetchStrategyInterface $fetchStrategy + * @param ManagerInterface $eventManager * @param string $mainTable * @param string $eventPrefix * @param string $eventObject * @param string $resourceModel + * @param ResolverInterface $localeResolver * @param string $model - * @param \Magento\Framework\DB\Adapter\AdapterInterface|string|null $connection - * @param \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource + * @param AdapterInterface|string|null $connection + * @param AbstractDb $resource * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( - \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory, - \Psr\Log\LoggerInterface $logger, - \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy, - \Magento\Framework\Event\ManagerInterface $eventManager, + EntityFactoryInterface $entityFactory, + LoggerInterface $logger, + FetchStrategyInterface $fetchStrategy, + ManagerInterface $eventManager, $mainTable, $eventPrefix, $eventObject, $resourceModel, - $model = \Magento\Framework\View\Element\UiComponent\DataProvider\Document::class, + ResolverInterface $localeResolver, + $model = Document::class, $connection = null, - \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null + AbstractDb $resource = null ) { $this->_eventPrefix = $eventPrefix; $this->_eventObject = $eventObject; + $this->_idFieldName = 'entity_id'; + $this->localeResolver = $localeResolver; $this->_init($model, $resourceModel); $this->setMainTable($mainTable); - $this->_idFieldName = 'entity_id'; parent::__construct( $entityFactory, $logger, @@ -65,8 +96,17 @@ public function __construct( /** * @inheritdoc - * - * @return AggregationInterface + */ + protected function _initSelect() + { + parent::_initSelect(); + $this->joinRegionNameTable(); + + return $this; + } + + /** + * @inheritdoc */ public function getAggregations() { @@ -75,9 +115,6 @@ public function getAggregations() /** * @inheritdoc - * - * @param AggregationInterface $aggregations - * @return $this */ public function setAggregations($aggregations) { @@ -88,7 +125,7 @@ public function setAggregations($aggregations) /** * Get search criteria. * - * @return \Magento\Framework\Api\SearchCriteriaInterface|null + * @return SearchCriteriaInterface|null */ public function getSearchCriteria() { @@ -98,11 +135,11 @@ public function getSearchCriteria() /** * Set search criteria. * - * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria + * @param SearchCriteriaInterface $searchCriteria * @return $this * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ - public function setSearchCriteria(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria = null) + public function setSearchCriteria(SearchCriteriaInterface $searchCriteria = null) { return $this; } @@ -132,7 +169,7 @@ public function setTotalCount($totalCount) /** * Set items list. * - * @param \Magento\Framework\Api\ExtensibleDataInterface[] $items + * @param ExtensibleDataInterface[] $items * @return $this * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ @@ -140,4 +177,97 @@ public function setItems(array $items = null) { return $this; } + + /** + * @inheritdoc + */ + public function addFieldToFilter($field, $condition = null) + { + if ($field === 'region') { + $conditionSql = $this->_getConditionSql( + $this->getRegionNameExpresion(), + $condition + ); + $this->getSelect()->where($conditionSql); + return $this; + } + + if (is_string($field) && count(explode('.', $field)) === 1) { + $field = 'main_table.' . $field; + } + + return parent::addFieldToFilter($field, $condition); + } + + /** + * Add fulltext filter + * + * @param string $value + * @return $this + */ + public function addFullTextFilter(string $value) + { + $fields = self::FIELDS_TO_FULLTEXT_SEARCH; + $whereCondition = ''; + foreach ($fields as $key => $field) { + $field = $field === 'region' + ? $this->getRegionNameExpresion() + : 'main_table.' . $field; + $condition = $this->_getConditionSql( + $this->getConnection()->quoteIdentifier($field), + ['like' => "%$value%"] + ); + $whereCondition .= ($key === 0 ? '' : ' OR ') . $condition; + } + if ($whereCondition) { + $this->getSelect()->where($whereCondition); + } + + return $this; + } + + /** + * Join region name table by current locale + * + * @return $this + */ + private function joinRegionNameTable() + { + $locale = $this->localeResolver->getLocale(); + $connection = $this->getConnection(); + $regionIdField = $connection->quoteIdentifier('main_table.region_id'); + $localeCondition = $connection->quoteInto("rnt.locale=?", $locale); + + $this->getSelect() + ->joinLeft( + ['rct' => $this->getTable('directory_country_region')], + "rct.region_id={$regionIdField}", + [] + )->joinLeft( + ['rnt' => $this->getTable('directory_country_region_name')], + "rnt.region_id={$regionIdField} AND {$localeCondition}", + ['region' => $this->getRegionNameExpresion()] + ); + + return $this; + } + + /** + * Get SQL Expresion to define Region Name field by locale + * + * @return \Zend_Db_Expr + */ + private function getRegionNameExpresion(): \Zend_Db_Expr + { + $connection = $this->getConnection(); + $defaultNameExpr = $connection->getIfNullSql( + $connection->quoteIdentifier('rct.default_name'), + $connection->quoteIdentifier('main_table.region') + ); + + return $connection->getIfNullSql( + $connection->quoteIdentifier('rnt.name'), + $defaultNameExpr + ); + } } diff --git a/app/code/Magento/Customer/Model/ResourceModel/Grid/Collection.php b/app/code/Magento/Customer/Model/ResourceModel/Grid/Collection.php index 15678bd3dfd3f..bf8ef767063bd 100644 --- a/app/code/Magento/Customer/Model/ResourceModel/Grid/Collection.php +++ b/app/code/Magento/Customer/Model/ResourceModel/Grid/Collection.php @@ -3,17 +3,27 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ - namespace Magento\Customer\Model\ResourceModel\Grid; +use Magento\Customer\Model\ResourceModel\Customer; use Magento\Customer\Ui\Component\DataProvider\Document; use Magento\Framework\Data\Collection\Db\FetchStrategyInterface as FetchStrategy; use Magento\Framework\Data\Collection\EntityFactoryInterface as EntityFactory; use Magento\Framework\Event\ManagerInterface as EventManager; +use Magento\Framework\Locale\ResolverInterface; +use Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult; use Psr\Log\LoggerInterface as Logger; -class Collection extends \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult +/** + * Collection to present grid of customers on admin area + */ +class Collection extends SearchResult { + /** + * @var ResolverInterface + */ + private $localeResolver; + /** * @inheritdoc */ @@ -25,12 +35,11 @@ class Collection extends \Magento\Framework\View\Element\UiComponent\DataProvide protected $_map = ['fields' => ['entity_id' => 'main_table.entity_id']]; /** - * Initialize dependencies. - * * @param EntityFactory $entityFactory * @param Logger $logger * @param FetchStrategy $fetchStrategy * @param EventManager $eventManager + * @param ResolverInterface $localeResolver * @param string $mainTable * @param string $resourceModel */ @@ -39,9 +48,132 @@ public function __construct( Logger $logger, FetchStrategy $fetchStrategy, EventManager $eventManager, + ResolverInterface $localeResolver, $mainTable = 'customer_grid_flat', - $resourceModel = \Magento\Customer\Model\ResourceModel\Customer::class + $resourceModel = Customer::class ) { + $this->localeResolver = $localeResolver; parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $mainTable, $resourceModel); } + + /** + * @inheritdoc + */ + protected function _initSelect() + { + parent::_initSelect(); + $this->joinRegionNameTable(); + + return $this; + } + + /** + * @inheritdoc + */ + public function addFieldToFilter($field, $condition = null) + { + if ($field === 'billing_region') { + $conditionSql = $this->_getConditionSql( + $this->getRegionNameExpresion(), + $condition + ); + $this->getSelect()->where($conditionSql); + return $this; + } + + if (is_string($field) && count(explode('.', $field)) === 1) { + $field = 'main_table.' . $field; + } + + return parent::addFieldToFilter($field, $condition); + } + + /** + * Add fulltext filter + * + * @param string $value + * @return $this + */ + public function addFullTextFilter(string $value) + { + $fields = $this->getFulltextIndexColumns(); + $whereCondition = ''; + foreach ($fields as $key => $field) { + $field = $field === 'billing_region' + ? $this->getRegionNameExpresion() + : 'main_table.' . $field; + $condition = $this->_getConditionSql( + $this->getConnection()->quoteIdentifier($field), + ['like' => "%$value%"] + ); + $whereCondition .= ($key === 0 ? '' : ' OR ') . $condition; + } + + if ($whereCondition) { + $this->getSelect()->where($whereCondition); + } + + return $this; + } + + /** + * Returns list of columns from fulltext index + * + * @return array + */ + private function getFulltextIndexColumns(): array + { + $indexes = $this->getConnection()->getIndexList($this->getMainTable()); + foreach ($indexes as $index) { + if (strtoupper($index['INDEX_TYPE']) == 'FULLTEXT') { + return $index['COLUMNS_LIST']; + } + } + return []; + } + + /** + * Join region name table by current locale + * + * @return $this + */ + private function joinRegionNameTable() + { + $locale = $this->localeResolver->getLocale(); + $connection = $this->getConnection(); + $regionIdField = $connection->quoteIdentifier('main_table.billing_region_id'); + $localeCondition = $connection->quoteInto("rnt.locale=?", $locale); + + $this->getSelect() + ->joinLeft( + ['rct' => $this->getTable('directory_country_region')], + "rct.region_id={$regionIdField}", + [] + )->joinLeft( + ['rnt' => $this->getTable('directory_country_region_name')], + "rnt.region_id={$regionIdField} AND {$localeCondition}", + ['billing_region' => $this->getRegionNameExpresion()] + ); + + return $this; + } + + /** + * Get SQL Expresion to define Region Name field by locale + * + * @return \Zend_Db_Expr + */ + private function getRegionNameExpresion(): \Zend_Db_Expr + { + $connection = $this->getConnection(); + $defaultNameExpr = $connection->getIfNullSql( + $connection->quoteIdentifier('rct.default_name'), + $connection->quoteIdentifier('main_table.billing_region') + ); + + return $connection->getIfNullSql( + $connection->quoteIdentifier('rnt.name'), + $defaultNameExpr + ); + } } diff --git a/app/code/Magento/Customer/Test/Mftf/Data/NewCustomerData.xml b/app/code/Magento/Customer/Test/Mftf/Data/NewCustomerData.xml index 347a04251f9cd..0a357c86ed9f8 100644 --- a/app/code/Magento/Customer/Test/Mftf/Data/NewCustomerData.xml +++ b/app/code/Magento/Customer/Test/Mftf/Data/NewCustomerData.xml @@ -8,18 +8,6 @@ - - Abgar - Abgaryan - m@m.com - Abgar - Abgaryan - Street - Yerevan - 9999 - 9999 - Armenia - John Doe diff --git a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontLoginWithIncorrectCredentialsTest.xml b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontLoginWithIncorrectCredentialsTest.xml index 104b5d56314ba..a7dc3c7fde7f4 100644 --- a/app/code/Magento/Customer/Test/Mftf/Test/StorefrontLoginWithIncorrectCredentialsTest.xml +++ b/app/code/Magento/Customer/Test/Mftf/Test/StorefrontLoginWithIncorrectCredentialsTest.xml @@ -26,10 +26,14 @@ - - - - - + + + + + + + + + diff --git a/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderWithDefaultAddressesTest.php b/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderWithDefaultAddressesTest.php index 0cb135ee66a12..fbeefb26efedb 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderWithDefaultAddressesTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Customer/DataProviderWithDefaultAddressesTest.php @@ -1,5 +1,4 @@ eavConfigMock = $this->getMockBuilder(Config::class) - ->disableOriginalConstructor() - ->getMock(); + $this->eavConfigMock = $this->getMockBuilder(Config::class)->disableOriginalConstructor()->getMock(); $this->customerCollectionFactoryMock = $this->createPartialMock(CustomerCollectionFactory::class, ['create']); $this->sessionMock = $this->getMockBuilder(SessionManagerInterface::class) ->setMethods(['getCustomerFormData', 'unsCustomerFormData']) @@ -161,20 +164,21 @@ protected function setUp(): void ], ] ); + $helper = new ObjectManager($this); $this->dataProvider = $helper->getObject( DataProviderWithDefaultAddresses::class, [ - 'name' => 'test-name', - 'primaryFieldName' => 'primary-field-name', - 'requestFieldName' => 'request-field-name', + 'name' => 'test-name', + 'primaryFieldName' => 'primary-field-name', + 'requestFieldName' => 'request-field-name', 'customerCollectionFactory' => $this->customerCollectionFactoryMock, - 'eavConfig' => $this->eavConfigMock, - 'countryFactory' => $this->countryFactoryMock, - 'session' => $this->sessionMock, - 'fileUploaderDataResolver' => $this->fileUploaderDataResolver, + 'eavConfig' => $this->eavConfigMock, + 'countryFactory' => $this->countryFactoryMock, + 'session' => $this->sessionMock, + 'fileUploaderDataResolver' => $this->fileUploaderDataResolver, 'attributeMetadataResolver' => $this->attributeMetadataResolver, - true + 'allowToShowHiddenAttributes' => true, ] ); } @@ -343,6 +347,7 @@ protected function getAttributeMock($options = []): array */ public function testGetData(): void { + $customerId = 1; $customerData = [ 'email' => 'test@test.ua', 'default_billing' => 2, @@ -350,18 +355,35 @@ public function testGetData(): void 'password_hash' => 'password_hash', 'rp_token' => 'rp_token', ]; + $addressData = [ + 'country_id' => 'code', + 'entity_id' => 2, + 'parent_id' => $customerId, + 'street' => "line 1\nline 2", + 'region' => 'Region Name', + ]; + $localeRegionName = 'Locale Region Name'; - $address = $this->getMockBuilder(Address::class) - ->disableOriginalConstructor() - ->getMock(); - $this->customerCollectionMock->expects($this->once())->method('getItems')->willReturn([$this->customerMock]); - $this->customerMock->expects($this->once())->method('getData')->willReturn($customerData); - $this->customerMock->expects($this->atLeastOnce())->method('getId')->willReturn(1); + $address = $this->createMock(Address::class); + $address->method('getData')->willReturn($addressData); + $address->method('getRegion')->willReturn($localeRegionName); + + $this->customerCollectionMock->method('getItems')->willReturn([$this->customerMock]); + $this->customerMock->method('getDefaultBillingAddress')->willReturn($address); + $this->customerMock->method('getDefaultShippingAddress')->willReturn(false); + $this->customerMock->method('getData')->willReturn($customerData); + $this->customerMock->method('getId')->willReturn($customerId); - $this->customerMock->expects($this->once())->method('getDefaultBillingAddress')->willReturn($address); - $this->countryFactoryMock->expects($this->once())->method('create')->willReturnSelf(); - $this->countryFactoryMock->expects($this->once())->method('loadByCode')->willReturnSelf(); - $this->countryFactoryMock->expects($this->once())->method('getName')->willReturn('Ukraine'); + $this->countryFactoryMock->expects($this->once()) + ->method('create') + ->willReturnSelf(); + $this->countryFactoryMock->expects($this->once()) + ->method('loadByCode') + ->with('code') + ->willReturnSelf(); + $this->countryFactoryMock->expects($this->once()) + ->method('getName') + ->willReturn('Ukraine'); $this->sessionMock->expects($this->once()) ->method('getCustomerFormData') @@ -369,7 +391,7 @@ public function testGetData(): void $this->assertEquals( [ - 1 => [ + $customerId => [ 'customer' => [ 'email' => 'test@test.ua', 'default_billing' => 2, @@ -377,9 +399,14 @@ public function testGetData(): void ], 'default_billing_address' => [ 'country' => 'Ukraine', + 'country_id' => 'code', + 'entity_id' => 2, + 'parent_id' => $customerId, + 'street' => ['line 1', 'line 2'], + 'region' => $localeRegionName, ], 'default_shipping_address' => [], - 'customer_id' => 1 + 'customer_id' => $customerId ] ], $this->dataProvider->getData() diff --git a/app/code/Magento/Customer/Test/Unit/Model/CustomerExtractorTest.php b/app/code/Magento/Customer/Test/Unit/Model/CustomerExtractorTest.php index 0bc45ab97e6e0..3613298ab85f2 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/CustomerExtractorTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/CustomerExtractorTest.php @@ -121,14 +121,27 @@ protected function setUp(): void ); } - public function testExtract() + /** + * @param int $storeId + * @param int $websiteId + * @param array $customerData + * @dataProvider getDataProvider + * @return void + */ + public function testExtract(int $storeId, int $websiteId, array $customerData) { - $customerData = [ - 'firstname' => 'firstname', - 'lastname' => 'firstname', - 'email' => 'email.example.com', - ]; + $this->initializeExpectation($storeId, $websiteId, $customerData); + $this->assertSame($this->customerData, $this->customerExtractor->extract('form-code', $this->request)); + } + + /** + * @param int $storeId + * @param int $websiteId + * @param array $customerData + */ + private function initializeExpectation(int $storeId, int $websiteId, array $customerData): void + { $this->formFactory->expects($this->once()) ->method('create') ->with('customer', 'form-code') @@ -156,17 +169,54 @@ public function testExtract() ->willReturn($this->store); $this->store->expects($this->once()) ->method('getId') - ->willReturn(1); + ->willReturn($storeId); $this->store->expects($this->once()) ->method('getWebsiteId') - ->willReturn(1); + ->willReturn($websiteId); $this->customerData->expects($this->once()) ->method('setWebsiteId') - ->with(1); + ->with($websiteId); $this->customerData->expects($this->once()) ->method('setStoreId') - ->with(1); + ->with($storeId); + } - $this->assertSame($this->customerData, $this->customerExtractor->extract('form-code', $this->request)); + /** + * @return array + */ + public function getDataProvider() + { + return [ + 'extract data when group id is null' => [ + 1, + 1, + [ + 'firstname' => 'firstname-1', + 'lastname' => 'firstname-1', + 'email' => 'email-1.example.com', + 'group_id' => null + ] + ], + 'extract data when group id is not null and default' => [ + 1, + 2, + [ + 'firstname' => 'firstname-2', + 'lastname' => 'firstname-3', + 'email' => 'email-2.example.com', + 'group_id' => 1 + ] + ], + 'extract data when group id is different from default' => [ + 1, + 1, + [ + 'firstname' => 'firstname-3', + 'lastname' => 'firstname-3', + 'email' => 'email-3.example.com', + 'group_id' => 2 + ] + ], + ]; } } diff --git a/app/code/Magento/Customer/Ui/Component/Listing/Address/DataProvider.php b/app/code/Magento/Customer/Ui/Component/Listing/Address/DataProvider.php index c70e25ee99ec3..e26a32ec15c62 100644 --- a/app/code/Magento/Customer/Ui/Component/Listing/Address/DataProvider.php +++ b/app/code/Magento/Customer/Ui/Component/Listing/Address/DataProvider.php @@ -5,17 +5,20 @@ */ namespace Magento\Customer\Ui\Component\Listing\Address; +use Magento\Customer\Model\ResourceModel\Address\Grid\Collection as GridCollection; use Magento\Customer\Model\ResourceModel\Address\Grid\CollectionFactory; use Magento\Directory\Model\CountryFactory; use Magento\Framework\Api\Filter; +use Magento\Framework\App\RequestInterface; +use Magento\Ui\DataProvider\AbstractDataProvider; /** * Custom DataProvider for customer addresses listing */ -class DataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider +class DataProvider extends AbstractDataProvider { /** - * @var \Magento\Framework\App\RequestInterface $request, + * @var RequestInterface $request, */ private $request; @@ -29,7 +32,7 @@ class DataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider * @param string $primaryFieldName * @param string $requestFieldName * @param CollectionFactory $collectionFactory - * @param \Magento\Framework\App\RequestInterface $request + * @param RequestInterface $request * @param CountryFactory $countryFactory * @param array $meta * @param array $data @@ -39,7 +42,7 @@ public function __construct( $primaryFieldName, $requestFieldName, CollectionFactory $collectionFactory, - \Magento\Framework\App\RequestInterface $request, + RequestInterface $request, CountryFactory $countryFactory, array $meta = [], array $data = [] @@ -57,6 +60,7 @@ public function __construct( */ public function getData(): array { + /** @var GridCollection $collection */ $collection = $this->getCollection(); $data['items'] = []; if ($this->request->getParam('parent_id')) { @@ -80,34 +84,15 @@ public function getData(): array */ public function addFilter(Filter $filter): void { - if ($filter->getField() !== 'fulltext') { - $this->collection->addFieldToFilter( + /** @var GridCollection $collection */ + $collection = $this->getCollection(); + if ($filter->getField() === 'fulltext') { + $collection->addFullTextFilter(trim($filter->getValue())); + } else { + $collection->addFieldToFilter( $filter->getField(), [$filter->getConditionType() => $filter->getValue()] ); - } else { - $value = trim($filter->getValue()); - $this->collection->addFieldToFilter( - [ - ['attribute' => 'firstname'], - ['attribute' => 'lastname'], - ['attribute' => 'street'], - ['attribute' => 'city'], - ['attribute' => 'region'], - ['attribute' => 'postcode'], - ['attribute' => 'telephone'] - ], - [ - ['like' => "%{$value}%"], - ['like' => "%{$value}%"], - ['like' => "%{$value}%"], - ['like' => "%{$value}%"], - ['like' => "%{$value}%"], - ['like' => "%{$value}%"], - ['like' => "%{$value}%"], - ['like' => "%{$value}%"], - ] - ); } } } diff --git a/app/code/Magento/Customer/Ui/Component/Listing/FulltextFilter.php b/app/code/Magento/Customer/Ui/Component/Listing/FulltextFilter.php new file mode 100644 index 0000000000000..b6821e002f645 --- /dev/null +++ b/app/code/Magento/Customer/Ui/Component/Listing/FulltextFilter.php @@ -0,0 +1,34 @@ +addFullTextFilter(trim($filter->getValue())); + } +} diff --git a/app/code/Magento/Customer/etc/adminhtml/di.xml b/app/code/Magento/Customer/etc/adminhtml/di.xml index 575fd639fa539..9f207ea8bebd1 100644 --- a/app/code/Magento/Customer/etc/adminhtml/di.xml +++ b/app/code/Magento/Customer/etc/adminhtml/di.xml @@ -23,4 +23,22 @@ + + + + Magento\Framework\View\Element\UiComponent\DataProvider\RegularFilter + Magento\Customer\Ui\Component\Listing\FulltextFilter + + + + + + CustomerGirdFilterPool + + + + + CustomerGridCollectionReporting + + diff --git a/app/code/Magento/Customer/etc/db_schema.xml b/app/code/Magento/Customer/etc/db_schema.xml index 9f6d75f8ff64f..63ac8d9c1e46b 100644 --- a/app/code/Magento/Customer/etc/db_schema.xml +++ b/app/code/Magento/Customer/etc/db_schema.xml @@ -8,23 +8,23 @@
- - - - - - @@ -37,15 +37,15 @@ - - - -
- - - @@ -97,19 +97,19 @@ - - - @@ -123,11 +123,11 @@
- - - @@ -154,11 +154,11 @@
- - - @@ -185,13 +185,13 @@
- - - - @@ -217,11 +217,11 @@
- - - @@ -243,11 +243,11 @@
- - - @@ -273,11 +273,11 @@
- - - @@ -303,11 +303,11 @@
- - - @@ -334,13 +334,13 @@
- - - - @@ -365,11 +365,11 @@
- - - @@ -390,11 +390,11 @@
- - - @@ -420,36 +420,36 @@
- + -
- - - - - - - - - @@ -463,7 +463,7 @@
- @@ -478,16 +478,16 @@
- - - - - @@ -504,9 +504,9 @@
- -
- - + diff --git a/app/code/Magento/Customer/view/frontend/layout/customer_account_index.xml b/app/code/Magento/Customer/view/frontend/layout/customer_account_index.xml index 4494a5dd67103..67b2c2ed02b53 100644 --- a/app/code/Magento/Customer/view/frontend/layout/customer_account_index.xml +++ b/app/code/Magento/Customer/view/frontend/layout/customer_account_index.xml @@ -14,7 +14,9 @@ - + + + diff --git a/app/code/Magento/Customer/view/frontend/templates/account/dashboard/info.phtml b/app/code/Magento/Customer/view/frontend/templates/account/dashboard/info.phtml index c4b3c9d657f3d..05d93cd56105a 100644 --- a/app/code/Magento/Customer/view/frontend/templates/account/dashboard/info.phtml +++ b/app/code/Magento/Customer/view/frontend/templates/account/dashboard/info.phtml @@ -29,24 +29,26 @@ - isNewsletterEnabled()) : ?> + isNewsletterEnabled()): ?>
escapeHtml(__('Newsletters')) ?>

- getIsSubscribed()) : ?> + getIsSubscribed()): ?> escapeHtml(__('You are subscribed to "General Subscription".')) ?> - + escapeHtml(__('You aren\'t subscribed to our newsletter.')) ?>

+ getChildHtml('additional_blocks'); ?> diff --git a/app/code/Magento/CustomerImportExport/Model/Import/Address.php b/app/code/Magento/CustomerImportExport/Model/Import/Address.php index 09d76ec3fb71f..a5947f48bea5f 100644 --- a/app/code/Magento/CustomerImportExport/Model/Import/Address.php +++ b/app/code/Magento/CustomerImportExport/Model/Import/Address.php @@ -54,6 +54,8 @@ class Address extends AbstractCustomer /**#@-*/ + const COLUMN_REGION_ID = 'region_id'; + /**#@+ * Particular columns that contains of customer default addresses */ @@ -666,13 +668,17 @@ protected function _prepareDataForUpdate(array $rowData): array } } // let's try to find region ID - $entityRow['region_id'] = null; + $entityRow[self::COLUMN_REGION_ID] = null; - if (!empty($rowData[self::COLUMN_REGION]) - && $this->getCountryRegionId($rowData[self::COLUMN_COUNTRY_ID], $rowData[self::COLUMN_REGION]) !== false) { - $regionId = $this->getCountryRegionId($rowData[self::COLUMN_COUNTRY_ID], $rowData[self::COLUMN_REGION]); - $entityRow[self::COLUMN_REGION] = $this->_regions[$regionId]; - $entityRow['region_id'] = $regionId; + if (!empty($entityRow[self::COLUMN_REGION]) && !empty($entityRow[self::COLUMN_COUNTRY_ID])) { + $entityRow[self::COLUMN_REGION_ID] = $this->getCountryRegionId( + $entityRow[self::COLUMN_COUNTRY_ID], + $entityRow[self::COLUMN_REGION] + ); + // override the region name with its proper name if region ID is found + $entityRow[self::COLUMN_REGION] = $entityRow[self::COLUMN_REGION_ID] !== null + ? $this->_regions[$entityRow[self::COLUMN_REGION_ID]] + : $entityRow[self::COLUMN_REGION]; } if ($newAddress) { $entityRowNew = $entityRow; @@ -833,7 +839,7 @@ public static function getDefaultAddressAttributeMapping() * Check if address for import is empty (for customer composite mode) * * @param array $rowData - * @return array + * @return bool */ protected function _isOptionalAddressEmpty(array $rowData) { @@ -914,7 +920,8 @@ protected function _validateRowForUpdate(array $rowData, $rowNumber) if (isset($rowData[self::COLUMN_REGION]) && !empty($rowData[self::COLUMN_REGION]) - && false === $this->getCountryRegionId( + && count($this->getCountryRegions($rowData[self::COLUMN_COUNTRY_ID])) > 0 + && null === $this->getCountryRegionId( $rowData[self::COLUMN_COUNTRY_ID], $rowData[self::COLUMN_REGION] ) @@ -994,18 +1001,22 @@ public function setCustomerAttributes($customerAttributes) * * @param string $countryId * @param string $region - * @return bool|int + * @return int|null */ - private function getCountryRegionId(string $countryId, string $region) + private function getCountryRegionId(string $countryId, string $region): ?int { - $countryNormalized = strtolower($countryId); - $regionNormalized = strtolower($region); - - if (isset($this->_countryRegions[$countryNormalized]) - && isset($this->_countryRegions[$countryNormalized][$regionNormalized])) { - return $this->_countryRegions[$countryNormalized][$regionNormalized]; - } + $countryRegions = $this->getCountryRegions($countryId); + return $countryRegions[strtolower($region)] ?? null; + } - return false; + /** + * Get country regions + * + * @param string $countryId + * @return array + */ + private function getCountryRegions(string $countryId): array + { + return $this->_countryRegions[strtolower($countryId)] ?? []; } } diff --git a/app/code/Magento/Directory/etc/db_schema.xml b/app/code/Magento/Directory/etc/db_schema.xml index a9fb2c536a3fd..5438a17159942 100644 --- a/app/code/Magento/Directory/etc/db_schema.xml +++ b/app/code/Magento/Directory/etc/db_schema.xml @@ -16,7 +16,7 @@
- @@ -30,7 +30,7 @@
- @@ -46,7 +46,7 @@
- diff --git a/app/code/Magento/Downloadable/etc/db_schema.xml b/app/code/Magento/Downloadable/etc/db_schema.xml index ee7b3c5683ea1..6fc1a48130e03 100644 --- a/app/code/Magento/Downloadable/etc/db_schema.xml +++ b/app/code/Magento/Downloadable/etc/db_schema.xml @@ -8,15 +8,15 @@
- - - - - @@ -36,11 +36,11 @@
- - - @@ -62,18 +62,18 @@
- - - - @@ -99,23 +99,23 @@
- - - - - - - - @@ -145,11 +145,11 @@
- - - @@ -170,14 +170,14 @@
- - - @@ -191,11 +191,11 @@
- - - @@ -217,11 +217,11 @@
- - - @@ -235,11 +235,11 @@
- - - diff --git a/app/code/Magento/Eav/etc/db_schema.xml b/app/code/Magento/Eav/etc/db_schema.xml index 0e0b599290ca2..f1f5d19dd2c74 100644 --- a/app/code/Magento/Eav/etc/db_schema.xml +++ b/app/code/Magento/Eav/etc/db_schema.xml @@ -8,7 +8,7 @@
- @@ -16,16 +16,16 @@ - - - - @@ -41,22 +41,22 @@
- - - - - - @@ -74,15 +74,15 @@
- - - - - @@ -114,15 +114,15 @@
- - - - - @@ -155,17 +155,17 @@
- - - - - - @@ -195,15 +195,15 @@
- - - - - @@ -232,15 +232,15 @@
- - - - - @@ -272,9 +272,9 @@
- - @@ -287,12 +287,12 @@ - - - @@ -312,11 +312,11 @@
- - - @@ -336,12 +336,12 @@
- - - @@ -359,15 +359,15 @@
- - - - @@ -392,17 +392,17 @@
- - - - - - @@ -430,11 +430,11 @@
- - - @@ -447,11 +447,11 @@
- - - @@ -471,11 +471,11 @@
- - - @@ -499,14 +499,14 @@
- - - @@ -523,9 +523,9 @@
- - @@ -542,12 +542,12 @@
- - - @@ -560,9 +560,9 @@
- - @@ -580,15 +580,15 @@
- - - - - diff --git a/app/code/Magento/Email/etc/db_schema.xml b/app/code/Magento/Email/etc/db_schema.xml index 82c5f18ddb9e9..d065c32b44486 100644 --- a/app/code/Magento/Email/etc/db_schema.xml +++ b/app/code/Magento/Email/etc/db_schema.xml @@ -8,12 +8,12 @@
- -
- - @@ -20,29 +20,29 @@
-
-
-
-
-
- -
diff --git a/app/code/Magento/GoogleOptimizer/etc/db_schema.xml b/app/code/Magento/GoogleOptimizer/etc/db_schema.xml index ed3dfcecb90f3..61286646a8fb7 100644 --- a/app/code/Magento/GoogleOptimizer/etc/db_schema.xml +++ b/app/code/Magento/GoogleOptimizer/etc/db_schema.xml @@ -8,12 +8,12 @@ - - - diff --git a/app/code/Magento/ImportExport/etc/db_schema.xml b/app/code/Magento/ImportExport/etc/db_schema.xml index 404999cb9e07a..12242364fbf18 100644 --- a/app/code/Magento/ImportExport/etc/db_schema.xml +++ b/app/code/Magento/ImportExport/etc/db_schema.xml @@ -8,7 +8,7 @@
- + @@ -17,11 +17,11 @@
- - diff --git a/app/code/Magento/Indexer/etc/db_schema.xml b/app/code/Magento/Indexer/etc/db_schema.xml index c9c8e665b3755..e316e50f79e9a 100644 --- a/app/code/Magento/Indexer/etc/db_schema.xml +++ b/app/code/Magento/Indexer/etc/db_schema.xml @@ -8,7 +8,7 @@
-
- - diff --git a/app/code/Magento/InstantPurchase/Test/Mftf/Test/StorefrontInstantPurchaseFunctionalityNegativeScenarioTest.xml b/app/code/Magento/InstantPurchase/Test/Mftf/Test/StorefrontInstantPurchaseFunctionalityNegativeScenarioTest.xml index fc1f92dba7ad6..ecbff39807f30 100644 --- a/app/code/Magento/InstantPurchase/Test/Mftf/Test/StorefrontInstantPurchaseFunctionalityNegativeScenarioTest.xml +++ b/app/code/Magento/InstantPurchase/Test/Mftf/Test/StorefrontInstantPurchaseFunctionalityNegativeScenarioTest.xml @@ -17,14 +17,14 @@ - + - - - - + + + + @@ -67,12 +67,12 @@ - - - - - - + + + + + + @@ -88,9 +88,8 @@ - - - + + @@ -173,8 +172,7 @@ - - + @@ -186,8 +184,8 @@ - - + + @@ -198,10 +196,9 @@ - - - - + + + diff --git a/app/code/Magento/InstantPurchase/Test/Mftf/Test/StorefrontInstantPurchaseFunctionalityTest.xml b/app/code/Magento/InstantPurchase/Test/Mftf/Test/StorefrontInstantPurchaseFunctionalityTest.xml index 4283f42660f1f..59697bb6f5bdf 100644 --- a/app/code/Magento/InstantPurchase/Test/Mftf/Test/StorefrontInstantPurchaseFunctionalityTest.xml +++ b/app/code/Magento/InstantPurchase/Test/Mftf/Test/StorefrontInstantPurchaseFunctionalityTest.xml @@ -18,14 +18,14 @@ - + - - - - + + + + @@ -63,12 +63,12 @@ - - - - - - + + + + + + @@ -81,8 +81,8 @@ - - + + @@ -123,7 +123,7 @@ - + @@ -142,12 +142,12 @@ - - - - - - + + + + + + diff --git a/app/code/Magento/Integration/etc/db_schema.xml b/app/code/Magento/Integration/etc/db_schema.xml index de0cec2e4e20d..91af330e8ef27 100644 --- a/app/code/Magento/Integration/etc/db_schema.xml +++ b/app/code/Magento/Integration/etc/db_schema.xml @@ -8,7 +8,7 @@
- @@ -36,24 +36,24 @@
- - - - - - - @@ -77,9 +77,9 @@
- -
- @@ -101,15 +101,15 @@ comment="Email address of the contact person"/> - - - @@ -128,13 +128,13 @@
- - - diff --git a/app/code/Magento/LoginAsCustomer/Model/AuthenticateCustomer.php b/app/code/Magento/LoginAsCustomer/Model/AuthenticateCustomerBySecret.php similarity index 60% rename from app/code/Magento/LoginAsCustomer/Model/AuthenticateCustomer.php rename to app/code/Magento/LoginAsCustomer/Model/AuthenticateCustomerBySecret.php index df51a1e43f525..a728f4c3a4393 100644 --- a/app/code/Magento/LoginAsCustomer/Model/AuthenticateCustomer.php +++ b/app/code/Magento/LoginAsCustomer/Model/AuthenticateCustomerBySecret.php @@ -9,35 +9,45 @@ use Magento\Customer\Model\Session; use Magento\Framework\Exception\LocalizedException; -use Magento\LoginAsCustomerApi\Api\AuthenticateCustomerInterface; -use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterface; +use Magento\LoginAsCustomerApi\Api\AuthenticateCustomerBySecretInterface; +use Magento\LoginAsCustomerApi\Api\GetAuthenticationDataBySecretInterface; /** * @inheritdoc * * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ -class AuthenticateCustomer implements AuthenticateCustomerInterface +class AuthenticateCustomerBySecret implements AuthenticateCustomerBySecretInterface { + /** + * @var GetAuthenticationDataBySecretInterface + */ + private $getAuthenticationDataBySecret; + /** * @var Session */ private $customerSession; /** + * @param GetAuthenticationDataBySecretInterface $getAuthenticationDataBySecret * @param Session $customerSession */ public function __construct( + GetAuthenticationDataBySecretInterface $getAuthenticationDataBySecret, Session $customerSession ) { + $this->getAuthenticationDataBySecret = $getAuthenticationDataBySecret; $this->customerSession = $customerSession; } /** * @inheritdoc */ - public function execute(AuthenticationDataInterface $authenticationData): void + public function execute(string $secret): void { + $authenticationData = $this->getAuthenticationDataBySecret->execute($secret); + if ($this->customerSession->getId()) { $this->customerSession->logout(); } diff --git a/app/code/Magento/LoginAsCustomer/Model/ResourceModel/DeleteExpiredAuthenticationData.php b/app/code/Magento/LoginAsCustomer/Model/ResourceModel/DeleteAuthenticationDataForUser.php similarity index 89% rename from app/code/Magento/LoginAsCustomer/Model/ResourceModel/DeleteExpiredAuthenticationData.php rename to app/code/Magento/LoginAsCustomer/Model/ResourceModel/DeleteAuthenticationDataForUser.php index 8778c20ab9257..f023d08e40253 100644 --- a/app/code/Magento/LoginAsCustomer/Model/ResourceModel/DeleteExpiredAuthenticationData.php +++ b/app/code/Magento/LoginAsCustomer/Model/ResourceModel/DeleteAuthenticationDataForUser.php @@ -10,12 +10,12 @@ use Magento\Framework\App\ResourceConnection; use Magento\Framework\Stdlib\DateTime\DateTime; use Magento\LoginAsCustomerApi\Api\ConfigInterface; -use Magento\LoginAsCustomerApi\Api\DeleteExpiredAuthenticationDataInterface; +use Magento\LoginAsCustomerApi\Api\DeleteAuthenticationDataForUserInterface; /** * @inheritdoc */ -class DeleteExpiredAuthenticationData implements DeleteExpiredAuthenticationDataInterface +class DeleteAuthenticationDataForUser implements DeleteAuthenticationDataForUserInterface { /** * @var ResourceConnection diff --git a/app/code/Magento/LoginAsCustomer/Model/ResourceModel/GetAuthenticationDataBySecret.php b/app/code/Magento/LoginAsCustomer/Model/ResourceModel/GetAuthenticationDataBySecret.php index 8951ae8f70939..078eb93405299 100644 --- a/app/code/Magento/LoginAsCustomer/Model/ResourceModel/GetAuthenticationDataBySecret.php +++ b/app/code/Magento/LoginAsCustomer/Model/ResourceModel/GetAuthenticationDataBySecret.php @@ -61,7 +61,7 @@ public function __construct( /** * @inheritdoc */ - public function execute(string $secretKey): AuthenticationDataInterface + public function execute(string $secret): AuthenticationDataInterface { $connection = $this->resourceConnection->getConnection(); $tableName = $this->resourceConnection->getTableName('login_as_customer'); @@ -73,7 +73,7 @@ public function execute(string $secretKey): AuthenticationDataInterface $select = $connection->select() ->from(['main_table' => $tableName]) - ->where('main_table.secret = ?', $secretKey) + ->where('main_table.secret = ?', $secret) ->where('main_table.created_at > ?', $timePoint); $data = $connection->fetchRow($select); diff --git a/app/code/Magento/LoginAsCustomerUi/Plugin/AdminLogoutPlugin.php b/app/code/Magento/LoginAsCustomer/Plugin/AdminLogoutPlugin.php similarity index 61% rename from app/code/Magento/LoginAsCustomerUi/Plugin/AdminLogoutPlugin.php rename to app/code/Magento/LoginAsCustomer/Plugin/AdminLogoutPlugin.php index ff61b9482ac17..3b8d26129a91e 100644 --- a/app/code/Magento/LoginAsCustomerUi/Plugin/AdminLogoutPlugin.php +++ b/app/code/Magento/LoginAsCustomer/Plugin/AdminLogoutPlugin.php @@ -5,11 +5,11 @@ */ declare(strict_types=1); -namespace Magento\LoginAsCustomerUi\Plugin; +namespace Magento\LoginAsCustomer\Plugin; use Magento\Backend\Model\Auth; use Magento\LoginAsCustomerApi\Api\ConfigInterface; -use Magento\LoginAsCustomerApi\Api\DeleteExpiredAuthenticationDataInterface; +use Magento\LoginAsCustomerApi\Api\DeleteAuthenticationDataForUserInterface; /** * Delete all Login as Customer sessions for logging out admin. @@ -22,20 +22,20 @@ class AdminLogoutPlugin private $config; /** - * @var DeleteExpiredAuthenticationDataInterface + * @var DeleteAuthenticationDataForUserInterface */ - private $deleteExpiredAuthenticationData; + private $deleteAuthenticationDataForUser; /** * @param ConfigInterface $config - * @param DeleteExpiredAuthenticationDataInterface $deleteExpiredAuthenticationData + * @param DeleteAuthenticationDataForUserInterface $deleteAuthenticationDataForUser */ public function __construct( ConfigInterface $config, - DeleteExpiredAuthenticationDataInterface $deleteExpiredAuthenticationData + DeleteAuthenticationDataForUserInterface $deleteAuthenticationDataForUser ) { $this->config = $config; - $this->deleteExpiredAuthenticationData = $deleteExpiredAuthenticationData; + $this->deleteAuthenticationDataForUser = $deleteAuthenticationDataForUser; } /** @@ -47,7 +47,7 @@ public function beforeLogout(Auth $subject): void { if ($this->config->isEnabled()) { $userId = (int)$subject->getUser()->getId(); - $this->deleteExpiredAuthenticationData->execute($userId); + $this->deleteAuthenticationDataForUser->execute($userId); } } } diff --git a/app/code/Magento/LoginAsCustomer/composer.json b/app/code/Magento/LoginAsCustomer/composer.json index 6ff68311f9ff9..ec81374528e7b 100755 --- a/app/code/Magento/LoginAsCustomer/composer.json +++ b/app/code/Magento/LoginAsCustomer/composer.json @@ -7,6 +7,9 @@ "magento/module-customer": "*", "magento/module-login-as-customer-api": "*" }, + "suggest": { + "magento/module-backend": "*" + }, "type": "magento2-module", "license": [ "OSL-3.0", diff --git a/app/code/Magento/LoginAsCustomer/etc/db_schema.xml b/app/code/Magento/LoginAsCustomer/etc/db_schema.xml index a693946f0c3ba..ef811b734e02d 100644 --- a/app/code/Magento/LoginAsCustomer/etc/db_schema.xml +++ b/app/code/Magento/LoginAsCustomer/etc/db_schema.xml @@ -7,7 +7,7 @@ --> -
+
diff --git a/app/code/Magento/LoginAsCustomer/etc/di.xml b/app/code/Magento/LoginAsCustomer/etc/di.xml index 76602534d31e8..c0ba4901ba7b8 100755 --- a/app/code/Magento/LoginAsCustomer/etc/di.xml +++ b/app/code/Magento/LoginAsCustomer/etc/di.xml @@ -9,9 +9,11 @@ - - - + + + + + diff --git a/app/code/Magento/LoginAsCustomerUi/Block/Adminhtml/ConfirmationPopup.php b/app/code/Magento/LoginAsCustomerAdminUi/Block/Adminhtml/ConfirmationPopup.php similarity index 88% rename from app/code/Magento/LoginAsCustomerUi/Block/Adminhtml/ConfirmationPopup.php rename to app/code/Magento/LoginAsCustomerAdminUi/Block/Adminhtml/ConfirmationPopup.php index 6655e0a3a8fc4..e2d11b2c8cb80 100644 --- a/app/code/Magento/LoginAsCustomerUi/Block/Adminhtml/ConfirmationPopup.php +++ b/app/code/Magento/LoginAsCustomerAdminUi/Block/Adminhtml/ConfirmationPopup.php @@ -5,37 +5,31 @@ */ declare(strict_types=1); -namespace Magento\LoginAsCustomerUi\Block\Adminhtml; +namespace Magento\LoginAsCustomerAdminUi\Block\Adminhtml; -use Magento\Framework\Serialize\Serializer\Json; -use Magento\Store\Ui\Component\Listing\Column\Store\Options as StoreOptions; use Magento\Backend\Block\Template; +use Magento\Framework\Serialize\Serializer\Json; use Magento\LoginAsCustomerApi\Api\ConfigInterface; +use Magento\Store\Ui\Component\Listing\Column\Store\Options as StoreOptions; /** - * Admin blog post + * Login confirmation pop-up * * @api */ class ConfirmationPopup extends Template { /** - * Store Options - * * @var StoreOptions */ private $storeOptions; /** - * Config - * * @var ConfigInterface */ private $config; /** - * Json Serializer - * * @var Json */ private $json; @@ -83,15 +77,13 @@ public function getJsLayout() } /** - * Render block HTML - * - * @return string + * @inheritdoc */ - protected function _toHtml() + public function toHtml() { if (!$this->config->isEnabled()) { return ''; } - return parent::_toHtml(); + return parent::toHtml(); } } diff --git a/app/code/Magento/LoginAsCustomerUi/Controller/Adminhtml/Login/Login.php b/app/code/Magento/LoginAsCustomerAdminUi/Controller/Adminhtml/Login/Login.php old mode 100755 new mode 100644 similarity index 76% rename from app/code/Magento/LoginAsCustomerUi/Controller/Adminhtml/Login/Login.php rename to app/code/Magento/LoginAsCustomerAdminUi/Controller/Adminhtml/Login/Login.php index c56b3c8e65fb0..7ccdcfe45e482 --- a/app/code/Magento/LoginAsCustomerUi/Controller/Adminhtml/Login/Login.php +++ b/app/code/Magento/LoginAsCustomerAdminUi/Controller/Adminhtml/Login/Login.php @@ -5,14 +5,13 @@ */ declare(strict_types=1); -namespace Magento\LoginAsCustomerUi\Controller\Adminhtml\Login; +namespace Magento\LoginAsCustomerAdminUi\Controller\Adminhtml\Login; use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; use Magento\Backend\Model\Auth\Session; use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Framework\App\Action\HttpGetActionInterface; -use Magento\Framework\App\Action\HttpPostActionInterface; use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Controller\ResultInterface; @@ -22,7 +21,7 @@ use Magento\LoginAsCustomerApi\Api\ConfigInterface; use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterface; use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterfaceFactory; -use Magento\LoginAsCustomerApi\Api\DeleteExpiredAuthenticationDataInterface; +use Magento\LoginAsCustomerApi\Api\DeleteAuthenticationDataForUserInterface; use Magento\LoginAsCustomerApi\Api\SaveAuthenticationDataInterface; use Magento\Store\Model\StoreManagerInterface; @@ -30,11 +29,9 @@ * Login as customer action * Generate secret key and forward to the storefront action * - * This action can be executed via GET request when "Store View To Login In" is disabled, and POST when it is enabled - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -class Login extends Action implements HttpGetActionInterface, HttpPostActionInterface +class Login extends Action implements HttpGetActionInterface { /** * Authorization level of a basic admin session @@ -74,9 +71,9 @@ class Login extends Action implements HttpGetActionInterface, HttpPostActionInte private $saveAuthenticationData; /** - * @var DeleteExpiredAuthenticationDataInterface + * @var DeleteAuthenticationDataForUserInterface */ - private $deleteExpiredAuthenticationData; + private $deleteAuthenticationDataForUser; /** * @var Url @@ -91,7 +88,7 @@ class Login extends Action implements HttpGetActionInterface, HttpPostActionInte * @param ConfigInterface $config * @param AuthenticationDataInterfaceFactory $authenticationDataFactory * @param SaveAuthenticationDataInterface $saveAuthenticationData , - * @param DeleteExpiredAuthenticationDataInterface $deleteExpiredAuthenticationData + * @param DeleteAuthenticationDataForUserInterface $deleteAuthenticationDataForUser * @param Url $url */ public function __construct( @@ -102,7 +99,7 @@ public function __construct( ConfigInterface $config, AuthenticationDataInterfaceFactory $authenticationDataFactory, SaveAuthenticationDataInterface $saveAuthenticationData, - DeleteExpiredAuthenticationDataInterface $deleteExpiredAuthenticationData, + DeleteAuthenticationDataForUserInterface $deleteAuthenticationDataForUser, Url $url ) { parent::__construct($context); @@ -113,7 +110,7 @@ public function __construct( $this->config = $config; $this->authenticationDataFactory = $authenticationDataFactory; $this->saveAuthenticationData = $saveAuthenticationData; - $this->deleteExpiredAuthenticationData = $deleteExpiredAuthenticationData; + $this->deleteAuthenticationDataForUser = $deleteAuthenticationDataForUser; $this->url = $url; } @@ -130,7 +127,7 @@ public function execute(): ResultInterface $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->config->isEnabled()) { - $this->messageManager->addErrorMessage(__('Login As Customer is disabled.')); + $this->messageManager->addErrorMessage(__('Login as Customer is disabled.')); return $resultRedirect->setPath('customer/index/index'); } @@ -140,16 +137,20 @@ public function execute(): ResultInterface } try { - $this->customerRepository->getById($customerId); + $customer = $this->customerRepository->getById($customerId); } catch (NoSuchEntityException $e) { $this->messageManager->addErrorMessage(__('Customer with this ID are no longer exist.')); return $resultRedirect->setPath('customer/index/index'); } - $storeId = (int)$this->_request->getParam('store_id'); - if (empty($storeId) && $this->config->isStoreManualChoiceEnabled()) { - $this->messageManager->addNoticeMessage(__('Please select a Store View to login in.')); - return $resultRedirect->setPath('customer/index/edit', ['id' => $customerId]); + if ($this->config->isStoreManualChoiceEnabled()) { + $storeId = (int)$this->_request->getParam('store_id'); + if (empty($storeId)) { + $this->messageManager->addNoticeMessage(__('Please select a Store View to login in.')); + return $resultRedirect->setPath('customer/index/edit', ['id' => $customerId]); + } + } else { + $storeId = (int)$customer->getStoreId(); } $adminUser = $this->authSession->getUser(); @@ -164,7 +165,7 @@ public function execute(): ResultInterface ] ); - $this->deleteExpiredAuthenticationData->execute($userId); + $this->deleteAuthenticationDataForUser->execute($userId); $secret = $this->saveAuthenticationData->execute($authenticationData); $redirectUrl = $this->getLoginProceedRedirectUrl($secret, $storeId); @@ -176,17 +177,13 @@ public function execute(): ResultInterface * Get login proceed redirect url * * @param string $secret - * @param int|null $storeId + * @param int $storeId * @return string * @throws NoSuchEntityException */ - private function getLoginProceedRedirectUrl(string $secret, ?int $storeId): string + private function getLoginProceedRedirectUrl(string $secret, int $storeId): string { - if (null === $storeId) { - $store = $this->storeManager->getDefaultStoreView(); - } else { - $store = $this->storeManager->getStore($storeId); - } + $store = $this->storeManager->getStore($storeId); return $this->url ->setScope($store) diff --git a/app/code/Magento/Braintree/LICENSE.txt b/app/code/Magento/LoginAsCustomerAdminUi/LICENSE.txt similarity index 100% rename from app/code/Magento/Braintree/LICENSE.txt rename to app/code/Magento/LoginAsCustomerAdminUi/LICENSE.txt diff --git a/app/code/Magento/Braintree/LICENSE_AFL.txt b/app/code/Magento/LoginAsCustomerAdminUi/LICENSE_AFL.txt similarity index 100% rename from app/code/Magento/Braintree/LICENSE_AFL.txt rename to app/code/Magento/LoginAsCustomerAdminUi/LICENSE_AFL.txt diff --git a/app/code/Magento/LoginAsCustomerUi/Model/Config/Source/StoreViewLogin.php b/app/code/Magento/LoginAsCustomerAdminUi/Model/Config/Source/StoreViewLogin.php similarity index 91% rename from app/code/Magento/LoginAsCustomerUi/Model/Config/Source/StoreViewLogin.php rename to app/code/Magento/LoginAsCustomerAdminUi/Model/Config/Source/StoreViewLogin.php index cf77f695287fd..265c4fedb722d 100644 --- a/app/code/Magento/LoginAsCustomerUi/Model/Config/Source/StoreViewLogin.php +++ b/app/code/Magento/LoginAsCustomerAdminUi/Model/Config/Source/StoreViewLogin.php @@ -5,7 +5,7 @@ */ declare(strict_types=1); -namespace Magento\LoginAsCustomerUi\Model\Config\Source; +namespace Magento\LoginAsCustomerAdminUi\Model\Config\Source; /** * @inheritdoc diff --git a/app/code/Magento/LoginAsCustomerUi/Plugin/Button/ToolbarPlugin.php b/app/code/Magento/LoginAsCustomerAdminUi/Plugin/Button/ToolbarPlugin.php similarity index 95% rename from app/code/Magento/LoginAsCustomerUi/Plugin/Button/ToolbarPlugin.php rename to app/code/Magento/LoginAsCustomerAdminUi/Plugin/Button/ToolbarPlugin.php index ec2c4dd5dcb65..89ee2791e38af 100644 --- a/app/code/Magento/LoginAsCustomerUi/Plugin/Button/ToolbarPlugin.php +++ b/app/code/Magento/LoginAsCustomerAdminUi/Plugin/Button/ToolbarPlugin.php @@ -5,7 +5,7 @@ */ declare(strict_types=1); -namespace Magento\LoginAsCustomerUi\Plugin\Button; +namespace Magento\LoginAsCustomerAdminUi\Plugin\Button; use Magento\Backend\Block\Widget\Button\ButtonList; use Magento\Backend\Block\Widget\Button\Toolbar; @@ -51,7 +51,7 @@ public function __construct( } /** - * Add Login As Customer button. + * Add Login as Customer button. * * @param \Magento\Backend\Block\Widget\Button\Toolbar $subject * @param \Magento\Framework\View\Element\AbstractBlock $context @@ -87,7 +87,7 @@ public function beforePushButtons( $buttonList->add( 'guest_to_customer', [ - 'label' => __('Login As Customer'), + 'label' => __('Login as Customer'), 'onclick' => 'window.lacConfirmationPopup("' . $this->escaper->escapeHtml($this->escaper->escapeJs($buttonUrl)) . '")', diff --git a/app/code/Magento/LoginAsCustomerAdminUi/README.md b/app/code/Magento/LoginAsCustomerAdminUi/README.md new file mode 100644 index 0000000000000..8c7e3483b3874 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerAdminUi/README.md @@ -0,0 +1,3 @@ +# Magento_LoginAsCustomerSales module + +The Magento_LoginAsCustomerAdminUi module provides UI for Admin Panel diff --git a/app/code/Magento/LoginAsCustomerUi/Ui/Customer/Component/Control/LoginAsCustomerButton.php b/app/code/Magento/LoginAsCustomerAdminUi/Ui/Customer/Component/Control/LoginAsCustomerButton.php similarity index 91% rename from app/code/Magento/LoginAsCustomerUi/Ui/Customer/Component/Control/LoginAsCustomerButton.php rename to app/code/Magento/LoginAsCustomerAdminUi/Ui/Customer/Component/Control/LoginAsCustomerButton.php index 88add39eb1efb..0f8f7750262f2 100644 --- a/app/code/Magento/LoginAsCustomerUi/Ui/Customer/Component/Control/LoginAsCustomerButton.php +++ b/app/code/Magento/LoginAsCustomerAdminUi/Ui/Customer/Component/Control/LoginAsCustomerButton.php @@ -5,7 +5,7 @@ */ declare(strict_types=1); -namespace Magento\LoginAsCustomerUi\Ui\Customer\Component\Control; +namespace Magento\LoginAsCustomerAdminUi\Ui\Customer\Component\Control; use Magento\Framework\View\Element\UiComponent\Control\ButtonProviderInterface; use Magento\Framework\AuthorizationInterface; @@ -16,7 +16,7 @@ use Magento\LoginAsCustomerApi\Api\ConfigInterface; /** - * Login As Customer button UI component. + * Login as Customer button UI component. */ class LoginAsCustomerButton extends GenericButton implements ButtonProviderInterface { @@ -64,7 +64,7 @@ public function getButtonData(): array $isEnabled = $this->config->isEnabled(); if ($isAllowed && $isEnabled) { $data = [ - 'label' => __('Login As Customer'), + 'label' => __('Login as Customer'), 'class' => 'login login-button', 'on_click' => 'window.lacConfirmationPopup("' . $this->escaper->escapeHtml($this->escaper->escapeJs($this->getLoginUrl())) @@ -77,7 +77,7 @@ public function getButtonData(): array } /** - * Get Login As Customer login url. + * Get Login as Customer login url. * * @return string */ diff --git a/app/code/Magento/LoginAsCustomerUi/composer.json b/app/code/Magento/LoginAsCustomerAdminUi/composer.json similarity index 76% rename from app/code/Magento/LoginAsCustomerUi/composer.json rename to app/code/Magento/LoginAsCustomerAdminUi/composer.json index fe0b2204a2856..8bbe0e2bd6c9e 100644 --- a/app/code/Magento/LoginAsCustomerUi/composer.json +++ b/app/code/Magento/LoginAsCustomerAdminUi/composer.json @@ -1,10 +1,11 @@ { - "name": "magento/module-login-as-customer-ui", + "name": "magento/module-login-as-customer-admin-ui", "description": "", "require": { "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-login-as-customer-api": "*", + "magento/module-login-as-customer-frontend-ui": "*", "magento/module-backend": "*", "magento/module-customer": "*", "magento/module-store": "*" @@ -20,7 +21,7 @@ "autoload": { "files": [ "registration.php" ], "psr-4": { - "Magento\\LoginAsCustomerUi\\": "" + "Magento\\LoginAsCustomerAdminUi\\": "" } } } diff --git a/app/code/Magento/LoginAsCustomerUi/etc/acl.xml b/app/code/Magento/LoginAsCustomerAdminUi/etc/acl.xml old mode 100755 new mode 100644 similarity index 100% rename from app/code/Magento/LoginAsCustomerUi/etc/acl.xml rename to app/code/Magento/LoginAsCustomerAdminUi/etc/acl.xml diff --git a/app/code/Magento/LoginAsCustomerUi/etc/adminhtml/di.xml b/app/code/Magento/LoginAsCustomerAdminUi/etc/adminhtml/di.xml similarity index 65% rename from app/code/Magento/LoginAsCustomerUi/etc/adminhtml/di.xml rename to app/code/Magento/LoginAsCustomerAdminUi/etc/adminhtml/di.xml index 2ee0b83be573e..dabab45205527 100644 --- a/app/code/Magento/LoginAsCustomerUi/etc/adminhtml/di.xml +++ b/app/code/Magento/LoginAsCustomerAdminUi/etc/adminhtml/di.xml @@ -7,9 +7,6 @@ --> - - - - + diff --git a/app/code/Magento/LoginAsCustomerUi/etc/adminhtml/routes.xml b/app/code/Magento/LoginAsCustomerAdminUi/etc/adminhtml/routes.xml old mode 100755 new mode 100644 similarity index 86% rename from app/code/Magento/LoginAsCustomerUi/etc/adminhtml/routes.xml rename to app/code/Magento/LoginAsCustomerAdminUi/etc/adminhtml/routes.xml index 1122e490db306..316869928c36e --- a/app/code/Magento/LoginAsCustomerUi/etc/adminhtml/routes.xml +++ b/app/code/Magento/LoginAsCustomerAdminUi/etc/adminhtml/routes.xml @@ -8,7 +8,7 @@ - + diff --git a/app/code/Magento/LoginAsCustomerUi/etc/adminhtml/system.xml b/app/code/Magento/LoginAsCustomerAdminUi/etc/adminhtml/system.xml old mode 100755 new mode 100644 similarity index 93% rename from app/code/Magento/LoginAsCustomerUi/etc/adminhtml/system.xml rename to app/code/Magento/LoginAsCustomerAdminUi/etc/adminhtml/system.xml index 2a5614d44d00c..580f478f32780 --- a/app/code/Magento/LoginAsCustomerUi/etc/adminhtml/system.xml +++ b/app/code/Magento/LoginAsCustomerAdminUi/etc/adminhtml/system.xml @@ -20,7 +20,7 @@ - Magento\LoginAsCustomerUi\Model\Config\Source\StoreViewLogin + Magento\LoginAsCustomerAdminUi\Model\Config\Source\StoreViewLogin + - + diff --git a/app/code/Magento/LoginAsCustomerAdminUi/registration.php b/app/code/Magento/LoginAsCustomerAdminUi/registration.php new file mode 100644 index 0000000000000..aa5381764f49d --- /dev/null +++ b/app/code/Magento/LoginAsCustomerAdminUi/registration.php @@ -0,0 +1,12 @@ + - + - Magento_LoginAsCustomerUi/js/confirmation-popup + Magento_LoginAsCustomerAdminUi/js/confirmation-popup diff --git a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/sales_order_creditmemo_view.xml b/app/code/Magento/LoginAsCustomerAdminUi/view/adminhtml/layout/sales_order_creditmemo_view.xml similarity index 100% rename from app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/sales_order_creditmemo_view.xml rename to app/code/Magento/LoginAsCustomerAdminUi/view/adminhtml/layout/sales_order_creditmemo_view.xml diff --git a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/sales_order_invoice_view.xml b/app/code/Magento/LoginAsCustomerAdminUi/view/adminhtml/layout/sales_order_invoice_view.xml similarity index 100% rename from app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/sales_order_invoice_view.xml rename to app/code/Magento/LoginAsCustomerAdminUi/view/adminhtml/layout/sales_order_invoice_view.xml diff --git a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/sales_order_view.xml b/app/code/Magento/LoginAsCustomerAdminUi/view/adminhtml/layout/sales_order_view.xml similarity index 100% rename from app/code/Magento/LoginAsCustomerUi/view/adminhtml/layout/sales_order_view.xml rename to app/code/Magento/LoginAsCustomerAdminUi/view/adminhtml/layout/sales_order_view.xml diff --git a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/templates/confirmation-popup.phtml b/app/code/Magento/LoginAsCustomerAdminUi/view/adminhtml/templates/confirmation-popup.phtml similarity index 77% rename from app/code/Magento/LoginAsCustomerUi/view/adminhtml/templates/confirmation-popup.phtml rename to app/code/Magento/LoginAsCustomerAdminUi/view/adminhtml/templates/confirmation-popup.phtml index 0f46bb952f9bb..bcd99fe37eccb 100644 --- a/app/code/Magento/LoginAsCustomerUi/view/adminhtml/templates/confirmation-popup.phtml +++ b/app/code/Magento/LoginAsCustomerAdminUi/view/adminhtml/templates/confirmation-popup.phtml @@ -3,7 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ -/** @var \Magento\LoginAsCustomerUi\Block\Adminhtml\ConfirmationPopup $block */ +/** @var \Magento\LoginAsCustomerAdminUi\Block\Adminhtml\ConfirmationPopup $block */ ?> diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/web/css/source/_module.less b/app/code/Magento/LoginAsCustomerFrontendUi/view/frontend/web/css/source/_module.less similarity index 94% rename from app/code/Magento/LoginAsCustomerUi/view/frontend/web/css/source/_module.less rename to app/code/Magento/LoginAsCustomerFrontendUi/view/frontend/web/css/source/_module.less index 372405c2635ef..d630ff06c3e34 100644 --- a/app/code/Magento/LoginAsCustomerUi/view/frontend/web/css/source/_module.less +++ b/app/code/Magento/LoginAsCustomerFrontendUi/view/frontend/web/css/source/_module.less @@ -46,7 +46,7 @@ .lac-notification-close-link { &:after { - background: url('../Magento_LoginAsCustomerUi/images/close.svg'); + background: url('../Magento_LoginAsCustomerFrontendUi/images/close.svg'); content: ' '; display: inline-block; height: 12px; diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/web/images/close.svg b/app/code/Magento/LoginAsCustomerFrontendUi/view/frontend/web/images/close.svg similarity index 100% rename from app/code/Magento/LoginAsCustomerUi/view/frontend/web/images/close.svg rename to app/code/Magento/LoginAsCustomerFrontendUi/view/frontend/web/images/close.svg diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/web/images/magento-icon.svg b/app/code/Magento/LoginAsCustomerFrontendUi/view/frontend/web/images/magento-icon.svg similarity index 100% rename from app/code/Magento/LoginAsCustomerUi/view/frontend/web/images/magento-icon.svg rename to app/code/Magento/LoginAsCustomerFrontendUi/view/frontend/web/images/magento-icon.svg diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/web/js/login.js b/app/code/Magento/LoginAsCustomerFrontendUi/view/frontend/web/js/login.js similarity index 91% rename from app/code/Magento/LoginAsCustomerUi/view/frontend/web/js/login.js rename to app/code/Magento/LoginAsCustomerFrontendUi/view/frontend/web/js/login.js index ab325bc90cf00..f3d3f15b770d5 100644 --- a/app/code/Magento/LoginAsCustomerUi/view/frontend/web/js/login.js +++ b/app/code/Magento/LoginAsCustomerFrontendUi/view/frontend/web/js/login.js @@ -12,7 +12,6 @@ define([ 'use strict'; return function (config) { - $('body').trigger('processStart'); customerData.reload(sectionConfig.getSectionNames()).done(function () { window.location.href = config.redirectUrl; }); diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/web/js/view/loginAsCustomer.js b/app/code/Magento/LoginAsCustomerFrontendUi/view/frontend/web/js/view/loginAsCustomer.js similarity index 100% rename from app/code/Magento/LoginAsCustomerUi/view/frontend/web/js/view/loginAsCustomer.js rename to app/code/Magento/LoginAsCustomerFrontendUi/view/frontend/web/js/view/loginAsCustomer.js diff --git a/app/code/Magento/LoginAsCustomerLog/Controller/Adminhtml/Log/Index.php b/app/code/Magento/LoginAsCustomerLog/Controller/Adminhtml/Log/Index.php index ce0c50bf347fc..76ee79ff08a14 100644 --- a/app/code/Magento/LoginAsCustomerLog/Controller/Adminhtml/Log/Index.php +++ b/app/code/Magento/LoginAsCustomerLog/Controller/Adminhtml/Log/Index.php @@ -8,17 +8,49 @@ namespace Magento\LoginAsCustomerLog\Controller\Adminhtml\Log; use Magento\Backend\App\Action; +use Magento\Backend\App\Action\Context; use Magento\Framework\App\Action\HttpGetActionInterface; +use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Controller\ResultInterface; +use Magento\LoginAsCustomerApi\Api\ConfigInterface; /** - * Login As Customer log grid controller. + * Login as Customer log grid controller. */ class Index extends Action implements HttpGetActionInterface { const ADMIN_RESOURCE = 'Magento_LoginAsCustomerLog::login_log'; + /** + * @var ConfigInterface + */ + private $config; + + /**. + * @param Context $context + * @param ConfigInterface $config + */ + public function __construct( + Context $context, + ConfigInterface $config + ) { + parent::__construct($context); + $this->config = $config; + } + + /** + * @inheritdoc + */ + public function dispatch(RequestInterface $request) + { + if (!$this->config->isEnabled() && ($request->getActionName() !== 'noroute')) { + $this->_forward('noroute'); + } + + return parent::dispatch($request); + } + /** * @inheritdoc */ diff --git a/app/code/Magento/LoginAsCustomerWebapi/LICENSE.txt b/app/code/Magento/LoginAsCustomerLog/LICENSE.txt similarity index 100% rename from app/code/Magento/LoginAsCustomerWebapi/LICENSE.txt rename to app/code/Magento/LoginAsCustomerLog/LICENSE.txt diff --git a/app/code/Magento/LoginAsCustomerWebapi/LICENSE_AFL.txt b/app/code/Magento/LoginAsCustomerLog/LICENSE_AFL.txt similarity index 100% rename from app/code/Magento/LoginAsCustomerWebapi/LICENSE_AFL.txt rename to app/code/Magento/LoginAsCustomerLog/LICENSE_AFL.txt diff --git a/app/code/Magento/LoginAsCustomerLog/Plugin/LoginAsCustomerApi/Api/AuthenticateCustomerInterface/LogAuthenticationPlugin.php b/app/code/Magento/LoginAsCustomerLog/Plugin/LoginAsCustomerApi/LogAuthenticationPlugin.php similarity index 69% rename from app/code/Magento/LoginAsCustomerLog/Plugin/LoginAsCustomerApi/Api/AuthenticateCustomerInterface/LogAuthenticationPlugin.php rename to app/code/Magento/LoginAsCustomerLog/Plugin/LoginAsCustomerApi/LogAuthenticationPlugin.php index c1d999b552821..abce250f3b367 100644 --- a/app/code/Magento/LoginAsCustomerLog/Plugin/LoginAsCustomerApi/Api/AuthenticateCustomerInterface/LogAuthenticationPlugin.php +++ b/app/code/Magento/LoginAsCustomerLog/Plugin/LoginAsCustomerApi/LogAuthenticationPlugin.php @@ -5,11 +5,11 @@ */ declare(strict_types=1); -namespace Magento\LoginAsCustomerLog\Plugin\LoginAsCustomerApi\Api\AuthenticateCustomerInterface; +namespace Magento\LoginAsCustomerLog\Plugin\LoginAsCustomerApi; use Magento\Customer\Api\CustomerRepositoryInterface; -use Magento\LoginAsCustomerApi\Api\AuthenticateCustomerInterface; -use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterface; +use Magento\LoginAsCustomerApi\Api\AuthenticateCustomerBySecretInterface; +use Magento\LoginAsCustomerApi\Api\GetAuthenticationDataBySecretInterface; use Magento\LoginAsCustomerLog\Api\Data\LogInterfaceFactory; use Magento\LoginAsCustomerLog\Api\SaveLogsInterface; use Magento\User\Api\Data\UserInterfaceFactory; @@ -20,6 +20,11 @@ */ class LogAuthenticationPlugin { + /** + * @var GetAuthenticationDataBySecretInterface + */ + private $getAuthenticationDataBySecret; + /** * @var LogInterfaceFactory */ @@ -46,6 +51,7 @@ class LogAuthenticationPlugin private $userResource; /** + * @param GetAuthenticationDataBySecretInterface $getAuthenticationDataBySecret * @param LogInterfaceFactory $logFactory * @param SaveLogsInterface $saveLogs * @param CustomerRepositoryInterface $customerRepository @@ -53,12 +59,14 @@ class LogAuthenticationPlugin * @param User $userResource */ public function __construct( + GetAuthenticationDataBySecretInterface $getAuthenticationDataBySecret, LogInterfaceFactory $logFactory, SaveLogsInterface $saveLogs, CustomerRepositoryInterface $customerRepository, UserInterfaceFactory $userFactory, User $userResource ) { + $this->getAuthenticationDataBySecret = $getAuthenticationDataBySecret; $this->logFactory = $logFactory; $this->saveLogs = $saveLogs; $this->customerRepository = $customerRepository; @@ -69,29 +77,34 @@ public function __construct( /** * Log user authentication as customer. * - * @param AuthenticateCustomerInterface $subject + * @param AuthenticateCustomerBySecretInterface $subject * @param void $result - * @param AuthenticationDataInterface $data + * @param string $secret * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterExecute( - AuthenticateCustomerInterface $subject, + AuthenticateCustomerBySecretInterface $subject, $result, - AuthenticationDataInterface $data + string $secret ): void { - $customerId = $data->getCustomerId(); + $authenticationData = $this->getAuthenticationDataBySecret->execute($secret); + + $customerId = $authenticationData->getCustomerId(); $customerEmail = $this->customerRepository->getById($customerId)->getEmail(); - $userId = $data->getAdminId(); + + $userId = $authenticationData->getAdminId(); $user = $this->userFactory->create(); $this->userResource->load($user, $userId); + $userName = $user->getUserName(); + $log = $this->logFactory->create( [ 'data' => [ 'customer_id' => $customerId, 'user_id' => $userId, 'customer_email' => $customerEmail, - 'user_name' => $user->getUserName(), + 'user_name' => $userName, ], ] ); diff --git a/app/code/Magento/LoginAsCustomerLog/README.md b/app/code/Magento/LoginAsCustomerLog/README.md index a44ae014f2c83..c8e546ae07f00 100644 --- a/app/code/Magento/LoginAsCustomerLog/README.md +++ b/app/code/Magento/LoginAsCustomerLog/README.md @@ -1,3 +1,3 @@ # Magento_LoginAsCustomerLog module -The Magento_LoginAsCustomerLog module provides log for Login As Customer functionality +The Magento_LoginAsCustomerLog module provides log for Login as Customer functionality diff --git a/app/code/Magento/LoginAsCustomerLog/etc/adminhtml/menu.xml b/app/code/Magento/LoginAsCustomerLog/etc/adminhtml/menu.xml index 143e0ad4b5a6c..2fd80c2d44a0c 100644 --- a/app/code/Magento/LoginAsCustomerLog/etc/adminhtml/menu.xml +++ b/app/code/Magento/LoginAsCustomerLog/etc/adminhtml/menu.xml @@ -9,11 +9,12 @@ xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd"> + action="loginascustomer_log/log/index" + dependsOnConfig="login_as_customer/general/enabled"/> diff --git a/app/code/Magento/LoginAsCustomerLog/etc/db_schema.xml b/app/code/Magento/LoginAsCustomerLog/etc/db_schema.xml index a1f40b4e5bbf5..c808e7a1d6b1d 100644 --- a/app/code/Magento/LoginAsCustomerLog/etc/db_schema.xml +++ b/app/code/Magento/LoginAsCustomerLog/etc/db_schema.xml @@ -7,11 +7,11 @@ -->
- + - + - + diff --git a/app/code/Magento/LoginAsCustomerLog/etc/frontend/di.xml b/app/code/Magento/LoginAsCustomerLog/etc/frontend/di.xml index 284b2db56e258..f645ecff73576 100755 --- a/app/code/Magento/LoginAsCustomerLog/etc/frontend/di.xml +++ b/app/code/Magento/LoginAsCustomerLog/etc/frontend/di.xml @@ -6,8 +6,8 @@ */ --> - - + + diff --git a/app/code/Magento/LoginAsCustomerPageCache/LICENSE.txt b/app/code/Magento/LoginAsCustomerPageCache/LICENSE.txt new file mode 100644 index 0000000000000..49525fd99da9c --- /dev/null +++ b/app/code/Magento/LoginAsCustomerPageCache/LICENSE.txt @@ -0,0 +1,48 @@ + +Open Software License ("OSL") v. 3.0 + +This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Open Software License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright (C) 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/app/code/Magento/LoginAsCustomerPageCache/LICENSE_AFL.txt b/app/code/Magento/LoginAsCustomerPageCache/LICENSE_AFL.txt new file mode 100644 index 0000000000000..f39d641b18a19 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerPageCache/LICENSE_AFL.txt @@ -0,0 +1,48 @@ + +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/app/code/Magento/LoginAsCustomerQuote/LICENSE.txt b/app/code/Magento/LoginAsCustomerQuote/LICENSE.txt new file mode 100644 index 0000000000000..49525fd99da9c --- /dev/null +++ b/app/code/Magento/LoginAsCustomerQuote/LICENSE.txt @@ -0,0 +1,48 @@ + +Open Software License ("OSL") v. 3.0 + +This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Open Software License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright (C) 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/app/code/Magento/LoginAsCustomerQuote/LICENSE_AFL.txt b/app/code/Magento/LoginAsCustomerQuote/LICENSE_AFL.txt new file mode 100644 index 0000000000000..f39d641b18a19 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerQuote/LICENSE_AFL.txt @@ -0,0 +1,48 @@ + +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/app/code/Magento/LoginAsCustomerSales/Plugin/AuthenticateCustomerPlugin.php b/app/code/Magento/LoginAsCustomerQuote/Plugin/LoginAsCustomerApi/ProcessShoppingCartPlugin.php similarity index 70% rename from app/code/Magento/LoginAsCustomerSales/Plugin/AuthenticateCustomerPlugin.php rename to app/code/Magento/LoginAsCustomerQuote/Plugin/LoginAsCustomerApi/ProcessShoppingCartPlugin.php index 5d8541d4dd440..cf25962a104b2 100644 --- a/app/code/Magento/LoginAsCustomerSales/Plugin/AuthenticateCustomerPlugin.php +++ b/app/code/Magento/LoginAsCustomerQuote/Plugin/LoginAsCustomerApi/ProcessShoppingCartPlugin.php @@ -5,24 +5,27 @@ */ declare(strict_types=1); -namespace Magento\LoginAsCustomerSales\Plugin; +namespace Magento\LoginAsCustomerQuote\Plugin\LoginAsCustomerApi; use Magento\Checkout\Model\Session as CheckoutSession; use Magento\Customer\Model\Session as CustomerSession; use Magento\Framework\Exception\LocalizedException; use Magento\Quote\Api\CartRepositoryInterface; -use Magento\LoginAsCustomerApi\Api\AuthenticateCustomerInterface; -use Magento\LoginAsCustomerApi\Api\Data\AuthenticationDataInterface; +use Magento\LoginAsCustomerApi\Api\AuthenticateCustomerBySecretInterface; +use Magento\LoginAsCustomerApi\Api\GetAuthenticationDataBySecretInterface; /** - * \Magento\LoginAsCustomerApi\Api\AuthenticateCustomerInterface Plugin - * * Remove all items from guest shopping cart before execute. Mark customer cart as not-guest after execute * * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) */ -class AuthenticateCustomerPlugin +class ProcessShoppingCartPlugin { + /** + * @var GetAuthenticationDataBySecretInterface + */ + private $getAuthenticationDataBySecret; + /** * @var CustomerSession */ @@ -39,15 +42,18 @@ class AuthenticateCustomerPlugin private $quoteRepository; /** + * @param GetAuthenticationDataBySecretInterface $getAuthenticationDataBySecret * @param CustomerSession $customerSession * @param CheckoutSession $checkoutSession * @param CartRepositoryInterface $quoteRepository */ public function __construct( + GetAuthenticationDataBySecretInterface $getAuthenticationDataBySecret, CustomerSession $customerSession, CheckoutSession $checkoutSession, CartRepositoryInterface $quoteRepository ) { + $this->getAuthenticationDataBySecret = $getAuthenticationDataBySecret; $this->customerSession = $customerSession; $this->checkoutSession = $checkoutSession; $this->quoteRepository = $quoteRepository; @@ -56,16 +62,16 @@ public function __construct( /** * Remove all items from guest shopping cart * - * @param AuthenticateCustomerInterface $subject - * @param AuthenticationDataInterface $authenticationData + * @param AuthenticateCustomerBySecretInterface $subject + * @param string $secret * @return null * @throws LocalizedException * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function beforeExecute( - AuthenticateCustomerInterface $subject, - AuthenticationDataInterface $authenticationData + AuthenticateCustomerBySecretInterface $subject, + string $secret ) { if (!$this->customerSession->getId()) { $quote = $this->checkoutSession->getQuote(); @@ -79,18 +85,18 @@ public function beforeExecute( /** * Mark customer cart as not-guest * - * @param AuthenticateCustomerInterface $subject + * @param AuthenticateCustomerBySecretInterface $subject * @param void $result - * @param AuthenticationDataInterface $authenticationData + * @param string $secret * @return void * @throws LocalizedException * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterExecute( - AuthenticateCustomerInterface $subject, + AuthenticateCustomerBySecretInterface $subject, $result, - AuthenticationDataInterface $authenticationData + string $secret ) { $this->checkoutSession->loadCustomerQuote(); $quote = $this->checkoutSession->getQuote(); diff --git a/app/code/Magento/LoginAsCustomerQuote/README.md b/app/code/Magento/LoginAsCustomerQuote/README.md new file mode 100644 index 0000000000000..fa1daddfceb36 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerQuote/README.md @@ -0,0 +1,3 @@ +# Magento_LoginAsCustomerQuote module + +The Magento_LoginAsCustomerQuote module is responsible for communication between Magento_LoginAsCustomer and shopping cart state. diff --git a/app/code/Magento/BraintreeGraphQl/composer.json b/app/code/Magento/LoginAsCustomerQuote/composer.json similarity index 50% rename from app/code/Magento/BraintreeGraphQl/composer.json rename to app/code/Magento/LoginAsCustomerQuote/composer.json index ceac826dd5ee4..556ffc0d3be43 100644 --- a/app/code/Magento/BraintreeGraphQl/composer.json +++ b/app/code/Magento/LoginAsCustomerQuote/composer.json @@ -1,18 +1,17 @@ { - "name": "magento/module-braintree-graph-ql", - "description": "N/A", - "type": "magento2-module", + "name": "magento/module-login-as-customer-quote", + "description": "", "require": { "php": "~7.3.0||~7.4.0", "magento/framework": "*", - "magento/module-braintree": "*", - "magento/module-store": "*", - "magento/module-quote": "*", - "magento/module-quote-graph-ql": "*" + "magento/module-checkout": "*", + "magento/module-customer": "*", + "magento/module-quote": "*" }, "suggest": { - "magento/module-graph-ql": "*" + "magento/module-login-as-customer-api": "*" }, + "type": "magento2-module", "license": [ "OSL-3.0", "AFL-3.0" @@ -22,7 +21,7 @@ "registration.php" ], "psr-4": { - "Magento\\BraintreeGraphQl\\": "" + "Magento\\LoginAsCustomerQuote\\": "" } } } diff --git a/app/code/Magento/LoginAsCustomerSales/etc/di.xml b/app/code/Magento/LoginAsCustomerQuote/etc/di.xml similarity index 68% rename from app/code/Magento/LoginAsCustomerSales/etc/di.xml rename to app/code/Magento/LoginAsCustomerQuote/etc/di.xml index f267fc3850234..090953f7b5da4 100644 --- a/app/code/Magento/LoginAsCustomerSales/etc/di.xml +++ b/app/code/Magento/LoginAsCustomerQuote/etc/di.xml @@ -7,8 +7,8 @@ --> - - + + \ No newline at end of file diff --git a/app/code/Magento/LoginAsCustomerUi/etc/module.xml b/app/code/Magento/LoginAsCustomerQuote/etc/module.xml similarity index 85% rename from app/code/Magento/LoginAsCustomerUi/etc/module.xml rename to app/code/Magento/LoginAsCustomerQuote/etc/module.xml index c937de225c306..c9a3a545cb538 100644 --- a/app/code/Magento/LoginAsCustomerUi/etc/module.xml +++ b/app/code/Magento/LoginAsCustomerQuote/etc/module.xml @@ -7,5 +7,5 @@ --> - + diff --git a/app/code/Magento/LoginAsCustomerUi/registration.php b/app/code/Magento/LoginAsCustomerQuote/registration.php similarity index 88% rename from app/code/Magento/LoginAsCustomerUi/registration.php rename to app/code/Magento/LoginAsCustomerQuote/registration.php index 501dc6a7ca382..704de78b05c53 100644 --- a/app/code/Magento/LoginAsCustomerUi/registration.php +++ b/app/code/Magento/LoginAsCustomerQuote/registration.php @@ -7,6 +7,6 @@ \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, - 'Magento_LoginAsCustomerUi', + 'Magento_LoginAsCustomerQuote', __DIR__ ); diff --git a/app/code/Magento/LoginAsCustomerSales/LICENSE.txt b/app/code/Magento/LoginAsCustomerSales/LICENSE.txt new file mode 100644 index 0000000000000..49525fd99da9c --- /dev/null +++ b/app/code/Magento/LoginAsCustomerSales/LICENSE.txt @@ -0,0 +1,48 @@ + +Open Software License ("OSL") v. 3.0 + +This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Open Software License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright (C) 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/app/code/Magento/LoginAsCustomerSales/LICENSE_AFL.txt b/app/code/Magento/LoginAsCustomerSales/LICENSE_AFL.txt new file mode 100644 index 0000000000000..f39d641b18a19 --- /dev/null +++ b/app/code/Magento/LoginAsCustomerSales/LICENSE_AFL.txt @@ -0,0 +1,48 @@ + +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/app/code/Magento/LoginAsCustomerSales/README.md b/app/code/Magento/LoginAsCustomerSales/README.md index d5e38d8ec5909..1aee19ba53e96 100644 --- a/app/code/Magento/LoginAsCustomerSales/README.md +++ b/app/code/Magento/LoginAsCustomerSales/README.md @@ -1,3 +1,3 @@ # Magento_LoginAsCustomerSales module -The Magento_LoginAsCustomerSales module is responsible for comunication between Magento_LoginAsCustomer and shopping cart state. +The Magento_LoginAsCustomerSales module is responsible for communication between Magento_LoginAsCustomer and order placement. diff --git a/app/code/Magento/LoginAsCustomerSales/composer.json b/app/code/Magento/LoginAsCustomerSales/composer.json index ac59056644dbf..3965e8acf87d8 100644 --- a/app/code/Magento/LoginAsCustomerSales/composer.json +++ b/app/code/Magento/LoginAsCustomerSales/composer.json @@ -5,14 +5,11 @@ "php": "~7.3.0||~7.4.0", "magento/framework": "*", "magento/module-backend": "*", - "magento/module-checkout": "*", "magento/module-customer": "*", - "magento/module-quote": "*", "magento/module-user": "*" }, "suggest": { - "magento/module-sales": "*", - "magento/module-login-as-customer-api": "*" + "magento/module-sales": "*" }, "type": "magento2-module", "license": [ diff --git a/app/code/Magento/LoginAsCustomerSales/registration.php b/app/code/Magento/LoginAsCustomerSales/registration.php index 4ee5647f5e837..64d73403f6f83 100644 --- a/app/code/Magento/LoginAsCustomerSales/registration.php +++ b/app/code/Magento/LoginAsCustomerSales/registration.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, diff --git a/app/code/Magento/LoginAsCustomerUi/README.md b/app/code/Magento/LoginAsCustomerUi/README.md deleted file mode 100644 index 11e8da9310920..0000000000000 --- a/app/code/Magento/LoginAsCustomerUi/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Magento_LoginAsCustomerSales module - -The Magento_LoginAsCustomerUi module provides UI for Magento_LoginAsCustomerUi diff --git a/app/code/Magento/LoginAsCustomerUi/Ui/Store/Component/Control/LoginAsCustomerButton.php b/app/code/Magento/LoginAsCustomerUi/Ui/Store/Component/Control/LoginAsCustomerButton.php deleted file mode 100644 index 265e1addc48ab..0000000000000 --- a/app/code/Magento/LoginAsCustomerUi/Ui/Store/Component/Control/LoginAsCustomerButton.php +++ /dev/null @@ -1,34 +0,0 @@ - __('Login As Customer'), - 'class' => 'save primary', - 'data_attribute' => [ - 'mage-init' => ['button' => ['event' => 'save']], - 'form-role' => 'save', - ], - 'sort_order' => 90, - ]; - } -} diff --git a/app/code/Magento/LoginAsCustomerUi/view/frontend/templates/login.phtml b/app/code/Magento/LoginAsCustomerUi/view/frontend/templates/login.phtml deleted file mode 100644 index 2abd8fc204831..0000000000000 --- a/app/code/Magento/LoginAsCustomerUi/view/frontend/templates/login.phtml +++ /dev/null @@ -1,17 +0,0 @@ - - - diff --git a/app/code/Magento/LoginAsCustomerWebapi/Api/CreateCustomerAccessTokenInterface.php b/app/code/Magento/LoginAsCustomerWebapi/Api/CreateCustomerAccessTokenInterface.php deleted file mode 100644 index 52acc695af0cc..0000000000000 --- a/app/code/Magento/LoginAsCustomerWebapi/Api/CreateCustomerAccessTokenInterface.php +++ /dev/null @@ -1,27 +0,0 @@ -config = $config; - $this->customerRepository = $customerRepository; - $this->eventManager = $eventManager; - $this->tokenFactory = $tokenFactory; - } - - /** - * @inheritdoc - */ - public function execute(int $customerId): string - { - if ($this->config->isEnabled()) { - $customer = $this->customerRepository->getById($customerId); - $this->eventManager->dispatch('customer_login', ['customer' => $customer]); - - return $this->tokenFactory->create()->createCustomerToken($customerId)->getToken(); - } else { - throw new LocalizedException(__('Service is disabled.')); - } - } -} diff --git a/app/code/Magento/LoginAsCustomerWebapi/README.md b/app/code/Magento/LoginAsCustomerWebapi/README.md deleted file mode 100644 index ef42fd292cda7..0000000000000 --- a/app/code/Magento/LoginAsCustomerWebapi/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# Magento_LoginAsCustomer module - -The Magento_LoginAsCustomerWebapi module provides API for ability to login into customer account for an admin user. - diff --git a/app/code/Magento/LoginAsCustomerWebapi/etc/acl.xml b/app/code/Magento/LoginAsCustomerWebapi/etc/acl.xml deleted file mode 100644 index 33d912843d7d3..0000000000000 --- a/app/code/Magento/LoginAsCustomerWebapi/etc/acl.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/app/code/Magento/LoginAsCustomerWebapi/etc/di.xml b/app/code/Magento/LoginAsCustomerWebapi/etc/di.xml deleted file mode 100644 index f825f533c4961..0000000000000 --- a/app/code/Magento/LoginAsCustomerWebapi/etc/di.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - diff --git a/app/code/Magento/LoginAsCustomerWebapi/etc/webapi.xml b/app/code/Magento/LoginAsCustomerWebapi/etc/webapi.xml deleted file mode 100644 index 6e80fb1725ae4..0000000000000 --- a/app/code/Magento/LoginAsCustomerWebapi/etc/webapi.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - diff --git a/app/code/Magento/LoginAsCustomerWebapi/registration.php b/app/code/Magento/LoginAsCustomerWebapi/registration.php deleted file mode 100644 index f56e57bd7a971..0000000000000 --- a/app/code/Magento/LoginAsCustomerWebapi/registration.php +++ /dev/null @@ -1,14 +0,0 @@ -
- + diff --git a/app/code/Magento/MediaGallery/etc/db_schema.xml b/app/code/Magento/MediaGallery/etc/db_schema.xml index 13e619dd9e74a..31a764ef00c4d 100644 --- a/app/code/Magento/MediaGallery/etc/db_schema.xml +++ b/app/code/Magento/MediaGallery/etc/db_schema.xml @@ -7,14 +7,14 @@ -->
- + - - - + + + @@ -31,7 +31,7 @@
- + @@ -44,8 +44,8 @@
- - + + diff --git a/app/code/Magento/MessageQueue/etc/db_schema.xml b/app/code/Magento/MessageQueue/etc/db_schema.xml index 4403384e9311a..98d550a91e21f 100644 --- a/app/code/Magento/MessageQueue/etc/db_schema.xml +++ b/app/code/Magento/MessageQueue/etc/db_schema.xml @@ -9,7 +9,7 @@ xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
-
- @@ -19,7 +19,7 @@
- @@ -29,17 +29,17 @@
- - - - - diff --git a/app/code/Magento/NewRelicReporting/etc/db_schema.xml b/app/code/Magento/NewRelicReporting/etc/db_schema.xml index e18d7c8077bb9..9388623f737ea 100644 --- a/app/code/Magento/NewRelicReporting/etc/db_schema.xml +++ b/app/code/Magento/NewRelicReporting/etc/db_schema.xml @@ -9,10 +9,10 @@ xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
- - @@ -21,7 +21,7 @@
- @@ -34,13 +34,13 @@
- - - @@ -49,7 +49,7 @@
- @@ -60,7 +60,7 @@
- diff --git a/app/code/Magento/Newsletter/etc/db_schema.xml b/app/code/Magento/Newsletter/etc/db_schema.xml index c038b02404875..3a8a537e8fcc3 100644 --- a/app/code/Magento/Newsletter/etc/db_schema.xml +++ b/app/code/Magento/Newsletter/etc/db_schema.xml @@ -8,16 +8,16 @@
- - - - @@ -38,19 +38,19 @@
- - - @@ -70,11 +70,11 @@
- - - @@ -83,7 +83,7 @@ comment="Newsletter Sender Name"/> -
- - - @@ -124,9 +124,9 @@
- - @@ -143,13 +143,13 @@
- - - - diff --git a/app/code/Magento/OfflineShipping/etc/db_schema.xml b/app/code/Magento/OfflineShipping/etc/db_schema.xml index 6bda6597e2f61..35df088f708a1 100644 --- a/app/code/Magento/OfflineShipping/etc/db_schema.xml +++ b/app/code/Magento/OfflineShipping/etc/db_schema.xml @@ -8,13 +8,13 @@
- - - @@ -38,23 +38,23 @@
-
-
-
-
-
diff --git a/app/code/Magento/Payment/Test/Unit/Plugin/PaymentConfigurationProcessTest.php b/app/code/Magento/Payment/Test/Unit/Plugin/PaymentConfigurationProcessTest.php index 97fb925826ec8..1063e7095514b 100644 --- a/app/code/Magento/Payment/Test/Unit/Plugin/PaymentConfigurationProcessTest.php +++ b/app/code/Magento/Payment/Test/Unit/Plugin/PaymentConfigurationProcessTest.php @@ -108,12 +108,6 @@ public function beforeProcessDataProvider() { $jsLayout['components']['checkout']['children']['steps']['children']['billing-step'] ['children']['payment']['children']['renders']['children'] = [ - 'braintree' => [ - 'methods' => [ - 'braintree_paypal' => [], - 'braintree' => [] - ] - ], 'paypal-payments' => [ 'methods' => [ 'payflowpro' => [], @@ -125,31 +119,31 @@ public function beforeProcessDataProvider() ['children']['payment']['children']['renders']['children'] = []; $result2['components']['checkout']['children']['steps']['children']['billing-step'] ['children']['payment']['children']['renders']['children'] = [ - 'braintree' => [ + 'paypal-payments' => [ 'methods' => [ - 'braintree' => [], - 'braintree_paypal' => [] + 'payflowpro' => [], + 'payflow_link' => [] ] ] ]; - $braintreePaymentMethod = $this + $payflowproPaymentMethod = $this ->getMockBuilder(PaymentMethodInterface::class) ->disableOriginalConstructor() ->setMethods(['getCode']) ->getMockForAbstractClass(); - $braintreePaypalPaymentMethod = $this + $payflowproLinkPaymentMethod = $this ->getMockBuilder(PaymentMethodInterface::class) ->disableOriginalConstructor() ->setMethods(['getCode']) ->getMockForAbstractClass(); - $braintreePaymentMethod->expects($this->any())->method('getCode')->willReturn('braintree'); - $braintreePaypalPaymentMethod->expects($this->any())->method('getCode')->willReturn('braintree_paypal'); + $payflowproPaymentMethod->expects($this->any())->method('getCode')->willReturn('payflowpro'); + $payflowproLinkPaymentMethod->expects($this->any())->method('getCode')->willReturn('payflow_link'); return [ [$jsLayout, [], $result1], - [$jsLayout, [$braintreePaymentMethod, $braintreePaypalPaymentMethod], $result2] + [$jsLayout, [$payflowproPaymentMethod, $payflowproLinkPaymentMethod], $result2] ]; } } diff --git a/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPaypalFillCardDataActionGroup.xml b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPaypalFillCardDataActionGroup.xml new file mode 100644 index 0000000000000..1fd9d52714989 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/ActionGroup/StorefrontPaypalFillCardDataActionGroup.xml @@ -0,0 +1,24 @@ + + + + + + + Fills Card Data with Paypal using the provided Data Entity. + + + + + + + + + + + diff --git a/app/code/Magento/Paypal/Test/Mftf/Data/PaypalConfigData.xml b/app/code/Magento/Paypal/Test/Mftf/Data/PaypalConfigData.xml index 1ad7642f6408a..59c7090956712 100644 --- a/app/code/Magento/Paypal/Test/Mftf/Data/PaypalConfigData.xml +++ b/app/code/Magento/Paypal/Test/Mftf/Data/PaypalConfigData.xml @@ -313,4 +313,8 @@ Black black + + payment/payflowpro_cc_vault/active + 0 + diff --git a/app/code/Magento/Paypal/Test/Mftf/Data/PaypalData.xml b/app/code/Magento/Paypal/Test/Mftf/Data/PaypalData.xml index f7d872bd43838..533df1003282d 100644 --- a/app/code/Magento/Paypal/Test/Mftf/Data/PaypalData.xml +++ b/app/code/Magento/Paypal/Test/Mftf/Data/PaypalData.xml @@ -127,4 +127,93 @@ Alex + + + + EnablePaypalPayflowProMethod + EnablePaypalPayflowProVault + + + DisablePaypalPayflowProMethod + DisablePaypalPayflowProVault + + + PaypalPayflowProBusinessAccount + PaypalPayflowProPartner + PaypalPayflowProUser + PaypalPayflowProVendor + PaypalPayflowProPassword + SandboxFlag + UseProxy + + + {{_CREDS.magento/payflow_pro_business_account}} + + + {{_CREDS.magento/payflow_pro_partner}} + + + {{_CREDS.magento/payflow_pro_user}} + + + {{_CREDS.magento/payflow_pro_vendor}} + + + {{_CREDS.magento/payflow_pro_pwd}} + + + + DefaultPaypalPayflowProBusinessAccount + DefaultPaypalPayflowProPartner + DefaultPaypalPayflowProUser + DefaultPaypalPayflowProVendor + DefaultPaypalPayflowProPassword + + + + + + + + + + + + + + + + + + 1 + + + 0 + + + 1 + + + 0 + + + 4000000000000002 + 12 + 30 + 113 + + + 0002 + 12/2030 + + + 4111111111111111 + 01 + 30 + 123 + + + 1111 + 01/2030 + diff --git a/app/code/Magento/Paypal/Test/Mftf/Metadata/PaypalConfigMeta.xml b/app/code/Magento/Paypal/Test/Mftf/Metadata/PaypalConfigMeta.xml index 7457a90150a0f..df378a922a08a 100644 --- a/app/code/Magento/Paypal/Test/Mftf/Metadata/PaypalConfigMeta.xml +++ b/app/code/Magento/Paypal/Test/Mftf/Metadata/PaypalConfigMeta.xml @@ -48,4 +48,68 @@ + + + + + + + + + + + + string + + + string + + + string + + + string + + + string + + + string + + + string + + + + + + + + + + + + + + + + + + + + + + string + + + string + + + + + + + + + diff --git a/app/code/Magento/Paypal/Test/Mftf/Page/StorefrontCheckoutPage.xml b/app/code/Magento/Paypal/Test/Mftf/Page/StorefrontCheckoutPage.xml new file mode 100644 index 0000000000000..b9990a04b5c91 --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Page/StorefrontCheckoutPage.xml @@ -0,0 +1,14 @@ + + + + + +
+ + diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/CheckoutPaymentSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/CheckoutPaymentSection.xml index e6eb4d875c434..2156add4f01ac 100644 --- a/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/CheckoutPaymentSection.xml +++ b/app/code/Magento/Paypal/Test/Mftf/Section/PayPalExpressCheckoutConfigSection/CheckoutPaymentSection.xml @@ -9,7 +9,6 @@ xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd">
- diff --git a/app/code/Magento/Paypal/Test/Mftf/Section/StorefrontPaypalCheckoutSection.xml b/app/code/Magento/Paypal/Test/Mftf/Section/StorefrontPaypalCheckoutSection.xml new file mode 100644 index 0000000000000..d0c17141ff6ba --- /dev/null +++ b/app/code/Magento/Paypal/Test/Mftf/Section/StorefrontPaypalCheckoutSection.xml @@ -0,0 +1,18 @@ + + + + +
+ + + + + +
+
diff --git a/app/code/Magento/Paypal/Test/Unit/Model/Adminhtml/ExpressTest.php b/app/code/Magento/Paypal/Test/Unit/Model/Adminhtml/ExpressTest.php index 1ad300e58e03e..e75a458d321d7 100644 --- a/app/code/Magento/Paypal/Test/Unit/Model/Adminhtml/ExpressTest.php +++ b/app/code/Magento/Paypal/Test/Unit/Model/Adminhtml/ExpressTest.php @@ -213,8 +213,6 @@ public function paymentDataProvider(): array ['paypal_express', 'order', 50, false], ['paypal_express', 'capture', 0, false], ['paypal_express', 'order', 0, true], - ['braintree', 'authorize', 10, false], - ['braintree', 'authorize', 0, false], ]; } } diff --git a/app/code/Magento/Paypal/etc/db_schema.xml b/app/code/Magento/Paypal/etc/db_schema.xml index 3300f3754e656..2f02f63b7516d 100644 --- a/app/code/Magento/Paypal/etc/db_schema.xml +++ b/app/code/Magento/Paypal/etc/db_schema.xml @@ -8,9 +8,9 @@ - - @@ -18,7 +18,7 @@ - @@ -39,9 +39,9 @@
- - @@ -58,7 +58,7 @@
- @@ -74,9 +74,9 @@
- - @@ -116,9 +116,9 @@
- - @@ -133,7 +133,7 @@
- @@ -153,7 +153,7 @@ comment="Paypal Correlation ID"/>
-
diff --git a/app/code/Magento/Persistent/etc/db_schema.xml b/app/code/Magento/Persistent/etc/db_schema.xml index e14dedba0ed56..085c2613efa50 100644 --- a/app/code/Magento/Persistent/etc/db_schema.xml +++ b/app/code/Magento/Persistent/etc/db_schema.xml @@ -8,12 +8,12 @@ - - -
-
diff --git a/app/code/Magento/ProductAlert/etc/db_schema.xml b/app/code/Magento/ProductAlert/etc/db_schema.xml index 17cc76246e5c6..e12d0523d01aa 100644 --- a/app/code/Magento/ProductAlert/etc/db_schema.xml +++ b/app/code/Magento/ProductAlert/etc/db_schema.xml @@ -8,25 +8,25 @@ - - - - - - - @@ -57,23 +57,23 @@
- - - - - - - diff --git a/app/code/Magento/ProductVideo/etc/db_schema.xml b/app/code/Magento/ProductVideo/etc/db_schema.xml index bfe087d9a5769..aa3dff4a27989 100644 --- a/app/code/Magento/ProductVideo/etc/db_schema.xml +++ b/app/code/Magento/ProductVideo/etc/db_schema.xml @@ -9,9 +9,9 @@ xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
- - diff --git a/app/code/Magento/Quote/Model/Quote/Address/Total/Subtotal.php b/app/code/Magento/Quote/Model/Quote/Address/Total/Subtotal.php index a22a9865db186..22876664fe53c 100644 --- a/app/code/Magento/Quote/Model/Quote/Address/Total/Subtotal.php +++ b/app/code/Magento/Quote/Model/Quote/Address/Total/Subtotal.php @@ -9,6 +9,9 @@ use Magento\Quote\Model\Quote\Address\Item as AddressItem; use Magento\Quote\Model\Quote\Item; +/** + * Address total collector model + */ class Subtotal extends \Magento\Quote\Model\Quote\Address\Total\AbstractTotal { /** @@ -89,40 +92,35 @@ protected function _initItem($address, $item) } else { $quoteItem = $item; } - $product = $quoteItem->getProduct(); - $product->setCustomerGroupId($quoteItem->getQuote()->getCustomerGroupId()); - - /** - * Quote super mode flag mean what we work with quote without restriction - */ - if ($item->getQuote()->getIsSuperMode()) { - if (!$product) { - return false; - } - } else { - if (!$product || !$product->isVisibleInCatalog()) { - return false; + $valid = false; + if ($quoteItem) { + $product = $quoteItem->getProduct(); + /** + * Quote super mode flag mean what we work with quote without restriction + */ + if ($product && ($item->getQuote()->getIsSuperMode() || $product->isVisibleInCatalog())) { + $product->setCustomerGroupId($quoteItem->getQuote()->getCustomerGroupId()); + $quoteItem->setConvertedPrice(null); + $originalPrice = $product->getPrice(); + if ($quoteItem->getParentItem() && $quoteItem->isChildrenCalculated()) { + $finalPrice = $quoteItem->getParentItem()->getProduct()->getPriceModel()->getChildFinalPrice( + $quoteItem->getParentItem()->getProduct(), + $quoteItem->getParentItem()->getQty(), + $product, + $quoteItem->getQty() + ); + $this->_calculateRowTotal($item, $finalPrice, $originalPrice); + } elseif (!$quoteItem->getParentItem()) { + $finalPrice = $product->getFinalPrice($quoteItem->getQty()); + $this->_calculateRowTotal($item, $finalPrice, $originalPrice); + $this->_addAmount($item->getRowTotal()); + $this->_addBaseAmount($item->getBaseRowTotal()); + $address->setTotalQty($address->getTotalQty() + $item->getQty()); + } + $valid = true; } } - - $quoteItem->setConvertedPrice(null); - $originalPrice = $product->getPrice(); - if ($quoteItem->getParentItem() && $quoteItem->isChildrenCalculated()) { - $finalPrice = $quoteItem->getParentItem()->getProduct()->getPriceModel()->getChildFinalPrice( - $quoteItem->getParentItem()->getProduct(), - $quoteItem->getParentItem()->getQty(), - $product, - $quoteItem->getQty() - ); - $this->_calculateRowTotal($item, $finalPrice, $originalPrice); - } elseif (!$quoteItem->getParentItem()) { - $finalPrice = $product->getFinalPrice($quoteItem->getQty()); - $this->_calculateRowTotal($item, $finalPrice, $originalPrice); - $this->_addAmount($item->getRowTotal()); - $this->_addBaseAmount($item->getBaseRowTotal()); - $address->setTotalQty($address->getTotalQty() + $item->getQty()); - } - return true; + return $valid; } /** @@ -147,7 +145,7 @@ protected function _calculateRowTotal($item, $finalPrice, $originalPrice) * Remove item * * @param Address $address - * @param AddressItem|Item $item + * @param AddressItem|Item $item * @return $this */ protected function _removeItem($address, $item) diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/SubtotalTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/SubtotalTest.php index 902f3e00c6610..2f8a5a344503c 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/SubtotalTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Address/Total/SubtotalTest.php @@ -1,5 +1,4 @@ objectManager = new ObjectManager($this); - $this->subtotalModel = $this->objectManager->getObject(Subtotal::class); + $this->subtotalModel = $this->objectManager->getObject( + Subtotal::class + ); - $this->stockRegistry = $this->createPartialMock(StockRegistry::class, ['getStockItem']); - $this->stockItemMock = $this->createPartialMock(Item::class, ['getIsInStock']); + $this->stockRegistry = $this->createPartialMock( + StockRegistry::class, + ['getStockItem', '__wakeup'] + ); + $this->stockItemMock = $this->createPartialMock( + \Magento\CatalogInventory\Model\Stock\Item::class, + ['getIsInStock', '__wakeup'] + ); } /** @@ -88,30 +96,28 @@ public function testCollect($price, $originalPrice, $itemHasParent, $expectedPri { $this->stockRegistry->expects($this->any())->method('getStockItem')->willReturn($this->stockItemMock); - $priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class) - ->getMock(); + $priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class)->getMock(); $convertedPrice = 1231313; // @TODO this is a wrong test and it does not check methods. Any digital value will be correct $priceCurrency->expects($this->any())->method('convert')->willReturn(1231313); - /** @var \Magento\Quote\Model\Quote\Item|MockObject $quoteItem */ + /** @var Item|MockObject $quoteItem */ $quoteItem = $this->objectManager->getObject( - \Magento\Quote\Model\Quote\Item::class, + Item::class, [ 'stockRegistry' => $this->stockRegistry, 'priceCurrency' => $priceCurrency, ] ); /** @var Address|MockObject $address */ - $address = $this->getMockBuilder(Address::class) - ->addMethods(['setTotalQty', 'getTotalQty']) - ->onlyMethods(['removeItem', 'getQuote']) - ->disableOriginalConstructor() - ->getMock(); + $address = $this->createPartialMock( + Address::class, + ['setTotalQty', 'getTotalQty', 'removeItem', 'getQuote'] + ); /** @var Product|MockObject $product */ $product = $this->createMock(Product::class); - $product->expects($this->any())->method('getPrice')->willReturn($originalPrice); + $product->expects($this->any())->method('getPrice')->will($this->returnValue($originalPrice)); /** @var Quote|MockObject $quote */ $quote = $this->createMock(Quote::class); @@ -121,22 +127,22 @@ public function testCollect($price, $originalPrice, $itemHasParent, $expectedPri $store = $this->createPartialMock(Store::class, ['getWebsiteId']); $store->expects($this->any())->method('getWebsiteId')->willReturn(10); $product->expects($this->any())->method('getStore')->willReturn($store); - $product->expects($this->any())->method('isVisibleInCatalog')->willReturn(true); + $product->expects($this->any())->method('isVisibleInCatalog')->will($this->returnValue(true)); $extensionAttribute = $this->getMockBuilder(ProductExtensionInterface::class) ->setMethods(['getStockItem']) ->disableOriginalConstructor() ->getMockForAbstractClass(); $extensionAttribute->expects($this->atLeastOnce()) ->method('getStockItem') - ->willReturn($this->stockItemMock); + ->will($this->returnValue($this->stockItemMock)); $product->expects($this->atLeastOnce())->method('getExtensionAttributes')->willReturn($extensionAttribute); - $quote->expects($this->any())->method('getStore')->willReturn($store); + $quote->expects($this->any())->method('getStore')->will($this->returnValue($store)); $quoteItem->setProduct($product)->setQuote($quote); $parentQuoteItem = false; if ($itemHasParent) { - $parentQuoteItem = $this->createMock(\Magento\Quote\Model\Quote\Item::class); - $parentQuoteItem->expects($this->any())->method('getProduct')->willReturn($product); + $parentQuoteItem = $this->createMock(Item::class); + $parentQuoteItem->expects($this->any())->method('getProduct')->will($this->returnValue($product)); } $quoteItem->setParentItem($parentQuoteItem); //This value will be overwritten @@ -147,18 +153,18 @@ public function testCollect($price, $originalPrice, $itemHasParent, $expectedPri $product->expects($this->any())->method('getPriceModel')->willReturn($priceModel); $product->expects($this->any())->method('getFinalPrice')->willReturn($price); - $shipping = $this->getMockForAbstractClass(ShippingInterface::class); + $shipping = $this->createMock(ShippingInterface::class); $shipping->expects($this->exactly(2))->method('getAddress')->willReturn($address); $address->expects($this->at(0))->method('setTotalQty')->with(0); $address->expects($this->any())->method('getTotalQty')->willReturn(0); - $shippingAssignmentMock = $this->getMockForAbstractClass(ShippingAssignmentInterface::class); + $shippingAssignmentMock = $this->createMock(ShippingAssignmentInterface::class); $shippingAssignmentMock->expects($this->exactly(2))->method('getShipping')->willReturn($shipping); $shippingAssignmentMock->expects($this->once())->method('getItems')->willReturn([$quoteItem]); - $total = $this->getMockBuilder(Total::class) - ->addMethods(['setBaseVirtualAmount', 'setVirtualAmount']) - ->disableOriginalConstructor() - ->getMock(); + $total = $this->createPartialMock( + Total::class, + ['setBaseVirtualAmount', 'setVirtualAmount'] + ); $total->expects($this->once())->method('setBaseVirtualAmount')->willReturnSelf(); $total->expects($this->once())->method('setVirtualAmount')->willReturnSelf(); @@ -179,12 +185,74 @@ public function testFetch() ]; $quoteMock = $this->createMock(Quote::class); - $totalMock = $this->getMockBuilder(Total::class) - ->addMethods(['getSubtotal']) - ->disableOriginalConstructor() - ->getMock(); + $totalMock = $this->createPartialMock(Total::class, ['getSubtotal']); $totalMock->expects($this->once())->method('getSubtotal')->willReturn(100); $this->assertEquals($expectedResult, $this->subtotalModel->fetch($quoteMock, $totalMock)); } + + /** + * Test that invalid items are not collected + */ + public function testCollectWithInvalidItems() + { + $addressItemId = 38203; + $addressQuoteItemId = 7643; + $storeId = 1; + $quote = $this->createPartialMock( + Quote::class, + [ + 'getItemsCollection', + ] + ); + $quote->setData( + [ + 'store_id' => $storeId + ] + ); + $quoteItem = $this->createPartialMock( + Item::class, + [] + ); + $quoteItem->setQuote($quote); + $quote->method('getItemsCollection') + ->willReturn([$quoteItem]); + $address = $this->createPartialMock( + Address::class, + [ + 'removeItem', + 'getQuote' + ] + ); + $address->method('getQuote') + ->willReturn($quote); + $address->expects($this->once()) + ->method('removeItem') + ->with($addressItemId); + $addressItem = $this->createPartialMock( + AddressItem::class, + [ + 'getId', + 'getQuoteItemId' + ] + ); + $addressItem->setAddress($address); + $addressItem->method('getId') + ->willReturn($addressItemId); + $addressItem->method('getQuoteItemId') + ->willReturn($addressQuoteItemId); + $shipping = $this->createMock(ShippingInterface::class); + $shipping->method('getAddress') + ->willReturn($address); + $shippingAssignmentMock = $this->createMock(ShippingAssignmentInterface::class); + $shippingAssignmentMock->method('getShipping') + ->willReturn($shipping); + $shippingAssignmentMock->method('getItems') + ->willReturn([$addressItem]); + $total = $this->createPartialMock( + Total::class, + [] + ); + $this->subtotalModel->collect($quote, $shippingAssignmentMock, $total); + } } diff --git a/app/code/Magento/Quote/etc/db_schema.xml b/app/code/Magento/Quote/etc/db_schema.xml index 44a5f275b4d9f..ff183e3150894 100644 --- a/app/code/Magento/Quote/etc/db_schema.xml +++ b/app/code/Magento/Quote/etc/db_schema.xml @@ -8,25 +8,25 @@
- - - - - - - @@ -42,11 +42,11 @@ - - - @@ -57,9 +57,9 @@ - - @@ -82,9 +82,9 @@ nullable="true" comment="Subtotal With Discount"/> - - @@ -102,19 +102,19 @@
- - - - - @@ -128,15 +128,15 @@ comment="Street"/> - - - - - @@ -214,30 +214,30 @@
- - - - - - - - @@ -314,13 +314,13 @@
- - - - @@ -348,25 +348,25 @@ default="0" comment="Base Tax Amount"/> - - - - - - @@ -412,11 +412,11 @@
- - - @@ -430,9 +430,9 @@
- - @@ -445,12 +445,12 @@ - - - @@ -466,9 +466,9 @@
- - @@ -494,9 +494,9 @@
- - diff --git a/app/code/Magento/ReleaseNotification/etc/db_schema.xml b/app/code/Magento/ReleaseNotification/etc/db_schema.xml index 6f3aa481f73d4..3bee4b6e1afe9 100644 --- a/app/code/Magento/ReleaseNotification/etc/db_schema.xml +++ b/app/code/Magento/ReleaseNotification/etc/db_schema.xml @@ -9,9 +9,9 @@ xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
- - diff --git a/app/code/Magento/Reports/etc/db_schema.xml b/app/code/Magento/Reports/etc/db_schema.xml index 30accf36a053e..719c5de61fe4e 100644 --- a/app/code/Magento/Reports/etc/db_schema.xml +++ b/app/code/Magento/Reports/etc/db_schema.xml @@ -9,15 +9,15 @@ xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
- - - - - @@ -53,15 +53,15 @@
- - - - - @@ -96,29 +96,29 @@
- -
- - - - - - @@ -146,18 +146,18 @@
- + - - - - @@ -182,18 +182,18 @@
- + - - - - @@ -218,18 +218,18 @@
- + - - - - diff --git a/app/code/Magento/Review/etc/db_schema.xml b/app/code/Magento/Review/etc/db_schema.xml index 7a451dbbbcf98..5afa6e9d7a3e8 100644 --- a/app/code/Magento/Review/etc/db_schema.xml +++ b/app/code/Magento/Review/etc/db_schema.xml @@ -8,7 +8,7 @@
- @@ -16,7 +16,7 @@
- @@ -24,15 +24,15 @@
- - - - @@ -52,16 +52,16 @@
- - - - @@ -84,17 +84,17 @@
- - - - - - @@ -107,9 +107,9 @@
- - @@ -124,7 +124,7 @@
- @@ -135,14 +135,14 @@
- - - - @@ -157,14 +157,14 @@
- - - - @@ -176,24 +176,24 @@
- - - - - - - - - @@ -208,21 +208,21 @@
- - - - - - - - @@ -241,9 +241,9 @@
- - @@ -258,9 +258,9 @@
- - diff --git a/app/code/Magento/Sales/Test/Mftf/ActionGroup/CreateNewOrderActionGroup.xml b/app/code/Magento/Sales/Test/Mftf/ActionGroup/CreateNewOrderActionGroup.xml deleted file mode 100644 index 985dee39f26ca..0000000000000 --- a/app/code/Magento/Sales/Test/Mftf/ActionGroup/CreateNewOrderActionGroup.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - Selects 'Braintree' as the Payment Method on the Admin New Order creation page. Enters Credit Card details. PLEASE NOTE: The Credit Card details used are Hardcoded using 'PaymentAndShippingInfo'. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/app/code/Magento/Sales/Test/Mftf/Section/NewOrderSection.xml b/app/code/Magento/Sales/Test/Mftf/Section/NewOrderSection.xml index 26e00bf4c0aa4..b1b07f4de8f35 100644 --- a/app/code/Magento/Sales/Test/Mftf/Section/NewOrderSection.xml +++ b/app/code/Magento/Sales/Test/Mftf/Section/NewOrderSection.xml @@ -19,13 +19,7 @@ - - - - - - diff --git a/app/code/Magento/Sales/Test/Unit/ViewModel/CreditMemo/Create/ItemsToRenderTest.php b/app/code/Magento/Sales/Test/Unit/ViewModel/CreditMemo/Create/ItemsToRenderTest.php new file mode 100644 index 0000000000000..28a99e06a2f69 --- /dev/null +++ b/app/code/Magento/Sales/Test/Unit/ViewModel/CreditMemo/Create/ItemsToRenderTest.php @@ -0,0 +1,143 @@ +converter = $this->getMockBuilder(ConvertOrder::class) + ->onlyMethods(['itemToCreditmemoItem']) + ->disableOriginalConstructor() + ->getMock(); + $this->blockItems = $this->getMockBuilder(BlockItems::class) + ->onlyMethods(['getCreditmemo']) + ->disableOriginalConstructor() + ->getMock(); + $this->creditmemo = $this->getMockBuilder(Creditmemo::class) + ->onlyMethods(['getAllItems', 'getId', 'getStoreId']) + ->disableOriginalConstructor() + ->getMock(); + $this->creditmemoItem = $this->getMockBuilder(CreditmemoItem::class) + ->onlyMethods(['getOrderItem', 'getCreditMemo']) + ->disableOriginalConstructor() + ->getMock(); + $this->creditmemoItemParent = $this->getMockBuilder(CreditmemoItem::class) + ->onlyMethods(['setCreditmemo', 'setParentId']) + ->disableOriginalConstructor() + ->getMock(); + $this->creditmemoItemParent = $this->getMockBuilder(CreditmemoItem::class) + ->addMethods(['getItemId', 'setStoreId']) + ->disableOriginalConstructor() + ->getMock(); + $this->orderItem = $this->getMockBuilder(OrderItem::class) + ->onlyMethods(['getParentItem']) + ->disableOriginalConstructor() + ->getMock(); + $this->orderItemParent = $this->getMockBuilder(OrderItem::class) + ->onlyMethods(['getItemId']) + ->disableOriginalConstructor() + ->getMock(); + /** @var ObjectManager */ + $objectManager = new ObjectManager($this); + $this->itemsToRender = $objectManager->getObject( + ItemsToRender::class, + [ + 'items' => $this->blockItems, + 'converter' => $this->converter + ] + ); + } + + /** + * Test get items + */ + public function testGetItems(): void + { + $this->blockItems->method('getCreditmemo') + ->willReturn($this->creditmemo); + $this->creditmemo->method('getAllItems') + ->willReturn([$this->creditmemoItem]); + $this->creditmemo->method('getId') + ->willReturn(1); + $this->creditmemoItem->method('getCreditmemo') + ->willReturn($this->creditmemo); + $this->creditmemo->method('getStoreId') + ->willReturn(1); + $this->creditmemoItem->method('getOrderItem') + ->willReturn($this->orderItem); + $this->orderItem->method('getParentItem') + ->willReturn($this->orderItemParent); + $this->orderItemParent->method('getItemId') + ->willReturn(1); + $this->converter->method('itemToCreditmemoItem') + ->willReturn($this->creditmemoItemParent); + + $this->assertEquals( + [$this->creditmemoItemParent, $this->creditmemoItem], + $this->itemsToRender->getItems() + ); + } +} diff --git a/app/code/Magento/Sales/ViewModel/CreditMemo/Create/ItemsToRender.php b/app/code/Magento/Sales/ViewModel/CreditMemo/Create/ItemsToRender.php new file mode 100644 index 0000000000000..51b54e80ed060 --- /dev/null +++ b/app/code/Magento/Sales/ViewModel/CreditMemo/Create/ItemsToRender.php @@ -0,0 +1,77 @@ +items = $items; + $this->converter = $convertOrderFactory->create(); + } + + /** + * Return creditmemo items for rendering and make sure all its parents are included + * + * @return Item[] + */ + public function getItems(): array + { + $creditMemo = null; + $parents = []; + $items = []; + foreach ($this->items->getCreditmemo()->getAllItems() as $item) { + if (!$creditMemo) { + $creditMemo = $item->getCreditmemo(); + } + $orderItem = $item->getOrderItem(); + if ($orderItem->getChildrenItems()) { + $parents[] = $orderItem->getItemId(); + } + } + foreach ($this->items->getCreditmemo()->getAllItems() as $item) { + $orderItemParent = $item->getOrderItem()->getParentItem(); + if ($orderItemParent && !in_array($orderItemParent->getItemId(), $parents)) { + $itemParent = $this->converter->itemToCreditmemoItem($orderItemParent); + $itemParent->setCreditmemo($creditMemo) + ->setParentId($creditMemo->getId()) + ->setStoreId($creditMemo->getStoreId()); + $items[] = $itemParent; + $parents[] = $orderItemParent->getItemId(); + } + $items[] = $item; + } + return $items; + } +} diff --git a/app/code/Magento/Sales/etc/db_schema.xml b/app/code/Magento/Sales/etc/db_schema.xml index ea7c768b0a786..9ede9a79f7f8b 100644 --- a/app/code/Magento/Sales/etc/db_schema.xml +++ b/app/code/Magento/Sales/etc/db_schema.xml @@ -8,7 +8,7 @@
- @@ -16,11 +16,11 @@ - - - @@ -136,32 +136,32 @@ comment="Total Qty Ordered"/> - - - - - - - + - - - - - - - @@ -226,9 +226,9 @@ comment="Created At"/> - - @@ -296,13 +296,13 @@
- - - @@ -385,17 +385,17 @@
- - - - - - @@ -413,11 +413,11 @@ - - @@ -430,13 +430,13 @@
- - - - @@ -458,36 +458,36 @@
- - - - - - - - - @@ -550,9 +550,9 @@ - - @@ -601,9 +601,9 @@
- - @@ -641,7 +641,7 @@ comment="Amount Ordered"/> - @@ -695,27 +695,27 @@
- - - - - - - - - - @@ -761,20 +761,20 @@
- - - - @@ -782,7 +782,7 @@ - + @@ -836,9 +836,9 @@
- - @@ -847,9 +847,9 @@ - - @@ -866,14 +866,14 @@
- - - @@ -900,13 +900,13 @@
- - - -
- - @@ -967,21 +967,21 @@ comment="Base Subtotal"/> - - - - - - - - @@ -1011,7 +1011,7 @@ - @@ -1050,22 +1050,22 @@
- - - - - + @@ -1135,9 +1135,9 @@
- - @@ -1166,9 +1166,9 @@ nullable="true" comment="Base Row Total Incl Tax"/> - - @@ -1191,13 +1191,13 @@
- - - -
- - @@ -1268,21 +1268,21 @@ comment="Shipping Tax Amount"/> - - - - - - - - @@ -1310,7 +1310,7 @@ - @@ -1349,29 +1349,29 @@
- - - - -
- - @@ -1468,9 +1468,9 @@ nullable="true" comment="Base Row Total Incl Tax"/> - - @@ -1493,13 +1493,13 @@
- - - -
- + - - @@ -1550,12 +1550,12 @@
- + - - @@ -1582,12 +1582,12 @@
- + - - @@ -1636,12 +1636,12 @@
- + - - @@ -1689,18 +1689,18 @@
- - - - -
- + - - @@ -1760,12 +1760,12 @@
- + - - @@ -1789,14 +1789,14 @@
- + - - @@ -1820,14 +1820,14 @@
- + - - @@ -1851,18 +1851,18 @@
- + - - - @@ -1884,18 +1884,18 @@
- + - - - @@ -1917,18 +1917,18 @@
- + - - - @@ -1949,9 +1949,9 @@
- - @@ -1959,13 +1959,13 @@ comment="Percent"/> - - - @@ -1979,11 +1979,11 @@
- - - @@ -1995,7 +1995,7 @@ comment="Real tax amount for the item and tax rate"/> - @@ -2029,9 +2029,9 @@
- - @@ -2043,7 +2043,7 @@
- diff --git a/app/code/Magento/Sales/view/adminhtml/layout/sales_order_creditmemo_new.xml b/app/code/Magento/Sales/view/adminhtml/layout/sales_order_creditmemo_new.xml index cd7ca1d7e0d42..1bf18bc4d2b22 100644 --- a/app/code/Magento/Sales/view/adminhtml/layout/sales_order_creditmemo_new.xml +++ b/app/code/Magento/Sales/view/adminhtml/layout/sales_order_creditmemo_new.xml @@ -20,6 +20,7 @@ Magento\Sales\ViewModel\CreditMemo\Create\UpdateTotalsButton + Magento\Sales\ViewModel\CreditMemo\Create\ItemsToRender diff --git a/app/code/Magento/Sales/view/adminhtml/layout/sales_order_creditmemo_updateqty.xml b/app/code/Magento/Sales/view/adminhtml/layout/sales_order_creditmemo_updateqty.xml index 94ef0bf9d7a03..ec7af89754d9a 100644 --- a/app/code/Magento/Sales/view/adminhtml/layout/sales_order_creditmemo_updateqty.xml +++ b/app/code/Magento/Sales/view/adminhtml/layout/sales_order_creditmemo_updateqty.xml @@ -11,6 +11,7 @@ Magento\Sales\ViewModel\CreditMemo\Create\UpdateTotalsButton + Magento\Sales\ViewModel\CreditMemo\Create\ItemsToRender diff --git a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/items.phtml b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/items.phtml index 81dc778cff2df..2bb085a51e377 100644 --- a/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/items.phtml +++ b/app/code/Magento/Sales/view/adminhtml/templates/order/creditmemo/create/items.phtml @@ -9,7 +9,10 @@ getData('viewModel'); -$_items = $block->getCreditmemo()->getAllItems(); +/** @var Magento\Sales\ViewModel\CreditMemo\Create\ItemsToRender $itemsToRenderViewModel */ +$itemsToRenderViewModel = $block->getData('itemsToRenderViewModel'); +$_items = $itemsToRenderViewModel->getItems(); +$commentText = $block->getCreditmemo()->getCommentText(); ?>
@@ -17,7 +20,7 @@ $_items = $block->getCreditmemo()->getAllItems(); escapeHtml(__('Items to Refund')) ?> - +
@@ -25,7 +28,7 @@ $_items = $block->getCreditmemo()->getAllItems(); - canReturnToStock()) : ?> + canReturnToStock()): ?> @@ -35,7 +38,7 @@ $_items = $block->getCreditmemo()->getAllItems(); - canEditQty()) : ?> + canEditQty()): ?> @@ -46,10 +49,10 @@ $_items = $block->getCreditmemo()->getAllItems(); - - getOrderItem()->getParentItem()) : + + getOrderItem()->getParentItem()): continue; - else : + else: $i++; endif; ?> @@ -59,7 +62,7 @@ $_items = $block->getCreditmemo()->getAllItems();
escapeHtml(__('Product')) ?> escapeHtml(__('Price')) ?> escapeHtml(__('Qty')) ?>escapeHtml(__('Return to Stock')) ?> escapeHtml(__('Qty to Refund')) ?>escapeHtml(__('Row Total')) ?>
 
- +
escapeHtml(__('No Items To Refund')) ?>
@@ -68,7 +71,7 @@ $_items = $block->getCreditmemo()->getAllItems(); getChildHtml('order_totalbar'); ?> - +
@@ -94,7 +97,7 @@ $_items = $block->getCreditmemo()->getAllItems(); class="admin__control-textarea" name="creditmemo[comment_text]" rows="3" - cols="5">escapeHtml($block->getCreditmemo()->getCommentText()) ?> + cols="5">escapeHtml($commentText) ?> @@ -116,7 +119,7 @@ $_items = $block->getCreditmemo()->getAllItems(); escapeHtml(__('Append Comments')) ?> - canSendCreditmemoEmail()) :?> + canSendCreditmemoEmail()):?>
getBaseShippingDiscountAmount() + $baseDiscountAmount, $baseShippingAmount ); - $address->setShippingDiscountAmount($discountAmount); - $address->setBaseShippingDiscountAmount($baseDiscountAmount); + $address->setShippingDiscountAmount($this->priceCurrency->roundPrice($discountAmount)); + $address->setBaseShippingDiscountAmount($this->priceCurrency->roundPrice($baseDiscountAmount)); $appliedRuleIds[$rule->getRuleId()] = $rule->getRuleId(); $this->rulesApplier->maintainAddressCouponCode($address, $rule, $this->getCouponCode()); diff --git a/app/code/Magento/SalesRule/Test/Mftf/ActionGroup/StorefrontClickOnMiniCartActionGroup.xml b/app/code/Magento/SalesRule/Test/Mftf/ActionGroup/StorefrontClickOnMiniCartActionGroup.xml deleted file mode 100644 index 498695dee9336..0000000000000 --- a/app/code/Magento/SalesRule/Test/Mftf/ActionGroup/StorefrontClickOnMiniCartActionGroup.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/ValidatorTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/ValidatorTest.php index 506cc1c7a7edc..8ba770e588924 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/ValidatorTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/ValidatorTest.php @@ -134,6 +134,7 @@ protected function setUp(): void $ruleCollectionFactoryMock = $this->prepareRuleCollectionMock($this->ruleCollection); $this->priceCurrency = $this->getMockBuilder(PriceCurrencyInterface::class) ->disableOriginalConstructor() + ->setMethods(['roundPrice']) ->getMockForAbstractClass(); /** @var Validator|MockObject $validator */ @@ -542,6 +543,9 @@ public function testProcessShippingAmountActions($action, $ruleDiscount, $shippi $this->priceCurrency->method('convert') ->willReturn($ruleDiscount); + $this->priceCurrency->method('roundPrice') + ->willReturn(round($shippingDiscount, 2)); + $this->model->init( $this->model->getWebsiteId(), $this->model->getCustomerGroupId(), diff --git a/app/code/Magento/SalesRule/etc/db_schema.xml b/app/code/Magento/SalesRule/etc/db_schema.xml index e100121bea345..3912ba3642ba1 100644 --- a/app/code/Magento/SalesRule/etc/db_schema.xml +++ b/app/code/Magento/SalesRule/etc/db_schema.xml @@ -8,43 +8,43 @@ - - - - - - - - - - - - - @@ -57,24 +57,24 @@
- - - - - - - @@ -93,11 +93,11 @@
- - - @@ -114,13 +114,13 @@
- - - - @@ -140,11 +140,11 @@
- - - @@ -163,13 +163,13 @@
- - - - @@ -200,13 +200,13 @@
- + - - @@ -242,13 +242,13 @@
- + - - @@ -284,13 +284,13 @@
- + - - @@ -319,9 +319,9 @@
- - @@ -338,9 +338,9 @@
- - diff --git a/app/code/Magento/SalesSequence/etc/db_schema.xml b/app/code/Magento/SalesSequence/etc/db_schema.xml index 5ae72319c5a69..5026ea34cb5a2 100644 --- a/app/code/Magento/SalesSequence/etc/db_schema.xml +++ b/app/code/Magento/SalesSequence/etc/db_schema.xml @@ -8,19 +8,19 @@
- - - - - - @@ -36,10 +36,10 @@
- - diff --git a/app/code/Magento/SampleData/README.md b/app/code/Magento/SampleData/README.md index cec2b0a46125d..c71439b929013 100644 --- a/app/code/Magento/SampleData/README.md +++ b/app/code/Magento/SampleData/README.md @@ -51,7 +51,7 @@ To deploy sample data from the GitHub repository: ## Install Sample Data -Once the sample data is deployed, it will be installed automatically when you install or upgrade your Magento instance either by using the Magento Setup Wizard or from the command line. +Once the sample data is deployed, it will be installed automatically when you install or upgrade your Magento instance by using the command line. ## Uninstall Sample Data @@ -74,4 +74,4 @@ The deleted sample data entities will be restored. Those entities, which were ch ## Documentation -You can find the more detailed description of sample data manipulation procedures at . +You can find the more detailed description of sample data manipulation procedures at . diff --git a/app/code/Magento/Search/etc/db_schema.xml b/app/code/Magento/Search/etc/db_schema.xml index 1a01ffa42401c..c5ad1aae1d60e 100644 --- a/app/code/Magento/Search/etc/db_schema.xml +++ b/app/code/Magento/Search/etc/db_schema.xml @@ -8,21 +8,21 @@
- - - - - - - @@ -52,12 +52,12 @@
- - - diff --git a/app/code/Magento/Security/Model/ResourceModel/AdminSessionInfo.php b/app/code/Magento/Security/Model/ResourceModel/AdminSessionInfo.php index 334449d74d195..5f81a0d121f25 100644 --- a/app/code/Magento/Security/Model/ResourceModel/AdminSessionInfo.php +++ b/app/code/Magento/Security/Model/ResourceModel/AdminSessionInfo.php @@ -23,7 +23,7 @@ class AdminSessionInfo extends \Magento\Framework\Model\ResourceModel\Db\Abstrac /** * @param \Magento\Framework\Model\ResourceModel\Db\Context $context * @param \Magento\Framework\Stdlib\DateTime $dateTime - * @param null $connectionName + * @param null|string $connectionName */ public function __construct( \Magento\Framework\Model\ResourceModel\Db\Context $context, @@ -83,9 +83,11 @@ public function updateStatusByUserId( $updateOlderThen = null ) { $whereStatement = [ - 'updated_at > ?' => $this->dateTime->formatDate($updateOlderThen), 'user_id = ?' => (int) $userId, ]; + if ($updateOlderThen) { + $whereStatement['updated_at > ?'] = $this->dateTime->formatDate($updateOlderThen); + } if (!empty($excludedSessionIds)) { $whereStatement['session_id NOT IN (?)'] = $excludedSessionIds; } diff --git a/app/code/Magento/Security/etc/db_schema.xml b/app/code/Magento/Security/etc/db_schema.xml index 34bb497954a7e..0775c08b46244 100644 --- a/app/code/Magento/Security/etc/db_schema.xml +++ b/app/code/Magento/Security/etc/db_schema.xml @@ -8,12 +8,12 @@
- - - @@ -35,9 +35,9 @@
- - @@ -56,7 +56,7 @@
- diff --git a/app/code/Magento/SendFriend/Model/ResourceModel/SendFriend.php b/app/code/Magento/SendFriend/Model/ResourceModel/SendFriend.php index dd8f7b05c058c..618d941f7047e 100644 --- a/app/code/Magento/SendFriend/Model/ResourceModel/SendFriend.php +++ b/app/code/Magento/SendFriend/Model/ResourceModel/SendFriend.php @@ -46,7 +46,7 @@ public function getSendCount($object, $ip, $startTime, $websiteId = null) AND time>=:time AND website_id=:website_id' ); - $bind = ['ip' => $ip, 'time' => $startTime, 'website_id' => (int)$websiteId]; + $bind = ['ip' => ip2long($ip), 'time' => $startTime, 'website_id' => (int)$websiteId]; $row = $connection->fetchRow($select, $bind); return $row['count']; @@ -64,7 +64,7 @@ public function addSendItem($ip, $startTime, $websiteId) { $this->getConnection()->insert( $this->getMainTable(), - ['ip' => $ip, 'time' => $startTime, 'website_id' => $websiteId] + ['ip' => ip2long($ip), 'time' => $startTime, 'website_id' => $websiteId] ); return $this; } diff --git a/app/code/Magento/SendFriend/etc/db_schema.xml b/app/code/Magento/SendFriend/etc/db_schema.xml index b9551749dfc6d..ace6b8359403d 100644 --- a/app/code/Magento/SendFriend/etc/db_schema.xml +++ b/app/code/Magento/SendFriend/etc/db_schema.xml @@ -8,13 +8,13 @@
- - - - diff --git a/app/code/Magento/Sitemap/etc/db_schema.xml b/app/code/Magento/Sitemap/etc/db_schema.xml index adf1f11124f52..c06cd24d30e0d 100644 --- a/app/code/Magento/Sitemap/etc/db_schema.xml +++ b/app/code/Magento/Sitemap/etc/db_schema.xml @@ -8,13 +8,13 @@
- - diff --git a/app/code/Magento/Store/Model/Config/Importer/DataDifferenceCalculator.php b/app/code/Magento/Store/Model/Config/Importer/DataDifferenceCalculator.php index 75fbe23d78f8b..fac02bfb92b3f 100644 --- a/app/code/Magento/Store/Model/Config/Importer/DataDifferenceCalculator.php +++ b/app/code/Magento/Store/Model/Config/Importer/DataDifferenceCalculator.php @@ -20,6 +20,17 @@ class DataDifferenceCalculator */ private $runtimeConfigSource; + /** + * Scopes identifier + * + * @var string[] + */ + private $identifiers = [ + 'websites' => 'website_id', + 'groups' => 'group_id', + 'stores' => 'store_id', + ]; + /** * @param ConfigSourceInterface $runtimeConfigSource The config source to retrieve current config */ @@ -28,6 +39,31 @@ public function __construct(ConfigSourceInterface $runtimeConfigSource) $this->runtimeConfigSource = $runtimeConfigSource; } + /** + * Update data by checking ID + * + * @param string $scope + * @param array $data + * @param array $runtimeScopeData + * @return array + */ + private function updateDataById(string $scope, array $data, array $runtimeScopeData): array + { + $diffData = array_diff_key($data, $runtimeScopeData); + foreach ($diffData as $code => $datum) { + foreach ($runtimeScopeData as $runTimeScopeCode => $runtimeScopeDatum) { + if (isset($datum[$this->identifiers[$scope]]) + && $datum[$this->identifiers[$scope]] === $runtimeScopeDatum[$this->identifiers[$scope]] + ) { + $data[$runTimeScopeCode] = $data[$code]; + unset($data[$code]); + } + } + } + + return $data; + } + /** * Calculates items to delete. * @@ -41,6 +77,7 @@ public function getItemsToDelete($scope, array $data) $runtimeScopeData = $this->changeDataKeyToCode( $this->getRuntimeData($scope) ); + $data = $this->updateDataById($scope, $data, $runtimeScopeData); return array_diff_key($runtimeScopeData, $data); } @@ -58,6 +95,7 @@ public function getItemsToCreate($scope, array $data) $runtimeScopeData = $this->changeDataKeyToCode( $this->getRuntimeData($scope) ); + $data = $this->updateDataById($scope, $data, $runtimeScopeData); return array_diff_key($data, $runtimeScopeData); } @@ -77,7 +115,7 @@ public function getItemsToUpdate($scope, array $data) $runtimeScopeData = $this->changeDataKeyToCode( $this->getRuntimeData($scope) ); - + $data = $this->updateDataById($scope, $data, $runtimeScopeData); foreach ($runtimeScopeData as $entityCode => $entityData) { if (isset($data[$entityCode]) && array_diff_assoc($entityData, $data[$entityCode])) { $itemsToUpdate[$entityCode] = array_replace($entityData, $data[$entityCode]); diff --git a/app/code/Magento/Store/etc/db_schema.xml b/app/code/Magento/Store/etc/db_schema.xml index 5b2e178ff24b8..9f9efce81440b 100644 --- a/app/code/Magento/Store/etc/db_schema.xml +++ b/app/code/Magento/Store/etc/db_schema.xml @@ -8,15 +8,15 @@
- - - - @@ -32,14 +32,14 @@
- - - - @@ -58,17 +58,17 @@
- - - - - diff --git a/app/code/Magento/Swatches/Test/Mftf/Data/SwatchAttributeData.xml b/app/code/Magento/Swatches/Test/Mftf/Data/SwatchAttributeData.xml index 97702b9deb9b6..b768def0a9f4b 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Data/SwatchAttributeData.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Data/SwatchAttributeData.xml @@ -49,4 +49,9 @@ 1 0 + + TextSwatchAttribute- + swatch_text + text_swatch_attribute_ + diff --git a/app/code/Magento/Swatches/Test/Mftf/Metadata/SwatchProductAttributeMeta.xml b/app/code/Magento/Swatches/Test/Mftf/Metadata/SwatchProductAttributeMeta.xml index 795892dbb4d47..a6d674ea22032 100644 --- a/app/code/Magento/Swatches/Test/Mftf/Metadata/SwatchProductAttributeMeta.xml +++ b/app/code/Magento/Swatches/Test/Mftf/Metadata/SwatchProductAttributeMeta.xml @@ -11,6 +11,7 @@ application/x-www-form-urlencoded + string string string string @@ -43,4 +44,7 @@ string string + + application/json + diff --git a/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontConfigurableProductSwatchTierPriceTest.xml b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontConfigurableProductSwatchTierPriceTest.xml new file mode 100644 index 0000000000000..b3fa367313789 --- /dev/null +++ b/app/code/Magento/Swatches/Test/Mftf/Test/StorefrontConfigurableProductSwatchTierPriceTest.xml @@ -0,0 +1,84 @@ + + + + + + + + + <description value="Configurable product with swatch attribute should show the tier price on product page"/> + <severity value="CRITICAL"/> + <testCaseId value="MC-34033"/> + <useCaseId value="MC-33147"/> + <group value="Swatches"/> + </annotations> + <before> + <!-- Create configurable product --> + <createData entity="ApiCategory" stepKey="createCategory"/> + <createData entity="ApiConfigurableProduct" stepKey="createConfigurableProduct"> + <requiredEntity createDataKey="createCategory"/> + </createData> + <!-- Login as Admin --> + <actionGroup ref="AdminLoginActionGroup" stepKey="loginAsAdmin"/> + </before> + <after> + <!-- Delete configurable product --> + <deleteData createDataKey="createConfigurableProduct" stepKey="deleteConfigurableProduct"/> + <deleteData createDataKey="createCategory" stepKey="deleteCategory"/> + <!-- Delete color attribute --> + <actionGroup ref="DeleteProductAttributeActionGroup" stepKey="deleteColorAttribute"> + <argument name="ProductAttribute" value="ProductColorAttribute"/> + </actionGroup> + <!-- Logout --> + <actionGroup ref="AdminLogoutActionGroup" stepKey="adminLogout"/> + </after> + + <!-- Create text swatch attribute with 3 options: Black, White and Blue --> + <actionGroup ref="AddTextSwatchToProductActionGroup" stepKey="addColorAttribute"> + <argument name="attributeName" value="{{ProductColorAttribute.frontend_label}}"/> + <argument name="attributeCode" value="{{ProductColorAttribute.attribute_code}}"/> + <argument name="option1" value="Black"/> + <argument name="option2" value="White"/> + <argument name="option3" value="Blue"/> + </actionGroup> + <!-- Open configurable product edit page --> + <amOnPage url="{{AdminProductEditPage.url($createConfigurableProduct.id$)}}" stepKey="goToConfigurableProduct"/> + <!-- Generate configurations for configurable product --> + <actionGroup ref="GenerateConfigurationsByAttributeCodeActionGroup" stepKey="createProductConfigurations"> + <argument name="attributeCode" value="{{ProductColorAttribute.attribute_code}}"/> + </actionGroup> + <actionGroup ref="SaveConfigurableProductAddToCurrentAttributeSetActionGroup" stepKey="saveConfigurableProduct"/> + <!-- Set Tier Price to one of configuration product --> + <actionGroup ref="FilterAndSelectProductActionGroup" stepKey="filterProduct"> + <argument name="productSku" value="$$createConfigurableProduct.sku$$-White"/> + </actionGroup> + <actionGroup ref="ProductSetAdvancedPricingActionGroup" stepKey="addTierPriceToSimpleProduct"> + <argument name="group" value="ALL GROUPS"/> + <argument name="quantity" value="5"/> + <argument name="price" value="Discount"/> + <argument name="amount" value="50"/> + </actionGroup> + <actionGroup ref="SaveProductFormActionGroup" stepKey="saveSimpleProduct"/> + <!-- Go to storefront product page --> + <actionGroup ref="StorefrontOpenProductPageActionGroup" stepKey="openConfigurableProductPage"> + <argument name="productUrl" value="$createConfigurableProduct.custom_attributes[url_key]$"/> + </actionGroup> + <waitForPageLoad stepKey="waitForConfigurableProductPage"/> + <!-- Select White configuration --> + <actionGroup ref="StorefrontSelectSwatchOptionOnProductPageActionGroup" stepKey="selectWhiteOption"> + <argument name="optionName" value="White"/> + </actionGroup> + <!-- Assert tier price on selected configuration --> + <actionGroup ref="AssertStorefrontProductDetailPageTierPriceActionGroup" stepKey="assertProductTierPriceText"> + <argument name="tierProductPriceDiscountQuantity" value="5"/> + <argument name="productPriceWithAppliedTierPriceDiscount" value="61.50"/> + <argument name="productSavedPricePercent" value="50"/> + </actionGroup> + </test> +</tests> diff --git a/app/code/Magento/Swatches/etc/db_schema.xml b/app/code/Magento/Swatches/etc/db_schema.xml index 3dafbc3876494..ce1092daf9d28 100644 --- a/app/code/Magento/Swatches/etc/db_schema.xml +++ b/app/code/Magento/Swatches/etc/db_schema.xml @@ -11,13 +11,13 @@ <column xsi:type="text" name="additional_data" nullable="true" comment="Additional swatch attributes data"/> </table> <table name="eav_attribute_option_swatch" resource="default" engine="innodb" comment="Magento Swatches table"> - <column xsi:type="int" name="swatch_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="swatch_id" unsigned="true" nullable="false" identity="true" comment="Swatch ID"/> - <column xsi:type="int" name="option_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="option_id" unsigned="true" nullable="false" identity="false" comment="Option ID"/> - <column xsi:type="smallint" name="store_id" padding="5" unsigned="true" nullable="false" identity="false" + <column xsi:type="smallint" name="store_id" unsigned="true" nullable="false" identity="false" comment="Store ID"/> - <column xsi:type="smallint" name="type" padding="5" unsigned="true" nullable="false" identity="false" + <column xsi:type="smallint" name="type" unsigned="true" nullable="false" identity="false" comment="Swatch type: 0 - text, 1 - visual color, 2 - visual image"/> <column xsi:type="varchar" name="value" nullable="true" length="255" comment="Swatch Value"/> <constraint xsi:type="primary" referenceId="PRIMARY"> diff --git a/app/code/Magento/Swatches/view/base/web/js/swatch-renderer.js b/app/code/Magento/Swatches/view/base/web/js/swatch-renderer.js index a45ee933584ba..ad5926d451e88 100644 --- a/app/code/Magento/Swatches/view/base/web/js/swatch-renderer.js +++ b/app/code/Magento/Swatches/view/base/web/js/swatch-renderer.js @@ -278,7 +278,7 @@ define([ // tier prise selectors end // A price label selector - normalPriceLabelSelector: '.normal-price .price-label' + normalPriceLabelSelector: '.product-info-main .normal-price .price-label' }, /** @@ -292,6 +292,17 @@ define([ return _.isArray(products) ? products[0] : null; }, + /** + * Get chosen product id + * + * @returns int|null + */ + getProductId: function () { + var products = this._CalcProducts(); + + return _.isArray(products) && products.length === 1 ? products[0] : null; + }, + /** * @private */ @@ -1018,22 +1029,11 @@ define([ */ _getNewPrices: function () { var $widget = this, - optionPriceDiff = 0, - allowedProduct = this._getAllowedProductWithMinPrice(this._CalcProducts()), - optionPrices = this.options.jsonConfig.optionPrices, - basePrice = parseFloat(this.options.jsonConfig.prices.basePrice.amount), - optionFinalPrice, - newPrices; + newPrices = $widget.options.jsonConfig.prices, + allowedProduct = this._getAllowedProductWithMinPrice(this._CalcProducts()); if (!_.isEmpty(allowedProduct)) { - optionFinalPrice = parseFloat(optionPrices[allowedProduct].finalPrice.amount); - optionPriceDiff = optionFinalPrice - basePrice; - } - - if (optionPriceDiff !== 0) { - newPrices = this.options.jsonConfig.optionPrices[allowedProduct]; - } else { - newPrices = $widget.options.jsonConfig.prices; + newPrices = this.options.jsonConfig.optionPrices[allowedProduct]; } return newPrices; diff --git a/app/code/Magento/Tax/etc/db_schema.xml b/app/code/Magento/Tax/etc/db_schema.xml index 1fe1a1fe33d8a..b38cfa2f6a70a 100644 --- a/app/code/Magento/Tax/etc/db_schema.xml +++ b/app/code/Magento/Tax/etc/db_schema.xml @@ -8,7 +8,7 @@ <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="tax_class" resource="default" engine="innodb" comment="Tax Class"> - <column xsi:type="smallint" name="class_id" padding="6" unsigned="false" nullable="false" identity="true" + <column xsi:type="smallint" name="class_id" unsigned="false" nullable="false" identity="true" comment="Class ID"/> <column xsi:type="varchar" name="class_name" nullable="false" length="255" comment="Class Name"/> <column xsi:type="varchar" name="class_type" nullable="false" length="8" default="CUSTOMER" @@ -18,14 +18,14 @@ </constraint> </table> <table name="tax_calculation_rule" resource="default" engine="innodb" comment="Tax Calculation Rule"> - <column xsi:type="int" name="tax_calculation_rule_id" padding="11" unsigned="false" nullable="false" + <column xsi:type="int" name="tax_calculation_rule_id" unsigned="false" nullable="false" identity="true" comment="Tax Calculation Rule ID"/> <column xsi:type="varchar" name="code" nullable="false" length="255" comment="Code"/> - <column xsi:type="int" name="priority" padding="11" unsigned="false" nullable="false" identity="false" + <column xsi:type="int" name="priority" unsigned="false" nullable="false" identity="false" comment="Priority"/> - <column xsi:type="int" name="position" padding="11" unsigned="false" nullable="false" identity="false" + <column xsi:type="int" name="position" unsigned="false" nullable="false" identity="false" comment="Position"/> - <column xsi:type="int" name="calculate_subtotal" padding="11" unsigned="false" nullable="false" identity="false" + <column xsi:type="int" name="calculate_subtotal" unsigned="false" nullable="false" identity="false" comment="Calculate off subtotal option"/> <constraint xsi:type="primary" referenceId="PRIMARY"> <column name="tax_calculation_rule_id"/> @@ -39,20 +39,20 @@ </index> </table> <table name="tax_calculation_rate" resource="default" engine="innodb" comment="Tax Calculation Rate"> - <column xsi:type="int" name="tax_calculation_rate_id" padding="11" unsigned="false" nullable="false" + <column xsi:type="int" name="tax_calculation_rate_id" unsigned="false" nullable="false" identity="true" comment="Tax Calculation Rate ID"/> <column xsi:type="varchar" name="tax_country_id" nullable="false" length="2" comment="Tax Country ID"/> - <column xsi:type="int" name="tax_region_id" padding="11" unsigned="false" nullable="false" identity="false" + <column xsi:type="int" name="tax_region_id" unsigned="false" nullable="false" identity="false" comment="Tax Region ID"/> <column xsi:type="varchar" name="tax_postcode" nullable="true" length="21" comment="Tax Postcode"/> <column xsi:type="varchar" name="code" nullable="false" length="255" comment="Code"/> <column xsi:type="decimal" name="rate" scale="4" precision="12" unsigned="false" nullable="false" comment="Rate"/> - <column xsi:type="smallint" name="zip_is_range" padding="6" unsigned="false" nullable="true" identity="false" + <column xsi:type="smallint" name="zip_is_range" unsigned="false" nullable="true" identity="false" comment="Zip Is Range"/> - <column xsi:type="int" name="zip_from" padding="10" unsigned="true" nullable="true" identity="false" + <column xsi:type="int" name="zip_from" unsigned="true" nullable="true" identity="false" comment="Zip From"/> - <column xsi:type="int" name="zip_to" padding="10" unsigned="true" nullable="true" identity="false" + <column xsi:type="int" name="zip_to" unsigned="true" nullable="true" identity="false" comment="Zip To"/> <constraint xsi:type="primary" referenceId="PRIMARY"> <column name="tax_calculation_rate_id"/> @@ -74,15 +74,15 @@ </index> </table> <table name="tax_calculation" resource="default" engine="innodb" comment="Tax Calculation"> - <column xsi:type="int" name="tax_calculation_id" padding="11" unsigned="false" nullable="false" identity="true" + <column xsi:type="int" name="tax_calculation_id" unsigned="false" nullable="false" identity="true" comment="Tax Calculation ID"/> - <column xsi:type="int" name="tax_calculation_rate_id" padding="11" unsigned="false" nullable="false" + <column xsi:type="int" name="tax_calculation_rate_id" unsigned="false" nullable="false" identity="false" comment="Tax Calculation Rate ID"/> - <column xsi:type="int" name="tax_calculation_rule_id" padding="11" unsigned="false" nullable="false" + <column xsi:type="int" name="tax_calculation_rule_id" unsigned="false" nullable="false" identity="false" comment="Tax Calculation Rule ID"/> - <column xsi:type="smallint" name="customer_tax_class_id" padding="6" unsigned="false" nullable="false" + <column xsi:type="smallint" name="customer_tax_class_id" unsigned="false" nullable="false" identity="false" comment="Customer Tax Class ID"/> - <column xsi:type="smallint" name="product_tax_class_id" padding="6" unsigned="false" nullable="false" + <column xsi:type="smallint" name="product_tax_class_id" unsigned="false" nullable="false" identity="false" comment="Product Tax Class ID"/> <constraint xsi:type="primary" referenceId="PRIMARY"> <column name="tax_calculation_id"/> @@ -115,11 +115,11 @@ </index> </table> <table name="tax_calculation_rate_title" resource="default" engine="innodb" comment="Tax Calculation Rate Title"> - <column xsi:type="int" name="tax_calculation_rate_title_id" padding="11" unsigned="false" nullable="false" + <column xsi:type="int" name="tax_calculation_rate_title_id" unsigned="false" nullable="false" identity="true" comment="Tax Calculation Rate Title ID"/> - <column xsi:type="int" name="tax_calculation_rate_id" padding="11" unsigned="false" nullable="false" + <column xsi:type="int" name="tax_calculation_rate_id" unsigned="false" nullable="false" identity="false" comment="Tax Calculation Rate ID"/> - <column xsi:type="smallint" name="store_id" padding="5" unsigned="true" nullable="false" identity="false" + <column xsi:type="smallint" name="store_id" unsigned="true" nullable="false" identity="false" comment="Store ID"/> <column xsi:type="varchar" name="value" nullable="false" length="255" comment="Value"/> <constraint xsi:type="primary" referenceId="PRIMARY"> @@ -140,14 +140,14 @@ </index> </table> <table name="tax_order_aggregated_created" resource="sales" engine="innodb" comment="Tax Order Aggregation"> - <column xsi:type="int" name="id" padding="10" unsigned="true" nullable="false" identity="true" comment="ID"/> + <column xsi:type="int" name="id" unsigned="true" nullable="false" identity="true" comment="ID"/> <column xsi:type="date" name="period" comment="Period"/> - <column xsi:type="smallint" name="store_id" padding="5" unsigned="true" nullable="true" identity="false" + <column xsi:type="smallint" name="store_id" unsigned="true" nullable="true" identity="false" comment="Store ID"/> <column xsi:type="varchar" name="code" nullable="false" length="255" comment="Code"/> <column xsi:type="varchar" name="order_status" nullable="false" length="50" comment="Order Status"/> <column xsi:type="float" name="percent" unsigned="false" nullable="true" comment="Percent"/> - <column xsi:type="int" name="orders_count" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="orders_count" unsigned="true" nullable="false" identity="false" default="0" comment="Orders Count"/> <column xsi:type="float" name="tax_base_amount_sum" unsigned="false" nullable="true" comment="Tax Base Amount Sum"/> @@ -170,14 +170,14 @@ </table> <table name="tax_order_aggregated_updated" resource="sales" engine="innodb" comment="Tax Order Aggregated Updated"> - <column xsi:type="int" name="id" padding="10" unsigned="true" nullable="false" identity="true" comment="ID"/> + <column xsi:type="int" name="id" unsigned="true" nullable="false" identity="true" comment="ID"/> <column xsi:type="date" name="period" comment="Period"/> - <column xsi:type="smallint" name="store_id" padding="5" unsigned="true" nullable="true" identity="false" + <column xsi:type="smallint" name="store_id" unsigned="true" nullable="true" identity="false" comment="Store ID"/> <column xsi:type="varchar" name="code" nullable="false" length="255" comment="Code"/> <column xsi:type="varchar" name="order_status" nullable="false" length="50" comment="Order Status"/> <column xsi:type="float" name="percent" unsigned="false" nullable="true" comment="Percent"/> - <column xsi:type="int" name="orders_count" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="orders_count" unsigned="true" nullable="false" identity="false" default="0" comment="Orders Count"/> <column xsi:type="float" name="tax_base_amount_sum" unsigned="false" nullable="true" comment="Tax Base Amount Sum"/> diff --git a/app/code/Magento/Theme/etc/adminhtml/system.xml b/app/code/Magento/Theme/etc/adminhtml/system.xml index 20500619354e0..af5e952584d1c 100644 --- a/app/code/Magento/Theme/etc/adminhtml/system.xml +++ b/app/code/Magento/Theme/etc/adminhtml/system.xml @@ -9,13 +9,13 @@ <system> <section id="dev" translate="label" type="text" sortOrder="920" showInDefault="1" showInWebsite="1" showInStore="1"> <group id="js"> - <field id="move_script_to_bottom" translate="label" type="select" sortOrder="25" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1"> + <field id="move_script_to_bottom" translate="label" type="select" sortOrder="25" showInDefault="1" showInWebsite="0" showInStore="0" canRestore="1"> <label>Move JS code to the bottom of the page</label> <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> </field> </group> <group id="css"> - <field id="use_css_critical_path" translate="label comment" type="select" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1"> + <field id="use_css_critical_path" translate="label comment" type="select" sortOrder="30" showInDefault="1" showInWebsite="0" showInStore="0" canRestore="1"> <label>Use CSS critical path</label> <source_model>Magento\Config\Model\Config\Source\Yesno</source_model> <comment> diff --git a/app/code/Magento/Theme/etc/db_schema.xml b/app/code/Magento/Theme/etc/db_schema.xml index 84b7654e69160..de4cf53410ab9 100644 --- a/app/code/Magento/Theme/etc/db_schema.xml +++ b/app/code/Magento/Theme/etc/db_schema.xml @@ -8,16 +8,16 @@ <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="theme" resource="default" engine="innodb" comment="Core theme"> - <column xsi:type="int" name="theme_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="theme_id" unsigned="true" nullable="false" identity="true" comment="Theme identifier"/> - <column xsi:type="int" name="parent_id" padding="11" unsigned="false" nullable="true" identity="false" + <column xsi:type="int" name="parent_id" unsigned="false" nullable="true" identity="false" comment="Parent ID"/> <column xsi:type="varchar" name="theme_path" nullable="true" length="255" comment="Theme Path"/> <column xsi:type="varchar" name="theme_title" nullable="false" length="255" comment="Theme Title"/> <column xsi:type="varchar" name="preview_image" nullable="true" length="255" comment="Preview Image"/> <column xsi:type="boolean" name="is_featured" nullable="false" default="false" comment="Is Theme Featured"/> <column xsi:type="varchar" name="area" nullable="false" length="255" comment="Theme Area"/> - <column xsi:type="smallint" name="type" padding="6" unsigned="false" nullable="false" identity="false" + <column xsi:type="smallint" name="type" unsigned="false" nullable="false" identity="false" comment="Theme type: 0:physical, 1:virtual, 2:staging"/> <column xsi:type="text" name="code" nullable="true" comment="Full theme code, including package"/> <constraint xsi:type="primary" referenceId="PRIMARY"> @@ -25,14 +25,14 @@ </constraint> </table> <table name="theme_file" resource="default" engine="innodb" comment="Core theme files"> - <column xsi:type="int" name="theme_files_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="theme_files_id" unsigned="true" nullable="false" identity="true" comment="Theme files identifier"/> - <column xsi:type="int" name="theme_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="theme_id" unsigned="true" nullable="false" identity="false" comment="Theme ID"/> <column xsi:type="varchar" name="file_path" nullable="true" length="255" comment="Relative path to file"/> <column xsi:type="varchar" name="file_type" nullable="false" length="32" comment="File Type"/> <column xsi:type="longtext" name="content" nullable="false" comment="File Content"/> - <column xsi:type="smallint" name="sort_order" padding="6" unsigned="false" nullable="false" identity="false" + <column xsi:type="smallint" name="sort_order" unsigned="false" nullable="false" identity="false" default="0" comment="Sort Order"/> <column xsi:type="boolean" name="is_temporary" nullable="false" default="false" comment="Is Temporary File"/> <constraint xsi:type="primary" referenceId="PRIMARY"> @@ -42,9 +42,9 @@ referenceTable="theme" referenceColumn="theme_id" onDelete="CASCADE"/> </table> <table name="design_change" resource="default" engine="innodb" comment="Design Changes"> - <column xsi:type="int" name="design_change_id" padding="11" unsigned="false" nullable="false" identity="true" + <column xsi:type="int" name="design_change_id" unsigned="false" nullable="false" identity="true" comment="Design Change ID"/> - <column xsi:type="smallint" name="store_id" padding="5" unsigned="true" nullable="false" identity="false" + <column xsi:type="smallint" name="store_id" unsigned="true" nullable="false" identity="false" default="0" comment="Store ID"/> <column xsi:type="varchar" name="design" nullable="true" length="255" comment="Design"/> <column xsi:type="date" name="date_from" comment="First Date of Design Activity"/> diff --git a/app/code/Magento/Theme/view/frontend/templates/html/header/criticalCss.phtml b/app/code/Magento/Theme/view/frontend/templates/html/header/criticalCss.phtml index 1a191f5649a19..7d59438fdbf46 100644 --- a/app/code/Magento/Theme/view/frontend/templates/html/header/criticalCss.phtml +++ b/app/code/Magento/Theme/view/frontend/templates/html/header/criticalCss.phtml @@ -12,4 +12,4 @@ <style type="text/css" data-type="criticalCss"> <?= /* @noEscape */ $criticalCssViewModel->getCriticalCssData() ?> -</style> \ No newline at end of file +</style> diff --git a/app/code/Magento/Translation/etc/db_schema.xml b/app/code/Magento/Translation/etc/db_schema.xml index a8ce30a0b4fd9..063ee33b5916b 100644 --- a/app/code/Magento/Translation/etc/db_schema.xml +++ b/app/code/Magento/Translation/etc/db_schema.xml @@ -8,15 +8,15 @@ <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="translation" resource="default" engine="innodb" comment="Translations"> - <column xsi:type="int" name="key_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="key_id" unsigned="true" nullable="false" identity="true" comment="Key ID of Translation"/> <column xsi:type="varchar" name="string" nullable="false" length="255" default="Translate String" comment="Translation String"/> - <column xsi:type="smallint" name="store_id" padding="5" unsigned="true" nullable="false" identity="false" + <column xsi:type="smallint" name="store_id" unsigned="true" nullable="false" identity="false" default="0" comment="Store ID"/> <column xsi:type="varchar" name="translate" nullable="true" length="255" comment="Translate"/> <column xsi:type="varchar" name="locale" nullable="false" length="20" default="en_US" comment="Locale"/> - <column xsi:type="bigint" name="crc_string" padding="20" unsigned="false" nullable="false" identity="false" + <column xsi:type="bigint" name="crc_string" unsigned="false" nullable="false" identity="false" default="1591228201" comment="Translation String CRC32 Hash"/> <constraint xsi:type="primary" referenceId="PRIMARY"> <column name="key_id"/> diff --git a/app/code/Magento/Ui/etc/db_schema.xml b/app/code/Magento/Ui/etc/db_schema.xml index 552bd267e707a..44c630ed144fc 100644 --- a/app/code/Magento/Ui/etc/db_schema.xml +++ b/app/code/Magento/Ui/etc/db_schema.xml @@ -8,13 +8,13 @@ <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="ui_bookmark" resource="default" engine="innodb" comment="Bookmark"> - <column xsi:type="int" name="bookmark_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="bookmark_id" unsigned="true" nullable="false" identity="true" comment="Bookmark identifier"/> - <column xsi:type="int" name="user_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="user_id" unsigned="true" nullable="false" identity="false" comment="User ID"/> <column xsi:type="varchar" name="namespace" nullable="false" length="255" comment="Bookmark namespace"/> <column xsi:type="varchar" name="identifier" nullable="false" length="255" comment="Bookmark Identifier"/> - <column xsi:type="smallint" name="current" padding="6" unsigned="false" nullable="false" identity="false" + <column xsi:type="smallint" name="current" unsigned="false" nullable="false" identity="false" comment="Mark current bookmark per user and identifier"/> <column xsi:type="varchar" name="title" nullable="true" length="255" comment="Bookmark title"/> <column xsi:type="longtext" name="config" nullable="true" comment="Bookmark config"/> diff --git a/app/code/Magento/Ui/view/base/web/js/dynamic-rows/dynamic-rows.js b/app/code/Magento/Ui/view/base/web/js/dynamic-rows/dynamic-rows.js index cbbfbdb127ad7..5f29c5982e094 100644 --- a/app/code/Magento/Ui/view/base/web/js/dynamic-rows/dynamic-rows.js +++ b/app/code/Magento/Ui/view/base/web/js/dynamic-rows/dynamic-rows.js @@ -657,7 +657,7 @@ define([ startIndex = page || this.startIndex; - return dataRecord.slice(startIndex, this.startIndex + this.pageSize); + return dataRecord.slice(startIndex, this.startIndex + parseInt(this.pageSize, 10)); }, /** @@ -960,6 +960,9 @@ define([ reload: function () { this.clear(); this.initChildren(false, true); + + /* After change page size need to check existing current page */ + this._reducePages(); }, /** diff --git a/app/code/Magento/Ups/Model/Carrier.php b/app/code/Magento/Ups/Model/Carrier.php index 5b333e2dc2d5c..57ad12a972dab 100644 --- a/app/code/Magento/Ups/Model/Carrier.php +++ b/app/code/Magento/Ups/Model/Carrier.php @@ -1361,20 +1361,11 @@ public function getAllowedMethods() */ protected function _formShipmentRequest(DataObject $request) { - $packageParams = $request->getPackageParams(); - $height = $packageParams->getHeight(); - $width = $packageParams->getWidth(); - $length = $packageParams->getLength(); - $weightUnits = $packageParams->getWeightUnits() == \Zend_Measure_Weight::POUND ? 'LBS' : 'KGS'; - $dimensionsUnits = $packageParams->getDimensionUnits() == \Zend_Measure_Length::INCH ? 'IN' : 'CM'; - - $itemsDesc = []; - $itemsShipment = $request->getPackageItems(); - foreach ($itemsShipment as $itemShipment) { - $item = new DataObject(); - $item->setData($itemShipment); - $itemsDesc[] = $item->getName(); + $packages = $request->getPackages(); + foreach ($packages as $package) { + $shipmentItems[] = $package['items']; } + $shipmentItems = array_merge(...$shipmentItems); $xmlRequest = $this->_xmlElFactory->create( ['data' => '<?xml version = "1.0" ?><ShipmentConfirmRequest xml:lang="en-US"/>'] @@ -1389,7 +1380,7 @@ protected function _formShipmentRequest(DataObject $request) // UPS Print Return Label $returnPart->addChild('Code', '9'); } - $shipmentPart->addChild('Description', substr(implode(' ', $itemsDesc), 0, 35)); + $shipmentPart->addChild('Description', $this->generateShipmentDescription($shipmentItems)); //empirical $shipperPart = $shipmentPart->addChild('Shipper'); @@ -1481,77 +1472,95 @@ protected function _formShipmentRequest(DataObject $request) $servicePart = $shipmentPart->addChild('Service'); $servicePart->addChild('Code', $request->getShippingMethod()); - $packagePart = $shipmentPart->addChild('Package'); - $packagePart->addChild('Description', substr(implode(' ', $itemsDesc), 0, 35)); - //empirical - $packagePart->addChild('PackagingType')->addChild('Code', $request->getPackagingType()); - $packageWeight = $packagePart->addChild('PackageWeight'); - $packageWeight->addChild('Weight', $request->getPackageWeight()); - $packageWeight->addChild('UnitOfMeasurement')->addChild('Code', $weightUnits); - - // set dimensions - if ($length || $width || $height) { - $packageDimensions = $packagePart->addChild('Dimensions'); - $packageDimensions->addChild('UnitOfMeasurement')->addChild('Code', $dimensionsUnits); - $packageDimensions->addChild('Length', $length); - $packageDimensions->addChild('Width', $width); - $packageDimensions->addChild('Height', $height); - } - - // ups support reference number only for domestic service - if ($this->_isUSCountry($request->getRecipientAddressCountryCode()) - && $this->_isUSCountry($request->getShipperAddressCountryCode()) - ) { - if ($request->getReferenceData()) { - $referenceData = $request->getReferenceData() . $request->getPackageId(); - } else { - $referenceData = 'Order #' . - $request->getOrderShipment()->getOrder()->getIncrementId() . - ' P' . - $request->getPackageId(); + + $packagePart = []; + $customsTotal = 0; + $packagingTypes = []; + $deliveryConfirmationLevel = $this->_getDeliveryConfirmationLevel( + $request->getRecipientAddressCountryCode() + ); + foreach ($packages as $packageId => $package) { + $packageItems = $package['items']; + $packageParams = new DataObject($package['params']); + $packagingType = $package['params']['container']; + $packagingTypes[] = $packagingType; + $height = $packageParams->getHeight(); + $width = $packageParams->getWidth(); + $length = $packageParams->getLength(); + $weight = $packageParams->getWeight(); + $weightUnits = $packageParams->getWeightUnits() == \Zend_Measure_Weight::POUND ? 'LBS' : 'KGS'; + $dimensionsUnits = $packageParams->getDimensionUnits() == \Zend_Measure_Length::INCH ? 'IN' : 'CM'; + $deliveryConfirmation = $packageParams->getDeliveryConfirmation(); + $customsTotal += $packageParams->getCustomsValue(); + + $packagePart[$packageId] = $shipmentPart->addChild('Package'); + $packagePart[$packageId]->addChild('Description', $this->generateShipmentDescription($packageItems)); + //empirical + $packagePart[$packageId]->addChild('PackagingType')->addChild('Code', $packagingType); + $packageWeight = $packagePart[$packageId]->addChild('PackageWeight'); + $packageWeight->addChild('Weight', $weight); + $packageWeight->addChild('UnitOfMeasurement')->addChild('Code', $weightUnits); + + // set dimensions + if ($length || $width || $height) { + $packageDimensions = $packagePart[$packageId]->addChild('Dimensions'); + $packageDimensions->addChild('UnitOfMeasurement')->addChild('Code', $dimensionsUnits); + $packageDimensions->addChild('Length', $length); + $packageDimensions->addChild('Width', $width); + $packageDimensions->addChild('Height', $height); } - $referencePart = $packagePart->addChild('ReferenceNumber'); - $referencePart->addChild('Code', '02'); - $referencePart->addChild('Value', $referenceData); - } - - $deliveryConfirmation = $packageParams->getDeliveryConfirmation(); - if ($deliveryConfirmation) { - /** @var $serviceOptionsNode Element */ - $serviceOptionsNode = null; - switch ($this->_getDeliveryConfirmationLevel($request->getRecipientAddressCountryCode())) { - case self::DELIVERY_CONFIRMATION_PACKAGE: - $serviceOptionsNode = $packagePart->addChild('PackageServiceOptions'); - break; - case self::DELIVERY_CONFIRMATION_SHIPMENT: - $serviceOptionsNode = $shipmentPart->addChild('ShipmentServiceOptions'); - break; - default: - break; + + // ups support reference number only for domestic service + if ($this->_isUSCountry($request->getRecipientAddressCountryCode()) + && $this->_isUSCountry($request->getShipperAddressCountryCode()) + ) { + if ($request->getReferenceData()) { + $referenceData = $request->getReferenceData() . $packageId; + } else { + $referenceData = 'Order #' . + $request->getOrderShipment()->getOrder()->getIncrementId() . + ' P' . + $packageId; + } + $referencePart = $packagePart[$packageId]->addChild('ReferenceNumber'); + $referencePart->addChild('Code', '02'); + $referencePart->addChild('Value', $referenceData); } - if ($serviceOptionsNode !== null) { - $serviceOptionsNode->addChild( - 'DeliveryConfirmation' - )->addChild( - 'DCISType', - $packageParams->getDeliveryConfirmation() - ); + + if ($deliveryConfirmation && $deliveryConfirmationLevel === self::DELIVERY_CONFIRMATION_PACKAGE) { + $serviceOptionsNode = $packagePart[$packageId]->addChild('PackageServiceOptions'); + $serviceOptionsNode->addChild( + 'DeliveryConfirmation' + )->addChild( + 'DCISType', + $deliveryConfirmation + ); } } + if (isset($deliveryConfirmation) && $deliveryConfirmationLevel === self::DELIVERY_CONFIRMATION_SHIPMENT) { + $serviceOptionsNode = $shipmentPart->addChild('ShipmentServiceOptions'); + $serviceOptionsNode->addChild( + 'DeliveryConfirmation' + )->addChild( + 'DCISType', + $deliveryConfirmation + ); + } + $shipmentPart->addChild('PaymentInformation') ->addChild('Prepaid') ->addChild('BillShipper') ->addChild('AccountNumber', $this->getConfigData('shipper_number')); - if ($request->getPackagingType() != $this->configHelper->getCode('container', 'ULE') + if (!in_array($this->configHelper->getCode('container', 'ULE'), $packagingTypes) && $request->getShipperAddressCountryCode() == self::USA_COUNTRY_ID && ($request->getRecipientAddressCountryCode() == 'CA' || $request->getRecipientAddressCountryCode() == 'PR') ) { $invoiceLineTotalPart = $shipmentPart->addChild('InvoiceLineTotal'); $invoiceLineTotalPart->addChild('CurrencyCode', $request->getBaseCurrencyCode()); - $invoiceLineTotalPart->addChild('MonetaryValue', ceil($packageParams->getCustomsValue())); + $invoiceLineTotalPart->addChild('MonetaryValue', ceil($customsTotal)); } $labelPart = $xmlRequest->addChild('LabelSpecification'); @@ -1561,6 +1570,25 @@ protected function _formShipmentRequest(DataObject $request) return $xmlRequest->asXml(); } + /** + * Generates shipment description. + * + * @param array $items + * @return string + */ + private function generateShipmentDescription(array $items): string + { + $itemsDesc = []; + $itemsShipment = $items; + foreach ($itemsShipment as $itemShipment) { + $item = new \Magento\Framework\DataObject(); + $item->setData($itemShipment); + $itemsDesc[] = $item->getName(); + } + + return substr(implode(' ', $itemsDesc), 0, 35); + } + /** * Send and process shipment accept request * @@ -1638,30 +1666,29 @@ public function getShipAcceptUrl() /** * Request quotes for given packages. * - * @param DataObject[] $packages + * @param DataObject $request * @return string[] Quote IDs. * @throws LocalizedException * @throws RuntimeException */ - private function requestQuotes(array $packages): array + private function requestQuotes(DataObject $request): array { /** @var HttpResponseDeferredInterface[] $quotesRequests */ - $quotesRequests = []; //Getting quotes - foreach ($packages as $package) { - $this->_prepareShipmentRequest($package); - $rawXmlRequest = $this->_formShipmentRequest($package); - $this->setXMLAccessRequest(); - $xmlRequest = $this->_xmlAccessRequest . $rawXmlRequest; - $quotesRequests[] = $this->asyncHttpClient->request( - new Request( - $this->getShipConfirmUrl(), - Request::METHOD_POST, - ['Content-Type' => 'application/xml'], - $xmlRequest - ) - ); - } + $this->_prepareShipmentRequest($request); + $rawXmlRequest = $this->_formShipmentRequest($request); + $this->setXMLAccessRequest(); + $xmlRequest = $this->_xmlAccessRequest . $rawXmlRequest; + $this->_debug(['request_quote' => $this->filterDebugData($this->_xmlAccessRequest) . $rawXmlRequest]); + $quotesRequests[] = $this->asyncHttpClient->request( + new Request( + $this->getShipConfirmUrl(), + Request::METHOD_POST, + ['Content-Type' => 'application/xml'], + $xmlRequest + ) + ); + $ids = []; //Processing quote responses foreach ($quotesRequests as $quotesRequest) { @@ -1672,6 +1699,7 @@ private function requestQuotes(array $packages): array try { /** @var Element $response */ $response = $this->_xmlElFactory->create(['data' => $httpResponse->getBody()]); + $this->_debug(['response_quote' => $response]); } catch (Throwable $e) { throw new RuntimeException($e->getMessage()); } @@ -1708,6 +1736,12 @@ private function requestShipments(array $quoteIds): array $request->addChild('RequestAction', 'ShipAccept'); $xmlRequest->addChild('ShipmentDigest', $quoteId); + $debugRequest = $this->filterDebugData($this->_xmlAccessRequest) . $xmlRequest->asXml(); + $this->_debug( + [ + 'request_shipment' => $debugRequest + ] + ); $shippingRequests[] = $this->asyncHttpClient->request( new Request( $this->getShipAcceptUrl(), @@ -1721,7 +1755,6 @@ private function requestShipments(array $quoteIds): array /** @var DataObject[] $results */ $results = []; foreach ($shippingRequests as $shippingRequest) { - $result = new DataObject(); $httpResponse = $shippingRequest->get(); if ($httpResponse->getStatusCode() >= 400) { throw new LocalizedException(__('Failed to send the package')); @@ -1729,19 +1762,23 @@ private function requestShipments(array $quoteIds): array try { /** @var Element $response */ $response = $this->_xmlElFactory->create(['data' => $httpResponse->getBody()]); + $this->_debug(['response_shipment' => $response]); } catch (Throwable $e) { throw new RuntimeException($e->getMessage()); } if (isset($response->Error)) { throw new RuntimeException((string)$response->Error->ErrorDescription); - } else { - $shippingLabelContent = (string)$response->ShipmentResults->PackageResults->LabelImage->GraphicImage; - $trackingNumber = (string)$response->ShipmentResults->PackageResults->TrackingNumber; + } + + foreach ($response->ShipmentResults->PackageResults as $packageResult) { + $result = new DataObject(); + $shippingLabelContent = (string)$packageResult->LabelImage->GraphicImage; + $trackingNumber = (string)$packageResult->TrackingNumber; // phpcs:ignore Magento2.Functions.DiscouragedFunction $result->setLabelContent(base64_decode($shippingLabelContent)); $result->setTrackingNumber($trackingNumber); + $results[] = $result; } - $results[] = $result; } return $results; @@ -1841,25 +1878,16 @@ public function requestToShipment($request) if ($request->getStoreId() != null) { $this->setStore($request->getStoreId()); } - /** @var Shipment[] $packageRequests */ - $packageRequests = []; - //Preparing packages info. - foreach ($packages as $packageId => $package) { - $request->setPackageId($packageId); - $request->setPackagingType($package['params']['container']); - $request->setPackageWeight($package['params']['weight']); - $request->setPackageParams(new DataObject($package['params'])); - $request->setPackageItems($package['items']); - $packageRequests[] = clone $request; - } // phpcs:disable try { - $quoteIds = $this->requestQuotes($packageRequests); + $quoteIds = $this->requestQuotes($request); $labels = $this->requestShipments($quoteIds); } catch (LocalizedException $exception) { + $this->_logger->critical($exception); return new DataObject(['errors' => [$exception->getMessage()]]); } catch (RuntimeException $exception) { + $this->_logger->critical($exception); return new DataObject(['errors' => __('Failed to send items')]); } // phpcs:enable diff --git a/app/code/Magento/UrlRewrite/etc/db_schema.xml b/app/code/Magento/UrlRewrite/etc/db_schema.xml index 93e84d8e02a0f..2812efac0bfb9 100644 --- a/app/code/Magento/UrlRewrite/etc/db_schema.xml +++ b/app/code/Magento/UrlRewrite/etc/db_schema.xml @@ -8,19 +8,19 @@ <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="url_rewrite" resource="default" engine="innodb" comment="Url Rewrites"> - <column xsi:type="int" name="url_rewrite_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="url_rewrite_id" unsigned="true" nullable="false" identity="true" comment="Rewrite ID"/> <column xsi:type="varchar" name="entity_type" nullable="false" length="32" comment="Entity type code"/> - <column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="entity_id" unsigned="true" nullable="false" identity="false" comment="Entity ID"/> <column xsi:type="varchar" name="request_path" nullable="true" length="255" comment="Request Path"/> <column xsi:type="varchar" name="target_path" nullable="true" length="255" comment="Target Path"/> - <column xsi:type="smallint" name="redirect_type" padding="5" unsigned="true" nullable="false" identity="false" + <column xsi:type="smallint" name="redirect_type" unsigned="true" nullable="false" identity="false" default="0" comment="Redirect Type"/> - <column xsi:type="smallint" name="store_id" padding="5" unsigned="true" nullable="false" identity="false" + <column xsi:type="smallint" name="store_id" unsigned="true" nullable="false" identity="false" comment="Store ID"/> <column xsi:type="varchar" name="description" nullable="true" length="255" comment="Description"/> - <column xsi:type="smallint" name="is_autogenerated" padding="5" unsigned="true" nullable="false" + <column xsi:type="smallint" name="is_autogenerated" unsigned="true" nullable="false" identity="false" default="0" comment="Is rewrite generated automatically flag"/> <column xsi:type="varchar" name="metadata" nullable="true" length="255" comment="Meta data for url rewrite"/> <constraint xsi:type="primary" referenceId="PRIMARY"> diff --git a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/AdminDeleteRoleActionGroup.xml b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminDeleteRoleActionGroup.xml similarity index 91% rename from app/code/Magento/Braintree/Test/Mftf/ActionGroup/AdminDeleteRoleActionGroup.xml rename to app/code/Magento/User/Test/Mftf/ActionGroup/AdminDeleteRoleActionGroup.xml index 9ee3c79d1288e..ac17c567a15a2 100644 --- a/app/code/Magento/Braintree/Test/Mftf/ActionGroup/AdminDeleteRoleActionGroup.xml +++ b/app/code/Magento/User/Test/Mftf/ActionGroup/AdminDeleteRoleActionGroup.xml @@ -7,7 +7,7 @@ --> <actionGroups xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> + xsi:noNamespaceSchemaLocation="urn:magento:mftf:Test/etc/actionGroupSchema.xsd"> <actionGroup name="AdminDeleteRoleActionGroup"> <annotations> <description>Deletes a User Role that contains the text 'Role'. PLEASE NOTE: The Action Group values are Hardcoded.</description> @@ -24,4 +24,4 @@ <waitForPageLoad stepKey="waitForPageLoad" time="10"/> <see stepKey="seeSuccessMessage" userInput="You deleted the role."/> </actionGroup> -</actionGroups> +</actionGroups> \ No newline at end of file diff --git a/app/code/Magento/User/Test/Mftf/Data/UserRoleData.xml b/app/code/Magento/User/Test/Mftf/Data/UserRoleData.xml index 4eec00ec4049b..c3cc81ce2574c 100644 --- a/app/code/Magento/User/Test/Mftf/Data/UserRoleData.xml +++ b/app/code/Magento/User/Test/Mftf/Data/UserRoleData.xml @@ -86,7 +86,6 @@ <item>Magento_Backend::main_actions</item> <item>Magento_Backend::mass_actions</item> <item>Magento_Backend::additional_cache_management</item> - <item>Magento_Backend::setup_wizard</item> <item>Magento_Backup::backup</item> <item>Magento_Indexer::index</item> <item>Magento_Indexer::changeMode</item> diff --git a/app/code/Magento/User/etc/db_schema.xml b/app/code/Magento/User/etc/db_schema.xml index e175b50108bd9..40b5fc16848b8 100644 --- a/app/code/Magento/User/etc/db_schema.xml +++ b/app/code/Magento/User/etc/db_schema.xml @@ -8,7 +8,7 @@ <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="admin_user" resource="default" engine="innodb" comment="Admin User Table"> - <column xsi:type="int" name="user_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="user_id" unsigned="true" nullable="false" identity="true" comment="User ID"/> <column xsi:type="varchar" name="firstname" nullable="true" length="32" comment="User First Name"/> <column xsi:type="varchar" name="lastname" nullable="true" length="32" comment="User Last Name"/> @@ -20,11 +20,11 @@ <column xsi:type="timestamp" name="modified" on_update="true" nullable="false" default="CURRENT_TIMESTAMP" comment="User Modified Time"/> <column xsi:type="timestamp" name="logdate" on_update="false" nullable="true" comment="User Last Login Time"/> - <column xsi:type="smallint" name="lognum" padding="5" unsigned="true" nullable="false" identity="false" + <column xsi:type="smallint" name="lognum" unsigned="true" nullable="false" identity="false" default="0" comment="User Login Number"/> - <column xsi:type="smallint" name="reload_acl_flag" padding="6" unsigned="false" nullable="false" + <column xsi:type="smallint" name="reload_acl_flag" unsigned="false" nullable="false" identity="false" default="0" comment="Reload ACL"/> - <column xsi:type="smallint" name="is_active" padding="6" unsigned="false" nullable="false" identity="false" + <column xsi:type="smallint" name="is_active" unsigned="false" nullable="false" identity="false" default="1" comment="User Is Active"/> <column xsi:type="text" name="extra" nullable="true" comment="User Extra Data"/> <column xsi:type="text" name="rp_token" nullable="true" comment="Reset Password Link Token"/> @@ -32,7 +32,7 @@ comment="Reset Password Link Token Creation Date"/> <column xsi:type="varchar" name="interface_locale" nullable="false" length="16" default="en_US" comment="Backend interface locale"/> - <column xsi:type="smallint" name="failures_num" padding="6" unsigned="false" nullable="true" identity="false" + <column xsi:type="smallint" name="failures_num" unsigned="false" nullable="true" identity="false" default="0" comment="Failure Number"/> <column xsi:type="timestamp" name="first_failure" on_update="false" nullable="true" comment="First Failure"/> <column xsi:type="timestamp" name="lock_expires" on_update="false" nullable="true" @@ -45,14 +45,14 @@ </constraint> </table> <table name="admin_passwords" resource="default" engine="innodb" comment="Admin Passwords"> - <column xsi:type="int" name="password_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="password_id" unsigned="true" nullable="false" identity="true" comment="Password ID"/> - <column xsi:type="int" name="user_id" padding="10" unsigned="true" nullable="false" identity="false" default="0" + <column xsi:type="int" name="user_id" unsigned="true" nullable="false" identity="false" default="0" comment="User ID"/> <column xsi:type="varchar" name="password_hash" nullable="true" length="100" comment="Password Hash"/> - <column xsi:type="int" name="expires" padding="10" unsigned="true" nullable="false" identity="false" default="0" + <column xsi:type="int" name="expires" unsigned="true" nullable="false" identity="false" default="0" comment="Deprecated"/> - <column xsi:type="int" name="last_updated" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="last_updated" unsigned="true" nullable="false" identity="false" default="0" comment="Last Updated"/> <constraint xsi:type="primary" referenceId="PRIMARY"> <column name="password_id"/> diff --git a/app/code/Magento/Variable/etc/db_schema.xml b/app/code/Magento/Variable/etc/db_schema.xml index cd6d7d105a08a..ff3274f979a4d 100644 --- a/app/code/Magento/Variable/etc/db_schema.xml +++ b/app/code/Magento/Variable/etc/db_schema.xml @@ -8,7 +8,7 @@ <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="variable" resource="default" engine="innodb" comment="Variables"> - <column xsi:type="int" name="variable_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="variable_id" unsigned="true" nullable="false" identity="true" comment="Variable ID"/> <column xsi:type="varchar" name="code" nullable="true" length="255" comment="Variable Code"/> <column xsi:type="varchar" name="name" nullable="true" length="255" comment="Variable Name"/> @@ -20,11 +20,11 @@ </constraint> </table> <table name="variable_value" resource="default" engine="innodb" comment="Variable Value"> - <column xsi:type="int" name="value_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="value_id" unsigned="true" nullable="false" identity="true" comment="Variable Value ID"/> - <column xsi:type="int" name="variable_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="variable_id" unsigned="true" nullable="false" identity="false" default="0" comment="Variable ID"/> - <column xsi:type="smallint" name="store_id" padding="5" unsigned="true" nullable="false" identity="false" + <column xsi:type="smallint" name="store_id" unsigned="true" nullable="false" identity="false" default="0" comment="Store ID"/> <column xsi:type="text" name="plain_value" nullable="true" comment="Plain Text Value"/> <column xsi:type="text" name="html_value" nullable="true" comment="Html Value"/> diff --git a/app/code/Magento/Vault/Test/Mftf/Section/StorefrontOnePageCheckoutSection.xml b/app/code/Magento/Vault/Test/Mftf/Section/StorefrontOnePageCheckoutSection.xml index 53ad03bd01ef8..ca85e79fa3f64 100644 --- a/app/code/Magento/Vault/Test/Mftf/Section/StorefrontOnePageCheckoutSection.xml +++ b/app/code/Magento/Vault/Test/Mftf/Section/StorefrontOnePageCheckoutSection.xml @@ -9,6 +9,6 @@ <sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:mftf:Page/etc/SectionObject.xsd"> <section name="StorefrontOnePageCheckoutPaymentSection"> - <element name="saveForLaterUse" type="checkbox" selector="fieldset.payment > div.choice > input[name='vault[is_enabled]']"/> + <element name="saveForLaterUse" type="checkbox" selector="input[name='vault[is_enabled]']"/> </section> </sections> diff --git a/app/code/Magento/Vault/Test/Unit/Plugin/PaymentVaultConfigurationProcessTest.php b/app/code/Magento/Vault/Test/Unit/Plugin/PaymentVaultConfigurationProcessTest.php index 0a233a858db86..ffce0b99632e2 100644 --- a/app/code/Magento/Vault/Test/Unit/Plugin/PaymentVaultConfigurationProcessTest.php +++ b/app/code/Magento/Vault/Test/Unit/Plugin/PaymentVaultConfigurationProcessTest.php @@ -122,12 +122,6 @@ public function beforeProcessDataProvider() 'vault' => [ 'methods' => [] ], - 'braintree' => [ - 'methods' => [ - 'braintree_paypal' => [], - 'braintree' => [] - ] - ], 'paypal-payments' => [ 'methods' => [ 'payflowpro' => [], @@ -142,9 +136,9 @@ public function beforeProcessDataProvider() 'vault' => [ 'methods' => [] ], - 'braintree' => [ + 'paypal-payments' => [ 'methods' => [ - 'braintree_paypal' => [] + 'payflowpro' => [], ] ] ]; @@ -155,8 +149,8 @@ public function beforeProcessDataProvider() ->setMethods(['getCode', 'getProviderCode']) ->getMockForAbstractClass(); - $vaultPaymentMethod->expects($this->any())->method('getCode')->willReturn('braintree_paypal_vault'); - $vaultPaymentMethod->expects($this->any())->method('getProviderCode')->willReturn('braintree_paypal'); + $vaultPaymentMethod->expects($this->any())->method('getCode')->willReturn('payflowpro_cc_vault'); + $vaultPaymentMethod->expects($this->any())->method('getProviderCode')->willReturn('payflowpro'); return [ [$jsLayout, [], [], $result1], diff --git a/app/code/Magento/Vault/etc/db_schema.xml b/app/code/Magento/Vault/etc/db_schema.xml index 7110978710048..e46a91daddde2 100644 --- a/app/code/Magento/Vault/etc/db_schema.xml +++ b/app/code/Magento/Vault/etc/db_schema.xml @@ -8,9 +8,9 @@ <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="vault_payment_token" resource="default" engine="innodb" comment="Vault tokens of payment"> - <column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="entity_id" unsigned="true" nullable="false" identity="true" comment="Entity ID"/> - <column xsi:type="int" name="customer_id" padding="10" unsigned="true" nullable="true" identity="false" + <column xsi:type="int" name="customer_id" unsigned="true" nullable="true" identity="false" comment="Customer ID"/> <column xsi:type="varchar" name="public_hash" nullable="false" length="128" comment="Hash code for using on frontend"/> @@ -41,9 +41,9 @@ </table> <table name="vault_payment_token_order_payment_link" resource="default" engine="innodb" comment="Order payments to vault token"> - <column xsi:type="int" name="order_payment_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="order_payment_id" unsigned="true" nullable="false" identity="false" comment="Order payment ID"/> - <column xsi:type="int" name="payment_token_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="payment_token_id" unsigned="true" nullable="false" identity="false" comment="Payment token ID"/> <constraint xsi:type="primary" referenceId="PRIMARY"> <column name="order_payment_id"/> diff --git a/app/code/Magento/Vault/view/adminhtml/web/js/vault.js b/app/code/Magento/Vault/view/adminhtml/web/js/vault.js index 68597f3d8adb9..1d0305a7046ab 100644 --- a/app/code/Magento/Vault/view/adminhtml/web/js/vault.js +++ b/app/code/Magento/Vault/view/adminhtml/web/js/vault.js @@ -27,18 +27,26 @@ define([ * @returns {exports.initObservable} */ initObservable: function () { - var self = this; + var self = this, + paymentSelector = '[name="payment[method]"][value="' + this.getCode() + '"]:checked'; self.$selector = $('#' + self.selector); this._super() .observe(['active']); + if (self.$selector.find(paymentSelector).length !== 0) { + this.active(true); + } + + $('#' + self.fieldset).find('[name="payment[token_switcher]"]') + .on('click', this.rememberTokenSwitcher.bind(this)); + // re-init payment method events self.$selector.off('changePaymentMethod.' + this.getCode()) .on('changePaymentMethod.' + this.getCode(), this.changePaymentMethod.bind(this)); if (this.active()) { - $('#' + this.fieldset + ' input:radio:first').trigger('click'); + this.chooseTokenSwitcher(); } return this; @@ -56,6 +64,33 @@ define([ return this; }, + /** + * Save last chosen token switcher + * @param {Object} event + * @returns {exports.rememberTokenSwitcher} + */ + rememberTokenSwitcher: function (event) { + $('#' + this.selector).data('lastTokenSwitcherId', event.target.id); + + return this; + }, + + /** + * Select token switcher + * @returns {exports.chooseTokenSwitcher} + */ + chooseTokenSwitcher: function () { + var lastTokenSwitcherId = $('#' + this.selector).data('lastTokenSwitcherId'); + + if (lastTokenSwitcherId) { + $('#' + lastTokenSwitcherId).trigger('click'); + } else { + $('#' + this.fieldset + ' input:radio:first').trigger('click'); + } + + return this; + }, + /** * Triggered when payment changed * @param {Boolean} isActive @@ -66,8 +101,7 @@ define([ return; } - - $('#' + this.fieldset + ' input:radio:first').trigger('click'); + this.chooseTokenSwitcher(); window.order.addExcludedPaymentMethod(this.getCode()); }, diff --git a/app/code/Magento/Weee/etc/db_schema.xml b/app/code/Magento/Weee/etc/db_schema.xml index aed8318993acf..b161c6b07a821 100644 --- a/app/code/Magento/Weee/etc/db_schema.xml +++ b/app/code/Magento/Weee/etc/db_schema.xml @@ -8,18 +8,18 @@ <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="weee_tax" resource="default" engine="innodb" comment="Weee Tax"> - <column xsi:type="int" name="value_id" padding="11" unsigned="false" nullable="false" identity="true" + <column xsi:type="int" name="value_id" unsigned="false" nullable="false" identity="true" comment="Value ID"/> - <column xsi:type="smallint" name="website_id" padding="5" unsigned="true" nullable="false" identity="false" + <column xsi:type="smallint" name="website_id" unsigned="true" nullable="false" identity="false" default="0" comment="Website ID"/> - <column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="entity_id" unsigned="true" nullable="false" identity="false" default="0" comment="Entity ID"/> <column xsi:type="varchar" name="country" nullable="true" length="2" comment="Country"/> <column xsi:type="decimal" name="value" scale="4" precision="12" unsigned="false" nullable="false" default="0" comment="Value"/> - <column xsi:type="int" name="state" padding="11" unsigned="false" nullable="false" identity="false" default="0" + <column xsi:type="int" name="state" unsigned="false" nullable="false" identity="false" default="0" comment="State"/> - <column xsi:type="smallint" name="attribute_id" padding="5" unsigned="true" nullable="false" identity="false" + <column xsi:type="smallint" name="attribute_id" unsigned="true" nullable="false" identity="false" comment="Attribute ID"/> <constraint xsi:type="primary" referenceId="PRIMARY"> <column name="value_id"/> diff --git a/app/code/Magento/Widget/etc/db_schema.xml b/app/code/Magento/Widget/etc/db_schema.xml index 6146761f6f251..565866bcded06 100644 --- a/app/code/Magento/Widget/etc/db_schema.xml +++ b/app/code/Magento/Widget/etc/db_schema.xml @@ -8,7 +8,7 @@ <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="widget" resource="default" engine="innodb" comment="Preconfigured Widgets"> - <column xsi:type="int" name="widget_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="widget_id" unsigned="true" nullable="false" identity="true" comment="Widget ID"/> <column xsi:type="varchar" name="widget_code" nullable="true" length="255" comment="Widget code for template directive"/> @@ -22,15 +22,15 @@ </index> </table> <table name="widget_instance" resource="default" engine="innodb" comment="Instances of Widget for Package Theme"> - <column xsi:type="int" name="instance_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="instance_id" unsigned="true" nullable="false" identity="true" comment="Instance ID"/> <column xsi:type="varchar" name="instance_type" nullable="true" length="255" comment="Instance Type"/> - <column xsi:type="int" name="theme_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="theme_id" unsigned="true" nullable="false" identity="false" comment="Theme ID"/> <column xsi:type="varchar" name="title" nullable="true" length="255" comment="Widget Title"/> <column xsi:type="varchar" name="store_ids" nullable="false" length="255" default="0" comment="Store ids"/> <column xsi:type="text" name="widget_parameters" nullable="true" comment="Widget parameters"/> - <column xsi:type="smallint" name="sort_order" padding="5" unsigned="true" nullable="false" identity="false" + <column xsi:type="smallint" name="sort_order" unsigned="true" nullable="false" identity="false" default="0" comment="Sort order"/> <constraint xsi:type="primary" referenceId="PRIMARY"> <column name="instance_id"/> @@ -39,9 +39,9 @@ column="theme_id" referenceTable="theme" referenceColumn="theme_id" onDelete="CASCADE"/> </table> <table name="widget_instance_page" resource="default" engine="innodb" comment="Instance of Widget on Page"> - <column xsi:type="int" name="page_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="page_id" unsigned="true" nullable="false" identity="true" comment="Page ID"/> - <column xsi:type="int" name="instance_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="instance_id" unsigned="true" nullable="false" identity="false" default="0" comment="Instance ID"/> <column xsi:type="varchar" name="page_group" nullable="true" length="25" comment="Block Group Type"/> <column xsi:type="varchar" name="layout_handle" nullable="true" length="255" comment="Layout Handle"/> @@ -60,9 +60,9 @@ </index> </table> <table name="widget_instance_page_layout" resource="default" engine="innodb" comment="Layout updates"> - <column xsi:type="int" name="page_id" padding="10" unsigned="true" nullable="false" identity="false" default="0" + <column xsi:type="int" name="page_id" unsigned="true" nullable="false" identity="false" default="0" comment="Page ID"/> - <column xsi:type="int" name="layout_update_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="layout_update_id" unsigned="true" nullable="false" identity="false" default="0" comment="Layout Update ID"/> <constraint xsi:type="foreign" referenceId="WIDGET_INSTANCE_PAGE_LAYOUT_PAGE_ID_WIDGET_INSTANCE_PAGE_PAGE_ID" table="widget_instance_page_layout" column="page_id" referenceTable="widget_instance_page" @@ -79,11 +79,11 @@ </index> </table> <table name="layout_update" resource="default" engine="innodb" comment="Layout Updates"> - <column xsi:type="int" name="layout_update_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="layout_update_id" unsigned="true" nullable="false" identity="true" comment="Layout Update ID"/> <column xsi:type="varchar" name="handle" nullable="true" length="255" comment="Handle"/> <column xsi:type="text" name="xml" nullable="true" comment="Xml"/> - <column xsi:type="smallint" name="sort_order" padding="6" unsigned="false" nullable="false" identity="false" + <column xsi:type="smallint" name="sort_order" unsigned="false" nullable="false" identity="false" default="0" comment="Sort Order"/> <column xsi:type="timestamp" name="updated_at" on_update="true" nullable="true" default="0" comment="Last Update Timestamp"/> @@ -95,13 +95,13 @@ </index> </table> <table name="layout_link" resource="default" engine="innodb" comment="Layout Link"> - <column xsi:type="int" name="layout_link_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="layout_link_id" unsigned="true" nullable="false" identity="true" comment="Link ID"/> - <column xsi:type="smallint" name="store_id" padding="5" unsigned="true" nullable="false" identity="false" + <column xsi:type="smallint" name="store_id" unsigned="true" nullable="false" identity="false" default="0" comment="Store ID"/> - <column xsi:type="int" name="theme_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="theme_id" unsigned="true" nullable="false" identity="false" comment="Theme ID"/> - <column xsi:type="int" name="layout_update_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="layout_update_id" unsigned="true" nullable="false" identity="false" default="0" comment="Layout Update ID"/> <column xsi:type="boolean" name="is_temporary" nullable="false" default="false" comment="Defines whether Layout Update is Temporary"/> diff --git a/app/code/Magento/Wishlist/etc/db_schema.xml b/app/code/Magento/Wishlist/etc/db_schema.xml index e3f3024df45fd..8038f04521516 100644 --- a/app/code/Magento/Wishlist/etc/db_schema.xml +++ b/app/code/Magento/Wishlist/etc/db_schema.xml @@ -8,11 +8,11 @@ <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="wishlist" resource="default" engine="innodb" comment="Wishlist main Table"> - <column xsi:type="int" name="wishlist_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="wishlist_id" unsigned="true" nullable="false" identity="true" comment="Wishlist ID"/> - <column xsi:type="int" name="customer_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="customer_id" unsigned="true" nullable="false" identity="false" default="0" comment="Customer ID"/> - <column xsi:type="smallint" name="shared" padding="5" unsigned="true" nullable="false" identity="false" + <column xsi:type="smallint" name="shared" unsigned="true" nullable="false" identity="false" default="0" comment="Sharing flag (0 or 1)"/> <column xsi:type="varchar" name="sharing_code" nullable="true" length="32" comment="Sharing encrypted code"/> <column xsi:type="timestamp" name="updated_at" on_update="false" nullable="true" comment="Last updated date"/> @@ -30,13 +30,13 @@ </index> </table> <table name="wishlist_item" resource="default" engine="innodb" comment="Wishlist items"> - <column xsi:type="int" name="wishlist_item_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="wishlist_item_id" unsigned="true" nullable="false" identity="true" comment="Wishlist item ID"/> - <column xsi:type="int" name="wishlist_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="wishlist_id" unsigned="true" nullable="false" identity="false" default="0" comment="Wishlist ID"/> - <column xsi:type="int" name="product_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="product_id" unsigned="true" nullable="false" identity="false" default="0" comment="Product ID"/> - <column xsi:type="smallint" name="store_id" padding="5" unsigned="true" nullable="true" identity="false" + <column xsi:type="smallint" name="store_id" unsigned="true" nullable="true" identity="false" comment="Store ID"/> <column xsi:type="timestamp" name="added_at" on_update="false" nullable="true" comment="Add date and time"/> <column xsi:type="text" name="description" nullable="true" comment="Short description of wish list item"/> @@ -63,11 +63,11 @@ </index> </table> <table name="wishlist_item_option" resource="default" engine="innodb" comment="Wishlist Item Option Table"> - <column xsi:type="int" name="option_id" padding="10" unsigned="true" nullable="false" identity="true" + <column xsi:type="int" name="option_id" unsigned="true" nullable="false" identity="true" comment="Option ID"/> - <column xsi:type="int" name="wishlist_item_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="wishlist_item_id" unsigned="true" nullable="false" identity="false" comment="Wishlist Item ID"/> - <column xsi:type="int" name="product_id" padding="10" unsigned="true" nullable="false" identity="false" + <column xsi:type="int" name="product_id" unsigned="true" nullable="false" identity="false" comment="Product ID"/> <column xsi:type="varchar" name="code" nullable="false" length="255" comment="Code"/> <column xsi:type="text" name="value" nullable="true" comment="Value"/> diff --git a/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less b/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less index 51a939cae1a5f..bdc986e918c2c 100644 --- a/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less +++ b/app/design/adminhtml/Magento/backend/Magento_Backend/web/css/source/module/main/_collapsible-blocks.less @@ -122,11 +122,6 @@ &:before { content: @icon-expand-close__content; } - &.active { - &:before { - content: @icon-expand-open__content; - } - } } } diff --git a/app/design/adminhtml/Magento/backend/Magento_Braintree/web/css/source/_module.less b/app/design/adminhtml/Magento/backend/Magento_Braintree/web/css/source/_module.less deleted file mode 100644 index efb2e664857c0..0000000000000 --- a/app/design/adminhtml/Magento/backend/Magento_Braintree/web/css/source/_module.less +++ /dev/null @@ -1,110 +0,0 @@ -// /** -// * Copyright © Magento, Inc. All rights reserved. -// * See COPYING.txt for license details. -// */ - -// -// Variables -// _____________________________________________ - -@braintree-error__color: @color-apricot; -@braintree-focus__color: @color-blue-pure; -@braintree-success__color: @color-green-apple; - -.hosted-date-wrap { - &:extend(.abs-clearfix all); -} - -.hosted-control { - height: 3.4rem; - position: relative; - - &.braintree-hosted-fields-focused { - border-color: @braintree-focus__color; - } - - &.braintree-hosted-fields-invalid:not(.braintree-hosted-fields-focused) { - border-color: @braintree-error__color; - - & ~ .hosted-error { - height: auto; - opacity: 1; - } - } - - &.braintree-hosted-fields-valid { - border-color: @braintree-success__color; - } - - &.hosted-date { - @distance: 50px; - - float: left; - margin-bottom: .2rem; - width: 5rem; - - &:first-of-type { - margin-right: @distance; - - &:after { - content: '/'; - display: inline; - padding-bottom: inherit; - padding-top: inherit; - position: absolute; - right: -@distance * (2 / 3.5); - top: 0; - } - } - } - - &.hosted-cid { - width: 6rem; - } - - .icon-type { - background-image: url('@{baseDir}images/cards.png'); - background-position: -1000px 0; - background-repeat: no-repeat; - height: 26px; - position: absolute; - right: 5px; - top: 3px; - width: 40px; - - &.icon-type-discover { - background-position: 0 0; - } - - &.icon-type-visa { - background-position: 0 -29px; - } - - &.icon-type-master-card { - background-position: 0 -58px; - } - - &.icon-type-maestro { - background-position: 0 -87px; - } - - &.icon-type-american-express { - background-position: 0 -114px; - } - - &.icon-type-unionpay { - background-position: 0 -140px; - } - - &.icon-type-diners-club { - background-position: 0 -168px; - } - } -} - -.hosted-error { - clear: both; - color: @braintree-error__color; - height: 0; - opacity: 0; -} diff --git a/app/design/frontend/Magento/blank/Magento_Braintree/web/css/source/_module.less b/app/design/frontend/Magento/blank/Magento_Braintree/web/css/source/_module.less deleted file mode 100644 index 8c1ec09afec1e..0000000000000 --- a/app/design/frontend/Magento/blank/Magento_Braintree/web/css/source/_module.less +++ /dev/null @@ -1,201 +0,0 @@ -// /** -// * Copyright © Magento, Inc. All rights reserved. -// * See COPYING.txt for license details. -// */ - -// -// Variables -// _____________________________________________ - -@braintree-input-border__color: @color-gray76; - -@braintree-error__color: @message-error__color; -@braintree-focus__color: @theme__color__primary-alt; -@braintree-success__color: @message-success__color; - -@braintree-paypal-icon__height: 16px; -@braintree-paypal-icon__width: 16px; -@braintree-paypal-account__padding-right: 50px; -@braintree-paypal-account__padding-vertical: 15px; - -// -// Common -// _____________________________________________ - -& when (@media-common = true) { - .payment-method-braintree { - - .hosted-date-wrap { - &:extend(.abs-add-clearfix all); - } - - .hosted-control { - .lib-form-element-input(@_type: input-text); - position: relative; - width: 225px; - - &.braintree-hosted-fields-focused { - border-color: @braintree-focus__color; - } - - &.braintree-hosted-fields-invalid:not(.braintree-hosted-fields-focused) { - border-color: @braintree-error__color; - - & ~ .hosted-error { - height: auto; - opacity: 1; - } - } - - &.braintree-hosted-fields-valid { - border-color: @braintree-success__color; - } - - &.hosted-cid { - width: 5rem; - } - - &.hosted-date { - @distance: 50px; - - float: left; - margin-bottom: 7px; - width: 6rem; - - &:first-of-type { - margin-right: @distance; - - &:after { - content: '/'; - display: inline; - padding-bottom: inherit; - padding-top: inherit; - position: absolute; - right: -@distance / 2; - top: 5px; - } - } - } - } - - .field-tooltip { - right: 0; - } - - .hosted-error { - clear: both; - color: @braintree-error__color; - font-size: 1.2rem; - height: 0; - margin-top: 7px; - opacity: 0; - } - } - - .braintree-paypal-logo { - margin-top: @indent__s; - text-align: center; - } - - .braintree-paypal-account { - padding: @braintree-paypal-account__padding-vertical 0 @braintree-paypal-account__padding-vertical @braintree-paypal-account__padding-right; - position: relative; - - .lib-icon-image( - @_icon-image: '@{baseDir}Magento_Braintree/images/paypal-small.png', - @_icon-image-position: before, - @_icon-image-width: @braintree-paypal-icon__width, - @_icon-image-height: @braintree-paypal-icon__height - ); - - &:before { - left: @braintree-paypal-account__padding-right/2 - @braintree-paypal-icon__width/2; - margin-top: -@braintree-paypal-icon__height/2; - position: absolute; - top: 50%; - } - - .payment-method-type { - font-weight: @font-weight__bold; - } - - .payment-method-description { - color: @color-gray34; - } - } - - .braintree-paypal-fieldset { - border: 0; - margin: 0; - padding: 0; - } - - .action-braintree-paypal-logo { - .lib-button-reset(); - - img { - margin: 0; - width: 114px; - } - } - - .payment-method { - .payment-method-content { - .actions-toolbar { - &.braintree-paypal-actions { - margin-left: 0; - } - } - } - } - - // My Account > Stored Payment Methods - .account { - .table { - .col { - &.paypal-account { - img { - vertical-align: middle; - } - - + .actions { - vertical-align: middle; - } - } - } - } - } -} - -// -// Desktop -// _____________________________________________ - -.media-width(@extremum, @break) when (@extremum = 'min') and (@break = @screen__m) { - .payment-method-braintree { - .cvv { - .field-tooltip { - left: 6rem; - } - } - } - - .braintree-paypal-account { - border-color: @color-gray80; - border-style: solid; - border-width: 1px 0; - display: inline-block; - width: 50%; - } - - // My Account > Stored Payment Methods - .account { - .table-credit-cards { - .col { - &.actions { - width: 100px; - } - } - } - } -} diff --git a/app/design/frontend/Magento/blank/Magento_Customer/web/css/source/_module.less b/app/design/frontend/Magento/blank/Magento_Customer/web/css/source/_module.less index adfcb117cc9d0..c3634239056db 100644 --- a/app/design/frontend/Magento/blank/Magento_Customer/web/css/source/_module.less +++ b/app/design/frontend/Magento/blank/Magento_Customer/web/css/source/_module.less @@ -414,8 +414,6 @@ &:extend(.abs-blocks-2columns all); .login { .actions-toolbar { - margin-left: 0; - > .primary { margin-bottom: 0; margin-right: @indent__l; @@ -430,19 +428,8 @@ .fieldset { &:after { - margin-left: 0; &:extend(.abs-margin-for-forms-desktop all); } - - > .field { - > .control { - width: 80%; - } - - .label { - text-align: left; - } - } } } diff --git a/app/design/frontend/Magento/blank/web/css/source/_buttons.less b/app/design/frontend/Magento/blank/web/css/source/_buttons.less index 93f99e9d4d594..dfc0aa0319d4f 100644 --- a/app/design/frontend/Magento/blank/web/css/source/_buttons.less +++ b/app/design/frontend/Magento/blank/web/css/source/_buttons.less @@ -25,7 +25,8 @@ .lib-link-as-button(); } - .action.primary { + .action.primary, + .action-primary { .lib-button-primary(); } } diff --git a/app/design/frontend/Magento/luma/web/css/source/_buttons.less b/app/design/frontend/Magento/luma/web/css/source/_buttons.less index 678b7e3401a86..5296bcc070fb4 100644 --- a/app/design/frontend/Magento/luma/web/css/source/_buttons.less +++ b/app/design/frontend/Magento/luma/web/css/source/_buttons.less @@ -17,7 +17,7 @@ button { &:not(.primary) { - .lib-css(box-shadow, @button__shadow); + .lib-css(box-shadow, none); &:active { .lib-css(box-shadow, @button__shadow-active); @@ -39,7 +39,8 @@ .lib-link-as-button(); } - .action.primary { + .action.primary, + .action-primary { .lib-button-primary(); } } diff --git a/app/etc/di.xml b/app/etc/di.xml index a94adaae5cf06..93ec69dfe1586 100644 --- a/app/etc/di.xml +++ b/app/etc/di.xml @@ -1815,4 +1815,13 @@ <argument name="cache" xsi:type="object">configured_block_cache</argument> </arguments> </type> + <type name="Magento\Framework\DB\Adapter\SqlVersionProvider"> + <arguments> + <argument name="supportedVersionPatterns" xsi:type="array"> + <item name="MySQL-8" xsi:type="string">^8\.0\.</item> + <item name="MySQL-5.7" xsi:type="string">^5\.7\.</item> + <item name="MariaDB-(10.2-10.4)" xsi:type="string">^10\.[2-4]\.</item> + </argument> + </arguments> + </type> </config> diff --git a/composer.json b/composer.json index bb70029021765..28602baa5c9ae 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,6 @@ "ext-xsl": "*", "ext-zip": "*", "lib-libxml": "*", - "braintree/braintree_php": "3.35.0", "colinmollenhour/cache-backend-file": "~1.4.1", "colinmollenhour/cache-backend-redis": "1.11.0", "colinmollenhour/credis": "1.11.1", @@ -93,7 +92,7 @@ "pdepend/pdepend": "~2.7.1", "phpcompatibility/php-compatibility": "^9.3", "phpmd/phpmd": "^2.8.0", - "phpstan/phpstan": "^0.12.3", + "phpstan/phpstan": ">=0.12.3 <=0.12.23", "phpunit/phpunit": "^9", "sebastian/phpcpd": "~5.0.0", "squizlabs/php_codesniffer": "~3.5.4" @@ -114,8 +113,6 @@ "magento/module-advanced-search": "*", "magento/module-backend": "*", "magento/module-backup": "*", - "magento/module-braintree": "*", - "magento/module-braintree-graph-ql": "*", "magento/module-bundle": "*", "magento/module-bundle-graph-ql": "*", "magento/module-bundle-import-export": "*", @@ -194,12 +191,13 @@ "magento/module-integration": "*", "magento/module-layered-navigation": "*", "magento/module-login-as-customer": "*", + "magento/module-login-as-customer-admin-ui": "*", "magento/module-login-as-customer-api": "*", + "magento/module-login-as-customer-frontend-ui": "*", "magento/module-login-as-customer-log": "*", + "magento/module-login-as-customer-quote": "*", "magento/module-login-as-customer-page-cache": "*", "magento/module-login-as-customer-sales": "*", - "magento/module-login-as-customer-ui": "*", - "magento/module-login-as-customer-webapi": "*", "magento/module-media-content": "*", "magento/module-media-content-api": "*", "magento/module-media-content-catalog": "*", diff --git a/composer.lock b/composer.lock index 350a2f9c5a2ed..167e801d3c318 100644 --- a/composer.lock +++ b/composer.lock @@ -4,55 +4,8 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "087f8432a6f317056b40a0b8a160a2cf", + "content-hash": "23086b14c6e4e9f771d89d7df324a06d", "packages": [ - { - "name": "braintree/braintree_php", - "version": "3.35.0", - "source": { - "type": "git", - "url": "https://github.com/braintree/braintree_php.git", - "reference": "6c4388199ce379432804a5c18b88585157ef2ed7" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/braintree/braintree_php/zipball/6c4388199ce379432804a5c18b88585157ef2ed7", - "reference": "6c4388199ce379432804a5c18b88585157ef2ed7", - "shasum": "" - }, - "require": { - "ext-curl": "*", - "ext-dom": "*", - "ext-hash": "*", - "ext-openssl": "*", - "ext-xmlwriter": "*", - "php": ">=5.4.0" - }, - "require-dev": { - "phpunit/phpunit": "3.7.*" - }, - "type": "library", - "autoload": { - "psr-0": { - "Braintree": "lib/" - }, - "psr-4": { - "Braintree\\": "lib/Braintree" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Braintree", - "homepage": "https://www.braintreepayments.com" - } - ], - "description": "Braintree PHP Client Library", - "time": "2018-07-26T14:37:38+00:00" - }, { "name": "colinmollenhour/cache-backend-file", "version": "v1.4.5", @@ -535,16 +488,16 @@ }, { "name": "elasticsearch/elasticsearch", - "version": "v7.6.1", + "version": "v7.7.0", "source": { "type": "git", "url": "https://github.com/elastic/elasticsearch-php.git", - "reference": "d4f24bc43c2af60aece3df20eb689d322f9c8acf" + "reference": "1d90a7ff4fb1936dc4376f09d723af75714f6f05" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/elastic/elasticsearch-php/zipball/d4f24bc43c2af60aece3df20eb689d322f9c8acf", - "reference": "d4f24bc43c2af60aece3df20eb689d322f9c8acf", + "url": "https://api.github.com/repos/elastic/elasticsearch-php/zipball/1d90a7ff4fb1936dc4376f09d723af75714f6f05", + "reference": "1d90a7ff4fb1936dc4376f09d723af75714f6f05", "shasum": "" }, "require": { @@ -594,7 +547,7 @@ "elasticsearch", "search" ], - "time": "2020-02-15T00:09:00+00:00" + "time": "2020-05-13T15:19:26+00:00" }, { "name": "ezimuel/guzzlestreams", @@ -1310,16 +1263,16 @@ }, { "name": "laminas/laminas-dependency-plugin", - "version": "1.0.3", + "version": "1.0.4", "source": { "type": "git", "url": "https://github.com/laminas/laminas-dependency-plugin.git", - "reference": "f269716dc584cd7b69e7f6e8ac1092d645ab56d5" + "reference": "38bf91861f5b4d49f9a1c530327c997f7a7fb2db" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laminas/laminas-dependency-plugin/zipball/f269716dc584cd7b69e7f6e8ac1092d645ab56d5", - "reference": "f269716dc584cd7b69e7f6e8ac1092d645ab56d5", + "url": "https://api.github.com/repos/laminas/laminas-dependency-plugin/zipball/38bf91861f5b4d49f9a1c530327c997f7a7fb2db", + "reference": "38bf91861f5b4d49f9a1c530327c997f7a7fb2db", "shasum": "" }, "require": { @@ -1352,7 +1305,7 @@ "BSD-3-Clause" ], "description": "Replace zendframework and zfcampus packages with their Laminas Project equivalents.", - "time": "2020-01-14T19:36:52+00:00" + "time": "2020-05-20T13:45:39+00:00" }, { "name": "laminas/laminas-di", @@ -3253,16 +3206,16 @@ }, { "name": "laminas/laminas-zendframework-bridge", - "version": "1.0.3", + "version": "1.0.4", "source": { "type": "git", "url": "https://github.com/laminas/laminas-zendframework-bridge.git", - "reference": "bfbbdb6c998d50dbf69d2187cb78a5f1fa36e1e9" + "reference": "fcd87520e4943d968557803919523772475e8ea3" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/laminas/laminas-zendframework-bridge/zipball/bfbbdb6c998d50dbf69d2187cb78a5f1fa36e1e9", - "reference": "bfbbdb6c998d50dbf69d2187cb78a5f1fa36e1e9", + "url": "https://api.github.com/repos/laminas/laminas-zendframework-bridge/zipball/fcd87520e4943d968557803919523772475e8ea3", + "reference": "fcd87520e4943d968557803919523772475e8ea3", "shasum": "" }, "require": { @@ -3301,7 +3254,7 @@ "laminas", "zf" ], - "time": "2020-04-03T16:01:00+00:00" + "time": "2020-05-20T16:45:56+00:00" }, { "name": "magento/composer", @@ -3420,16 +3373,16 @@ }, { "name": "magento/zendframework1", - "version": "1.14.3", + "version": "1.14.4", "source": { "type": "git", "url": "https://github.com/magento/zf1.git", - "reference": "726855dfb080089dc7bc7b016624129f8e7bc4e5" + "reference": "250f35c0e80b5e6fa1a1598c144cba2fff36b565" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/magento/zf1/zipball/726855dfb080089dc7bc7b016624129f8e7bc4e5", - "reference": "726855dfb080089dc7bc7b016624129f8e7bc4e5", + "url": "https://api.github.com/repos/magento/zf1/zipball/250f35c0e80b5e6fa1a1598c144cba2fff36b565", + "reference": "250f35c0e80b5e6fa1a1598c144cba2fff36b565", "shasum": "" }, "require": { @@ -3463,20 +3416,20 @@ "ZF1", "framework" ], - "time": "2019-11-26T15:09:40+00:00" + "time": "2020-05-19T23:25:07+00:00" }, { "name": "monolog/monolog", - "version": "1.25.3", + "version": "1.25.4", "source": { "type": "git", "url": "https://github.com/Seldaek/monolog.git", - "reference": "fa82921994db851a8becaf3787a9e73c5976b6f1" + "reference": "3022efff205e2448b560c833c6fbbf91c3139168" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/Seldaek/monolog/zipball/fa82921994db851a8becaf3787a9e73c5976b6f1", - "reference": "fa82921994db851a8becaf3787a9e73c5976b6f1", + "url": "https://api.github.com/repos/Seldaek/monolog/zipball/3022efff205e2448b560c833c6fbbf91c3139168", + "reference": "3022efff205e2448b560c833c6fbbf91c3139168", "shasum": "" }, "require": { @@ -3490,11 +3443,10 @@ "aws/aws-sdk-php": "^2.4.9 || ^3.0", "doctrine/couchdb": "~1.0@dev", "graylog2/gelf-php": "~1.0", - "jakub-onderka/php-parallel-lint": "0.9", "php-amqplib/php-amqplib": "~2.4", "php-console/php-console": "^3.1.3", + "php-parallel-lint/php-parallel-lint": "^1.0", "phpunit/phpunit": "~4.5", - "phpunit/phpunit-mock-objects": "2.3.0", "ruflin/elastica": ">=0.90 <3.0", "sentry/sentry": "^0.13", "swiftmailer/swiftmailer": "^5.3|^6.0" @@ -3541,7 +3493,7 @@ "logging", "psr-3" ], - "time": "2019-12-20T14:15:16+00:00" + "time": "2020-05-22T07:31:27+00:00" }, { "name": "paragonie/random_compat", @@ -4228,23 +4180,23 @@ }, { "name": "react/promise", - "version": "v2.7.1", + "version": "v2.8.0", "source": { "type": "git", "url": "https://github.com/reactphp/promise.git", - "reference": "31ffa96f8d2ed0341a57848cbb84d88b89dd664d" + "reference": "f3cff96a19736714524ca0dd1d4130de73dbbbc4" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/reactphp/promise/zipball/31ffa96f8d2ed0341a57848cbb84d88b89dd664d", - "reference": "31ffa96f8d2ed0341a57848cbb84d88b89dd664d", + "url": "https://api.github.com/repos/reactphp/promise/zipball/f3cff96a19736714524ca0dd1d4130de73dbbbc4", + "reference": "f3cff96a19736714524ca0dd1d4130de73dbbbc4", "shasum": "" }, "require": { "php": ">=5.4.0" }, "require-dev": { - "phpunit/phpunit": "~4.8" + "phpunit/phpunit": "^7.0 || ^6.5 || ^5.7 || ^4.8.36" }, "type": "library", "autoload": { @@ -4270,7 +4222,7 @@ "promise", "promises" ], - "time": "2019-01-07T21:25:54+00:00" + "time": "2020-05-12T15:16:56+00:00" }, { "name": "seld/jsonlint", @@ -4723,16 +4675,16 @@ }, { "name": "symfony/polyfill-ctype", - "version": "v1.15.0", + "version": "v1.17.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-ctype.git", - "reference": "4719fa9c18b0464d399f1a63bf624b42b6fa8d14" + "reference": "e94c8b1bbe2bc77507a1056cdb06451c75b427f9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/4719fa9c18b0464d399f1a63bf624b42b6fa8d14", - "reference": "4719fa9c18b0464d399f1a63bf624b42b6fa8d14", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/e94c8b1bbe2bc77507a1056cdb06451c75b427f9", + "reference": "e94c8b1bbe2bc77507a1056cdb06451c75b427f9", "shasum": "" }, "require": { @@ -4744,7 +4696,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.15-dev" + "dev-master": "1.17-dev" } }, "autoload": { @@ -4777,20 +4729,20 @@ "polyfill", "portable" ], - "time": "2020-02-27T09:26:54+00:00" + "time": "2020-05-12T16:14:59+00:00" }, { "name": "symfony/polyfill-intl-idn", - "version": "v1.15.0", + "version": "v1.17.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-intl-idn.git", - "reference": "47bd6aa45beb1cd7c6a16b7d1810133b728bdfcf" + "reference": "3bff59ea7047e925be6b7f2059d60af31bb46d6a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-intl-idn/zipball/47bd6aa45beb1cd7c6a16b7d1810133b728bdfcf", - "reference": "47bd6aa45beb1cd7c6a16b7d1810133b728bdfcf", + "url": "https://api.github.com/repos/symfony/polyfill-intl-idn/zipball/3bff59ea7047e925be6b7f2059d60af31bb46d6a", + "reference": "3bff59ea7047e925be6b7f2059d60af31bb46d6a", "shasum": "" }, "require": { @@ -4804,7 +4756,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.15-dev" + "dev-master": "1.17-dev" } }, "autoload": { @@ -4839,20 +4791,20 @@ "portable", "shim" ], - "time": "2020-03-09T19:04:49+00:00" + "time": "2020-05-12T16:47:27+00:00" }, { "name": "symfony/polyfill-mbstring", - "version": "v1.15.0", + "version": "v1.17.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-mbstring.git", - "reference": "81ffd3a9c6d707be22e3012b827de1c9775fc5ac" + "reference": "fa79b11539418b02fc5e1897267673ba2c19419c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/81ffd3a9c6d707be22e3012b827de1c9775fc5ac", - "reference": "81ffd3a9c6d707be22e3012b827de1c9775fc5ac", + "url": "https://api.github.com/repos/symfony/polyfill-mbstring/zipball/fa79b11539418b02fc5e1897267673ba2c19419c", + "reference": "fa79b11539418b02fc5e1897267673ba2c19419c", "shasum": "" }, "require": { @@ -4864,7 +4816,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.15-dev" + "dev-master": "1.17-dev" } }, "autoload": { @@ -4898,20 +4850,20 @@ "portable", "shim" ], - "time": "2020-03-09T19:04:49+00:00" + "time": "2020-05-12T16:47:27+00:00" }, { "name": "symfony/polyfill-php72", - "version": "v1.15.0", + "version": "v1.17.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php72.git", - "reference": "37b0976c78b94856543260ce09b460a7bc852747" + "reference": "f048e612a3905f34931127360bdd2def19a5e582" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/37b0976c78b94856543260ce09b460a7bc852747", - "reference": "37b0976c78b94856543260ce09b460a7bc852747", + "url": "https://api.github.com/repos/symfony/polyfill-php72/zipball/f048e612a3905f34931127360bdd2def19a5e582", + "reference": "f048e612a3905f34931127360bdd2def19a5e582", "shasum": "" }, "require": { @@ -4920,7 +4872,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.15-dev" + "dev-master": "1.17-dev" } }, "autoload": { @@ -4953,20 +4905,20 @@ "portable", "shim" ], - "time": "2020-02-27T09:26:54+00:00" + "time": "2020-05-12T16:47:27+00:00" }, { "name": "symfony/polyfill-php73", - "version": "v1.15.0", + "version": "v1.17.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php73.git", - "reference": "0f27e9f464ea3da33cbe7ca3bdf4eb66def9d0f7" + "reference": "a760d8964ff79ab9bf057613a5808284ec852ccc" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php73/zipball/0f27e9f464ea3da33cbe7ca3bdf4eb66def9d0f7", - "reference": "0f27e9f464ea3da33cbe7ca3bdf4eb66def9d0f7", + "url": "https://api.github.com/repos/symfony/polyfill-php73/zipball/a760d8964ff79ab9bf057613a5808284ec852ccc", + "reference": "a760d8964ff79ab9bf057613a5808284ec852ccc", "shasum": "" }, "require": { @@ -4975,7 +4927,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.15-dev" + "dev-master": "1.17-dev" } }, "autoload": { @@ -5011,7 +4963,7 @@ "portable", "shim" ], - "time": "2020-02-27T09:26:54+00:00" + "time": "2020-05-12T16:47:27+00:00" }, { "name": "symfony/process", @@ -5536,16 +5488,16 @@ }, { "name": "aws/aws-sdk-php", - "version": "3.137.5", + "version": "3.138.6", "source": { "type": "git", "url": "https://github.com/aws/aws-sdk-php.git", - "reference": "b3309075ec2a2c695c33d8e21c07b3d5c10cdb9a" + "reference": "e4672392e63e91085cde5f1fbcbf5883a69b26a0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/b3309075ec2a2c695c33d8e21c07b3d5c10cdb9a", - "reference": "b3309075ec2a2c695c33d8e21c07b3d5c10cdb9a", + "url": "https://api.github.com/repos/aws/aws-sdk-php/zipball/e4672392e63e91085cde5f1fbcbf5883a69b26a0", + "reference": "e4672392e63e91085cde5f1fbcbf5883a69b26a0", "shasum": "" }, "require": { @@ -5616,7 +5568,7 @@ "s3", "sdk" ], - "time": "2020-05-07T18:16:43+00:00" + "time": "2020-05-21T18:14:47+00:00" }, { "name": "behat/gherkin", @@ -6879,16 +6831,16 @@ }, { "name": "league/flysystem", - "version": "1.0.67", + "version": "1.0.69", "source": { "type": "git", "url": "https://github.com/thephpleague/flysystem.git", - "reference": "5b1f36c75c4bdde981294c2a0ebdb437ee6f275e" + "reference": "7106f78428a344bc4f643c233a94e48795f10967" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/5b1f36c75c4bdde981294c2a0ebdb437ee6f275e", - "reference": "5b1f36c75c4bdde981294c2a0ebdb437ee6f275e", + "url": "https://api.github.com/repos/thephpleague/flysystem/zipball/7106f78428a344bc4f643c233a94e48795f10967", + "reference": "7106f78428a344bc4f643c233a94e48795f10967", "shasum": "" }, "require": { @@ -6959,7 +6911,7 @@ "sftp", "storage" ], - "time": "2020-04-16T13:21:26+00:00" + "time": "2020-05-18T15:13:39+00:00" }, { "name": "lusitanian/oauth", @@ -8413,16 +8365,16 @@ }, { "name": "phpunit/phpunit", - "version": "9.1.4", + "version": "9.1.5", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/phpunit.git", - "reference": "2d7080c622cf7884992e7c3cf87853877bae8ff4" + "reference": "1b570cd7edbe136055bf5f651857dc8af6b829d2" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/2d7080c622cf7884992e7c3cf87853877bae8ff4", - "reference": "2d7080c622cf7884992e7c3cf87853877bae8ff4", + "url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/1b570cd7edbe136055bf5f651857dc8af6b829d2", + "reference": "1b570cd7edbe136055bf5f651857dc8af6b829d2", "shasum": "" }, "require": { @@ -8497,7 +8449,7 @@ "testing", "xunit" ], - "time": "2020-04-30T06:32:53+00:00" + "time": "2020-05-22T13:54:05+00:00" }, { "name": "psr/cache", @@ -8750,16 +8702,16 @@ }, { "name": "sebastian/diff", - "version": "4.0.0", + "version": "4.0.1", "source": { "type": "git", "url": "https://github.com/sebastianbergmann/diff.git", - "reference": "c0c26c9188b538bfa985ae10c9f05d278f12060d" + "reference": "3e523c576f29dacecff309f35e4cc5a5c168e78a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/c0c26c9188b538bfa985ae10c9f05d278f12060d", - "reference": "c0c26c9188b538bfa985ae10c9f05d278f12060d", + "url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/3e523c576f29dacecff309f35e4cc5a5c168e78a", + "reference": "3e523c576f29dacecff309f35e4cc5a5c168e78a", "shasum": "" }, "require": { @@ -8767,7 +8719,7 @@ }, "require-dev": { "phpunit/phpunit": "^9.0", - "symfony/process": "^4 || ^5" + "symfony/process": "^4.2 || ^5" }, "type": "library", "extra": { @@ -8802,7 +8754,7 @@ "unidiff", "unified diff" ], - "time": "2020-02-07T06:09:38+00:00" + "time": "2020-05-08T05:01:12+00:00" }, { "name": "sebastian/environment", @@ -9715,16 +9667,16 @@ }, { "name": "symfony/polyfill-php70", - "version": "v1.15.0", + "version": "v1.17.0", "source": { "type": "git", "url": "https://github.com/symfony/polyfill-php70.git", - "reference": "2a18e37a489803559284416df58c71ccebe50bf0" + "reference": "82225c2d7d23d7e70515496d249c0152679b468e" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/polyfill-php70/zipball/2a18e37a489803559284416df58c71ccebe50bf0", - "reference": "2a18e37a489803559284416df58c71ccebe50bf0", + "url": "https://api.github.com/repos/symfony/polyfill-php70/zipball/82225c2d7d23d7e70515496d249c0152679b468e", + "reference": "82225c2d7d23d7e70515496d249c0152679b468e", "shasum": "" }, "require": { @@ -9734,7 +9686,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "1.15-dev" + "dev-master": "1.17-dev" } }, "autoload": { @@ -9770,7 +9722,7 @@ "portable", "shim" ], - "time": "2020-02-27T09:26:54+00:00" + "time": "2020-05-12T16:47:27+00:00" }, { "name": "symfony/stopwatch", diff --git a/dev/tests/api-functional/_files/Magento/TestModuleBraintree/Model/Adapter/BraintreeAdapter.php b/dev/tests/api-functional/_files/Magento/TestModuleBraintree/Model/Adapter/BraintreeAdapter.php deleted file mode 100644 index 58932e7e8ea87..0000000000000 --- a/dev/tests/api-functional/_files/Magento/TestModuleBraintree/Model/Adapter/BraintreeAdapter.php +++ /dev/null @@ -1,75 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\TestModuleBraintree\Model\Adapter; - -use Braintree\ClientToken; -use Braintree\Configuration; -use Braintree\CreditCard; -use Braintree\Transaction; -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Model\Adminhtml\Source\Environment; -use Magento\TestModuleBraintree\Model\MockResponseDataProvider; - -/** - * Class BraintreeAdapter mock for testing - * Use \Magento\TestModuleBraintree\Model\Adapter\BraintreeAdapterFactory to create new instance of adapter. - * @codeCoverageIgnore - */ -class BraintreeAdapter extends \Magento\Braintree\Model\Adapter\BraintreeAdapter -{ - /** - * @var MockResponseDataProvider - */ - private $mockResponseDataProvider; - - /** - * @param string $merchantId - * @param string $publicKey - * @param string $privateKey - * @param string $environment - * @param MockResponseDataProvider $mockResponseDataProvider - */ - public function __construct( - $merchantId, - $publicKey, - $privateKey, - $environment, - MockResponseDataProvider $mockResponseDataProvider - ) { - parent::__construct($merchantId, $publicKey, $privateKey, $environment); - $this->mockResponseDataProvider = $mockResponseDataProvider; - } - - /** - * @param string $token - * @return \Braintree\Result\Successful|\Braintree\Result\Error - */ - public function createNonce($token) - { - return $this->mockResponseDataProvider->generateMockNonceResponse($token); - } - - /** - * @param array $attributes - * @return \Braintree\Result\Successful|\Braintree\Result\Error - */ - public function sale(array $attributes) - { - return $this->mockResponseDataProvider->generateMockSaleResponse($attributes); - } - - /** - * @param array $params - * @return string|\Braintree\Result\Error - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public function generate(array $params = []) - { - return $this->mockResponseDataProvider->generateMockClientToken(); - } -} diff --git a/dev/tests/api-functional/_files/Magento/TestModuleBraintree/Model/MockResponseDataProvider.php b/dev/tests/api-functional/_files/Magento/TestModuleBraintree/Model/MockResponseDataProvider.php deleted file mode 100644 index ab86109c6f914..0000000000000 --- a/dev/tests/api-functional/_files/Magento/TestModuleBraintree/Model/MockResponseDataProvider.php +++ /dev/null @@ -1,161 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\TestModuleBraintree\Model; - -use Magento\Framework\Math\Random; - -/** - * Provide mock responses for Braintree adapter - */ -class MockResponseDataProvider -{ - /** - * @var Random - */ - private $random; - - /** - * @param Random $random - */ - public function __construct( - Random $random - ) { - $this->random = $random; - } - - /** - * Create mock sale response for testing - * - * @param array $attributes - * @return \Braintree\Result\Error|\Braintree\Result\Successful - */ - public function generateMockSaleResponse(array $attributes) - { - if (empty($attributes['paymentMethodNonce'])) { - return new \Braintree\Result\Error( - [ - 'errors' => [ - [ - 'errorData' => [ - 'code' => 2019, - 'message' => 'Your transaction has been declined.' - ] - ] - ], - 'transaction' => $this->createTransaction($attributes)->jsonSerialize(), - ] - ); - } - - $transaction = $this->createTransaction($attributes); - - return new \Braintree\Result\Successful([$transaction]); - } - - /** - * Create mock nonce response for testing - * - * @param string $token - * @return \Braintree\Instance - */ - public function generateMockNonceResponse(string $token): \Braintree\Instance - { - $nonce = $this->createNonce($token); - - return new \Braintree\Result\Successful($nonce, 'paymentMethodNonce'); - } - - /** - * Create mock client token - * - * @return string - */ - public function generateMockClientToken(): string - { - return $this->random->getRandomString(32); - } - - /** - * Create Braintree transaction from provided request attributes - * - * @param array $attributes - * @return \Braintree\Transaction - * @throws \Magento\Framework\Exception\LocalizedException - */ - private function createTransaction(array $attributes): \Braintree\Transaction - { - $creditCardInfo = $this->generateCardDetails(); - return \Braintree\Transaction::factory( - [ - 'amount' => $attributes['amount'], - 'billing' => $attributes['billing'] ?? null, - 'creditCard' => $creditCardInfo, - 'cardDetails' => new \Braintree\Transaction\CreditCardDetails($creditCardInfo), - 'currencyIsoCode' => 'USD', - 'customer' => $attributes['customer'], - 'cvvResponseCode' => 'M', - 'id' => $this->random->getRandomString(8), - 'options' => $attributes['options'] ?? null, - 'shipping' => $attributes['shipping'] ?? null, - 'paymentMethodNonce' => $attributes['paymentMethodNonce'], - 'status' => 'authorized', - 'type' => 'sale', - ] - ); - } - - /** - * Generate fake Braintree card details - * - * @return array - * @throws \Magento\Framework\Exception\LocalizedException - */ - private function generateCardDetails(): array - { - return [ - 'bin' => $this->random->getRandomString(6), - 'cardType' => 'Visa', - 'expirationMonth' => '12', - 'expirationYear' => '2020', //TODO: make dynamic - 'last4' => (string) random_int(1000, 9999), - 'token' => $this->random->getRandomString(6), - 'uniqueNumberIdentifier' => $this->random->getRandomString(32), - ]; - } - - /** - * Create fake Braintree nonce - * - * @param string $token - * @return \Braintree\PaymentMethodNonce - * @throws \Magento\Framework\Exception\LocalizedException - */ - private function createNonce(string $token): \Braintree\PaymentMethodNonce - { - $lastFour = (string) random_int(1000, 9999); - $lastTwo = substr($lastFour, -2); - return \Braintree\PaymentMethodNonce::factory( - [ - 'bin' => $token, - 'consumed' => false, - 'default' => true, - 'description' => 'ending in ' . $lastTwo, - 'details' => [ - 'bin' => $this->random->getRandomString(6), - 'cardType' => 'Visa', - 'lastFour' => $lastFour, - 'lastTwo' => $lastTwo, - ], - 'hasSubscription' => false, - 'isLocked' => false, - 'nonce' => $this->random->getRandomString(36), - 'type' => 'CreditCard' - ] - ); - } -} diff --git a/dev/tests/api-functional/_files/Magento/TestModuleBraintree/etc/di.xml b/dev/tests/api-functional/_files/Magento/TestModuleBraintree/etc/di.xml deleted file mode 100644 index db5c136840680..0000000000000 --- a/dev/tests/api-functional/_files/Magento/TestModuleBraintree/etc/di.xml +++ /dev/null @@ -1,10 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> - <preference for="Magento\Braintree\Model\Adapter\BraintreeAdapter" type="Magento\TestModuleBraintree\Model\Adapter\BraintreeAdapter" /> -</config> diff --git a/dev/tests/api-functional/_files/Magento/TestModuleBraintree/etc/module.xml b/dev/tests/api-functional/_files/Magento/TestModuleBraintree/etc/module.xml deleted file mode 100644 index 22df4e5fe7ead..0000000000000 --- a/dev/tests/api-functional/_files/Magento/TestModuleBraintree/etc/module.xml +++ /dev/null @@ -1,10 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd"> - <module name="Magento_TestModuleBraintree" /> -</config> diff --git a/dev/tests/api-functional/_files/Magento/TestModuleBraintree/registration.php b/dev/tests/api-functional/_files/Magento/TestModuleBraintree/registration.php deleted file mode 100644 index c95e68f3f48fa..0000000000000 --- a/dev/tests/api-functional/_files/Magento/TestModuleBraintree/registration.php +++ /dev/null @@ -1,11 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -use Magento\Framework\Component\ComponentRegistrar; - -$registrar = new ComponentRegistrar(); -if ($registrar->getPath(ComponentRegistrar::MODULE, 'Magento_TestModuleBraintree') === null) { - ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Magento_TestModuleBraintree', __DIR__); -} diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryAttributeRepositoryTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryAttributeRepositoryTest.php index f14fe207bfe6b..f5334c505e5c9 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryAttributeRepositoryTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/CategoryAttributeRepositoryTest.php @@ -69,7 +69,6 @@ public function testGetList() $this->assertTrue($response['total_count'] > 0); $this->assertTrue(count($response['items']) > 0); - $this->assertNotNull($response['items'][0]['default_frontend_label']); $this->assertNotNull($response['items'][0]['attribute_id']); } diff --git a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/SpecialPriceStorageTest.php b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/SpecialPriceStorageTest.php index a0bad2c69ee1f..ef374dc1873cf 100644 --- a/dev/tests/api-functional/testsuite/Magento/Catalog/Api/SpecialPriceStorageTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Catalog/Api/SpecialPriceStorageTest.php @@ -5,20 +5,28 @@ */ namespace Magento\Catalog\Api; +use Magento\Catalog\Api\Data\ProductInterface; +use Magento\Framework\Exception\CouldNotSaveException; +use Magento\Framework\Exception\InputException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Exception\StateException; +use Magento\Framework\Webapi\Rest\Request; +use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\ObjectManager; use Magento\TestFramework\TestCase\WebapiAbstract; -use Magento\Framework\Webapi\Exception as HTTPExceptionCodes; /** - * SpecialPriceStorage test. + * SpecialPriceStorage API operations test */ class SpecialPriceStorageTest extends WebapiAbstract { const SERVICE_NAME = 'catalogSpecialPriceStorageV1'; const SERVICE_VERSION = 'V1'; const SIMPLE_PRODUCT_SKU = 'simple'; + const VIRTUAL_PRODUCT_SKU = 'virtual-product'; /** - * @var \Magento\TestFramework\ObjectManager + * @var ObjectManager */ private $objectManager; @@ -27,7 +35,7 @@ class SpecialPriceStorageTest extends WebapiAbstract */ protected function setUp(): void { - $this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); + $this->objectManager = Bootstrap::getObjectManager(); } /** @@ -38,14 +46,14 @@ protected function setUp(): void public function testGet() { $specialPrice = 3057; - $productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class); + $productRepository = $this->objectManager->create(ProductRepositoryInterface::class); $product = $productRepository->get(self::SIMPLE_PRODUCT_SKU, true); $product->setData('special_price', $specialPrice); $productRepository->save($product); $serviceInfo = [ 'rest' => [ 'resourcePath' => '/V1/products/special-price-information', - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST + 'httpMethod' => Request::HTTP_METHOD_POST ], 'soap' => [ 'service' => self::SERVICE_NAME, @@ -54,7 +62,7 @@ public function testGet() ], ]; $response = $this->_webApiCall($serviceInfo, ['skus' => [self::SIMPLE_PRODUCT_SKU]]); - /** @var \Magento\Catalog\Api\Data\ProductInterface $product */ + /** @var ProductInterface $product */ $product = $productRepository->get(self::SIMPLE_PRODUCT_SKU); $this->assertNotEmpty($response); $this->assertEquals($product->getSpecialPrice(), $response[0]['price']); @@ -64,14 +72,15 @@ public function testGet() * Test update method. * * @magentoApiDataFixture Magento/Catalog/_files/product_virtual.php + * @dataProvider updateData + * @param array $data */ - public function testUpdate() + public function testUpdate(array $data) { - $sku = 'virtual-product'; $serviceInfo = [ 'rest' => [ 'resourcePath' => '/V1/products/special-price', - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST + 'httpMethod' => Request::HTTP_METHOD_POST ], 'soap' => [ 'service' => self::SERVICE_NAME, @@ -79,19 +88,11 @@ public function testUpdate() 'operation' => self::SERVICE_NAME . 'Update', ], ]; - $storeId = 0; - $newPrice = 31337; $response = $this->_webApiCall( $serviceInfo, [ 'prices' => [ - [ - 'price' => $newPrice, - 'store_id' => $storeId, - 'sku' => $sku, - 'price_from' => '2037-01-19 03:14:07', - 'price_to' => '2038-01-19 03:14:07', - ] + $data ] ] ); @@ -102,23 +103,28 @@ public function testUpdate() * Test delete method. * * @magentoApiDataFixture Magento/Catalog/_files/product_simple.php + * @dataProvider deleteData + * @param array $data + * @throws CouldNotSaveException + * @throws InputException + * @throws NoSuchEntityException + * @throws StateException */ - public function testDelete() + public function testDelete(array $data) { - $specialPrice = 3057; - /** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */ - $productRepository = $this->objectManager->create(\Magento\Catalog\Api\ProductRepositoryInterface::class); - $fromDate = '1970-01-01 00:00:01'; - $toDate = '2038-01-19 03:14:07'; - $product = $productRepository->get(self::SIMPLE_PRODUCT_SKU, true); - $product->setData('special_price', $specialPrice) - ->setData('special_from_date', $fromDate) - ->setData('special_to_date', $toDate); + /** @var ProductRepositoryInterface $productRepository */ + $productRepository = $this->objectManager->create(ProductRepositoryInterface::class); + $product = $productRepository->get($data['sku'], true); + $product->setData('special_price', $data['price']); + $product->setData('special_from_date', $data['price_from']); + if ($data['price_to']) { + $product->setData('special_to_date', $data['price_to']); + } $productRepository->save($product); $serviceInfo = [ 'rest' => [ 'resourcePath' => '/V1/products/special-price-delete', - 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST + 'httpMethod' => Request::HTTP_METHOD_POST ], 'soap' => [ 'service' => self::SERVICE_NAME, @@ -130,19 +136,80 @@ public function testDelete() $serviceInfo, [ 'prices' => [ - [ - 'price' => $specialPrice, - 'store_id' => 0, - 'sku' => self::SIMPLE_PRODUCT_SKU, - 'price_from' => $fromDate, - 'price_to' => $toDate, - ] + $data ] ] ); - /** @var \Magento\Catalog\Api\Data\ProductInterface $product */ - $product = $productRepository->get(self::SIMPLE_PRODUCT_SKU, false, null, true); + $product = $productRepository->get($data['sku'], false, null, true); $this->assertEmpty($response); $this->assertNull($product->getSpecialPrice()); } + + /** + * Data provider for testUpdate + * + * @return array + */ + public function updateData(): array + { + $fromDate = '2037-01-19 03:14:07'; + $toDate = '2038-01-19 03:14:07'; + + return [ + [ + // data set with 'price_to' specified + [ + 'price' => 31337, + 'store_id' => 0, + 'sku' => self::VIRTUAL_PRODUCT_SKU, + 'price_from' => $fromDate, + 'price_to' => $toDate + ] + ], + [ + // data set without 'price_to' specified + [ + 'price' => 31337, + 'store_id' => 0, + 'sku' => self::VIRTUAL_PRODUCT_SKU, + 'price_from' => $fromDate, + 'price_to' => false + ] + ], + ]; + } + + /** + * Data provider for testDelete + * + * @return array + */ + public function deleteData(): array + { + $fromDate = '1970-01-01 00:00:01'; + $toDate = '2038-01-19 03:14:07'; + + return [ + [ + // data set with 'price_to' specified + [ + 'price' => 3057, + 'store_id' => 0, + 'sku' => self::SIMPLE_PRODUCT_SKU, + 'price_from' => $fromDate, + 'price_to' => $toDate + ] + ], + [ + // data set without 'price_to' specified + [ + 'price' => 3057, + 'store_id' => 0, + 'sku' => self::SIMPLE_PRODUCT_SKU, + 'price_from' => $fromDate, + 'price_to' => false + ] + ], + ]; + } } diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/CreateBraintreeClientTokenTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/CreateBraintreeClientTokenTest.php deleted file mode 100644 index a60afde1f067e..0000000000000 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/CreateBraintreeClientTokenTest.php +++ /dev/null @@ -1,55 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\GraphQl\Braintree; - -use Magento\TestFramework\TestCase\GraphQlAbstract; - -/** - * Test creating Braintree client token mutation - */ -class CreateBraintreeClientTokenTest extends GraphQlAbstract -{ - /** - * Test creating Braintree client token - * - * @magentoConfigFixture default_store payment/braintree/active 1 - * @magentoConfigFixture default_store payment/braintree/environment sandbox - * @magentoConfigFixture default_store payment/braintree/merchant_id def_merchant_id - * @magentoConfigFixture default_store payment/braintree/merchant_account_id def_merchant_id - * @magentoConfigFixture default_store payment/braintree/public_key def_public_key - * @magentoConfigFixture default_store payment/braintree/private_key def_private_key - */ - public function testCreateBraintreeClientToken() - { - $response = $this->graphQlMutation($this->getMutation()); - - self::assertArrayHasKey('createBraintreeClientToken', $response); - self::assertNotEmpty($response['createBraintreeClientToken']); - } - - /** - * Test creating Braintree client token when method is disabled - * - */ - public function testCreateBraintreeClientTokenNotActive() - { - $this->expectException(\Exception::class); - $this->expectExceptionMessage('payment method is not active'); - - $this->graphQlMutation($this->getMutation()); - } - - private function getMutation(): string - { - return <<<QUERY -mutation { - createBraintreeClientToken -} -QUERY; - } -} diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/Customer/SetPaymentMethodTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/Customer/SetPaymentMethodTest.php deleted file mode 100644 index 74ee7a3c77c4f..0000000000000 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/Customer/SetPaymentMethodTest.php +++ /dev/null @@ -1,482 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\GraphQl\Braintree\Customer; - -use Magento\Braintree\Gateway\Command\GetPaymentNonceCommand; -use Magento\Framework\Exception\AuthenticationException; -use Magento\Framework\Registry; -use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId; -use Magento\Integration\Api\CustomerTokenServiceInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\ResourceModel\Order\CollectionFactory; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\TestCase\GraphQlAbstract; -use Magento\Vault\Model\ResourceModel\PaymentToken; -use Magento\Vault\Model\ResourceModel\PaymentToken\CollectionFactory as TokenCollectionFactory; - -/** - * Test setting payment method and placing order with Braintree - */ -class SetPaymentMethodTest extends GraphQlAbstract -{ - /** - * @var CustomerTokenServiceInterface - */ - private $customerTokenService; - - /** - * @var GetMaskedQuoteIdByReservedOrderId - */ - private $getMaskedQuoteIdByReservedOrderId; - - /** - * @var CollectionFactory - */ - private $orderCollectionFactory; - - /** - * @var OrderRepositoryInterface - */ - private $orderRepository; - - /** - * @var Registry - */ - private $registry; - - /** - * @var TokenCollectionFactory - */ - private $tokenCollectionFactory; - - /** - * @var PaymentToken - */ - private $tokenResource; - - /** - * @var GetPaymentNonceCommand - */ - private $getNonceCommand; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $objectManager = Bootstrap::getObjectManager(); - $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); - $this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class); - $this->orderCollectionFactory = $objectManager->get(CollectionFactory::class); - $this->orderRepository = $objectManager->get(OrderRepositoryInterface::class); - $this->registry = Bootstrap::getObjectManager()->get(Registry::class); - $this->tokenCollectionFactory = Bootstrap::getObjectManager()->get(TokenCollectionFactory::class); - $this->tokenResource = Bootstrap::getObjectManager()->get(PaymentToken::class); - $this->getNonceCommand = Bootstrap::getObjectManager()->get(GetPaymentNonceCommand::class); - } - - /** - * @magentoConfigFixture default_store carriers/flatrate/active 1 - * @magentoConfigFixture default_store payment/braintree/active 1 - * @magentoConfigFixture default_store payment/braintree/environment sandbox - * @magentoConfigFixture default_store payment/braintree/merchant_id def_merchant_id - * @magentoConfigFixture default_store payment/braintree/public_key def_public_key - * @magentoConfigFixture default_store payment/braintree/private_key def_private_key - * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php - */ - public function testPlaceOrder() - { - $reservedOrderId = 'test_quote'; - $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); - - $setPaymentQuery = $this->getSetPaymentBraintreeQuery($maskedQuoteId); - $setPaymentResponse = $this->graphQlMutation($setPaymentQuery, [], '', $this->getHeaderMap()); - - $this->assertSetPaymentMethodResponse($setPaymentResponse, 'braintree'); - - $placeOrderQuery = $this->getPlaceOrderQuery($maskedQuoteId); - $placeOrderResponse = $this->graphQlMutation($placeOrderQuery, [], '', $this->getHeaderMap()); - - $this->assertPlaceOrderResponse($placeOrderResponse, $reservedOrderId); - - $tokenQueryResult = $this->graphQlQuery($this->getPaymentTokenQuery(), [], '', $this->getHeaderMap()); - - self::assertArrayHasKey('customerPaymentTokens', $tokenQueryResult); - self::assertArrayHasKey('items', $tokenQueryResult['customerPaymentTokens']); - self::assertCount(0, $tokenQueryResult['customerPaymentTokens']['items']); - } - - /** - * @magentoConfigFixture default_store carriers/flatrate/active 1 - * @magentoConfigFixture default_store payment/braintree/active 1 - * @magentoConfigFixture default_store payment/braintree_cc_vault/active 1 - * @magentoConfigFixture default_store payment/braintree/environment sandbox - * @magentoConfigFixture default_store payment/braintree/merchant_id def_merchant_id - * @magentoConfigFixture default_store payment/braintree/public_key def_public_key - * @magentoConfigFixture default_store payment/braintree/private_key def_private_key - * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php - */ - public function testPlaceOrderSaveInVault() - { - $reservedOrderId = 'test_quote'; - $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); - - $setPaymentQuery = $this->getSetPaymentBraintreeQuery($maskedQuoteId, true); - $setPaymentResponse = $this->graphQlMutation($setPaymentQuery, [], '', $this->getHeaderMap()); - - $this->assertSetPaymentMethodResponse($setPaymentResponse, 'braintree'); - - $placeOrderQuery = $this->getPlaceOrderQuery($maskedQuoteId); - $placeOrderResponse = $this->graphQlMutation($placeOrderQuery, [], '', $this->getHeaderMap()); - - $this->assertPlaceOrderResponse($placeOrderResponse, $reservedOrderId); - - $tokenQueryResult = $this->graphQlQuery($this->getPaymentTokenQuery(), [], '', $this->getHeaderMap()); - - self::assertArrayHasKey('customerPaymentTokens', $tokenQueryResult); - self::assertArrayHasKey('items', $tokenQueryResult['customerPaymentTokens']); - self::assertCount(1, $tokenQueryResult['customerPaymentTokens']['items']); - $token = current($tokenQueryResult['customerPaymentTokens']['items']); - self::assertArrayHasKey('payment_method_code', $token); - self::assertEquals('braintree', $token['payment_method_code']); - self::assertArrayHasKey('type', $token); - self::assertEquals('card', $token['type']); - self::assertArrayHasKey('details', $token); - self::assertArrayHasKey('public_hash', $token); - } - - /** - * @magentoConfigFixture default_store carriers/flatrate/active 1 - * @magentoConfigFixture default_store payment/braintree/active 1 - * @magentoConfigFixture default_store payment/braintree_cc_vault/active 1 - * @magentoConfigFixture default_store payment/braintree/environment sandbox - * @magentoConfigFixture default_store payment/braintree/merchant_id def_merchant_id - * @magentoConfigFixture default_store payment/braintree/public_key def_public_key - * @magentoConfigFixture default_store payment/braintree/private_key def_private_key - * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php - * @magentoApiDataFixture Magento/GraphQl/Braintree/_files/token.php - */ - public function testPlaceOrderWithVault() - { - $reservedOrderId = 'test_quote'; - $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); - - $setPaymentQuery = $this->getSetPaymentBraintreeVaultQuery( - $maskedQuoteId, - 'braintree_public_hash' - ); - $setPaymentResponse = $this->graphQlMutation($setPaymentQuery, [], '', $this->getHeaderMap()); - - $this->assertSetPaymentMethodResponse($setPaymentResponse, 'braintree_cc_vault'); - - $placeOrderQuery = $this->getPlaceOrderQuery($maskedQuoteId); - $placeOrderResponse = $this->graphQlMutation($placeOrderQuery, [], '', $this->getHeaderMap()); - - $this->assertPlaceOrderResponse($placeOrderResponse, $reservedOrderId); - } - - /** - * @magentoConfigFixture default_store carriers/flatrate/active 1 - * @magentoConfigFixture default_store payment/braintree/active 1 - * @magentoConfigFixture default_store payment/braintree_cc_vault/active 1 - * @magentoConfigFixture default_store payment/braintree/environment sandbox - * @magentoConfigFixture default_store payment/braintree/merchant_id def_merchant_id - * @magentoConfigFixture default_store payment/braintree/public_key def_public_key - * @magentoConfigFixture default_store payment/braintree/private_key def_private_key - * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php - * @dataProvider dataProviderTestSetPaymentMethodInvalidInput - * @param string $methodCode - */ - public function testSetPaymentMethodInvalidInput(string $methodCode) - { - $this->expectException(\Exception::class); - - $reservedOrderId = 'test_quote'; - $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); - - $setPaymentQuery = $this->getSetPaymentBraintreeQueryInvalidInput( - $maskedQuoteId, - $methodCode - ); - $this->expectExceptionMessage("Required parameter \"$methodCode\" for \"payment_method\" is missing."); - $this->graphQlMutation($setPaymentQuery, [], '', $this->getHeaderMap()); - } - - /** - * @magentoConfigFixture default_store carriers/flatrate/active 1 - * @magentoConfigFixture default_store payment/braintree/active 1 - * @magentoConfigFixture default_store payment/braintree_cc_vault/active 1 - * @magentoConfigFixture default_store payment/braintree/environment sandbox - * @magentoConfigFixture default_store payment/braintree/merchant_id def_merchant_id - * @magentoConfigFixture default_store payment/braintree/public_key def_public_key - * @magentoConfigFixture default_store payment/braintree/private_key def_private_key - * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/customer/create_empty_cart.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php - * @dataProvider dataProviderTestSetPaymentMethodInvalidInput - * @param string $methodCode - */ - public function testSetPaymentMethodInvalidMethodInput(string $methodCode) - { - $this->expectException(\Exception::class); - - $reservedOrderId = 'test_quote'; - $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); - - $setPaymentQuery = $this->getSetPaymentBraintreeQueryInvalidMethodInput( - $maskedQuoteId, - $methodCode - ); - $this->expectExceptionMessage("for \"$methodCode\" is missing."); - $expectedExceptionMessages = [ - 'braintree' => - 'Field BraintreeInput.is_active_payment_token_enabler of required type Boolean! was not provided.', - 'braintree_cc_vault' => - 'Field BraintreeCcVaultInput.public_hash of required type String! was not provided.' - ]; - - $this->expectExceptionMessage($expectedExceptionMessages[$methodCode]); - $this->graphQlMutation($setPaymentQuery, [], '', $this->getHeaderMap()); - } - - public function dataProviderTestSetPaymentMethodInvalidInput(): array - { - return [ - ['braintree'], - ['braintree_cc_vault'], - ]; - } - - private function assertPlaceOrderResponse(array $response, string $reservedOrderId): void - { - self::assertArrayHasKey('placeOrder', $response); - self::assertArrayHasKey('order', $response['placeOrder']); - self::assertArrayHasKey('order_number', $response['placeOrder']['order']); - self::assertEquals($reservedOrderId, $response['placeOrder']['order']['order_number']); - } - - private function assertSetPaymentMethodResponse(array $response, string $methodCode): void - { - self::assertArrayHasKey('setPaymentMethodOnCart', $response); - self::assertArrayHasKey('cart', $response['setPaymentMethodOnCart']); - self::assertArrayHasKey('selected_payment_method', $response['setPaymentMethodOnCart']['cart']); - self::assertArrayHasKey('code', $response['setPaymentMethodOnCart']['cart']['selected_payment_method']); - self::assertEquals($methodCode, $response['setPaymentMethodOnCart']['cart']['selected_payment_method']['code']); - } - - /** - * @param string $maskedQuoteId - * @param bool $saveInVault - * @return string - */ - private function getSetPaymentBraintreeQuery(string $maskedQuoteId, bool $saveInVault = false): string - { - $saveInVault = json_encode($saveInVault); - return <<<QUERY -mutation { - setPaymentMethodOnCart(input:{ - cart_id:"{$maskedQuoteId}" - payment_method:{ - code:"braintree" - braintree:{ - is_active_payment_token_enabler:{$saveInVault} - payment_method_nonce:"fake-valid-nonce" - } - } - }) { - cart { - selected_payment_method { - code - } - } - } -} -QUERY; - } - - /** - * @param string $maskedQuoteId - * @param string $publicHash - * @return string - */ - private function getSetPaymentBraintreeVaultQuery( - string $maskedQuoteId, - string $publicHash - ): string { - return <<<QUERY -mutation { - setPaymentMethodOnCart(input:{ - cart_id:"{$maskedQuoteId}" - payment_method:{ - code:"braintree_cc_vault" - braintree_cc_vault:{ - public_hash:"{$publicHash}" - } - } - }) { - cart { - selected_payment_method { - code - } - } - } -} -QUERY; - } - - /** - * @param string $maskedQuoteId - * @param string $methodCode - * @return string - */ - private function getSetPaymentBraintreeQueryInvalidInput(string $maskedQuoteId, string $methodCode): string - { - return <<<QUERY -mutation { - setPaymentMethodOnCart(input:{ - cart_id:"{$maskedQuoteId}" - payment_method:{ - code:"{$methodCode}" - } - }) { - cart { - selected_payment_method { - code - } - } - } -} -QUERY; - } - - /** - * @param string $maskedQuoteId - * @param string $methodCode - * @return string - */ - private function getSetPaymentBraintreeQueryInvalidMethodInput(string $maskedQuoteId, string $methodCode): string - { - return <<<QUERY -mutation { - setPaymentMethodOnCart(input:{ - cart_id:"{$maskedQuoteId}" - payment_method:{ - code:"{$methodCode}" - {$methodCode}: {} - } - }) { - cart { - selected_payment_method { - code - } - } - } -} -QUERY; - } - - /** - * @param string $maskedQuoteId - * @return string - */ - private function getPlaceOrderQuery(string $maskedQuoteId): string - { - return <<<QUERY -mutation { - placeOrder(input: {cart_id: "{$maskedQuoteId}"}) { - order { - order_number - } - } -} -QUERY; - } - - /** - * @return string - */ - private function getPaymentTokenQuery(): string - { - return <<<QUERY -query { - customerPaymentTokens { - items { - details - payment_method_code - public_hash - type - } - } -} -QUERY; - } - - /** - * @param string $username - * @param string $password - * @return array - * @throws AuthenticationException - */ - private function getHeaderMap(string $username = 'customer@example.com', string $password = 'password'): array - { - $customerToken = $this->customerTokenService->createCustomerAccessToken($username, $password); - $headerMap = ['Authorization' => 'Bearer ' . $customerToken]; - return $headerMap; - } - - /** - * @inheritdoc - */ - protected function tearDown(): void - { - $this->registry->unregister('isSecureArea'); - $this->registry->register('isSecureArea', true); - - $orderCollection = $this->orderCollectionFactory->create(); - foreach ($orderCollection as $order) { - $this->orderRepository->delete($order); - } - - $tokenCollection = $this->tokenCollectionFactory->create(); - foreach ($tokenCollection as $token) { - $this->tokenResource->delete($token); - } - $this->registry->unregister('isSecureArea'); - $this->registry->register('isSecureArea', false); - - parent::tearDown(); - } -} diff --git a/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/Guest/SetPaymentMethodTest.php b/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/Guest/SetPaymentMethodTest.php deleted file mode 100644 index f217e63c9b61c..0000000000000 --- a/dev/tests/api-functional/testsuite/Magento/GraphQl/Braintree/Guest/SetPaymentMethodTest.php +++ /dev/null @@ -1,236 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\GraphQl\Braintree\Guest; - -use Magento\Framework\Registry; -use Magento\GraphQl\Quote\GetMaskedQuoteIdByReservedOrderId; -use Magento\Integration\Api\CustomerTokenServiceInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\ResourceModel\Order\CollectionFactory; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\TestCase\GraphQlAbstract; - -/** - * Test setting payment method and placing order with Braintree - */ -class SetPaymentMethodTest extends GraphQlAbstract -{ - /** - * @var CustomerTokenServiceInterface - */ - private $customerTokenService; - - /** - * @var GetMaskedQuoteIdByReservedOrderId - */ - private $getMaskedQuoteIdByReservedOrderId; - - /** - * @var CollectionFactory - */ - private $orderCollectionFactory; - - /** - * @var OrderRepositoryInterface - */ - private $orderRepository; - - /** - * @var Registry - */ - private $registry; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $objectManager = Bootstrap::getObjectManager(); - $this->getMaskedQuoteIdByReservedOrderId = $objectManager->get(GetMaskedQuoteIdByReservedOrderId::class); - $this->customerTokenService = $objectManager->get(CustomerTokenServiceInterface::class); - $this->orderCollectionFactory = $objectManager->get(CollectionFactory::class); - $this->orderRepository = $objectManager->get(OrderRepositoryInterface::class); - $this->registry = Bootstrap::getObjectManager()->get(Registry::class); - } - - /** - * @magentoConfigFixture default_store carriers/flatrate/active 1 - * @magentoConfigFixture default_store payment/braintree/active 1 - * @magentoConfigFixture default_store payment/braintree/environment sandbox - * @magentoConfigFixture default_store payment/braintree/merchant_id def_merchant_id - * @magentoConfigFixture default_store payment/braintree/public_key def_public_key - * @magentoConfigFixture default_store payment/braintree/private_key def_private_key - * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/set_guest_email.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php - * @dataProvider dataProviderTestPlaceOrder - */ - public function testPlaceOrder(string $nonce) - { - $reservedOrderId = 'test_quote'; - $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); - - $setPaymentQuery = $this->getSetPaymentBraintreeQuery($maskedQuoteId, $nonce); - $setPaymentResponse = $this->graphQlMutation($setPaymentQuery); - - $this->assertSetPaymentMethodResponse($setPaymentResponse, 'braintree'); - - $placeOrderQuery = $this->getPlaceOrderQuery($maskedQuoteId); - $placeOrderResponse = $this->graphQlMutation($placeOrderQuery); - - $this->assertPlaceOrderResponse($placeOrderResponse, $reservedOrderId); - } - - /** - * Data provider for testPlaceOrder - * - * @return array - */ - public function dataProviderTestPlaceOrder(): array - { - return [ - ['fake-valid-nonce'], - ['fake-apple-pay-visa-nonce'], - ]; - } - - /** - * @magentoConfigFixture default_store carriers/flatrate/active 1 - * @magentoConfigFixture default_store payment/braintree/active 1 - * @magentoConfigFixture default_store payment/braintree/environment sandbox - * @magentoConfigFixture default_store payment/braintree/merchant_id def_merchant_id - * @magentoConfigFixture default_store payment/braintree/public_key def_public_key - * @magentoConfigFixture default_store payment/braintree/private_key def_private_key - * @magentoApiDataFixture Magento/GraphQl/Catalog/_files/simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/create_empty_cart.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/guest/set_guest_email.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/add_simple_product.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_shipping_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_new_billing_address.php - * @magentoApiDataFixture Magento/GraphQl/Quote/_files/set_flatrate_shipping_method.php - */ - public function testSetPaymentMethodInvalidInput() - { - $this->expectException(\Exception::class); - - $reservedOrderId = 'test_quote'; - $maskedQuoteId = $this->getMaskedQuoteIdByReservedOrderId->execute($reservedOrderId); - - $setPaymentQuery = $this->getSetPaymentBraintreeQueryInvalidInput($maskedQuoteId); - $this->expectExceptionMessage("Required parameter \"braintree\" for \"payment_method\" is missing."); - $this->graphQlMutation($setPaymentQuery); - } - - private function assertPlaceOrderResponse(array $response, string $reservedOrderId): void - { - self::assertArrayHasKey('placeOrder', $response); - self::assertArrayHasKey('order', $response['placeOrder']); - self::assertArrayHasKey('order_number', $response['placeOrder']['order']); - self::assertEquals($reservedOrderId, $response['placeOrder']['order']['order_number']); - } - - private function assertSetPaymentMethodResponse(array $response, string $methodCode): void - { - self::assertArrayHasKey('setPaymentMethodOnCart', $response); - self::assertArrayHasKey('cart', $response['setPaymentMethodOnCart']); - self::assertArrayHasKey('selected_payment_method', $response['setPaymentMethodOnCart']['cart']); - self::assertArrayHasKey('code', $response['setPaymentMethodOnCart']['cart']['selected_payment_method']); - self::assertEquals($methodCode, $response['setPaymentMethodOnCart']['cart']['selected_payment_method']['code']); - } - - /** - * @param string $maskedQuoteId - * @return string - */ - private function getSetPaymentBraintreeQuery(string $maskedQuoteId, string $nonce): string - { - return <<<QUERY -mutation { - setPaymentMethodOnCart(input:{ - cart_id:"{$maskedQuoteId}" - payment_method:{ - code:"braintree" - braintree:{ - is_active_payment_token_enabler:false - payment_method_nonce:"{$nonce}" - } - } - }) { - cart { - selected_payment_method { - code - } - } - } -} -QUERY; - } - - /** - * @param string $maskedQuoteId - * @return string - */ - private function getSetPaymentBraintreeQueryInvalidInput(string $maskedQuoteId): string - { - return <<<QUERY -mutation { - setPaymentMethodOnCart(input:{ - cart_id:"{$maskedQuoteId}" - payment_method:{ - code:"braintree" - } - }) { - cart { - selected_payment_method { - code - } - } - } -} -QUERY; - } - - /** - * @param string $maskedQuoteId - * @return string - */ - private function getPlaceOrderQuery(string $maskedQuoteId): string - { - return <<<QUERY -mutation { - placeOrder(input: {cart_id: "{$maskedQuoteId}"}) { - order { - order_number - } - } -} -QUERY; - } - - /** - * @inheritdoc - */ - protected function tearDown(): void - { - $this->registry->unregister('isSecureArea'); - $this->registry->register('isSecureArea', true); - - $orderCollection = $this->orderCollectionFactory->create(); - foreach ($orderCollection as $order) { - $this->orderRepository->delete($order); - } - $this->registry->unregister('isSecureArea'); - $this->registry->register('isSecureArea', false); - - parent::tearDown(); - } -} diff --git a/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php b/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php index a392520928183..c75b2a2cacfda 100644 --- a/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php +++ b/dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTest.php @@ -49,6 +49,7 @@ class AdminTokenServiceTest extends WebapiAbstract */ protected function setUp(): void { + $this->markTestSkipped('Skipped until MC-34201 is addressed'); $this->_markTestAsRestOnly(); $this->tokenService = Bootstrap::getObjectManager()->get(\Magento\Integration\Model\AdminTokenService::class); $this->tokenModel = Bootstrap::getObjectManager()->get(\Magento\Integration\Model\Oauth\Token::class); diff --git a/dev/tests/api-functional/testsuite/Magento/LoginAsCustomerWebapi/Api/LoginAsCustomerWebapiCreateCustomerAccessTokenTest.php b/dev/tests/api-functional/testsuite/Magento/LoginAsCustomerWebapi/Api/LoginAsCustomerWebapiCreateCustomerAccessTokenTest.php deleted file mode 100644 index 3c64d24d813a3..0000000000000 --- a/dev/tests/api-functional/testsuite/Magento/LoginAsCustomerWebapi/Api/LoginAsCustomerWebapiCreateCustomerAccessTokenTest.php +++ /dev/null @@ -1,141 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\LoginAsCustomerWebapi\Api; - -use Magento\Framework\Webapi\Rest\Request; -use Magento\Integration\Model\Oauth\Token as TokenModel; -use Magento\Integration\Model\ResourceModel\Oauth\Token\Collection; -use Magento\Integration\Model\ResourceModel\Oauth\Token\CollectionFactory; -use Magento\TestFramework\Authentication\OauthHelper; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\TestCase\WebapiAbstract; - -/** - * Api-functional test for \Magento\LoginAsCustomerWebapi\Api\LoginAsCustomerWebapiCreateCustomerAccessTokenInterface. - */ -class LoginAsCustomerWebapiCreateCustomerAccessTokenTest extends WebapiAbstract -{ - const RESOURCE_PATH = "/V1/login-as-customer/token"; - - /** - * @var Collection - */ - private $tokenCollection; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->_markTestAsRestOnly(); - $tokenCollectionFactory = Bootstrap::getObjectManager()->get(CollectionFactory::class); - $this->tokenCollection = $tokenCollectionFactory->create(); - } - - /** - * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @magentoConfigFixture login_as_customer/general/enabled 1 - */ - public function testCreateCustomerAccessToken() - { - // 'Magento_LoginAsCustomerWebapi::login_token' resource required for access. - OauthHelper::clearApiAccessCredentials(); - OauthHelper::getApiAccessCredentials(['Magento_LoginAsCustomerWebapi::login_token']); - try { - $customerId = 1; - - $serviceInfo = [ - 'rest' => [ - 'resourcePath' => self::RESOURCE_PATH, - 'httpMethod' => Request::HTTP_METHOD_POST, - ], - ]; - $requestData = ['customerId' => $customerId]; - $response = $this->_webApiCall($serviceInfo, $requestData); - - $this->assertToken($response, $customerId); - } catch (\Exception $e) { - OauthHelper::clearApiAccessCredentials(); - throw $e; - } - // Restore credentials - OauthHelper::clearApiAccessCredentials(); - } - - /** - * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @magentoConfigFixture login_as_customer/general/enabled 0 - */ - public function testCreateCustomerAccessTokenLoginModuleDisabled() - { - $this->expectException(\Exception::class); - $this->expectExceptionMessage('Service is disabled.'); - - $customerId = 1; - - $serviceInfo = [ - 'rest' => [ - 'resourcePath' => self::RESOURCE_PATH, - 'httpMethod' => Request::HTTP_METHOD_POST, - ], - ]; - $requestData = ['customerId' => $customerId]; - $this->_webApiCall($serviceInfo, $requestData); - } - - /** - * @magentoApiDataFixture Magento/Customer/_files/customer.php - * @magentoConfigFixture login_as_customer/general/enabled 1 - */ - public function testCreateCustomerAccessTokenLoginNoAccess() - { - $this->expectException(\Exception::class); - $this->expectExceptionMessage('The consumer isn\'t authorized to access %resources.'); - - // 'Magento_LoginAsCustomerWebapi::login_token' resource required for access. - OauthHelper::clearApiAccessCredentials(); - OauthHelper::getApiAccessCredentials([]); - try { - $customerId = 1; - - $serviceInfo = [ - 'rest' => [ - 'resourcePath' => self::RESOURCE_PATH, - 'httpMethod' => Request::HTTP_METHOD_POST, - ], - ]; - $requestData = ['customerId' => $customerId]; - $this->_webApiCall($serviceInfo, $requestData); - } catch (\Exception $e) { - OauthHelper::clearApiAccessCredentials(); - throw $e; - } - // Restore credentials - OauthHelper::clearApiAccessCredentials(); - } - - /** - * Make sure provided token is valid and belongs to the specified user. - * - * @param string $response - * @param int $customerId - */ - private function assertToken(string $response, int $customerId) - { - $this->tokenCollection->addFilterByCustomerId($customerId); - $isTokenCorrect = false; - foreach ($this->tokenCollection->getItems() as $item) { - /** @var $item TokenModel */ - if ($item->getToken() == $response) { - $isTokenCorrect = true; - } - } - - $this->assertTrue($isTokenCorrect); - } -} diff --git a/dev/tests/functional/credentials.xml.dist b/dev/tests/functional/credentials.xml.dist index 97c854dcb7132..99c62395f1f88 100644 --- a/dev/tests/functional/credentials.xml.dist +++ b/dev/tests/functional/credentials.xml.dist @@ -28,16 +28,6 @@ <field replace="carriers_dhl_password_eu" value="" /> <field replace="carriers_dhl_account_eu" value="" /> - <field replace="braintree_enabled_fraud_merchant_account_id" value="" /> - <field replace="braintree_enabled_fraud_merchant_id" value="" /> - <field replace="braintree_enabled_fraud_public_key" value="" /> - <field replace="braintree_enabled_fraud_private_key" value="" /> - - <field replace="braintree_disabled_fraud_merchant_account_id" value="" /> - <field replace="braintree_disabled_fraud_merchant_id" value="" /> - <field replace="braintree_disabled_fraud_public_key" value="" /> - <field replace="braintree_disabled_fraud_private_key" value="" /> - <field path="payment/paypal_group_all_in_one/wpp_usuk/wpp_required_settings/wpp_and_express_checkout/business_account" value="" /> <field path="payment/paypal_group_all_in_one/wpp_usuk/wpp_required_settings/wpp_and_express_checkout/api_username" value="" /> <field path="payment/paypal_group_all_in_one/wpp_usuk/wpp_required_settings/wpp_and_express_checkout/api_password" value="" /> diff --git a/dev/tests/functional/etc/repository_replacer_payments.xml b/dev/tests/functional/etc/repository_replacer_payments.xml deleted file mode 100644 index 5141280399e42..0000000000000 --- a/dev/tests/functional/etc/repository_replacer_payments.xml +++ /dev/null @@ -1,17 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../vendor/magento/mtf/Magento/Mtf/Repository/etc/repository.xsd"> - <repository class="Magento\Braintree\Test\Repository\BraintreeSandboxCustomer"> - <dataset name="braintree_sandbox_default"> - <field name="environment" xsi:type="string">BRAINTREEE_ENVIRONMENT</field> - <field name="merchantId" xsi:type="string">BRAINTREEE_MERCHANT_ID</field> - <field name="publicKey" xsi:type="string">BRAINTREE_PUBLIC_KEY</field> - <field name="privateKey" xsi:type="string">BRAINTREE_PRIVATE_KEY</field> - </dataset> - </repository> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Analytics/Test/TestCase/InstallTest.xml b/dev/tests/functional/tests/app/Magento/Analytics/Test/TestCase/InstallTest.xml deleted file mode 100644 index fe2346b2a83f8..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Analytics/Test/TestCase/InstallTest.xml +++ /dev/null @@ -1,16 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Install\Test\TestCase\InstallTest" summary="[Web Setup][Auto] Install CE Magento via Web Interface"> - <variation name="InstallTestVariation" summary="Magento analytics opt-in by default" ticketId="MAGETWO-86059"> - <data name="tag" xsi:type="string">severity:S1</data> - <constraint name="Magento\User\Test\Constraint\AssertUserSuccessLogin" next="Magento\Analytics\Test\Constraint\AssertConfigAnalyticsEnabled"/> - <constraint name="Magento\Analytics\Test\Constraint\AssertConfigAnalyticsEnabled" prev="Magento\User\Test\Constraint\AssertUserSuccessLogin" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Adminhtml/Report/Grid.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Adminhtml/Report/Grid.php deleted file mode 100644 index b7e8e1b1c377f..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Adminhtml/Report/Grid.php +++ /dev/null @@ -1,46 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\Block\Adminhtml\Report; - -use Magento\Ui\Test\Block\Adminhtml\DataGrid; - -/** - * Class Grid - */ -class Grid extends DataGrid -{ - /** - * List of filters for grid - * @var array - */ - protected $filters = [ - 'id' => [ - 'selector' => '[name="id"]' - ] - ]; - - /** - * Selector for transaction ids container - * @var string - */ - private $txnId = '.data-grid tbody tr td:nth-child(2) div'; - - /** - * Get list of transaction ids - * @return array - */ - public function getTransactionIds() - { - $elements = $this->_rootElement->getElements($this->txnId); - $result = []; - - foreach ($elements as $element) { - $result[] = trim($element->getText()); - } - - return $result; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Form/BraintreeCc.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Form/BraintreeCc.php deleted file mode 100644 index 5f02a29a0f5ff..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Form/BraintreeCc.php +++ /dev/null @@ -1,89 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Test\Block\Form; - -use Magento\Mtf\Client\Locator; -use Magento\Mtf\Client\Element\SimpleElement; -use Magento\Mtf\Fixture\FixtureInterface; -use Magento\Mtf\ObjectManager; -use Magento\Payment\Test\Block\Form\PaymentCc; - -/** - * Form for filling credit card data for Braintree payment method. - */ -class BraintreeCc extends PaymentCc -{ - /** - * Braintree iFrame locator. - * - * @var array - */ - protected $braintreeForm = [ - "cc_number" => "//*[@id='braintree-hosted-field-number']", - "cc_exp_month" => "//*[@id='braintree-hosted-field-expirationMonth']", - "cc_exp_year" => "//*[@id='braintree-hosted-field-expirationYear']", - "cc_cid" => "//*[@id='braintree-hosted-field-cvv']", - ]; - - /** - * Error container selector. - * - * @var string - */ - protected $errorSelector = "/../../div[@class='hosted-error']"; - - /** - * Fill Braintree credit card form. - * - * @param FixtureInterface $fixture - * @param SimpleElement|null $element - * @return void - */ - public function fill(FixtureInterface $fixture, SimpleElement $element = null) - { - $this->braintreeForm = array_intersect_key($this->braintreeForm, $fixture->getData()); - $mapping = $this->dataMapping($fixture->getData()); - foreach ($this->braintreeForm as $field => $iframe) { - $element = $this->browser->find('body'); - $this->browser->waitUntil( - function () use ($element, $iframe) { - $fieldElement = $element->find($iframe, Locator::SELECTOR_XPATH); - return $fieldElement->isVisible() ? true : null; - } - ); - $iframeLocator = ObjectManager::getInstance()->create( - Locator::class, - [ - 'value' => $iframe, - 'strategy' => Locator::SELECTOR_XPATH - ] - ); - $this->browser->switchToFrame($iframeLocator); - $element = $this->browser->find('body'); - $this->_fill([$mapping[$field]], $element); - $this->browser->switchToFrame(); - } - } - - /** - * Returns visible error messages. - * - * @param array $messages - * @return array - */ - public function getVisibleMessages(array $messages) - { - $textMessages = []; - foreach (array_keys($messages) as $field) { - $selector = $this->braintreeForm[$field] . $this->errorSelector; - $errorElement = $this->_rootElement->find($selector, Locator::SELECTOR_XPATH); - $textMessages[$field] = $errorElement->isVisible() ? $errorElement->getText() : null; - } - - return $textMessages; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Form/BraintreeCc.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Form/BraintreeCc.xml deleted file mode 100644 index f57a1380fba00..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Form/BraintreeCc.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<mapping strict="0"> - <fields> - <cc_number> - <selector>#credit-card-number</selector> - </cc_number> - <cc_exp_month> - <selector>#expiration-month</selector> - </cc_exp_month> - <cc_exp_year> - <selector>#expiration-year</selector> - </cc_exp_year> - <cc_cid> - <selector>#cvv</selector> - </cc_cid> - </fields> -</mapping> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Form/Secure3d.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Form/Secure3d.php deleted file mode 100644 index 02f016cbe79c9..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Form/Secure3d.php +++ /dev/null @@ -1,91 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Test\Block\Form; - -use Magento\Mtf\Client\Locator; -use Magento\Mtf\Client\Element\SimpleElement; -use Magento\Mtf\Fixture\FixtureInterface; -use Magento\Mtf\Block\Form; - -/** - * Form for filling 3D Secure password for Braintree payment method - */ -class Secure3d extends Form -{ - /** - * 3D Secure iFrame locator. - * - * @var string - */ - protected $braintree3dSecure = "//iframe[contains(@id, 'braintreethreedsecurelanding')]"; - - /** - * AuthWindow locator. - * - * @var string - */ - private $authWindow3dSecure = "//iframe[contains(@id, 'authWindow')]"; - - /** - * Password field locator. - * - * @var string - */ - private $passwordField = "//*[@name='external.field.password']"; - - /** - * Submit button button css selector. - * - * @var string - */ - protected $submitButton = 'input[name="UsernamePasswordEntry"]'; - - /** - * Switch to 3D Secure iFrame. - * - * @param string $locator - */ - public function switchToFrame($locator) - { - $this->browser->switchToFrame(new Locator($locator, Locator::SELECTOR_XPATH)); - $this->browser->switchToFrame(new Locator($this->authWindow3dSecure, Locator::SELECTOR_XPATH)); - } - - /** - * Click Submit button. - * - * @return void - */ - public function submit() - { - $this->browser->find($this->submitButton)->click(); - } - - /** - * Fill the 3D Secure form and submit it. - * - * @param FixtureInterface $fixture - * @param SimpleElement|null $element - * - * @return $this|void - */ - public function fill(FixtureInterface $fixture, SimpleElement $element = null) - { - $mapping = $this->dataMapping($fixture->getData()); - $this->switchToFrame($this->braintree3dSecure); - $element = $this->browser->find('body'); - $this->browser->waitUntil( - function () use ($element) { - $fieldElement = $element->find($this->passwordField, Locator::SELECTOR_XPATH); - return $fieldElement->isVisible() ? true : null; - } - ); - $this->_fill([$mapping['secure3d_password']], $element); - $this->submit(); - $this->browser->switchToFrame(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Form/Secure3d.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Form/Secure3d.xml deleted file mode 100644 index 06b8ade797700..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Form/Secure3d.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<mapping strict="1"> - <fields> - <secure3d_password> - <selector>input[name="external.field.password"]</selector> - </secure3d_password> - </fields> -</mapping> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Paypal/PopupWindow.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Paypal/PopupWindow.php deleted file mode 100644 index 7d1459746d533..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/Paypal/PopupWindow.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\Block\Paypal; - -use Magento\Mtf\Block\Block; - -/** - * Class PopupWindow - */ -class PopupWindow extends Block -{ - /** - * @var string - */ - private $selector = '#login-preview'; - - /** - * @var string - */ - private $submitButton = '#return_url'; - - /** - * @var string - */ - private $loader = '.loader'; - - /** - * Waits for PayPal popup loading - * - * @return void - */ - public function waitForFormLoaded() - { - $this->waitForElementVisible($this->selector); - } - - /** - * Process PayPal auth flow - * - * @param null|string $parentWindow - * - */ - public function process($parentWindow = null) - { - $this->browser->selectWindow(); - $this->waitForFormLoaded(); - $this->browser->find($this->submitButton)->click(); - $this->browser->selectWindow($parentWindow); - $this->waitForElementNotVisible($this->loader); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/System/Config/Braintree.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/System/Config/Braintree.php deleted file mode 100644 index 5d5fdef3e2e7e..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Block/System/Config/Braintree.php +++ /dev/null @@ -1,127 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Test\Block\System\Config; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; - -/** - * Configuration for Braintree payment method. - */ -class Braintree extends Block -{ - /** - * Braintree credentials fields sectors array. - * - * @var array - */ - private $fields = [ - 'Merchant ID' => '#payment_us_braintree_section_braintree_braintree_required_merchant_id', - 'Public Key' => '#payment_us_braintree_section_braintree_braintree_required_public_key', - 'Private Key' => '#payment_us_braintree_section_braintree_braintree_required_private_key', - ]; - - /** - * Braintree enablers fields sectors array. - * - * @var array - */ - private $enablers = [ - 'Enable this Solution' => "#payment_us_braintree_section_braintree_active", - 'Enable PayPal through Braintree' => '#payment_us_braintree_section_braintree_active_braintree_paypal', - 'Vault Enabled' => '#payment_us_braintree_section_braintree_braintree_cc_vault_active' - ]; - - /** - * Braintree 'Configure' button. - * - * @var string - */ - private $configureBraintreeButton = '#payment_us_braintree_section_braintree-head'; - - /** - * Return credentials fields selectors. - * - * @return array - */ - public function getFields() - { - return $this->fields; - } - - /** - * Specify credentials in Braintree configuration. - * - * @return void - */ - public function specifyCredentials() - { - $this->_rootElement->find($this->fields['Merchant ID'])->setValue('1'); - $this->_rootElement->find($this->fields['Public Key'])->setValue('1'); - $this->_rootElement->find($this->fields['Private Key'])->setValue('1'); - } - - /** - * Clear credentials in Braintree configuration. - * - * @return void - */ - public function clearCredentials() - { - $this->_rootElement->find($this->fields['Merchant ID'])->setValue(''); - $this->_rootElement->find($this->fields['Public Key'])->setValue(''); - $this->_rootElement->find($this->fields['Private Key'])->setValue(''); - } - - /** - * Return enabler fields selectors. - * - * @return array - */ - public function getEnablerFields() - { - return $this->enablers; - } - - /** - * Click 'Configure' button to expand Braintree configuration. - * - * @return void - */ - public function clickConfigureButton() - { - $this->_rootElement->find($this->configureBraintreeButton)->click(); - } - - /** - * Set 'Enable this Solution' = Yes. - * - * @return void - */ - public function enableBraintree() - { - $this->_rootElement->find( - $this->enablers['Enable this Solution'], - Locator::SELECTOR_CSS, - 'select' - )->setValue('Yes'); - } - - /** - * Set 'Enable this Solution' = No. - * - * @return void - */ - public function disableBraintree() - { - $this->_rootElement->find( - $this->enablers['Enable this Solution'], - Locator::SELECTOR_CSS, - 'select' - )->setValue('No'); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Constraint/Assert3dSecureInfoIsPresent.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/Constraint/Assert3dSecureInfoIsPresent.php deleted file mode 100644 index b3a2a8bc55e1f..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Constraint/Assert3dSecureInfoIsPresent.php +++ /dev/null @@ -1,52 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Test\Constraint; - -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Sales\Test\Page\Adminhtml\SalesOrderView; - -/** - * Assert that 3D Secure information is present on order page in Admin. - */ -class Assert3dSecureInfoIsPresent extends AbstractConstraint -{ - /** - * Assert that 3D Secure information is present on order page in Admin. - * - * @param SalesOrderView $salesOrderView - * @param array $paymentInformation - * @return void - */ - public function processAssert(SalesOrderView $salesOrderView, array $paymentInformation) - { - /** @var \Magento\Sales\Test\Block\Adminhtml\Order\View\Tab\Info $infoTab */ - $infoTab = $salesOrderView->getOrderForm()->openTab('info')->getTab('info'); - $actualPaymentInformation = $infoTab->getPaymentInfoBlock()->getData(); - foreach ($paymentInformation as $key => $value) { - \PHPUnit\Framework\Assert::assertArrayHasKey( - $key, - $actualPaymentInformation, - '3D Secure information is not present.' - ); - \PHPUnit\Framework\Assert::assertEquals( - $paymentInformation[$key], - $value, - '3D Secure information is not equal to information from data set.' - ); - } - } - - /** - * Returns a string representation of the object. - * - * @return string - */ - public function toString() - { - return '3D Secure information is present and equals to information from data set.'; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Constraint/AssertCreditCardJsValidationMessagesArePresent.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/Constraint/AssertCreditCardJsValidationMessagesArePresent.php deleted file mode 100644 index 28bb60ff3f186..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Constraint/AssertCreditCardJsValidationMessagesArePresent.php +++ /dev/null @@ -1,46 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Test\Constraint; - -use Magento\Checkout\Test\Page\CheckoutOnepage; -use Magento\Mtf\Constraint\AbstractConstraint; - -/** - * Assert js validation error messages are present for required fields. - */ -class AssertCreditCardJsValidationMessagesArePresent extends AbstractConstraint -{ - /** - * Assert js validation error messages are present for required fields. - * - * @param CheckoutOnepage $checkoutOnepage - * @param array $expectedErrorMessages - * @return void - */ - public function processAssert(CheckoutOnepage $checkoutOnepage, array $expectedErrorMessages) - { - $errorMessages = $checkoutOnepage->getBraintreeBlock()->getVisibleMessages($expectedErrorMessages); - - foreach (array_keys($errorMessages) as $field) { - \PHPUnit\Framework\Assert::assertEquals( - $expectedErrorMessages[$field], - $errorMessages[$field], - "Wrong js validation error message is displayed for field: $field." - ); - } - } - - /** - * Returns string representation of successful assertion - * - * @return string - */ - public function toString() - { - return 'Js validation error messages are correct for required fields.'; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Constraint/AssertDeviceDataIsPresentInBraintreeRequest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/Constraint/AssertDeviceDataIsPresentInBraintreeRequest.php deleted file mode 100644 index b238302e8f47f..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Constraint/AssertDeviceDataIsPresentInBraintreeRequest.php +++ /dev/null @@ -1,52 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Test\Constraint; - -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Mtf\Util\Command\File\Log; - -/** - * Assert that device data is present in Braintree request. - */ -class AssertDeviceDataIsPresentInBraintreeRequest extends AbstractConstraint -{ - /** - * Log file name. - */ - const FILE_NAME = 'payment.log'; - - /** - * Device data pattern for regular expression. - */ - const DEVICE_DATA_PATTERN = '/\'deviceData\' => \'{"device_session_id":"\w*","fraud_merchant_id":"\w*"}\'/'; - - /** - * Assert that device data is present in Braintree request. - * - * @param Log $log - * @return void - */ - public function processAssert(Log $log) - { - $file = $log->getFileContent(self::FILE_NAME); - \PHPUnit\Framework\Assert::assertRegExp( - self::DEVICE_DATA_PATTERN, - $file, - 'The device data is not present in Braintree request.' - ); - } - - /** - * Returns a string representation of the object. - * - * @return string - */ - public function toString() - { - return 'The device data is present in Braintree request.'; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Constraint/AssertTransactionIsPresentInSettlementReport.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/Constraint/AssertTransactionIsPresentInSettlementReport.php deleted file mode 100644 index 9ec9acc9e9cb7..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Constraint/AssertTransactionIsPresentInSettlementReport.php +++ /dev/null @@ -1,91 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\Constraint; - -use Magento\Braintree\Test\Page\Adminhtml\BraintreeSettlementReportIndex; -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Sales\Test\Page\Adminhtml\OrderIndex; -use Magento\Sales\Test\Page\Adminhtml\SalesOrderView; - -/** - * Assert that comment with transaction id exists in Comments History section on order page in Admin. - */ -class AssertTransactionIsPresentInSettlementReport extends AbstractConstraint -{ - /** - * @var SalesOrderView - */ - private $salesOrderView; - - /** - * @var BraintreeSettlementReportIndex - */ - private $settlementReportIndex; - - /** - * Assert that comment with transaction id exists in Comments History section on order page in Admin. - * - * @param $orderId - * @param OrderIndex $orderIndex - * @param SalesOrderView $salesOrderView - * @param BraintreeSettlementReportIndex $braintreeSettlementReportIndex - * @throws \Exception - */ - public function processAssert( - $orderId, - OrderIndex $orderIndex, - SalesOrderView $salesOrderView, - BraintreeSettlementReportIndex $braintreeSettlementReportIndex - ) { - $this->salesOrderView = $salesOrderView; - $this->settlementReportIndex = $braintreeSettlementReportIndex; - - $orderIndex->open(); - $orderIndex->getSalesOrderGrid()->searchAndOpen(['id' => $orderId]); - - $transactionId = $this->getTransactionId(); - \PHPUnit\Framework\Assert::assertNotEmpty($transactionId); - - $this->settlementReportIndex->open(); - - $grid = $this->settlementReportIndex->getSettlementReportGrid(); - $grid->search(['id' => $transactionId]); - - $ids = $grid->getTransactionIds(); - - \PHPUnit\Framework\Assert::assertTrue(in_array($transactionId, $ids)); - } - - /** - * Returns a string representation of the object. - * - * @return string - */ - public function toString() - { - return 'Transaction is present in settlement report.'; - } - - /** - * Get transaction id from order comments. - * - * @return null|string - */ - private function getTransactionId() - { - /** @var \Magento\Sales\Test\Block\Adminhtml\Order\View\Tab\Info $infoTab */ - $infoTab = $this->salesOrderView->getOrderForm()->openTab('info')->getTab('info'); - $latestComment = $infoTab->getCommentsHistoryBlock()->getLatestComment(); - $transactionId = null; - - preg_match('/(\w+-*\w+)"/', $latestComment['comment'], $matches); - if (!empty($matches[1])) { - $transactionId = $matches[1]; - } - - return $transactionId; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Fixture/BraintreeSandboxCustomer.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Fixture/BraintreeSandboxCustomer.xml deleted file mode 100644 index 17f05e23825ab..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Fixture/BraintreeSandboxCustomer.xml +++ /dev/null @@ -1,19 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/fixture.xsd"> - <fixture name="braintree_sandbox_customer" - module="Magento_Braintree" - type="virtual" - repository_class="Magento\Braintree\Test\Repository\BraintreeSandboxCustomer" - class="Magento\Braintree\Test\Fixture\BraintreeSandboxCustomer"> - <field name="environment" /> - <field name="merchantId" /> - <field name="publicKey" /> - <field name="privateKey" /> - </fixture> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Fixture/Secure3dBraintree.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Fixture/Secure3dBraintree.xml deleted file mode 100644 index a51d782214771..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Fixture/Secure3dBraintree.xml +++ /dev/null @@ -1,17 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/fixture.xsd"> - <fixture name="secure3d_braintree" - module="Magento_Braintree" - type="virtual" - entity_type="secure3d_braintree" - repository_class="Magento\Braintree\Test\Repository\Secure3d" - class="Magento\Braintree\Test\Fixture\Secure3dBraintree"> - <field name="secure3d_password" /> - </fixture> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/Adminhtml/BraintreeSettlementReport.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/Adminhtml/BraintreeSettlementReport.xml deleted file mode 100644 index c882b96314b18..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/Adminhtml/BraintreeSettlementReport.xml +++ /dev/null @@ -1,12 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../vendor/magento/mtf/etc/pages.xsd"> - <page name="BraintreeSettlementReportIndex" area="Adminhtml" mca="braintree/report/index" module="Magento_Braintree"> - <block name="settlementReportGrid" class="Magento\Braintree\Test\Block\Adminhtml\Report\Grid" locator="//div[contains(@data-bind, 'braintree_report')]" strategy="xpath"/> - </page> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/Adminhtml/SystemConfigEditSectionPayment.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/Adminhtml/SystemConfigEditSectionPayment.xml deleted file mode 100644 index ae06b66d3fa18..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/Adminhtml/SystemConfigEditSectionPayment.xml +++ /dev/null @@ -1,12 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../vendor/magento/mtf/etc/pages.xsd"> - <page name="SystemConfigEditSectionPayment" area="Adminhtml" mca="admin/system_config/edit/section/payment" module="Magento_Backend"> - <block name="braintreeConfigBlock" class="Magento\Braintree\Test\Block\System\Config\Braintree" locator="#row_payment_us_braintree_section_braintree" strategy="css selector" /> - </page> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/CatalogProductView.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/CatalogProductView.xml deleted file mode 100644 index a2c4cfeb2e759..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/CatalogProductView.xml +++ /dev/null @@ -1,12 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/pages.xsd"> - <page name="CatalogProductView" area="Product" mca="catalog/product/view" module="Magento_Catalog"> - <block name="braintreePaypalBlock" class="Magento\Braintree\Test\Block\Paypal\PopupWindow" locator="body" strategy="xpath"/> - </page> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/CheckoutCart.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/CheckoutCart.xml deleted file mode 100644 index 404390f4001eb..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/CheckoutCart.xml +++ /dev/null @@ -1,13 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/pages.xsd"> - <page name="CheckoutCart" mca="checkout/cart/index" module="Magento_Checkout"> - <block name="cartBlock" class="Magento\Checkout\Test\Block\Cart" locator="//div[contains(@class, 'column main')]" strategy="xpath"/> - <block name="braintreePaypalBlock" class="Magento\Braintree\Test\Block\Paypal\PopupWindow" locator="body" strategy="xpath"/> - </page> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/CheckoutOnepage.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/CheckoutOnepage.xml deleted file mode 100644 index a69f7942cd944..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Page/CheckoutOnepage.xml +++ /dev/null @@ -1,17 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/pages.xsd"> - <page name="CheckoutOnepage" mca="checkout/index"> - <block name="braintreeBlock" class="Magento\Braintree\Test\Block\Form\BraintreeCc" locator="#payment_form_braintree" strategy="css selector"/> - <block name="braintree3dSecureBlock" class="Magento\Braintree\Test\Block\Form\Secure3d" locator="body" strategy="xpath"/> - <block name="braintreePaypalBlock" class="Magento\Braintree\Test\Block\Paypal\PopupWindow" locator="body" strategy="xpath"/> - <block name="paymentBlock"> - <render name="braintree" class="Magento\Braintree\Test\Block\Form\BraintreeCc" /> - </block> - </page> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/BraintreeSandboxCustomer.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/BraintreeSandboxCustomer.xml deleted file mode 100644 index 3a9923f0880aa..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/BraintreeSandboxCustomer.xml +++ /dev/null @@ -1,17 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/Magento/Mtf/Repository/etc/repository.xsd"> - <repository class="Magento\Braintree\Test\Repository\BraintreeSandboxCustomer"> - <dataset name="braintree_sandbox_default"> - <field name="environment" xsi:type="string">BRAINTREEE_ENVIRONMENT</field> - <field name="merchantId" xsi:type="string">BRAINTREEE_MERCHANT_ID</field> - <field name="publicKey" xsi:type="string">BRAINTREE_PUBLIC_KEY</field> - <field name="privateKey" xsi:type="string">BRAINTREE_PRIVATE_KEY</field> - </dataset> - </repository> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/ConfigData.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/ConfigData.xml deleted file mode 100644 index 58840da4e42a1..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/ConfigData.xml +++ /dev/null @@ -1,443 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/Magento/Mtf/Repository/etc/repository.xsd"> - <repository class="Magento\Config\Test\Repository\ConfigData"> - <dataset name="braintree"> - <field name="payment/braintree_section/braintree/braintree_required/merchant_id" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Merchant ID</item> - <item name="value" xsi:type="string">%braintree_disabled_fraud_merchant_id%</item> - </field> - <field name="payment/braintree_section/braintree/braintree_required/public_key" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Public Key</item> - <item name="value" xsi:type="string">%braintree_disabled_fraud_public_key%</item> - </field> - <field name="payment/braintree_section/braintree/braintree_required/private_key" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Private Key</item> - <item name="value" xsi:type="string">%braintree_disabled_fraud_private_key%</item> - </field> - <field name="payment/braintree_section/braintree/braintree_advanced/merchant_account_id" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Merchant Account ID</item> - <item name="value" xsi:type="string">%braintree_disabled_fraud_merchant_account_id%</item> - </field> - <field name="payment/braintree_section/braintree/braintree_required/payment_action" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Authorize</item> - <item name="value" xsi:type="string">authorize</item> - </field> - <field name="payment/braintree_section/braintree/braintree_advanced/debug" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - <field name="payment/braintree_section/braintree/active" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - </dataset> - - <dataset name="braintree_rollback"> - <field name="payment/braintree/active" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">No</item> - <item name="value" xsi:type="number">0</item> - </field> - </dataset> - - <dataset name="braintree_incorrect_merchant_account_id"> - <field name="payment/braintree_section/braintree/braintree_advanced/merchant_account_id" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Merchant Account ID</item> - <item name="value" xsi:type="string">incorrect</item> - </field> - </dataset> - - <dataset name="braintree_sale"> - <field name="payment/braintree/payment_action" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Authorize and Capture</item> - <item name="value" xsi:type="string">authorize_capture</item> - </field> - </dataset> - - <dataset name="braintree_3d_secure"> - <field name="payment/braintree_section/braintree/braintree_3dsecure/verify_3dsecure" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - </dataset> - - <dataset name="braintree_3d_secure_rollback"> - <field name="payment/braintree_section/braintree/braintree_3dsecure/verify_3dsecure" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">No</item> - <item name="value" xsi:type="number">0</item> - </field> - </dataset> - - <dataset name="braintree_3d_secure_uk"> - <field name="payment/braintree/verify_3dsecure" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - <field name="payment/braintree_section/braintree/braintree_3dsecure/allowspecific" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - <field name="payment/braintree_section/braintree/braintree_3dsecure/specificcountry" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="array"> - <item name="United Kingdom" xsi:type="string">GB</item> - </item> - <item name="value" xsi:type="array"> - <item name="United Kingdom" xsi:type="string">GB</item> - </item> - </field> - </dataset> - - <dataset name="braintree_3d_secure_uk_rollback"> - <field name="payment/braintree_section/braintree/braintree_3dsecure/verify_3dsecure" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">No</item> - <item name="value" xsi:type="number">0</item> - </field> - <field name="payment/braintree_section/braintree/braintree_3dsecure/allowspecific" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">No</item> - <item name="value" xsi:type="number">0</item> - </field> - </dataset> - - <dataset name="braintree_3d_secure_not_triggered_due_threshold"> - <field name="payment/braintree/verify_3dsecure" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - <field name="payment/braintree/threshold_amount" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">300</item> - <item name="value" xsi:type="number">300</item> - </field> - </dataset> - - <dataset name="braintree_3d_secure_not_triggered_due_threshold_rollback"> - <field name="payment/braintree/verify_3dsecure" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">No</item> - <item name="value" xsi:type="number">0</item> - </field> - </dataset> - - <dataset name="braintree_use_vault"> - <field name="payment/braintree_section/braintree/braintree_cc_vault_active" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - </dataset> - - <dataset name="braintree_use_vault_rollback"> - <field name="payment/braintree_section/braintree/braintree_cc_vault_active" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">No</item> - <item name="value" xsi:type="number">0</item> - </field> - </dataset> - - <dataset name="braintree_paypal"> - <field name="payment/braintree_section/braintree/active_braintree_paypal" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - <field name="payment/braintree_section/braintree/braintree_paypal/payment_action" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Authorize</item> - <item name="value" xsi:type="string">authorize</item> - </field> - </dataset> - - <dataset name="braintree_paypal_rollback"> - <field name="payment/braintree_section/braintree/active_braintree_paypal" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">No</item> - <item name="value" xsi:type="number">0</item> - </field> - </dataset> - - <dataset name="braintree_paypal_sale"> - <field name="payment/braintree_section/braintree/active_braintree_paypal" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - <field name="payment/braintree_section/braintree/braintree_paypal/payment_action" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Authorize and Capture</item> - <item name="value" xsi:type="string">authorize_capture</item> - </field> - </dataset> - - <dataset name="braintree_paypal_sale_rollback"> - <field name="payment/braintree_section/braintree/active_braintree_paypal" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">No</item> - <item name="value" xsi:type="number">0</item> - </field> - </dataset> - - <dataset name="braintree_paypal_skip_order_review"> - <field name="payment/braintree_section/braintree/braintree_paypal/skip_order_review" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - </dataset> - - <dataset name="braintree_paypal_skip_order_review_rollback"> - <field name="payment/braintree_section/braintree/braintree_paypal/skip_order_review" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">No</item> - <item name="value" xsi:type="number">0</item> - </field> - </dataset> - - <dataset name="braintree_paypal_use_vault"> - <field name="payment/braintree_section/braintree/braintree_paypal/braintree_paypal_vault_active" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - </dataset> - - <dataset name="braintree_paypal_use_vault_rollback"> - <field name="payment/braintree_section/braintree/braintree_paypal/braintree_paypal_vault_active" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">No</item> - <item name="value" xsi:type="number">0</item> - </field> - </dataset> - - <dataset name="braintree_paypal_require_billing_address"> - <field name="payment/braintree_paypal/require_billing_address" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - </dataset> - - <dataset name="braintree_paypal_require_billing_address_rollback"> - <field name="payment/braintree_paypal/require_billing_address" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">No</item> - <item name="value" xsi:type="number">0</item> - </field> - </dataset> - - <dataset name="braintree_fraudprotection"> - <field name="payment/braintree/fraudprotection" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - </dataset> - - <dataset name="braintree_fraudprotection_rollback"> - <field name="payment/braintree/fraudprotection" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">No</item> - <item name="value" xsi:type="number">0</item> - </field> - </dataset> - - <dataset name="braintree_fraud_tool_enabled_account"> - <field name="payment/braintree_section/braintree/braintree_required/merchant_id" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Merchant ID</item> - <item name="value" xsi:type="string">%braintree_enabled_fraud_merchant_id%</item> - </field> - <field name="payment/braintree_section/braintree/braintree_required/public_key" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Public Key</item> - <item name="value" xsi:type="string">%braintree_enabled_fraud_public_key%</item> - </field> - <field name="payment/braintree_section/braintree/braintree_required/private_key" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Private Key</item> - <item name="value" xsi:type="string">%braintree_enabled_fraud_private_key%</item> - </field> - <field name="payment/braintree_section/braintree/braintree_advanced/merchant_account_id" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Merchant Account ID</item> - <item name="value" xsi:type="string">%braintree_enabled_fraud_merchant_account_id%</item> - </field> - <field name="payment/braintree_section/braintree/braintree_required/payment_action" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Authorize</item> - <item name="value" xsi:type="string">authorize</item> - </field> - <field name="payment/braintree_section/braintree/braintree_advanced/debug" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - <field name="payment/braintree_section/braintree/active" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - </dataset> - - <dataset name="braintree_fraud_tool_enabled_account_rollback"> - <field name="payment/braintree/active" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">No</item> - <item name="value" xsi:type="number">0</item> - </field> - </dataset> - - <dataset name="braintree_cvv_disabled"> - <field name="payment/braintree/useccv" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">No</item> - <item name="value" xsi:type="number">0</item> - </field> - </dataset> - - <dataset name="braintree_cvv_disabled_rollback"> - <field name="payment/braintree/useccv" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Yes</item> - <item name="value" xsi:type="number">1</item> - </field> - </dataset> - - <dataset name="braintree_cctypes_AE_VI"> - <field name="payment/braintree/cctypes" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="value" xsi:type="array"> - <item name="American Express" xsi:type="string">AE</item> - <item name="Visa" xsi:type="string">VI</item> - </item> - </field> - </dataset> - - <dataset name="braintree_cctypes_AE_VI_rollback"> - <field name="payment/braintree/cctypes" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="value" xsi:type="array"> - <item name="China Union Pay" xsi:type="string">CUP</item> - <item name="American Express" xsi:type="string">AE</item> - <item name="Visa" xsi:type="string">VI</item> - <item name="MasterCard" xsi:type="string">MC</item> - <item name="Discover" xsi:type="string">DI</item> - <item name="JCB" xsi:type="string">JCB</item> - <item name="Diners" xsi:type="string">DN</item> - <item name="Maestro International" xsi:type="string">MI</item> - </item> - </field> - </dataset> - - <dataset name="braintree_specific_country_GB"> - <field name="payment/braintree/allowspecific" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">Specific Countries</item> - <item name="value" xsi:type="number">1</item> - </field> - <field name="payment/braintree/specificcountry" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="value" xsi:type="array"> - <item name="United Kingdom" xsi:type="string">GB</item> - </item> - </field> - </dataset> - - <dataset name="braintree_specific_country_GB_rollback"> - <field name="payment/braintree/allowspecific" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="label" xsi:type="string">All Allowed Countries</item> - <item name="value" xsi:type="number">0</item> - </field> - </dataset> - - <dataset name="braintree_countrycreditcard_US_MS_GB_VI"> - <field name="payment/braintree/countrycreditcard" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="value" xsi:type="string">{"GB":["VI"],"US":["MC"]}</item> - </field> - </dataset> - - <dataset name="braintree_countrycreditcard_US_MS_GB_VI_rollback"> - <field name="payment/braintree/countrycreditcard" xsi:type="array"> - <item name="scope" xsi:type="string">payment</item> - <item name="scope_id" xsi:type="number">1</item> - <item name="value" xsi:type="string">[]</item> - </field> - </dataset> - </repository> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/CreditCard.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/CreditCard.xml deleted file mode 100644 index 83ab138dacf55..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/CreditCard.xml +++ /dev/null @@ -1,41 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/Magento/Mtf/Repository/etc/repository.xsd"> - <repository class="Magento\Payment\Test\Repository\CreditCard"> - <dataset name="visa_braintree_3dsecure"> - <field name="payment_code" xsi:type="string">braintree</field> - <field name="cc_number" xsi:type="string">4000000000000002</field> - <field name="cc_exp_month" xsi:type="string">01</field> - <field name="cc_exp_year" xsi:type="string">24</field> - <field name="cc_cid" xsi:type="string">123</field> - </dataset> - - <dataset name="visa_braintree_3dsecure_failed"> - <field name="payment_code" xsi:type="string">braintree</field> - <field name="cc_number" xsi:type="string">4000000000000028</field> - <field name="cc_exp_month" xsi:type="string">01</field> - <field name="cc_exp_year" xsi:type="string">2024</field> - <field name="cc_cid" xsi:type="string">123</field> - </dataset> - - <dataset name="visa_braintree_fraud_rejected"> - <field name="payment_code" xsi:type="string">braintree</field> - <field name="cc_number" xsi:type="string">4000111111111511</field> - <field name="cc_exp_month" xsi:type="string">01</field> - <field name="cc_exp_year" xsi:type="string">2024</field> - <field name="cc_cid" xsi:type="string">123</field> - </dataset> - - <dataset name="visa_braintree_no_cvv"> - <field name="payment_code" xsi:type="string">braintree</field> - <field name="cc_number" xsi:type="string">4111111111111111</field> - <field name="cc_exp_month" xsi:type="string">01 - January</field> - <field name="cc_exp_year" xsi:type="string">2024</field> - </dataset> - </repository> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/Secure3d.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/Secure3d.xml deleted file mode 100644 index 966e798212996..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/Repository/Secure3d.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/Magento/Mtf/Repository/etc/repository.xsd"> - <repository class="Magento\Braintree\Test\Repository\Secure3d"> - <dataset name="secure3d_braintree"> - <field name="secure3d_password" xsi:type="string">1234</field> - </dataset> - </repository> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/BraintreeSettlementReportTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/BraintreeSettlementReportTest.php deleted file mode 100644 index 979e267c3748e..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/BraintreeSettlementReportTest.php +++ /dev/null @@ -1,53 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * Preconditions: - * 1. Configure shipping method. - * 2. Configure payment method. - * 3. Create products. - * 4. Create and setup customer. - * 5. Create sales rule according to dataset. - * - * Steps: - * 1. Log in Storefront. - * 2. Add products to the Shopping Cart. - * 3. In 'Estimate Shipping and Tax' section specify destination using values from Test Data. - * 4. Click the 'Proceed to Checkout' button. - * 5. Fill shipping information. - * 6. Select shipping method. - * 7. Select payment method (use reward points and store credit if available). - * 8. Verify order total on review step. - * 9. Click 'Place Order' button. - * 10. Go to admin panel. - * 11. Open 'Reports' -> 'Braintree Settlement'. - * 12. Find transaction for latest order. - * 13. Perform assertions. - * - * @group Braintree - * @ZephyrId MAGETWO-48162 - */ -class BraintreeSettlementReportTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = '3rd_party_test'; - const SEVERITY = 'S1'; - /* end tags */ - - /** - * Runs one page checkout test. - * - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/BraintreeSettlementReportTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/BraintreeSettlementReportTest.xml deleted file mode 100644 index db81e3dec5c35..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/BraintreeSettlementReportTest.xml +++ /dev/null @@ -1,34 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Braintree\Test\TestCase\BraintreeSettlementReportTest" summary="Braintree Settlement Report."> - <variation name="BraintreeSettlementReportTestVariation1" summary="Braintree Settlement Report" ticketId="MAGETWO-48162"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">15.00</item> - </data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:extended_acceptance_test, test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertAuthorizationInCommentsHistory" /> - <constraint name="Magento\Braintree\Test\Constraint\AssertTransactionIsPresentInSettlementReport" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalCartTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalCartTest.php deleted file mode 100644 index 58e7c542939e2..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalCartTest.php +++ /dev/null @@ -1,48 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * Preconditions: - * 1. Configure shipping method. - * 2. Configure payment method. - * 3. Create products. - * 4. Create and setup customer. - * 5. Create sales rule according to dataset. - * - * Steps: - * 1. Log in Storefront. - * 2. Add products to the Shopping Cart. - * 3. Open the Shopping cart and click "Checkout with PayPal" - * 4. Click 'Proceed purchase' in popup. - * 5. Select a shipping method. - * 6. Click 'Place Order' button. - * 8. Select payment method - * 12. Perform assertions. - * - * @group Braintree - * @ZephyrId MAGETWO-39363 - */ -class CheckoutWithBraintreePaypalCartTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = '3rd_party_test'; - const SEVERITY = 'S0'; - /* end tags */ - - /** - * Runs one page checkout test. - * - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalCartTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalCartTest.xml deleted file mode 100644 index 82e7cde4e4a31..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalCartTest.xml +++ /dev/null @@ -1,50 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Braintree\Test\TestCase\CheckoutWithBraintreePaypalCartTest" summary="One page checkout with Braintree PayPal."> - <variation name="CheckoutWithBraintreePaypalCartTestVariation1" summary="Registered Checkout with Braintree PayPal from Cart" ticketId="MAGETWO-39363"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">15.00</item> - </data> - <data name="payment/method" xsi:type="string">braintree_paypal</data> - <data name="configData" xsi:type="string">braintree, braintree_paypal, braintree_paypal_skip_order_review</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S0</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertAuthorizationInCommentsHistory" /> - </variation> - <variation name="CheckoutWithBraintreePaypalCartTestVariation2" summary="Registered Checkout with Braintree PayPal from Mini Cart with payment action Authorize and Capture" ticketId="MAGETWO-39363"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">15.00</item> - </data> - <data name="order/data/price/dataset" xsi:type="string">captured_price_15.00</data> - <data name="payment/method" xsi:type="string">braintree_paypal</data> - <data name="configData" xsi:type="string">braintree, braintree_paypal, braintree_paypal_sale, braintree_paypal_skip_order_review</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S0</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertCaptureInCommentsHistory" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalMinicartTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalMinicartTest.php deleted file mode 100644 index 3cd08788dcca3..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalMinicartTest.php +++ /dev/null @@ -1,48 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * Preconditions: - * 1. Configure shipping method. - * 2. Configure payment method. - * 3. Create products. - * 4. Create and setup customer. - * 5. Create sales rule according to dataset. - * - * Steps: - * 1. Log in Storefront. - * 2. Add products to the Shopping Cart. - * 3. Open the Mini shopping cart and click "Checkout with PayPal" - * 4. Click 'Proceed purchase' in popup. - * 5. Select a shipping method. - * 6. Click 'Place Order' button. - * 8. Select payment method - * 12. Perform assertions. - * - * @group Braintree - * @ZephyrId MAGETWO-39359 - */ -class CheckoutWithBraintreePaypalMinicartTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = '3rd_party_test'; - const SEVERITY = 'S0'; - /* end tags */ - - /** - * Runs one page checkout test. - * - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalMinicartTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalMinicartTest.xml deleted file mode 100644 index 272d698a32501..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CheckoutWithBraintreePaypalMinicartTest.xml +++ /dev/null @@ -1,62 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Braintree\Test\TestCase\CheckoutWithBraintreePaypalMinicartTest" summary="One page checkout with Braintree PayPal."> - <variation name="CheckoutWithBraintreePaypalMinicartTestVariation1" summary="Registered Checkout with Braintree PayPal from Mini Cart" ticketId="MAGETWO-39359"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">15.00</item> - </data> - <data name="payment/method" xsi:type="string">braintree_paypal</data> - <data name="configData" xsi:type="string">braintree, braintree_paypal, braintree_paypal_skip_order_review</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S0</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertAuthorizationInCommentsHistory" /> - </variation> - <variation name="CheckoutWithBraintreePaypalMinicartTestVariation2" summary="Registered Checkout with Braintree PayPal from Mini Cart with payment action Authorize and Capture" ticketId="MAGETWO-39359"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">15.00</item> - </data> - <data name="order/data/price/dataset" xsi:type="string">captured_price_15.00</data> - <data name="payment/method" xsi:type="string">braintree_paypal</data> - <data name="configData" xsi:type="string">braintree, braintree_paypal, braintree_paypal_sale, braintree_paypal_skip_order_review</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S0</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertCaptureInCommentsHistory" /> - </variation> - <variation name="CheckoutWithBraintreePaypalMinicartTestVariation3" summary="Checkout using PayPal Braintree button if Require Customer's Billing Address = Yes" ticketId="MAGETWO-48101"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping/shipping_service" xsi:type="string">Free Shipping</data> - <data name="shipping/shipping_method" xsi:type="string">Free</data> - <data name="payment/method" xsi:type="string">braintree_paypal</data> - <data name="configData" xsi:type="string">braintree, braintree_paypal, freeshipping, braintree_paypal_require_billing_address</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderBillingAndShippingAddressesAreDifferent" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreePaypalTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreePaypalTest.php deleted file mode 100644 index 83a8e072fbf97..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreePaypalTest.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * Preconditions: - * 1. PLace order via Briantree PayPal. - * - * Steps: - * 1. Log in to Admin. - * 2. Open created order. - * 3. Create credit memo. - * 4. Perform assertions. - * - * @group Braintree - * @ZephyrId MAGETWO-48689, MAGETWO-48698 - */ -class CreateOnlineCreditMemoBraintreePaypalTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = '3rd_party_test'; - const SEVERITY = 'S1'; - /* end tags */ - - /** - * Runs test for online credit memo creation for order placed via Braintree PayPal. - * - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreePaypalTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreePaypalTest.xml deleted file mode 100644 index 647f117e87517..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreePaypalTest.xml +++ /dev/null @@ -1,83 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Braintree\Test\TestCase\CreateOnlineCreditMemoBraintreePaypalTest" summary="Create online credit memo for Braintree credit card" ticketId="MAGETWO-38324"> - <variation name="CreateCreditMemoBraintreePaypalTestVariation1" summary="Full refund of order placed within Braintree PayPal" ticketId="MAGETWO-48689"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="products/1" xsi:type="string">bundleProduct::bundle_fixed_100_dollar_product</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="taxRule" xsi:type="string">us_ca_ny_rule</data> - <data name="order/data/refund" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="invoiceId" xsi:type="string">0</item> - </item> - </data> - <data name="order/data/price/refund" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="grand_creditmemo_total" xsi:type="string">139.90</item> - </item> - </data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree_paypal</data> - <data name="configData" xsi:type="string">braintree, braintree_paypal, braintree_paypal_sale, braintree_paypal_skip_order_review</data> - <data name="paymentAction" xsi:type="string">sale</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Sales\Test\Constraint\AssertRefundSuccessCreateMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertRefundInCreditMemoTab" /> - <constraint name="Magento\Sales\Test\Constraint\AssertRefundInCommentsHistory" /> - </variation> - <variation name="CreateOnlineCreditMemoBraintreePaypalTestVariation2" summary="Partial refund of order placed within Braintree PayPal" ticketId="MAGETWO-48698"> - <data name="products/0" xsi:type="string">catalogProductSimple::simple_for_sales</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="taxRule" xsi:type="string">us_ca_ny_rule</data> - <data name="order/data/refund" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="invoiceId" xsi:type="string">0</item> - <item name="items_data" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="qty" xsi:type="string">1</item> - </item> - </item> - </item> - <item name="1" xsi:type="array"> - <item name="invoiceId" xsi:type="string">0</item> - </item> - </data> - <data name="order/data/price/refund" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="grand_creditmemo_total" xsi:type="string">621.20</item> - </item> - <item name="1" xsi:type="array"> - <item name="grand_creditmemo_total" xsi:type="string">606.20</item> - </item> - </data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree_paypal</data> - <data name="configData" xsi:type="string">braintree, braintree_paypal, braintree_paypal_skip_order_review</data> - <data name="order/data/invoice" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="items_data" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="qty" xsi:type="string">2</item> - </item> - </item> - </item> - </data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Sales\Test\Constraint\AssertRefundSuccessCreateMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertRefundInCreditMemoTab" /> - <constraint name="Magento\Sales\Test\Constraint\AssertRefundInCommentsHistory" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreeTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreeTest.php deleted file mode 100644 index 146ea9408d7d2..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreeTest.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * Preconditions: - * 1. Full capture of order placed within Braintree. - * - * Steps: - * 1. Log in to Admin. - * 2. Open created order. - * 3. Create credit memo. - * 4. Perform assertions. - * - * @group Braintree - * @ZephyrId MAGETWO-38324 - */ -class CreateOnlineCreditMemoBraintreeTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = '3rd_party_test'; - const SEVERITY = 'S1'; - /* end tags */ - - /** - * Runs test for online credit memo creation for order placed via Braintree Credit Card. - * - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreeTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreeTest.xml deleted file mode 100644 index 10dcac2336c16..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineCreditMemoBraintreeTest.xml +++ /dev/null @@ -1,108 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Braintree\Test\TestCase\CreateOnlineCreditMemoBraintreeTest" summary="Create online credit memo for Braintree credit card" ticketId="MAGETWO-38324"> - <variation name="CreateOnlineCreditMemoBraintreeTestVariation1" summary="Refund an order placed through Braintree with full capture" ticketId="MAGETWO-38324"> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <data name="products" xsi:type="array"> - <item name="0" xsi:type="string">catalogProductSimple::product_10_dollar</item> - <item name="1" xsi:type="string">configurableProduct::with_one_option</item> - <item name="2" xsi:type="string">bundleProduct::bundle_fixed_100_dollar_product</item> - </data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="braintreeSandboxCustomer/dataset" xsi:type="string">braintree_sandbox_default</data> - <data name="taxRule" xsi:type="string">us_ca_ny_rule</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping" xsi:type="array"> - <item name="shipping_service" xsi:type="string">Flat Rate</item> - <item name="shipping_method" xsi:type="string">Fixed</item> - </data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree</data> - <data name="status" xsi:type="string">Closed</data> - <data name="order/data/refund" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="invoiceId" xsi:type="string">0</item> - </item> - </data> - <data name="order/data/price/refund" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="grand_creditmemo_total" xsi:type="string">145.98</item> - </item> - </data> - <data name="transactions/refund" xsi:type="array"> - <item name="transactionType" xsi:type="string">Refund</item> - <item name="statusIsClosed" xsi:type="string">Yes</item> - </data> - <constraint name="Magento\Sales\Test\Constraint\AssertRefundSuccessCreateMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertRefundInCommentsHistory" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertTransactionStatus" /> - </variation> - <variation name="CreateOnlineCreditMemoBraintreeTestVariation2" summary="Partial Refund an order placed through Braintree with Partial capture" ticketId="MAGETWO-38325"> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <data name="products" xsi:type="array"> - <item name="0" xsi:type="string">catalogProductSimple::product_10_dollar</item> - <item name="1" xsi:type="string">configurableProduct::with_one_option</item> - <item name="2" xsi:type="string">bundleProduct::bundle_fixed_100_dollar_product</item> - </data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="braintreeSandboxCustomer/dataset" xsi:type="string">braintree_sandbox_default</data> - <data name="taxRule" xsi:type="string">us_ca_ny_rule</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping" xsi:type="array"> - <item name="shipping_service" xsi:type="string">Flat Rate</item> - <item name="shipping_method" xsi:type="string">Fixed</item> - </data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree</data> - <data name="status" xsi:type="string">Processing</data> - <data name="order/data/refund" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="invoiceId" xsi:type="string">0</item> - <item name="items_data" xsi:type="array"> - <item name="1" xsi:type="array"> - <item name="qty" xsi:type="string">0</item> - </item> - </item> - </item> - <item name="1" xsi:type="array"> - <item name="invoiceId" xsi:type="string">0</item> - </item> - </data> - <data name="order/data/price/refund" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="grand_creditmemo_total" xsi:type="string">134.07</item> - </item> - <item name="1" xsi:type="array"> - <item name="grand_creditmemo_total" xsi:type="string">1.08</item> - </item> - </data> - <data name="order/data/invoice" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="items_data" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="qty" xsi:type="string">0</item> - </item> - </item> - </item> - </data> - <constraint name="Magento\Sales\Test\Constraint\AssertRefundSuccessCreateMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertRefundInCommentsHistory" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineInvoiceEntityTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineInvoiceEntityTest.xml deleted file mode 100644 index 4ce50ea9c4723..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOnlineInvoiceEntityTest.xml +++ /dev/null @@ -1,58 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Sales\Test\TestCase\CreateOnlineInvoiceEntityTest" summary="Capture for order placed within Braintree Credit Card"> - <variation name="CreateOnlineInvoiceEntityTestBraintreeVariation1" summary="Full capture of order placed within Braintree Credit Card" ticketId="MAGETWO-38319"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="products/1" xsi:type="string">bundleProduct::bundle_fixed_100_dollar_product</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="taxRule" xsi:type="string">us_ca_ny_rule</data> - <data name="billingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="saveAddress" xsi:type="string">No</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree</data> - <data name="status" xsi:type="string">Processing</data> - <data name="orderButtonsAvailable" xsi:type="string">Back, Send Email, Credit Memo, Hold, Ship, Reorder</data> - <data name="order/data/invoice/dataset" xsi:type="string">full_invoice</data> - <data name="order/data/price/dataset" xsi:type="string">captured_price_139.90</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Sales\Test\Constraint\AssertInvoiceSuccessCreateMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderButtonsAvailable" /> - <constraint name="Magento\Sales\Test\Constraint\AssertCaptureInCommentsHistory" /> - <constraint name="Magento\Sales\Test\Constraint\AssertInvoiceItems" /> - </variation> - <variation name="CreateOnlineInvoiceEntityTestBraintreeVariation2" summary="Partial capture for order placed within Braintree Credit Card" ticketId="MAGETWO-38322"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_100_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="taxRule" xsi:type="string">us_ca_ny_rule</data> - <data name="billingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="saveAddress" xsi:type="string">No</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree</data> - <data name="status" xsi:type="string">Processing</data> - <data name="orderButtonsAvailable" xsi:type="string">Back, Send Email, Credit Memo, Hold, Ship, Reorder</data> - <data name="order/data/invoice/dataset" xsi:type="string">partial_capture</data> - <data name="order/data/price/dataset" xsi:type="string">captured_prices_108.25_118.25</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Sales\Test\Constraint\AssertInvoiceSuccessCreateMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderButtonsAvailable" /> - <constraint name="Magento\Sales\Test\Constraint\AssertCaptureInCommentsHistory" /> - <constraint name="Magento\Sales\Test\Constraint\AssertInvoiceItems" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderBackendTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderBackendTest.xml deleted file mode 100644 index 70582077ed29d..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderBackendTest.xml +++ /dev/null @@ -1,68 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Sales\Test\TestCase\CreateOrderBackendTest" summary="Checkout with Braintree Credit Card from Admin"> - <variation name="CreateOrderBackendTestBraintreeVariation1" summary="Checkout with Braintree Credit Card from Admin (Payment Action = Authorize Only)" ticketId="MAGETWO-46294"> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S0</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="products/1" xsi:type="string">configurableProduct::with_one_option</data> - <data name="products/2" xsi:type="string">bundleProduct::bundle_fixed_100_dollar_product</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="taxRule" xsi:type="string">us_ca_ny_rule</data> - <data name="billingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="saveAddress" xsi:type="string">No</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">145.98</item> - </data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree</data> - <data name="status" xsi:type="string">Processing</data> - <data name="orderButtonsAvailable" xsi:type="string">Back, Cancel, Send Email, Invoice, Reorder, Edit</data> - <constraint name="Magento\Shipping\Test\Constraint\AssertShipmentSuccessCreateMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderButtonsAvailable" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertAuthorizationInCommentsHistory" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderInOrdersGridOnFrontend" /> - </variation> - <variation name="CreateOrderBackendTestBraintreeVariation2" summary="Checkout with Braintree Credit Card from Admin (Payment Action = Authorize and Capture)" ticketId="MAGETWO-38316"> - <data name="tag" xsi:type="string">test_type:extended_acceptance_test, test_type:3rd_party_test, severity:S0</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="products/1" xsi:type="string">configurableProduct::with_one_option</data> - <data name="products/2" xsi:type="string">bundleProduct::bundle_fixed_100_dollar_product</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="taxRule" xsi:type="string">us_ca_ny_rule</data> - <data name="billingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="saveAddress" xsi:type="string">No</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">145.98</item> - </data> - <data name="order/data/price/dataset" xsi:type="string">captured_price_145.98</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree, braintree_sale</data> - <data name="status" xsi:type="string">Complete</data> - <data name="orderButtonsAvailable" xsi:type="string">Back, Send Email, Reorder</data> - <constraint name="Magento\Shipping\Test\Constraint\AssertShipmentSuccessCreateMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderButtonsAvailable" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertCaptureInCommentsHistory" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderInOrdersGridOnFrontend" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderWithPayPalBraintreeVaultBackendTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderWithPayPalBraintreeVaultBackendTest.php deleted file mode 100644 index b09fb6165b768..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderWithPayPalBraintreeVaultBackendTest.php +++ /dev/null @@ -1,56 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * Preconditions: - * 1. Configure shipping method. - * 2. Configure payment method. - * 3. Create products. - * 4. Create and setup customer. - * - * Steps: - * 1. Log in Storefront. - * 2. Add products to the Shopping Cart. - * 3. In 'Estimate Shipping and Tax' section specify destination using values from Test Data. - * 4. Click the 'Proceed to Checkout' button. - * 5. Fill shipping information. - * 6. Select shipping method. - * 8. Select payment method - * 9. Verify order total on review step. - * 10. Click 'Continue to PayPal' button. - * 11. Click 'Proceed purchase' in popup. - * 12. Log in Admin panel. - * 13. Open placed order. - * 14. Click 'Reorder' button. - * 15. Select stored Braintree PayPal token. - * 16. Click 'Submit Order'. - * 17. Perform assertions. - * - * @group Braintree - * @ZephyrId MAGETWO-59259 - */ -class CreateOrderWithPayPalBraintreeVaultBackendTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - - const TEST_TYPE = '3rd_party_test'; - - const SEVERITY = 'S0'; - /* end tags */ - - /** - * Runs test scenario - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderWithPayPalBraintreeVaultBackendTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderWithPayPalBraintreeVaultBackendTest.xml deleted file mode 100644 index c8d3e9a71b7a5..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateOrderWithPayPalBraintreeVaultBackendTest.xml +++ /dev/null @@ -1,32 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Braintree\Test\TestCase\CreateOrderWithPayPalBraintreeVaultBackendTest" summary="Checkout with PayPal Braintree Vault token from Admin"> - <variation name="CreateOrderWithPayPalBraintreeVaultBackendTestVariation1" summary="Checkout with PayPal Braintree Vault token from Admin" ticketId="MAGETWO-59259"> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S0</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree_paypal</data> - <data name="vault/method" xsi:type="string">braintree_paypal_vault</data> - <data name="status" xsi:type="string">Processing</data> - <data name="configData" xsi:type="string">braintree, braintree_paypal, braintree_paypal_use_vault, braintree_paypal_skip_order_review</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">15.00</item> - </data> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderSuccessCreateMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertAuthorizationInCommentsHistory" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderInOrdersGrid" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderInOrdersGridOnFrontend" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateVaultOrderBackendTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateVaultOrderBackendTest.xml deleted file mode 100644 index 6d40744468a1c..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/CreateVaultOrderBackendTest.xml +++ /dev/null @@ -1,37 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Vault\Test\TestCase\CreateVaultOrderBackendTest" summary="Create Order from Admin via Braintree with saving Credit Cards"> - <variation name="CreateVaultOrderBackendTestBraintreeVariation1" summary="Checkout with Braintree Credit Card from Admin (Payment Action = Authorize Only)" ticketId="MAGETWO-47137, MAGETWO-47139"> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S0</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="billingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="saveAddress" xsi:type="string">No</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">15.00</item> - </data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="vault/method" xsi:type="string">braintree_cc_vault</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="creditCardSave" xsi:type="string">Yes</data> - <data name="configData" xsi:type="string">braintree, braintree_use_vault</data> - <data name="status" xsi:type="string">Processing</data> - <data name="orderButtonsAvailable" xsi:type="string">Back, Cancel, Send Email, Hold, Invoice, Ship, Reorder, Edit</data> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderSuccessCreateMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderButtonsAvailable" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertAuthorizationInCommentsHistory" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderInOrdersGridOnFrontend" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/InvoicePayPalBraintreeTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/InvoicePayPalBraintreeTest.php deleted file mode 100644 index ebe8020423f28..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/InvoicePayPalBraintreeTest.php +++ /dev/null @@ -1,44 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * Preconditions: - * 1. Order 1 is placed with Braintree PayPal. - * - * Steps: - * 1. Log in to Admin. - * 2. Go to Sales > Orders page. - * 3. Open order 1. - * 4. Click Invoice button. - * 5. Ensure Capture Online is selected, click Submit Invoice button. - * 6. Open Invoices tab. - * 7. Perform assertions. - * - * @group Braintree - * @ZephyrId MAGETWO-48614, MAGETWO-48615 - */ -class InvoicePayPalBraintreeTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = '3rd_party_test'; - const SEVERITY = 'S1'; - /* end tags */ - - /** - * Create invoice for order placed within Braintree PayPal. - * - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/InvoicePaypalBraintreeTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/InvoicePaypalBraintreeTest.xml deleted file mode 100644 index dfd464bb2fafc..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/InvoicePaypalBraintreeTest.xml +++ /dev/null @@ -1,56 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Braintree\Test\TestCase\InvoicePayPalBraintreeTest" summary="Capture for order placed within PayPal Braintree"> - <variation name="InvoicePayPalBraintreeTestVariation1" summary="Full capture of order placed within Braintree PayPal" ticketId="MAGETWO-48614"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="products/1" xsi:type="string">bundleProduct::bundle_fixed_100_dollar_product</data> - <data name="taxRule" xsi:type="string">us_illinois_tax_rule</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">139.90</item> - </data> - <data name="order/data/price/dataset" xsi:type="string">captured_price_139.90</data> - <data name="order/data/invoice/dataset" xsi:type="string">full_invoice</data> - <data name="payment/method" xsi:type="string">braintree_paypal</data> - <data name="configData" xsi:type="string">braintree, braintree_paypal, braintree_paypal_skip_order_review</data> - <data name="orderButtonsAvailable" xsi:type="string">Back, Send Email, Credit Memo, Hold, Ship, Reorder</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Sales\Test\Constraint\AssertInvoiceSuccessCreateMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderButtonsAvailable" /> - <constraint name="Magento\Sales\Test\Constraint\AssertInvoiceItems" /> - </variation> - <variation name="InvoicePayPalBraintreeTestVariation2" summary="Partial capture for order placed within Braintree PayPal" ticketId="MAGETWO-48615, MAGETWO-48684"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_100_dollar</data> - <data name="taxRule" xsi:type="string">us_illinois_tax_rule</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">226.50</item> - </data> - <data name="payment/method" xsi:type="string">braintree_paypal</data> - <data name="configData" xsi:type="string">braintree, braintree_paypal, braintree_paypal_skip_order_review</data> - <data name="orderButtonsAvailable" xsi:type="string">Back, Send Email, Credit Memo, Hold, Ship, Reorder</data> - <data name="order/data/invoice/dataset" xsi:type="string">partial_capture_one_item</data> - <data name="order/data/price/dataset" xsi:type="string">captured_and_grand_invoice_price_118.25</data> - <data name="status" xsi:type="string">Processing</data> - <data name="transactions/Capture" xsi:type="array"> - <item name="transactionType" xsi:type="string">Capture</item> - <item name="statusIsClosed" xsi:type="string">No</item> - </data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S0</data> - <constraint name="Magento\Sales\Test\Constraint\AssertInvoiceSuccessCreateMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderButtonsAvailable" /> - <constraint name="Magento\Sales\Test\Constraint\AssertCaptureInCommentsHistory" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertInvoiceInInvoicesGrid" /> - <constraint name="Magento\Sales\Test\Constraint\AssertTransactionStatus" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutAcceptPaymentTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutAcceptPaymentTest.php deleted file mode 100644 index 80f24116a1ec4..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutAcceptPaymentTest.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * Preconditions: - * 1. Order is placed with Braintree Credit Card from Storefront with Advanced Fraud Protection. - * - * Steps: - * 1. Log in to Admin. - * 2. Go to Sales > Orders page. - * 3. Open the placed order. - * 4. Click Accept button. - * 5. Perform assertions. - * - * @group Braintree - * @ZephyrId MAGETWO-56023 - */ -class OnePageCheckoutAcceptPaymentTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = 'acceptance_test, 3rd_party_test'; - const SEVERITY = 'S2'; - /* end tags */ - - /** - * Runs one page checkout test. - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutAcceptPaymentTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutAcceptPaymentTest.xml deleted file mode 100644 index b9e7177b015ea..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutAcceptPaymentTest.xml +++ /dev/null @@ -1,53 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Braintree\Test\TestCase\OnePageCheckoutAcceptPaymentTest" summary="One page checkout with Braintree payment method."> - <variation name="OnePageCheckoutBraintreeAcceptPaymentVariation1" summary="Guest Checkout with Braintree Credit Card with Review Kount status" ticketId="MAGETWO-56023"> - <data name="products" xsi:type="array"> - <item name="0" xsi:type="string">catalogProductSimple::product_10_dollar</item> - </data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree,braintree_fraudprotection</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S2</data> - <constraint name="Magento\Sales\Test\Constraint\AssertAcceptPaymentSuccessMessagePresent" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertAcceptPaymentMessageInCommentsHistory" /> - </variation> - <variation name="OnePageCheckoutBraintreeAcceptPaymentVariation2" summary="Guest Checkout with Braintree Credit Card (Sale payment aciton) with Review Kount status" ticketId="MAGETWO-56023"> - <data name="products" xsi:type="array"> - <item name="0" xsi:type="string">catalogProductSimple::product_10_dollar</item> - </data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree,braintree_sale,braintree_fraudprotection</data> - <data name="status" xsi:type="string">Processing</data> - <data name="prices" xsi:type="array"> - <item name="totalPaid" xsi:type="string">15.00</item> - </data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S2</data> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderTotalPaid" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDeclinedTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDeclinedTest.xml deleted file mode 100644 index 62ff35448938f..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDeclinedTest.xml +++ /dev/null @@ -1,76 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Checkout\Test\TestCase\OnePageCheckoutDeclinedTest" summary="Error message during OnePageCheckout"> - <variation name="OnePageCheckoutBraintreeDeclinedTestVariation1" summary="Registered Checkout with Braintree Credit Card from Storefront with Advanced Fraud Protection failed" ticketId="MAGETWO-46469"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_braintree_fraud_rejected</data> - <data name="expectedErrorMessage" xsi:type="string">Transaction has been declined. Please try again later.</data> - <data name="configData" xsi:type="string">braintree_fraud_tool_enabled_account, braintree_fraudprotection</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertCheckoutErrorMessage" /> - <constraint name="Magento\Customer\Test\Constraint\AssertCustomerDoesNotHaveDefaultAddresses" /> - </variation> - <variation name="OnePageCheckoutBraintreeDeclinedTestVariation2" summary="Checkout with Braintree Credit Card configured with incorrect credentials" ticketId="MAGETWO-46244"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="expectedErrorMessage" xsi:type="string">Sorry, but something went wrong</data> - <data name="configData" xsi:type="string">braintree, braintree_incorrect_merchant_account_id</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertCheckoutErrorMessage" /> - </variation> - <variation name="OnePageCheckoutBraintreeDeclinedTestVariation3" summary="Checkout with Braintree Credit Card with specific allowed credit card types" ticketId="MAGETWO-38400"> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">mastercard_default</data> - <data name="expectedErrorMessages/cc_number" xsi:type="string">Please, enter valid Credit Card Number</data> - <data name="configData" xsi:type="string">braintree, braintree_cctypes_AE_VI</data> - <constraint name="Magento\Braintree\Test\Constraint\AssertCreditCardJsValidationMessagesArePresent" /> - </variation> - <variation name="OnePageCheckoutBraintreeDeclinedTestVariation4" summary="Checkout with Braintree Credit Card with specific allowed credit card types per country" ticketId="MAGETWO-38438"> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">customer_UK_1_default_billing_address</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">mastercard_default</data> - <data name="expectedErrorMessages/cc_number" xsi:type="string">Please, enter valid Credit Card Number</data> - <data name="configData" xsi:type="string">braintree, braintree_countrycreditcard_US_MS_GB_VI</data> - <constraint name="Magento\Braintree\Test\Constraint\AssertCreditCardJsValidationMessagesArePresent" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDenyPaymentTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDenyPaymentTest.php deleted file mode 100644 index 09739feb49750..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDenyPaymentTest.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * Preconditions: - * 1. Order is placed with Braintree Credit Card from Storefront with Advanced Fraud Protection. - * - * Steps: - * 1. Log in to Admin. - * 2. Go to Sales > Orders page. - * 3. Open the placed order. - * 4. Click Deny button. - * 5. Perform assertions. - * - * @group Braintree - * @ZephyrId MAGETWO-56024 - */ -class OnePageCheckoutDenyPaymentTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = 'acceptance_test, 3rd_party_test'; - const SEVERITY = 'S2'; - /* end tags */ - - /** - * Runs one page checkout test. - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDenyPaymentTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDenyPaymentTest.xml deleted file mode 100644 index 0fc675305e7fa..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutDenyPaymentTest.xml +++ /dev/null @@ -1,31 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Braintree\Test\TestCase\OnePageCheckoutDenyPaymentTest" summary="One page checkout with Braintree payment method."> - <variation name="OnePageCheckoutBraintreeDenyPaymentVariation1" summary="Registered Checkout with Braintree Credit Card with Review Kount status" ticketId="MAGETWO-56024"> - <data name="products" xsi:type="array"> - <item name="0" xsi:type="string">catalogProductSimple::product_10_dollar</item> - </data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree,braintree_fraudprotection</data> - <data name="status" xsi:type="string">Canceled</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S2</data> - <constraint name="Magento\Sales\Test\Constraint\AssertDenyPaymentSuccessMessagePresent" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertDenyPaymentMessageInCommentsHistory" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutFromMiniShoppingCartTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutFromMiniShoppingCartTest.xml deleted file mode 100644 index 83457f0aecd63..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutFromMiniShoppingCartTest.xml +++ /dev/null @@ -1,66 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Checkout\Test\TestCase\OnePageCheckoutFromMiniShoppingCartTest" summary="One page check out with Braintree payment method from mini shopping cart."> - <variation name="OnePageCheckoutFromMiniShoppingCartBraintreeTestVariation1" summary="Registered Checkout with Braintree Credit Card from Storefront with virtual quote and CVV Verification = No" ticketId="MAGETWO-38399"> - <data name="products/0" xsi:type="string">catalogProductVirtual::product_50_dollar</data> - <data name="customer/dataset" xsi:type="string">johndoe_with_addresses</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_braintree_no_cvv</data> - <data name="configData" xsi:type="string">braintree, braintree_paypal_skip_order_review, braintree_cvv_disabled</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - </variation> - <variation name="OnePageCheckoutFromMiniShoppingCartBraintreeTestVariation2" summary="Checkout with Braintree Credit Card with specific allowed credit card types" ticketId="MAGETWO-38400"> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree, braintree_cctypes_AE_VI</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - </variation> - <variation name="OnePageCheckoutFromMiniShoppingCartBraintreeTestVariation3" summary="Checkout with Braintree Credit Card with specific allowed countries" ticketId="MAGETWO-38437"> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">UK_address_without_email</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree, braintree_specific_country_GB</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - </variation> - <variation name="OnePageCheckoutFromMiniShoppingCartBraintreeTestVariation4" summary="Checkout with Braintree Credit Card with specific allowed credit card types per country" ticketId="MAGETWO-38438"> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">customer_UK_1_default_billing_address</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree, braintree_countrycreditcard_US_MS_GB_VI</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutTest.xml deleted file mode 100644 index e899eac7b98c7..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutTest.xml +++ /dev/null @@ -1,128 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Checkout\Test\TestCase\OnePageCheckoutTest" summary="One page check out with Braintree payment method."> - <variation name="OnePageCheckoutBraintree3dSecureNotTriggeredThresholdTestVariation1" summary="Registered Checkout with Braintree Credit Card from Storefront with 3D Secure verification not triggered due to Threshold Amount" ticketId="MAGETWO-46763"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="products/1" xsi:type="string">configurableProduct::with_one_option</data> - <data name="products/2" xsi:type="string">bundleProduct::bundle_fixed_100_dollar_product</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="taxRule" xsi:type="string">us_ca_ny_rule</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">145.98</item> - </data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_braintree_3dsecure</data> - <data name="isVaultPresent" xsi:type="boolean">false</data> - <data name="configData" xsi:type="string">braintree, braintree_3d_secure_not_triggered_due_threshold</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - </variation> - <variation name="OnePageCheckoutBraintree3dSecureNotTriggeredSpecificCountryTestVariation2" summary="Guest Checkout with Braintree Credit Card from Storefront with 3D Secure verification not triggered due to selected Specific Country" ticketId="MAGETWO-46488"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="products/1" xsi:type="string">configurableProduct::with_one_option</data> - <data name="products/2" xsi:type="string">bundleProduct::bundle_fixed_100_dollar_product</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="taxRule" xsi:type="string">us_ca_ny_rule</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">145.98</item> - </data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_braintree_3dsecure</data> - <data name="isVaultPresent" xsi:type="boolean">false</data> - <data name="configData" xsi:type="string">braintree, braintree_3d_secure_uk</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - </variation> - <variation name="OnePageCheckoutBraintreeTestVariation3" summary="Checkout with Braintree Credit Card from Storefront (Payment Action = Authorize)" ticketId="MAGETWO-38313"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="products/1" xsi:type="string">configurableProduct::with_one_option</data> - <data name="products/2" xsi:type="string">bundleProduct::bundle_fixed_100_dollar_product</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="taxRule" xsi:type="string">us_ca_ny_rule</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">145.98</item> - </data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="isVaultPresent" xsi:type="boolean">false</data> - <data name="configData" xsi:type="string">braintree</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:extended_acceptance_test, test_type:3rd_party_test, severity:S0</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertAuthorizationInCommentsHistory" /> - </variation> - <variation name="OnePageCheckoutBraintreeTestVariation4" summary="Checkout with Braintree for payment action Authorize and Capture" ticketId="MAGETWO-59403"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="products/1" xsi:type="string">configurableProduct::with_one_option</data> - <data name="products/2" xsi:type="string">bundleProduct::bundle_fixed_100_dollar_product</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="taxRule" xsi:type="string">us_ca_ny_rule</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">145.98</item> - </data> - <data name="order/data/price/dataset" xsi:type="string">captured_price_145.98</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="isVaultPresent" xsi:type="boolean">false</data> - <data name="configData" xsi:type="string">braintree, braintree_sale</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S0</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertCaptureInCommentsHistory" /> - </variation> - <variation name="OnePageCheckoutBraintreeTestVariation5" summary="Registered Checkout with Braintree Credit Card from Storefront with Advanced Fraud Protection" ticketId="MAGETWO-38721"> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree_fraud_tool_enabled_account, braintree_fraudprotection</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Braintree\Test\Constraint\AssertDeviceDataIsPresentInBraintreeRequest" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureFailedTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureFailedTest.php deleted file mode 100644 index 70c206333723f..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureFailedTest.php +++ /dev/null @@ -1,49 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * Preconditions: - * 1. Configure payment method. - * 2. Create products. - * - * Steps: - * 1. Log in Storefront. - * 2. Add products to the Shopping Cart. - * 5. Click the 'Proceed to Checkout' button. - * 6. Fill shipping information. - * 7. Select shipping method. - * 8. Select payment method. - * 9. Verify order total on review step. - * 10. Click 'Place Order' button. - * 11. Specify password in 3D Secure popup. - * 12. Click 'Submit'. - * 13. Perform assertions. - * - * @group Braintree - * @ZephyrId MAGETWO-46477 - */ -class OnePageCheckoutWith3dSecureFailedTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = '3rd_party_test'; - const SEVERITY = 'S1'; - /* end tags */ - - /** - * Verifies error message on Onepage Checkout if 3d secure validation is failed. - * - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureFailedTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureFailedTest.xml deleted file mode 100644 index 012bf56838170..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureFailedTest.xml +++ /dev/null @@ -1,28 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Braintree\Test\TestCase\OnePageCheckoutWith3dSecureFailedTest" summary="Onepage checkout with Braintree payment method with 3D Secure enabled."> - <variation name="OnePageCheckoutBraintree3dSecureFailedTestVariation1" summary="Guest Checkout with Braintree Credit Card from Storefront with 3D Secure verification failed" ticketId="MAGETWO-46477"> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_braintree_3dsecure_failed</data> - <data name="secure3d/dataset" xsi:type="string">secure3d_braintree</data> - <data name="configData" xsi:type="string">braintree, braintree_3d_secure</data> - <data name="expectedErrorMessage" xsi:type="string">Please try again with another form of payment.</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertCheckoutErrorMessage" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureTest.php deleted file mode 100644 index 81bd615893087..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureTest.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * Preconditions: - * 1. Configure shipping method. - * 2. Configure payment method. - * 3. Create products. - * 4. Create and setup customer. - * 5. Create sales rule according to dataset. - * - * Steps: - * 1. Log in Storefront. - * 2. Add products to the Shopping Cart. - * 3. Apply discounts in Shopping Cart according to dataset. - * 4. In 'Estimate Shipping and Tax' section specify destination using values from Test Data. - * 5. Click the 'Proceed to Checkout' button. - * 6. Fill shipping information. - * 7. Select shipping method. - * 8. Select payment method (use reward points and store credit if available). - * 9. Verify order total on review step. - * 10. Click 'Place Order' button. - * 11. Specify password in 3D Secure popup. - * 12. Click 'Submit' to place order. - * 13. Perform assertions. - * - * @group Braintree - * @ZephyrId MAGETWO-46479 - */ -class OnePageCheckoutWith3dSecureTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = '3rd_party_test'; - const SEVERITY = 'S1'; - /* end tags */ - - /** - * Runs one page checkout test. - * - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureTest.xml deleted file mode 100644 index 68ff8a390b3c7..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWith3dSecureTest.xml +++ /dev/null @@ -1,41 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Braintree\Test\TestCase\OnePageCheckoutWith3dSecureTest" summary="One page check out with Braintree payment method with 3D Secure enabled."> - <variation name="OnePageCheckoutBraintree3dSecureTestVariation1" summary="Registered Checkout with Braintree Credit Card from Storefront with success 3D Secure verification" ticketId="MAGETWO-46479"> - <data name="description" xsi:type="string">Registered Checkout with Braintree Credit Card from Storefront with success 3D Secure verification</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="products/1" xsi:type="string">configurableProduct::with_one_option</data> - <data name="products/2" xsi:type="string">bundleProduct::bundle_fixed_100_dollar_product</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="taxRule" xsi:type="string">us_ca_ny_rule</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">145.98</item> - </data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_braintree_3dsecure</data> - <data name="paymentInformation" xsi:type="array"> - <item name="Liability Shifted" xsi:type="string">1</item> - <item name="Liability Shift Possible" xsi:type="string">1</item> - </data> - <data name="secure3d/dataset" xsi:type="string">secure3d_braintree</data> - <data name="configData" xsi:type="string">braintree, braintree_3d_secure</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Braintree\Test\Constraint\Assert3dSecureInfoIsPresent" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithBraintreePaypalTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithBraintreePaypalTest.php deleted file mode 100644 index da8d0e803b770..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithBraintreePaypalTest.php +++ /dev/null @@ -1,52 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * Preconditions: - * 1. Configure shipping method. - * 2. Configure payment method. - * 3. Create products. - * 4. Create and setup customer. - * 5. Create sales rule according to dataset. - * - * Steps: - * 1. Log in Storefront. - * 2. Add products to the Shopping Cart. - * 3. In 'Estimate Shipping and Tax' section specify destination using values from Test Data. - * 4. Click the 'Proceed to Checkout' button. - * 5. Fill shipping information. - * 6. Select shipping method. - * 8. Select payment method - * 9. Verify order total on review step. - * 10. Click 'Continue to PayPal' button. - * 11. Click 'Proceed purchase' in popup. - * 12. Perform assertions. - * - * @group Braintree - * @ZephyrId MAGETWO-47805 - * @ZephyrId MAGETWO-47810 - */ -class OnePageCheckoutWithBraintreePaypalTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = '3rd_party_test'; - const SEVERITY = 'S0'; - /* end tags */ - - /** - * Runs one page checkout test. - * - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithBraintreePaypalTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithBraintreePaypalTest.xml deleted file mode 100644 index 2d7ae548d14ee..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithBraintreePaypalTest.xml +++ /dev/null @@ -1,68 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Braintree\Test\TestCase\OnePageCheckoutWithBraintreePaypalTest" summary="One page checkout with Braintree PayPal."> - <variation name="OnePageCheckoutWithBraintreePaypalTestVariation1" summary="Registered Checkout with Braintree PayPal from Storefront" ticketId="MAGETWO-47805"> - <data name="description" xsi:type="string">Registered Checkout with Braintree PayPal from Storefront</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">15.00</item> - </data> - <data name="payment/method" xsi:type="string">braintree_paypal</data> - <data name="configData" xsi:type="string">braintree, braintree_paypal, braintree_paypal_skip_order_review</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S0</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertAuthorizationInCommentsHistory" /> - </variation> - <variation name="OnePageCheckoutWithBraintreePaypalTestVariation2" summary="Registered Checkout with Braintree PayPal from Storefront with payment action Authorize and Capture" ticketId="MAGETWO-47810"> - <data name="description" xsi:type="string">Registered Checkout with Braintree PayPal from Storefront with payment action Authorize and Capture</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">15.00</item> - </data> - <data name="order/data/price/dataset" xsi:type="string">captured_price_15.00</data> - <data name="payment/method" xsi:type="string">braintree_paypal</data> - <data name="configData" xsi:type="string">braintree, braintree_paypal, braintree_paypal_sale, braintree_paypal_skip_order_review</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S0</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertCaptureInCommentsHistory" /> - </variation> - <variation name="OnePageCheckoutWithBraintreePaypalTestVariation3" summary="Guest Checkout virtual quote with Braintree PayPal from Cart" ticketId="MAGETWO-41559"> - <data name="products/0" xsi:type="string">catalogProductVirtual::product_50_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">50.00</item> - </data> - <data name="payment/method" xsi:type="string">braintree_paypal</data> - <data name="configData" xsi:type="string">braintree, braintree_paypal, braintree_paypal_skip_order_review</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S2</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertAuthorizationInCommentsHistory" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithDiscountTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithDiscountTest.xml deleted file mode 100644 index 614375627f908..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/OnePageCheckoutWithDiscountTest.xml +++ /dev/null @@ -1,55 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\SalesRule\Test\TestCase\OnePageCheckoutWithDiscountTest" summary="Checkout with Braintree credit card on Storefront with discount applied during checkout"> - <variation name="OnePageCheckoutWithDiscountTestVariation1" summary="Checkout with Braintree credit card on Storefront with discount applied during checkout" ticketId="MAGETWO-55319"> - <data name="description" xsi:type="string">Use saved for Braintree credit card on checkout</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="salesRule" xsi:type="string">active_sales_rule_for_all_groups</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">10.00</item> - </data> - <data name="creditCardSave" xsi:type="string">Yes</data> - <data name="configData" xsi:type="string">braintree, braintree_use_vault</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - </variation> - <variation name="OnePageCheckoutWithDiscountTestVariation2" summary="Checkout with 100% discount and free shipping if Braintree through PayPal is enabled" ticketId="MAGETWO-59940"> - <data name="description" xsi:type="string">Use saved for Braintree credit card on checkout</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="salesRule" xsi:type="string">active_sales_rule_with_fixed_price_discount_coupon</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Free Shipping</data> - <data name="shipping/shipping_method" xsi:type="string">Free</data> - <data name="payment/method" xsi:type="string">free</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">0.00</item> - </data> - <data name="configData" xsi:type="string">braintree, braintree_use_vault, freeshipping</data> - <data name="status" xsi:type="string">Pending</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderGrandTotal" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/ReorderUsingVaultTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/ReorderUsingVaultTest.xml deleted file mode 100644 index 7f15a6ba03f15..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/ReorderUsingVaultTest.xml +++ /dev/null @@ -1,35 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Vault\Test\TestCase\ReorderUsingVaultTest" summary="Reorder from Admin with saved within Braintree credit card"> - <variation name="ReorderUsingVaultBraintreeTestVariation1" summary="Reorder from Admin with saved within Braintree credit card for Guest Customer" ticketId="MAGETWO-54869, MAGETWO-54870"> - <data name="description" xsi:type="string">Reorder from Admin with saved within Braintree credit card for Guest Customer</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">15.00</item> - </data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="vault/method" xsi:type="string">braintree_cc_vault</data> - <data name="isVaultPresent" xsi:type="boolean">false</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree, braintree_use_vault</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">severity:S1</data> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderSuccessCreateMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertAuthorizationInCommentsHistory" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/SaveUseDeleteVaultForPaypalBraintreeTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/SaveUseDeleteVaultForPaypalBraintreeTest.php deleted file mode 100644 index aaab2534d23a1..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/SaveUseDeleteVaultForPaypalBraintreeTest.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * Preconditions: - * 1. Configure shipping method. - * 2. Configure payment method. - * 3. Create products. - * 4. Create and setup customer. - * - * Steps: - * 1. Go to Storefront as registered customer. - * 2. Add products to the cart. - * 3. Click the *Proceed to Checkout* button. - * 4. Select shipping method. - * 5. Select payment method (use reward points and store credit if available). - * 6. Select *Save for later use* checkbox. - * 7. Click *Continue to PayPal* button. - * 8. Click *Proceed with Sandbox Purchase* button. - * 9. Click Place Order button. - * 8. Add products to the cart. - * 9. Click the *Proceed to Checkout* button. - * 10. Select shipping method. - * 11. Select PayPal payer account as a payment. - * 12. Click Place Order button. - * 13. Go to *My Account > Stored Payment Methods* section. - * 14. Click *Delete* link next to stored PayPal payer account. - * 15. Click *Delete* button on appeared pop up. - * 16. Perform assertions. * - * - * @group Braintree - * @ZephyrId MAGETWO-54838, MAGETWO-54843, MAGETWO-54844" - */ -class SaveUseDeleteVaultForPaypalBraintreeTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = '3rd_party_test'; - const SEVERITY = 'S0'; - /* end tags */ - - /** - * Saves vault for PayPal Braintree on checkout, uses it during checkout, deletes it from My Account. - * - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/SaveUseDeleteVaultForPaypalBraintreeTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/SaveUseDeleteVaultForPaypalBraintreeTest.xml deleted file mode 100644 index 9c12fbf83b241..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/SaveUseDeleteVaultForPaypalBraintreeTest.xml +++ /dev/null @@ -1,30 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Braintree\Test\TestCase\SaveUseDeleteVaultForPaypalBraintreeTest" summary="Saves vault for PayPal Braintree on checkout, uses it during checkout, deletes it from My Account"> - <variation name="SaveUseDeleteVaultForPaypalBraintreeTestVariation1" summary="Saves vault for PayPal Braintree on checkout, uses it during checkout, deletes it from My Account" ticketId="MAGETWO-54838, MAGETWO-54843, MAGETWO-54844"> - <data name="description" xsi:type="string">Use saved for Braintree credit card on checkout</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="prices" xsi:type="array"> - <item name="grandTotal" xsi:type="string">15.00</item> - </data> - <data name="payment/method" xsi:type="string">braintree_paypal</data> - <data name="vault/method" xsi:type="string">braintree_paypal_vault</data> - <data name="creditCardSave" xsi:type="string">Yes</data> - <data name="configData" xsi:type="string">braintree, braintree_paypal, braintree_paypal_use_vault</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S0</data> - <constraint name="Magento\Vault\Test\Constraint\AssertStoredPaymentDeletedMessage" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultOnCheckoutTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultOnCheckoutTest.xml deleted file mode 100644 index c28e790e091a0..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultOnCheckoutTest.xml +++ /dev/null @@ -1,33 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Vault\Test\TestCase\UseVaultOnCheckoutTest" summary="Use saved for Braintree credit card on checkout."> - <variation name="UseVaultOnCheckoutBraintreeTestVariation1" summary="Use saved for Braintree credit card on checkout" ticketId="MAGETWO-46530, MAGETWO-38382"> - <data name="description" xsi:type="string">Use saved for Braintree credit card on checkout</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="vault/method" xsi:type="string">braintree_cc_vault</data> - <data name="creditCard/dataset" xsi:type="string">visa_default</data> - <data name="creditCard/data/payment_code" xsi:type="string">braintree</data> - <data name="creditCardSave" xsi:type="string">Yes</data> - <data name="configData" xsi:type="string">braintree, braintree_use_vault</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S0</data> - <data name="orderButtonsAvailable" xsi:type="string">Back, Cancel, Send Email, Hold, Invoice, Ship, Reorder, Edit</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderButtonsAvailable" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultWith3dSecureOnCheckoutTest.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultWith3dSecureOnCheckoutTest.php deleted file mode 100644 index 0651b137252f1..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultWith3dSecureOnCheckoutTest.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Test\TestCase; - -use Magento\Mtf\TestCase\Scenario; - -/** - * Preconditions: - * 1. Configure shipping method. - * 2. Configure payment method. - * 3. Create products. - * 4. Create and setup customer. - * 5. Configure taxes. - * - * Steps: - * 1. Log in Storefront. - * 2. Add products to the cart. - * 3. Click the 'Proceed to Checkout' button. - * 4. Select shipping method. - * 5. Select payment method (use reward points and store credit if available). - * 6. Enter credit card data and select *Save credit card* checkbox. - * 7. Click Place Order button. - * 8. Specify password in 3D Secure popup. - * 9. Click 'Submit' to place order. - * 10. Add products to the cart. - * 11. Click the 'Proceed to Checkout' button. - * 12. Select shipping method. - * 13. Select saved credit card as a payment. - * 14. Click Place Order button. - * 15. Specify password in 3D Secure popup. - * 16. Click 'Submit' to place order. - * 17. Perform assertions. - * - * @group One_Page_Checkout - * @ZephyrId MAGETWO-55310 - */ -class UseVaultWith3dSecureOnCheckoutTest extends Scenario -{ - /* tags */ - const MVP = 'yes'; - const TEST_TYPE = '3rd_party_test'; - const SEVERITY = 'S1'; - /* end tags */ - - /** - * Runs one page checkout test. - * - * @return void - */ - public function test() - { - $this->executeScenario(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultWith3dSecureOnCheckoutTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultWith3dSecureOnCheckoutTest.xml deleted file mode 100644 index d6f2e1e57932d..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/UseVaultWith3dSecureOnCheckoutTest.xml +++ /dev/null @@ -1,38 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Braintree\Test\TestCase\UseVaultWith3dSecureOnCheckoutTest" summary="Use saved for Braintree Credit card with 3D secure enabled."> - <variation name="UseVaultWith3dSecureOnCheckoutTestVariation1" summary="Use saved for Braintree credit card on checkout with 3D Secure" ticketId="MAGETWO-55310"> - <data name="description" xsi:type="string">Use saved for Braintree credit card on checkout</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">login</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="vault/method" xsi:type="string">braintree_cc_vault</data> - <data name="creditCard/dataset" xsi:type="string">visa_braintree_3dsecure</data> - <data name="paymentInformation" xsi:type="array"> - <item name="Liability Shifted" xsi:type="string">1</item> - <item name="Liability Shift Possible" xsi:type="string">1</item> - </data> - <data name="secure3d/dataset" xsi:type="string">secure3d_braintree</data> - <data name="creditCardSave" xsi:type="string">Yes</data> - <data name="configData" xsi:type="string">braintree, braintree_use_vault, braintree_3d_secure</data> - <data name="status" xsi:type="string">Processing</data> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <data name="orderButtonsAvailable" xsi:type="string">Back, Cancel, Send Email, Hold, Invoice, Ship</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertOrderSuccessPlacedMessage" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderStatusIsCorrect" /> - <constraint name="Magento\Sales\Test\Constraint\AssertOrderButtonsAvailable" /> - <constraint name="Magento\Braintree\Test\Constraint\Assert3dSecureInfoIsPresent" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/VerifyPaymentMethodOnCheckoutTest.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/VerifyPaymentMethodOnCheckoutTest.xml deleted file mode 100644 index 23c7d69b69ce1..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestCase/VerifyPaymentMethodOnCheckoutTest.xml +++ /dev/null @@ -1,24 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Checkout\Test\TestCase\VerifyPaymentMethodOnCheckoutTest" summary="Verifies payment method availability on One Page Checkout"> - <variation name="VerifyPaymentMethodOnCheckoutBraintreeTestVariation1" summary="Checkout with Braintree Credit Card with specific allowed countries" ticketId="MAGETWO-38437"> - <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> - <data name="products/0" xsi:type="string">catalogProductSimple::product_10_dollar</data> - <data name="customer/dataset" xsi:type="string">default</data> - <data name="shippingAddress/dataset" xsi:type="string">US_address_1_without_email</data> - <data name="checkoutMethod" xsi:type="string">guest</data> - <data name="shipping/shipping_service" xsi:type="string">Flat Rate</data> - <data name="shipping/shipping_method" xsi:type="string">Fixed</data> - <data name="payment/method" xsi:type="string">braintree</data> - <data name="paymentForm" xsi:type="string">braintree</data> - <data name="configData" xsi:type="string">braintree, braintree_specific_country_GB</data> - <constraint name="Magento\Checkout\Test\Constraint\AssertPaymentMethodIsAbsentOnPaymentPage" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/ChangeOrderStatusToPaymentReviewStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/ChangeOrderStatusToPaymentReviewStep.php deleted file mode 100644 index df6673b011606..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/ChangeOrderStatusToPaymentReviewStep.php +++ /dev/null @@ -1,84 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\TestStep; - -use Magento\Mtf\TestStep\TestStepInterface; -use Magento\Mtf\Util\Protocol\CurlTransport\WebapiDecorator; - -/** - * Class ChangeOrderStatusToPaymentReviewStep - * - * This step changes order status via WEB API to "Payment Review", because Kount service always - * return "Review" status for sandbox transactions. - */ -class ChangeOrderStatusToPaymentReviewStep implements TestStepInterface -{ - /** - * @var string - */ - private $orderId; - - /** - * @var WebapiDecorator - */ - private $webApi; - - /** - * ChangeOrderStatusToPaymentReviewStep constructor. - * @param $orderId - * @param WebapiDecorator $webApi - */ - public function __construct($orderId, WebapiDecorator $webApi) - { - $this->orderId = $orderId; - $this->webApi = $webApi; - } - - /** - * @inheritdoc - */ - public function run() - { - $order = $this->getOrder($this->orderId); - $order['state'] = 'payment_review'; - $order['status'] = 'fraud'; - $this->saveOrder($order); - } - - /** - * Get order by increment id - * @param string $incrementId - * @return array - */ - private function getOrder($incrementId) - { - $url = $_ENV['app_frontend_url'] . 'rest/V1/orders/'; - $url .= '?searchCriteria[filterGroups][0][filters][0][field]=increment_id'; - $url .= '&searchCriteria[filterGroups][0][filters][0][value]=' . $incrementId; - $this->webApi->write($url, [], WebapiDecorator::GET); - $response = json_decode($this->webApi->read(), true); - $this->webApi->close(); - return $response['items'][0]; - } - - /** - * Update order entity - * @param array $order - * @throws \Exception - */ - private function saveOrder(array $order) - { - $url = $_ENV['app_frontend_url'] . 'rest/V1/orders'; - // web api doesn't allow to save payment additional information - unset($order['payment']['additional_information']); - $this->webApi->write($url, ['entity' => $order], WebapiDecorator::POST); - $response = json_decode($this->webApi->read(), true); - $this->webApi->close(); - if (empty($response['entity_id'])) { - throw new \Exception('Couldn\'t update order details'); - } - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CheckBraintreeConfigStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CheckBraintreeConfigStep.php deleted file mode 100644 index 204223d0cff4f..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CheckBraintreeConfigStep.php +++ /dev/null @@ -1,145 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Test\TestStep; - -use Magento\Backend\Test\Page\Adminhtml\SystemConfigEditSectionPayment; -use Magento\Mtf\TestStep\TestStepInterface; -use Magento\Payment\Test\Constraint\AssertFieldsAreActive; -use Magento\Payment\Test\Constraint\AssertFieldsAreDisabled; -use Magento\Payment\Test\Constraint\AssertFieldsAreEnabled; -use Magento\Payment\Test\Constraint\AssertFieldsArePresent; - -/** - * Check configuration of Braintree payment method. - */ -class CheckBraintreeConfigStep implements TestStepInterface -{ - /** - * Payments configuration page. - * - * @var SystemConfigEditSectionPayment - */ - private $systemConfigEditSectionPayment; - - /** - * @var AssertFieldsAreDisabled - */ - private $assertFieldsAreDisabled; - - /** - * @var AssertFieldsArePresent - */ - private $assertFieldsArePresent; - - /** - * @var AssertFieldsAreActive - */ - private $assertFieldsAreActive; - - /** - * @var AssertFieldsAreEnabled - */ - private $assertFieldsAreEnabled; - - /** - * Country code. - * - * @var string - */ - private $countryCode; - - /** - * Payment sections on Payments configuration page. - * - * @var array - */ - private $sections; - - /** - * @var \Magento\Braintree\Test\Block\System\Config\Braintree - */ - private $braintreeConfigBlock; - - /** - * @param SystemConfigEditSectionPayment $systemConfigEditSectionPayment - * @param AssertFieldsAreDisabled $assertFieldsAreDisabled - * @param AssertFieldsArePresent $assertFieldsArePresent - * @param AssertFieldsAreActive $assertFieldsAreActive - * @param AssertFieldsAreEnabled $assertFieldsAreEnabled - * @param string $countryCode - * @param array $sections - */ - public function __construct( - SystemConfigEditSectionPayment $systemConfigEditSectionPayment, - AssertFieldsAreDisabled $assertFieldsAreDisabled, - AssertFieldsArePresent $assertFieldsArePresent, - AssertFieldsAreActive $assertFieldsAreActive, - AssertFieldsAreEnabled $assertFieldsAreEnabled, - $countryCode, - array $sections - ) { - $this->systemConfigEditSectionPayment = $systemConfigEditSectionPayment; - $this->assertFieldsAreDisabled = $assertFieldsAreDisabled; - $this->assertFieldsArePresent = $assertFieldsArePresent; - $this->assertFieldsAreActive = $assertFieldsAreActive; - $this->assertFieldsAreEnabled = $assertFieldsAreEnabled; - $this->countryCode = $countryCode; - $this->sections = $sections; - $this->braintreeConfigBlock = $this->systemConfigEditSectionPayment->getBraintreeConfigBlock(); - } - - /** - * Run step for checking Braintree configuration. - * - * @return void - */ - public function run() - { - $this->systemConfigEditSectionPayment->getPaymentsConfigBlock()->expandPaymentSections($this->sections); - $this->enableBraintree(); - $this->disableBraintree(); - } - - /** - * Enables Braintree and makes assertions for fields. - * - * @return void - */ - private function enableBraintree() - { - $this->braintreeConfigBlock->clickConfigureButton(); - $this->braintreeConfigBlock->clearCredentials(); - $enablers = $this->braintreeConfigBlock->getEnablerFields(); - $this->assertFieldsAreDisabled->processAssert($this->systemConfigEditSectionPayment, $enablers); - $this->braintreeConfigBlock->specifyCredentials(); - $this->assertFieldsAreActive->processAssert($this->systemConfigEditSectionPayment, $enablers); - $this->braintreeConfigBlock->enableBraintree(); - $this->assertFieldsAreActive->processAssert($this->systemConfigEditSectionPayment, $enablers); - $this->systemConfigEditSectionPayment->getPageActions()->save(); - $this->systemConfigEditSectionPayment->getMessagesBlock()->waitSuccessMessage(); - } - - /** - * Disables Express Checkout and makes assertions for fields. - * - * @return void - */ - private function disableBraintree() - { - $enablers = $this->braintreeConfigBlock->getEnablerFields(); - $this->braintreeConfigBlock->clickConfigureButton(); - $this->assertFieldsAreActive->processAssert($this->systemConfigEditSectionPayment, $enablers); - $this->assertFieldsAreEnabled->processAssert( - $this->systemConfigEditSectionPayment, - [$enablers['Enable this Solution']] - ); - $this->braintreeConfigBlock->disableBraintree(); - $this->assertFieldsAreActive->processAssert($this->systemConfigEditSectionPayment, $enablers); - $this->systemConfigEditSectionPayment->getPageActions()->save(); - $this->systemConfigEditSectionPayment->getMessagesBlock()->waitSuccessMessage(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CheckoutWithPaypalFromCartStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CheckoutWithPaypalFromCartStep.php deleted file mode 100644 index 4c45ca4db772c..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CheckoutWithPaypalFromCartStep.php +++ /dev/null @@ -1,46 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\TestStep; - -use Magento\Mtf\TestStep\TestStepInterface; -use Magento\Checkout\Test\Page\CheckoutCart; - -/** - * Checkout with Braintree PayPal from Shopping Cart. - */ -class CheckoutWithPaypalFromCartStep implements TestStepInterface -{ - /** - * Shopping Cart page. - * - * @var CheckoutCart - */ - protected $checkoutCart; - - /** - * @constructor - * @param CheckoutCart $checkoutCart - */ - public function __construct(CheckoutCart $checkoutCart) - { - $this->checkoutCart = $checkoutCart; - } - - /** - * Checkout with Braintree PayPal from Shopping Cart. - * - * @return void - */ - public function run() - { - $this->checkoutCart->open(); - $this->checkoutCart->getTotalsBlock()->waitForShippingPriceBlock(); - $this->checkoutCart->getTotalsBlock()->waitForUpdatedTotals(); - $currentWindow = $this->checkoutCart->getCartBlock() - ->braintreePaypalCheckout(); - $this->checkoutCart->getBraintreePaypalBlock()->process($currentWindow); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CheckoutWithPaypalFromMinicartStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CheckoutWithPaypalFromMinicartStep.php deleted file mode 100644 index 6136f488f280e..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/CheckoutWithPaypalFromMinicartStep.php +++ /dev/null @@ -1,67 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\TestStep; - -use Magento\Mtf\Client\BrowserInterface; -use Magento\Mtf\Fixture\FixtureInterface; -use Magento\Mtf\TestStep\TestStepInterface; -use Magento\Catalog\Test\Page\Product\CatalogProductView; - -/** - * Class CheckoutWithPaypalFromMinicartStep - */ -class CheckoutWithPaypalFromMinicartStep implements TestStepInterface -{ - /** - * Product fixture. - * - * @var FixtureInterface[] - */ - protected $products; - - /** - * Catalog product view frontend page. - * - * @var CatalogProductView - */ - protected $catalogProductView; - - /** - * Browser. - * - * @var BrowserInterface - */ - protected $browser; - - /** - * @constructor - * @param CatalogProductView $catalogProductView - * @param BrowserInterface $browser - * @param array $products - */ - public function __construct( - CatalogProductView $catalogProductView, - BrowserInterface $browser, - array $products - ) { - $this->catalogProductView = $catalogProductView; - $this->browser = $browser; - $this->products = $products; - } - - /** - * Open product on frontend and click Checkout with PayPal button. - * - * @return void - */ - public function run() - { - $product = reset($this->products); - $this->browser->open($_ENV['app_frontend_url'] . $product->getUrlKey() . '.html'); - $parentWindow = $this->catalogProductView->getViewBlock()->braintreePaypalCheckout(); - $this->catalogProductView->getBraintreePaypalBlock()->process($parentWindow); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/ContinueToPaypalStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/ContinueToPaypalStep.php deleted file mode 100644 index 0572ac1e27acc..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/ContinueToPaypalStep.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\TestStep; - -use Magento\Checkout\Test\Page\CheckoutOnepage; -use Magento\Mtf\TestStep\TestStepInterface; - -/** - * Proceeds with checkout on PayPal side. - */ -class ContinueToPaypalStep implements TestStepInterface -{ - /** - * @var CheckoutOnepage - */ - private $checkoutOnepage; - - /** - * @param CheckoutOnepage $checkoutOnepage - */ - public function __construct( - CheckoutOnepage $checkoutOnepage - ) { - $this->checkoutOnepage = $checkoutOnepage; - } - - /** - * Clicks Continue to PayPal button, proceeds with checkout on PayPal side. - */ - public function run() - { - $parentWindow = $this->checkoutOnepage->getPaymentBlock() - ->getSelectedPaymentMethodBlock() - ->clickContinueToPaypal(); - $this->checkoutOnepage->getBraintreePaypalBlock()->process($parentWindow); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/PlaceOrderWith3dSecureFailedStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/PlaceOrderWith3dSecureFailedStep.php deleted file mode 100644 index 0a9e27e7e30b6..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/PlaceOrderWith3dSecureFailedStep.php +++ /dev/null @@ -1,55 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Test\TestStep; - -use Magento\Checkout\Test\Page\CheckoutOnepage; -use Magento\Mtf\TestStep\TestStepInterface; -use Magento\Braintree\Test\Fixture\Secure3dBraintree; - -/** - * Click 'Place order' button and submit 3D secure verification step. - */ -class PlaceOrderWith3dSecureFailedStep implements TestStepInterface -{ - /** - * Onepage checkout page. - * - * @var CheckoutOnepage - */ - private $checkoutOnepage; - - /** - * 3D Secure fixture. - * - * @var Secure3dBraintree - */ - private $secure3d; - - /** - * @param CheckoutOnepage $checkoutOnepage - * @param Secure3dBraintree $secure3d - */ - public function __construct( - CheckoutOnepage $checkoutOnepage, - Secure3dBraintree $secure3d - ) { - $this->checkoutOnepage = $checkoutOnepage; - $this->secure3d = $secure3d; - } - - /** - * Click 'Place order' button and submit 3D secure verification. - * - * @return array - */ - public function run() - { - $this->checkoutOnepage->getPaymentBlock()->getSelectedPaymentMethodBlock()->clickPlaceOrder(); - - $this->checkoutOnepage->getBraintree3dSecureBlock()->fill($this->secure3d); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/PlaceOrderWith3dSecureStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/PlaceOrderWith3dSecureStep.php deleted file mode 100644 index 19d6756aab41a..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/PlaceOrderWith3dSecureStep.php +++ /dev/null @@ -1,92 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Test\TestStep; - -use Magento\Checkout\Test\Constraint\AssertGrandTotalOrderReview; -use Magento\Checkout\Test\Page\CheckoutOnepage; -use Magento\Checkout\Test\Page\CheckoutOnepageSuccess; -use Magento\Mtf\TestStep\TestStepInterface; -use Magento\Braintree\Test\Fixture\Secure3dBraintree; - -/** - * Place order with 3D Secure step. - */ -class PlaceOrderWith3dSecureStep implements TestStepInterface -{ - /** - * Onepage checkout page. - * - * @var CheckoutOnepage - */ - protected $checkoutOnepage; - - /** - * 3D Secure fixture. - * - * @var Secure3dBraintree - */ - private $secure3d; - - /** - * Assert that Order Grand Total is correct on checkout page review block. - * - * @var AssertGrandTotalOrderReview - */ - private $assertGrandTotalOrderReview; - - /** - * One page checkout success page. - * - * @var CheckoutOnepageSuccess - */ - private $checkoutOnepageSuccess; - - /** - * Price array. - * - * @var array - */ - private $prices; - - /** - * @constructor - * @param CheckoutOnepage $checkoutOnepage - * @param AssertGrandTotalOrderReview $assertGrandTotalOrderReview - * @param CheckoutOnepageSuccess $checkoutOnepageSuccess - * @param Secure3dBraintree $secure3d - * @param array $prices - */ - public function __construct( - CheckoutOnepage $checkoutOnepage, - AssertGrandTotalOrderReview $assertGrandTotalOrderReview, - CheckoutOnepageSuccess $checkoutOnepageSuccess, - Secure3dBraintree $secure3d, - array $prices = [] - ) { - $this->checkoutOnepage = $checkoutOnepage; - $this->secure3d = $secure3d; - $this->assertGrandTotalOrderReview = $assertGrandTotalOrderReview; - $this->checkoutOnepageSuccess = $checkoutOnepageSuccess; - $this->prices = $prices; - } - - /** - * Place order after checking order totals and passing 3D Secure on review step. - * - * @return array - */ - public function run() - { - if (isset($this->prices['grandTotal'])) { - $this->assertGrandTotalOrderReview->processAssert($this->checkoutOnepage, $this->prices['grandTotal']); - } - $this->checkoutOnepage->getPaymentBlock()->getSelectedPaymentMethodBlock()->clickPlaceOrder(); - - $this->checkoutOnepage->getBraintree3dSecureBlock()->fill($this->secure3d); - return ['orderId' => $this->checkoutOnepageSuccess->getSuccessBlock()->getGuestOrderId()]; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/PlaceOrderWithPaypalStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/PlaceOrderWithPaypalStep.php deleted file mode 100644 index 83276ab17c406..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/PlaceOrderWithPaypalStep.php +++ /dev/null @@ -1,138 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\TestStep; - -use Magento\Checkout\Test\Constraint\AssertGrandTotalOrderReview; -use Magento\Checkout\Test\Constraint\AssertBillingAddressAbsentInPayment; -use Magento\Checkout\Test\Page\CheckoutOnepage; -use Magento\Checkout\Test\Page\CheckoutOnepageSuccess; -use Magento\Mtf\Fixture\FixtureFactory; -use Magento\Mtf\TestStep\TestStepInterface; -use Magento\Sales\Test\Fixture\OrderInjectable; - -/** - * Place order with Paypal in one page checkout. - */ -class PlaceOrderWithPaypalStep implements TestStepInterface -{ - /** - * Onepage checkout page. - * - * @var CheckoutOnepage - */ - private $checkoutOnepage; - - /** - * Assert that Order Grand Total is correct on checkout page review block. - * - * @var AssertGrandTotalOrderReview - */ - private $assertGrandTotalOrderReview; - - /** - * Assert billing address is not present in selected payment method. - * - * @var AssertBillingAddressAbsentInPayment - */ - private $assertBillingAddressAbsentInPayment; - - /** - * One page checkout success page. - * - * @var CheckoutOnepageSuccess - */ - private $checkoutOnepageSuccess; - - /** - * Price array. - * - * @var array - */ - private $prices; - - /** - * Factory for fixtures. - * - * @var FixtureFactory - */ - private $fixtureFactory; - - /** - * Array of product entities. - * - * @var array - */ - private $products; - - /** - * Fixture OrderInjectable. - * - * @var OrderInjectable - */ - private $order; - - /** - * @param CheckoutOnepage $checkoutOnepage - * @param AssertGrandTotalOrderReview $assertGrandTotalOrderReview - * @param AssertBillingAddressAbsentInPayment $assertBillingAddressAbsentInPayment - * @param CheckoutOnepageSuccess $checkoutOnepageSuccess - * @param FixtureFactory $fixtureFactory - * @param array $products - * @param array $prices - * @param OrderInjectable|null $order - */ - public function __construct( - CheckoutOnepage $checkoutOnepage, - AssertGrandTotalOrderReview $assertGrandTotalOrderReview, - AssertBillingAddressAbsentInPayment $assertBillingAddressAbsentInPayment, - CheckoutOnepageSuccess $checkoutOnepageSuccess, - FixtureFactory $fixtureFactory, - array $products, - array $prices = [], - OrderInjectable $order = null - ) { - $this->checkoutOnepage = $checkoutOnepage; - $this->assertGrandTotalOrderReview = $assertGrandTotalOrderReview; - $this->assertBillingAddressAbsentInPayment = $assertBillingAddressAbsentInPayment; - $this->checkoutOnepageSuccess = $checkoutOnepageSuccess; - $this->fixtureFactory = $fixtureFactory; - $this->products = $products; - $this->prices = $prices; - $this->order = $order; - } - - /** - * Place order after checking order totals on review step. - * - * @return array - */ - public function run() - { - if (isset($this->prices['grandTotal'])) { - $this->assertGrandTotalOrderReview->processAssert($this->checkoutOnepage, $this->prices['grandTotal']); - } - - $this->assertBillingAddressAbsentInPayment->processAssert($this->checkoutOnepage); - - $parentWindow = $this->checkoutOnepage->getPaymentBlock() - ->getSelectedPaymentMethodBlock() - ->clickPayWithPaypal(); - $this->checkoutOnepage->getBraintreePaypalBlock()->process($parentWindow); - $data = [ - 'entity_id' => ['products' => $this->products] - ]; - $orderData = $this->order !== null ? $this->order->getData() : []; - $order = $this->fixtureFactory->createByCode( - 'orderInjectable', - ['data' => array_merge($data, $orderData)] - ); - - return [ - 'orderId' => $this->checkoutOnepageSuccess->getSuccessBlock()->getGuestOrderId(), - 'order' => $order - ]; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/SettleTransactionStep.php b/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/SettleTransactionStep.php deleted file mode 100644 index 0a0beeeb0a685..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/TestStep/SettleTransactionStep.php +++ /dev/null @@ -1,93 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Test\TestStep; - -use Magento\Braintree\Test\Fixture\BraintreeSandboxCustomer; -use Magento\Sales\Test\Page\Adminhtml\OrderIndex; -use Magento\Sales\Test\Page\Adminhtml\SalesOrderView; -use Magento\Mtf\ObjectManagerFactory; -use Braintree\Gateway; -use Magento\Mtf\TestStep\TestStepInterface; - -/** - * Settle transaction for Braintree Credit Card. - */ -class SettleTransactionStep implements TestStepInterface -{ - /** - * Braintree Sandbox customer fixture. - * - * @var BraintreeSandboxCustomer - */ - private $braintreeSandboxCustomer; - - /** - * Sales order page. - * - * @var OrderIndex - */ - private $salesOrder; - - /** - * Sales order view page. - * - * @var SalesOrderView - */ - private $salesOrderView; - - /** - * Order id. - * - * @var string - */ - private $orderId; - - /** - * @param BraintreeSandboxCustomer $braintreeSandboxCustomer - * @param OrderIndex $salesOrder - * @param SalesOrderView $salesOrderView - * @param string $orderId - */ - public function __construct( - BraintreeSandboxCustomer $braintreeSandboxCustomer, - OrderIndex $salesOrder, - SalesOrderView $salesOrderView, - $orderId - ) { - $this->braintreeSandboxCustomer = $braintreeSandboxCustomer; - $this->salesOrder = $salesOrder; - $this->salesOrderView = $salesOrderView; - $this->orderId = $orderId; - } - - /** - * Settle transaction for Braintree Credit Card. - * - * @return void - */ - public function run() - { - $credentials = $this->braintreeSandboxCustomer->getData(); - $gateway = ObjectManagerFactory::getObjectManager()->create(Gateway::class, ['config' => $credentials]); - $transactionId = $this->getTransactionId(); - $gateway->testing()->settle($transactionId); - } - - /** - * Get transaction id. - * - * @return string - */ - private function getTransactionId() - { - $this->salesOrder->open(); - $this->salesOrder->getSalesOrderGrid()->searchAndOpen(['id' => $this->orderId]); - $this->salesOrderView->getOrderForm()->openTab('transactions'); - $actualTransactions = $this->salesOrderView->getOrderForm()->getTab('transactions')->getGridBlock()->getIds(); - - return current(array_keys($actualTransactions)); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/etc/di.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/etc/di.xml deleted file mode 100644 index ad7b553378e8b..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/etc/di.xml +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> - <type name="Magento\Braintree\Test\Constraint\Assert3dSecureInfoIsPresent"> - <arguments> - <argument name="severity" xsi:type="string">S1</argument> - </arguments> - </type> - <type name="Magento\Braintree\Test\Constraint\AssertTransactionIsPresentInSettlementReport"> - <arguments> - <argument name="severity" xsi:type="string">S1</argument> - </arguments> - </type> - <type name="Magento\Braintree\Test\Constraint\AssertDeviceDataIsPresentInBraintreeRequest"> - <arguments> - <argument name="severity" xsi:type="string">S1</argument> - </arguments> - </type> - <type name="Magento\Braintree\Test\Constraint\AssertCreditCardJsValidationMessagesArePresent"> - <arguments> - <argument name="severity" xsi:type="string">S1</argument> - </arguments> - </type> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Braintree/Test/etc/testcase.xml b/dev/tests/functional/tests/app/Magento/Braintree/Test/etc/testcase.xml deleted file mode 100644 index c41f5ce026ce2..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Braintree/Test/etc/testcase.xml +++ /dev/null @@ -1,209 +0,0 @@ -<?xml version="1.0"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/Magento/Mtf/TestCase/etc/testcase.xsd"> - <scenario name="OnePageCheckoutWith3dSecureTest" firstStep="setupConfiguration"> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="createTaxRule" /> - <step name="createTaxRule" module="Magento_Tax" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="estimateShippingAndTax" /> - <step name="estimateShippingAndTax" module="Magento_Checkout" next="clickProceedToCheckout" /> - <step name="clickProceedToCheckout" module="Magento_Checkout" next="createCustomer" /> - <step name="createCustomer" module="Magento_Customer" next="selectCheckoutMethod" /> - <step name="selectCheckoutMethod" module="Magento_Checkout" next="fillShippingAddress" /> - <step name="fillShippingAddress" module="Magento_Checkout" next="fillShippingMethod" /> - <step name="fillShippingMethod" module="Magento_Checkout" next="selectPaymentMethod" /> - <step name="selectPaymentMethod" module="Magento_Checkout" next="fillBillingInformation" /> - <step name="fillBillingInformation" module="Magento_Checkout" next="placeOrderWith3dSecure" /> - <step name="placeOrderWith3dSecure" module="Magento_Braintree" /> - </scenario> - <scenario name="OnePageCheckoutWith3dSecureFailedTest" firstStep="setupConfiguration"> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="proceedToCheckout" /> - <step name="proceedToCheckout" module="Magento_Checkout" next="createCustomer" /> - <step name="createCustomer" module="Magento_Customer" next="selectCheckoutMethod" /> - <step name="selectCheckoutMethod" module="Magento_Checkout" next="fillShippingAddress" /> - <step name="fillShippingAddress" module="Magento_Checkout" next="fillShippingMethod" /> - <step name="fillShippingMethod" module="Magento_Checkout" next="selectPaymentMethod" /> - <step name="selectPaymentMethod" module="Magento_Checkout" next="fillBillingInformation" /> - <step name="fillBillingInformation" module="Magento_Checkout" next="placeOrderWith3dSecureFailed" /> - <step name="placeOrderWith3dSecureFailed" module="Magento_Braintree" /> - </scenario> - <scenario name="UseVaultWith3dSecureOnCheckoutTest" firstStep="setupConfiguration"> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="estimateShippingAndTax" /> - <step name="estimateShippingAndTax" module="Magento_Checkout" next="clickProceedToCheckout" /> - <step name="clickProceedToCheckout" module="Magento_Checkout" next="createCustomer" /> - <step name="createCustomer" module="Magento_Customer" next="selectCheckoutMethod" /> - <step name="selectCheckoutMethod" module="Magento_Checkout" next="fillShippingAddress" /> - <step name="fillShippingAddress" module="Magento_Checkout" next="fillShippingMethod" /> - <step name="fillShippingMethod" module="Magento_Checkout" next="selectPaymentMethod" /> - <step name="selectPaymentMethod" module="Magento_Checkout" next="saveCreditCard" /> - <step name="saveCreditCard" module="Magento_Vault" next="fillBillingInformation" /> - <step name="fillBillingInformation" module="Magento_Checkout" next="placeOrderWith3dSecure" /> - <step name="placeOrderWith3dSecure" module="Magento_Braintree" next="addProductsToTheCartVault" /> - <step name="addProductsToTheCartVault" alias="addProductsToTheCart" module="Magento_Checkout" next="estimateShippingAndTaxVault" /> - <step name="estimateShippingAndTaxVault" alias="estimateShippingAndTax" module="Magento_Checkout" next="clickProceedToCheckoutVault" /> - <step name="clickProceedToCheckoutVault" alias="clickProceedToCheckout" module="Magento_Checkout" next="fillShippingMethodVault" /> - <step name="fillShippingMethodVault" alias="fillShippingMethod" module="Magento_Checkout" next="useSavedPaymentMethod" /> - <step name="useSavedPaymentMethod" module="Magento_Vault" next="placeOrder3dSecureVault" /> - <step name="placeOrder3dSecureVault" alias="placeOrderWith3dSecure" module="Magento_Braintree" /> - </scenario> - <scenario name="OnePageCheckoutWithBraintreePaypalTest" firstStep="setupConfiguration"> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="estimateShippingAndTax" /> - <step name="estimateShippingAndTax" module="Magento_Checkout" next="clickProceedToCheckout" /> - <step name="clickProceedToCheckout" module="Magento_Checkout" next="createCustomer" /> - <step name="createCustomer" module="Magento_Customer" next="selectCheckoutMethod" /> - <step name="selectCheckoutMethod" module="Magento_Checkout" next="fillShippingAddress" /> - <step name="fillShippingAddress" module="Magento_Checkout" next="fillShippingMethod" /> - <step name="fillShippingMethod" module="Magento_Checkout" next="selectPaymentMethod" /> - <step name="selectPaymentMethod" module="Magento_Checkout" next="placeOrderWithPaypal" /> - <step name="placeOrderWithPaypal" module="Magento_Braintree" /> - </scenario> - <scenario name="CheckoutWithBraintreePaypalCartTest" firstStep="setupConfiguration"> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="checkoutWithPaypalFromCart" /> - <step name="checkoutWithPaypalFromCart" module="Magento_Braintree" next="expressCheckoutOrderPlace" /> - <step name="expressCheckoutOrderPlace" module="Magento_Paypal" /> - </scenario> - <scenario name="CheckoutWithBraintreePaypalMinicartTest" firstStep="setupConfiguration"> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="checkoutWithPaypalFromMinicart" /> - <step name="checkoutWithPaypalFromMinicart" module="Magento_Braintree" next="expressCheckoutOrderPlace" /> - <step name="expressCheckoutOrderPlace" module="Magento_Paypal" /> - </scenario> - <scenario name="BraintreeSettlementReportTest" firstStep="setupConfiguration"> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="estimateShippingAndTax" /> - <step name="estimateShippingAndTax" module="Magento_Checkout" next="clickProceedToCheckout" /> - <step name="clickProceedToCheckout" module="Magento_Checkout" next="createCustomer" /> - <step name="createCustomer" module="Magento_Customer" next="selectCheckoutMethod" /> - <step name="selectCheckoutMethod" module="Magento_Checkout" next="fillShippingAddress" /> - <step name="fillShippingAddress" module="Magento_Checkout" next="fillShippingMethod" /> - <step name="fillShippingMethod" module="Magento_Checkout" next="selectPaymentMethod" /> - <step name="selectPaymentMethod" module="Magento_Checkout" next="fillBillingInformation" /> - <step name="fillBillingInformation" module="Magento_Checkout" next="placeOrder" /> - <step name="placeOrder" module="Magento_Checkout" /> - </scenario> - <scenario name="InvoicePayPalBraintreeTest" firstStep="setupConfiguration"> - <step name="setupConfiguration" module="Magento_Config" next="createTaxRule" /> - <step name="createTaxRule" module="Magento_Tax" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="checkoutWithPaypalFromCart" /> - <step name="checkoutWithPaypalFromCart" module="Magento_Braintree" next="expressCheckoutOrderPlace" /> - <step name="expressCheckoutOrderPlace" module="Magento_Paypal" next="createInvoice" /> - <step name="createInvoice" module="Magento_Sales" /> - </scenario> - <scenario name="CreateOnlineCreditMemoBraintreePaypalTest" firstStep="setupConfiguration"> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="createTaxRule" /> - <step name="createTaxRule" module="Magento_Tax" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="estimateShippingAndTax" /> - <step name="estimateShippingAndTax" module="Magento_Checkout" next="clickProceedToCheckout" /> - <step name="clickProceedToCheckout" module="Magento_Checkout" next="createCustomer" /> - <step name="createCustomer" module="Magento_Customer" next="selectCheckoutMethod" /> - <step name="selectCheckoutMethod" module="Magento_Checkout" next="fillShippingAddress" /> - <step name="fillShippingAddress" module="Magento_Checkout" next="fillShippingMethod" /> - <step name="fillShippingMethod" module="Magento_Checkout" next="selectPaymentMethod" /> - <step name="selectPaymentMethod" module="Magento_Checkout" next="fillBillingInformation" /> - <step name="fillBillingInformation" module="Magento_Checkout" next="placeOrderWithPaypal" /> - <step name="placeOrderWithPaypal" module="Magento_Braintree" next="createInvoice" /> - <step name="createInvoice" module="Magento_Sales" next="createOnlineCreditMemo" /> - <step name="createOnlineCreditMemo" module="Magento_Sales" /> - </scenario> - <scenario name="SaveUseDeleteVaultForPaypalBraintreeTest" firstStep="setupConfiguration"> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="estimateShippingAndTax" /> - <step name="estimateShippingAndTax" module="Magento_Checkout" next="clickProceedToCheckout" /> - <step name="clickProceedToCheckout" module="Magento_Checkout" next="createCustomer" /> - <step name="createCustomer" module="Magento_Customer" next="selectCheckoutMethod" /> - <step name="selectCheckoutMethod" module="Magento_Checkout" next="fillShippingAddress" /> - <step name="fillShippingAddress" module="Magento_Checkout" next="fillShippingMethod" /> - <step name="fillShippingMethod" module="Magento_Checkout" next="selectPaymentMethod" /> - <step name="selectPaymentMethod" module="Magento_Checkout" next="continueToPaypal" /> - <step name="continueToPaypal" module="Magento_Braintree" next="placeOrder" /> - <step name="placeOrder" module="Magento_Checkout" next="addProductsToTheCartVault" /> - <step name="addProductsToTheCartVault" alias="addProductsToTheCart" module="Magento_Checkout" next="estimateShippingAndTaxVault" /> - <step name="estimateShippingAndTaxVault" alias="estimateShippingAndTax" module="Magento_Checkout" next="clickProceedToCheckoutVault" /> - <step name="clickProceedToCheckoutVault" alias="clickProceedToCheckout" module="Magento_Checkout" next="fillShippingMethodVault" /> - <step name="fillShippingMethodVault" alias="fillShippingMethod" module="Magento_Checkout" next="useSavedPaymentMethod" /> - <step name="useSavedPaymentMethod" module="Magento_Vault" next="placeOrderVault" /> - <step name="placeOrderVault" alias="placeOrder" module="Magento_Checkout" next="deleteStoredPayment" /> - <step name="deleteStoredPayment" module="Magento_Vault" /> - </scenario> - <scenario name="OnePageCheckoutAcceptPaymentTest" firstStep="setupConfiguration"> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="proceedToCheckout" /> - <step name="proceedToCheckout" module="Magento_Checkout" next="selectCheckoutMethod" /> - <step name="selectCheckoutMethod" module="Magento_Checkout" next="fillShippingAddress" /> - <step name="fillShippingAddress" module="Magento_Checkout" next="fillShippingMethod" /> - <step name="fillShippingMethod" module="Magento_Checkout" next="selectPaymentMethod" /> - <step name="selectPaymentMethod" module="Magento_Checkout" next="fillBillingInformation" /> - <step name="fillBillingInformation" module="Magento_Checkout" next="placeOrder" /> - <step name="placeOrder" module="Magento_Checkout" next="changeOrderStatusToPaymentReview" /> - <step name="changeOrderStatusToPaymentReview" module="Magento_Braintree" next="acceptPayment" /> - <step name="acceptPayment" module="Magento_Sales" /> - </scenario> - <scenario name="OnePageCheckoutDenyPaymentTest" firstStep="setupConfiguration"> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="proceedToCheckout" /> - <step name="proceedToCheckout" module="Magento_Checkout" next="selectCheckoutMethod" /> - <step name="selectCheckoutMethod" module="Magento_Checkout" next="fillShippingAddress" /> - <step name="fillShippingAddress" module="Magento_Checkout" next="fillShippingMethod" /> - <step name="fillShippingMethod" module="Magento_Checkout" next="selectPaymentMethod" /> - <step name="selectPaymentMethod" module="Magento_Checkout" next="fillBillingInformation" /> - <step name="fillBillingInformation" module="Magento_Checkout" next="placeOrder" /> - <step name="placeOrder" module="Magento_Checkout" next="changeOrderStatusToPaymentReview" /> - <step name="changeOrderStatusToPaymentReview" module="Magento_Braintree" next="denyPayment" /> - <step name="denyPayment" module="Magento_Sales" /> - </scenario> - <scenario name="CreateOrderWithPayPalBraintreeVaultBackendTest" firstStep="setupConfiguration"> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="estimateShippingAndTax" /> - <step name="estimateShippingAndTax" module="Magento_Checkout" next="clickProceedToCheckout" /> - <step name="clickProceedToCheckout" module="Magento_Checkout" next="createCustomer" /> - <step name="createCustomer" module="Magento_Customer" next="selectCheckoutMethod" /> - <step name="selectCheckoutMethod" module="Magento_Checkout" next="fillShippingAddress" /> - <step name="fillShippingAddress" module="Magento_Checkout" next="fillShippingMethod" /> - <step name="fillShippingMethod" module="Magento_Checkout" next="selectPaymentMethod" /> - <step name="selectPaymentMethod" module="Magento_Checkout" next="placeOrderWithPaypal" /> - <step name="placeOrderWithPaypal" module="Magento_Braintree" next="openOrder"/> - <step name="openOrder" module="Magento_Sales" next="reorder" /> - <step name="reorder" module="Magento_Sales" next="useVaultPaymentToken" /> - <step name="useVaultPaymentToken" module="Magento_Vault" next="submitOrder" /> - <step name="submitOrder" module="Magento_Sales" /> - </scenario> - <scenario name="CreateOnlineCreditMemoBraintreeTest" firstStep="setupConfiguration"> - <step name="setupConfiguration" module="Magento_Config" next="createProducts" /> - <step name="createProducts" module="Magento_Catalog" next="createTaxRule" /> - <step name="createTaxRule" module="Magento_Tax" next="addProductsToTheCart" /> - <step name="addProductsToTheCart" module="Magento_Checkout" next="estimateShippingAndTax" /> - <step name="estimateShippingAndTax" module="Magento_Checkout" next="clickProceedToCheckout" /> - <step name="clickProceedToCheckout" module="Magento_Checkout" next="createCustomer" /> - <step name="createCustomer" module="Magento_Customer" next="selectCheckoutMethod" /> - <step name="selectCheckoutMethod" module="Magento_Checkout" next="fillShippingAddress" /> - <step name="fillShippingAddress" module="Magento_Checkout" next="fillShippingMethod" /> - <step name="fillShippingMethod" module="Magento_Checkout" next="selectPaymentMethod" /> - <step name="selectPaymentMethod" module="Magento_Checkout" next="fillBillingInformation" /> - <step name="fillBillingInformation" module="Magento_Checkout" next="placeOrder" /> - <step name="placeOrder" module="Magento_Checkout" next="createInvoice" /> - <step name="createInvoice" module="Magento_Sales" next="settleTransaction" /> - <step name="settleTransaction" module="Magento_Braintree" next="createOnlineCreditMemo" /> - <step name="createOnlineCreditMemo" module="Magento_Sales" /> - </scenario> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Catalog/Test/Block/Product/View.php b/dev/tests/functional/tests/app/Magento/Catalog/Test/Block/Product/View.php index c4ac7f32a94bf..5ae13ce094fa2 100644 --- a/dev/tests/functional/tests/app/Magento/Catalog/Test/Block/Product/View.php +++ b/dev/tests/functional/tests/app/Magento/Catalog/Test/Block/Product/View.php @@ -387,19 +387,6 @@ public function inContextPaypalCheckout() $this->waitForElementNotVisible($this->inContextPaypalCheckout); } - /** - * Press 'Check out with Braintree PayPal' button. - * - * @return string - */ - public function braintreePaypalCheckout() - { - $currentWindow = $this->browser->getCurrentWindow(); - $this->getMiniCartBlock()->openMiniCart(); - $this->getMiniCartBlock()->clickBraintreePaypalButton(); - return $currentWindow; - } - /** * Get product name displayed on page. * diff --git a/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Cart.php b/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Cart.php index bbe6fe293ab50..c24de1865e3e4 100644 --- a/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Cart.php +++ b/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Cart.php @@ -64,13 +64,6 @@ class Cart extends Block */ protected $inContextPaypalCheckoutButton = 'ul.checkout-methods-items a[data-action="paypal-in-context-checkout"]'; - /** - * Locator value for "Check out with Braintree PayPal" button. - * - * @var string - */ - protected $braintreePaypalCheckoutButton = './/button[contains(@id, "braintree-paypal-mini-cart")]'; - /** * Locator value for "empty Shopping Cart" block. * @@ -163,19 +156,6 @@ public function getOnepageLinkBlock() ); } - /** - * Click "Check out with Braintree PayPal" button. - * - * @return string - */ - public function braintreePaypalCheckout() - { - $currentWindow = $this->browser->getCurrentWindow(); - $this->_rootElement->find($this->braintreePaypalCheckoutButton, Locator::SELECTOR_XPATH) - ->click(); - return $currentWindow; - } - /** * Click "Check out with PayPal" button. * diff --git a/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Cart/Sidebar.php b/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Cart/Sidebar.php index 18153c9e1ff01..e40fda9c75eb5 100644 --- a/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Cart/Sidebar.php +++ b/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Cart/Sidebar.php @@ -29,13 +29,6 @@ class Sidebar extends Block */ protected $cartLink = 'a.showcart'; - /** - * Locator value for "Check out with Braintree PayPal" button. - * - * @var string - */ - protected $braintreePaypalCheckoutButton = 'button[id^="braintree-paypal-mini-cart"]'; - /** * Locator value for "Proceed to Checkout" button. * @@ -120,27 +113,6 @@ public function openMiniCart() sleep(5); } - /** - * Click "Check out with Braintree PayPal" button. - * - * @return void - */ - public function clickBraintreePaypalButton() - { - // Button can be enabled/disabled few times. - sleep(3); - - $windowsCount = count($this->browser->getWindowHandles()); - $this->_rootElement->find($this->braintreePaypalCheckoutButton) - ->click(); - $browser = $this->browser; - $this->browser->waitUntil( - function () use ($browser, $windowsCount) { - return count($browser->getWindowHandles()) === ($windowsCount + 1) ? true: null; - } - ); - } - /** * Click "Proceed to Checkout" button. * diff --git a/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Onepage/Payment/Method.php b/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Onepage/Payment/Method.php index 09f643d2e72bb..ac12df884072c 100644 --- a/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Onepage/Payment/Method.php +++ b/dev/tests/functional/tests/app/Magento/Checkout/Test/Block/Onepage/Payment/Method.php @@ -42,20 +42,6 @@ class Method extends Block */ protected $preloaderSpinner = '#preloaderSpinner'; - /** - * Continue to PayPal button for Braintree. - * - * @var string - */ - protected $continueToBraintreePaypalButton = '#braintree_paypal_continue_to'; - - /** - * Pay with Paypal button for Braintree. - * - * @var string - */ - protected $payWithBraintreePaypalButton = '#braintree_paypal_pay_with'; - /** * Wait for PayPal page is loaded. * @@ -76,34 +62,6 @@ public function clickPlaceOrder() $this->_rootElement->find($this->placeOrderButton)->click(); $this->waitForElementNotVisible($this->waitElement); } - - /** - * Click Continue to Paypal button. - * - * @return string - */ - public function clickContinueToPaypal() - { - $currentWindow = $this->browser->getCurrentWindow(); - $this->waitForElementNotVisible($this->waitElement); - $this->_rootElement->find($this->continueToBraintreePaypalButton)->click(); - $this->waitForElementNotVisible($this->waitElement); - return $currentWindow; - } - - /** - * Click Pay with Paypal button. - * - * @return string - */ - public function clickPayWithPaypal() - { - $currentWindow = $this->browser->getCurrentWindow(); - $this->waitForElementNotVisible($this->waitElement); - $this->_rootElement->find($this->payWithBraintreePaypalButton)->click(); - $this->waitForElementNotVisible($this->waitElement); - return $currentWindow; - } /** * Click "Check out with PayPal" button. diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Block/CreateAdmin.php b/dev/tests/functional/tests/app/Magento/Install/Test/Block/CreateAdmin.php deleted file mode 100644 index df28ad2804258..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Block/CreateAdmin.php +++ /dev/null @@ -1,55 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Block; - -use Magento\Mtf\Block\Form; -use Magento\Mtf\Client\Element\SimpleElement; -use Magento\Mtf\Client\Locator; -use Magento\Mtf\Fixture\FixtureInterface; - -/** - * Create Admin Account block. - */ -class CreateAdmin extends Form -{ - /** - * 'Next' button. - * - * @var string - */ - protected $next = "[ng-click*='validateCredentials']"; - - /** - * First field selector - * - * @var string - */ - protected $firstField = '[name="adminUsername"]'; - - /** - * Click on 'Next' button. - * - * @return void - */ - public function clickNext() - { - $this->_rootElement->find($this->next, Locator::SELECTOR_CSS)->click(); - } - - /** - * Ensure the form is loaded and fill the root form - * - * @param FixtureInterface $fixture - * @param SimpleElement|null $element - * @return $this - */ - public function fill(FixtureInterface $fixture, SimpleElement $element = null) - { - $this->waitForElementVisible($this->firstField); - return parent::fill($fixture, $element); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Block/CreateAdmin.xml b/dev/tests/functional/tests/app/Magento/Install/Test/Block/CreateAdmin.xml deleted file mode 100644 index 40648d6d0dc7b..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Block/CreateAdmin.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<mapping strict="1"> - <fields> - <username> - <selector>[name='adminUsername']</selector> - </username> - <email> - <selector>[name='adminEmail']</selector> - </email> - <password> - <selector>[name='adminPassword']</selector> - </password> - <password_confirmation> - <selector>[name='adminConfirm']</selector> - </password_confirmation> - </fields> -</mapping> diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Block/CustomizeStore.php b/dev/tests/functional/tests/app/Magento/Install/Test/Block/CustomizeStore.php deleted file mode 100644 index 0a95180b98464..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Block/CustomizeStore.php +++ /dev/null @@ -1,65 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Block; - -use Magento\Mtf\Block\Form; -use Magento\Mtf\Client\Element\SimpleElement; -use Magento\Mtf\Client\Locator; -use Magento\Mtf\Fixture\FixtureInterface; - -/** - * Customize Your Store block. - */ -class CustomizeStore extends Form -{ - /** - * 'Next' button. - * - * @var string - */ - protected $next = "[ng-click*='checkModuleConstraints']"; - - /** - * Module configuration section. - * - * @var string - */ - protected $moduleConfiguration = '.customize-your-store-advanced'; - - /** - * Click on 'Next' button. - * - * @return void - */ - public function clickNext() - { - $this->_rootElement->find($this->next, Locator::SELECTOR_CSS)->click(); - } - - /** - * Ensure the form is loaded and fill the root form - * - * @param FixtureInterface $fixture - * @param SimpleElement|null $element - * @return $this - */ - public function fill(FixtureInterface $fixture, SimpleElement $element = null) - { - $this->waitForElementVisible($this->moduleConfiguration); - $data = $fixture->getData(); - $storeData = []; - foreach ($data as $key => $value) { - if (strpos($key, 'store') === 0) { - $storeData[$key] = $value; - } - } - $mapping = $this->dataMapping($storeData); - $this->_fill($mapping, $element); - - return $this; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Block/CustomizeStore.xml b/dev/tests/functional/tests/app/Magento/Install/Test/Block/CustomizeStore.xml deleted file mode 100644 index b07e0356b1378..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Block/CustomizeStore.xml +++ /dev/null @@ -1,19 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<mapping strict="0"> - <fields> - <storeCurrency> - <selector>#storeCurrency</selector> - <input>select</input> - </storeCurrency> - <storeLanguage> - <selector>#storeLanguage</selector> - <input>select</input> - </storeLanguage> - </fields> -</mapping> diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Block/Database.php b/dev/tests/functional/tests/app/Magento/Install/Test/Block/Database.php deleted file mode 100644 index ed0def5b02257..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Block/Database.php +++ /dev/null @@ -1,74 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Block; - -use Magento\Mtf\Block\Form; -use Magento\Mtf\Client\Locator; -use Magento\Mtf\Fixture\FixtureInterface; -use Magento\Mtf\Client\Element\SimpleElement; - -/** - * Database form. - */ -class Database extends Form -{ - /** - * 'Test connection successful.' message. - * - * @var string - */ - protected $successConnectionMessage = ".text-success"; - - /** - * 'Next' button. - * - * @var string - */ - protected $next = "[ng-click*='testConnection']"; - - /** - * Fill database form. - * - * @param FixtureInterface $fixture - * @param SimpleElement|null $element - * @return $this - */ - public function fill(FixtureInterface $fixture, SimpleElement $element = null) - { - $data = $fixture->getData(); - $dbData = []; - foreach ($data as $key => $value) { - if (strpos($key, 'db') === 0) { - $dbData[$key] = $value; - } - } - $mapping = $this->dataMapping($dbData); - $this->_fill($mapping, $element); - - return $this; - } - - /** - * Get 'Test connection successful.' message. - * - * @return string - */ - public function getSuccessConnectionMessage() - { - return $this->_rootElement->find($this->successConnectionMessage, Locator::SELECTOR_CSS)->getText(); - } - - /** - * Click on 'Next' button. - * - * @return void - */ - public function clickNext() - { - $this->_rootElement->find($this->next, Locator::SELECTOR_CSS)->click(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Block/Database.xml b/dev/tests/functional/tests/app/Magento/Install/Test/Block/Database.xml deleted file mode 100644 index 19fbed561171e..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Block/Database.xml +++ /dev/null @@ -1,18 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<mapping strict="0"> - <fields> - <dbHost /> - <dbUser /> - <dbPassword /> - <dbName> - <selector>[name="dbname"]</selector> - </dbName> - <dbTablePrefix /> - </fields> -</mapping> diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Block/Devdocs.php b/dev/tests/functional/tests/app/Magento/Install/Test/Block/Devdocs.php deleted file mode 100644 index 57b33583f6c4b..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Block/Devdocs.php +++ /dev/null @@ -1,32 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Block; - -use Magento\Mtf\Block\Block; - -/** - * Developer Documentation block. - */ -class Devdocs extends Block -{ - /** - * Developer Documentation title. - * - * @var string - */ - protected $devdocsTitle = '.page-heading'; - - /** - * Get Developer Documentation title text. - * - * @return string - */ - public function getDevdocsTitle() - { - return $this->_rootElement->find($this->devdocsTitle)->getText(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Block/Install.php b/dev/tests/functional/tests/app/Magento/Install/Test/Block/Install.php deleted file mode 100644 index bb2a218f38914..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Block/Install.php +++ /dev/null @@ -1,148 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Block; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; - -/** - * Install block. - */ -class Install extends Block -{ - /** - * 'Install Now' button. - * - * @var string - */ - protected $installNow = "//*[@ng-show='!isStarted']/button"; - - /** - * Admin info block. - * - * @var string - */ - protected $adminInfo = '#admin-info'; - - /** - * Database info block. - * - * @var string - */ - protected $dbInfo = '#db-info'; - - /** - * 'Launch Magento Admin' button. - * - * @var string - */ - protected $launchAdmin = '.btn-large.btn-prime'; - - /** - * Text for installation is completed. - * - * @var string - */ - private $successInstallText = "//p[contains(., 'Installing... 100%')]"; - - /** - * Click on 'Install Now' button. - * - * @return void - */ - public function clickInstallNow() - { - $this->_rootElement->find($this->installNow, Locator::SELECTOR_XPATH)->click(); - $this->waitSuccessInstall(); - } - - /** - * Get admin info. - * - * @return array - */ - public function getAdminInfo() - { - return $this->getTableDataByCssLocator($this->adminInfo); - } - - /** - * Get database info. - * - * @return array - */ - public function getDbInfo() - { - return $this->getTableDataByCssLocator($this->dbInfo); - } - - /** - * Get table data by correspondent div css selector. - * Data inside the table must be presented via <dt>/<dd>/<dl> tags due to actual HTML5 standard. - * - * @param string $selector - * @return array - */ - protected function getTableDataByCssLocator($selector) - { - $data = []; - $keys = []; - $definitionTitles = $this->_rootElement->getElements($selector . ' dt'); - foreach ($definitionTitles as $dt) { - $keys[] = strtolower(str_replace(' ', '_', str_replace(':', '', $dt->getText()))); - } - reset($keys); - - $definitionDescriptions = $this->_rootElement->getElements($selector . ' dd'); - foreach ($definitionDescriptions as $dd) { - $data[current($keys)] = $dd->getText(); - next($keys); - } - - return $data; - } - - /** - * Click on 'Launch Magento Admin' button. - * - * @return void - */ - public function clickLaunchAdmin() - { - $this->_rootElement->find($this->launchAdmin, Locator::SELECTOR_XPATH)->click(); - } - - /** - * Check that success install text is visible. - * - * @return bool - */ - public function isInstallationCompleted() - { - return $this->_rootElement->find($this->successInstallText, Locator::SELECTOR_XPATH)->isVisible(); - } - - /** - * Waiting for success install text. - * - * @return void - */ - private function waitSuccessInstall() - { - $root = $this->_rootElement; - $successInstallText = $this->successInstallText; - $launchAdmin = $this->launchAdmin; - - $root->waitUntil( - function () use ($root, $successInstallText, $launchAdmin) { - $isInstallText = $root->find($successInstallText, Locator::SELECTOR_XPATH)->isVisible(); - $isLaunchAdmin = $root->find($launchAdmin, Locator::SELECTOR_CSS)->isVisible(); - return $isInstallText == true || $isLaunchAdmin == true ? true : null; - } - ); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Block/Landing.php b/dev/tests/functional/tests/app/Magento/Install/Test/Block/Landing.php deleted file mode 100644 index 515c6c536e3da..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Block/Landing.php +++ /dev/null @@ -1,68 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Block; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; - -/** - * Landing block. - */ -class Landing extends Block -{ - /** - * Link by text. - * - * @var string - */ - protected $linkSelector = '//a[text()="%s"]'; - - /** - * 'Agree and Set up Magento' button. - * - * @var string - */ - protected $agreeAndSetup = '.btn-prime.btn-submit'; - - /** - * 'Terms & Agreement' link. - * - * @var string - */ - protected $termsAndAgreement = "[ng-click*='previous']"; - - /** - * Click on 'Agree and Set up Magento' button. - * - * @return void - */ - public function clickAgreeAndSetup() - { - $this->_rootElement->find($this->agreeAndSetup, Locator::SELECTOR_CSS)->click(); - } - - /** - * Click on 'Terms & Agreement' link. - * - * @return void - */ - public function clickTermsAndAgreement() - { - $this->_rootElement->find($this->termsAndAgreement, Locator::SELECTOR_CSS)->click(); - } - - /** - * Click on link. - * - * @param string $text - * @return void - */ - public function clickLink($text) - { - $this->_rootElement->find(sprintf($this->linkSelector, $text), Locator::SELECTOR_XPATH)->click(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Block/License.php b/dev/tests/functional/tests/app/Magento/Install/Test/Block/License.php deleted file mode 100644 index b45278316444b..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Block/License.php +++ /dev/null @@ -1,50 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Block; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; - -/** - * License block. - */ -class License extends Block -{ - /** - * 'Back' button. - * - * @var string - */ - protected $back = '[ng-click="nextState()"]'; - - /** - * License text. - * - * @var string - */ - protected $license = '.license-text'; - - /** - * Click on 'Back' button. - * - * @return void - */ - public function clickBack() - { - $this->_rootElement->find($this->back, Locator::SELECTOR_CSS)->click(); - } - - /** - * Get license text. - * - * @return string - */ - public function getLicense() - { - return $this->_rootElement->find($this->license, Locator::SELECTOR_CSS)->getText(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Block/Readiness.php b/dev/tests/functional/tests/app/Magento/Install/Test/Block/Readiness.php deleted file mode 100644 index 315cd7ce52b8e..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Block/Readiness.php +++ /dev/null @@ -1,109 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Block; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; - -/** - * Readiness block. - */ -class Readiness extends Block -{ - /** - * 'Start Readiness Check' button. - * - * @var string - */ - protected $readinessCheck = "[ng-click*='state.go']"; - - /** - * 'Next' button. - * - * @var string - */ - protected $next = "[ng-click*='next']"; - - /** - * 'Completed!' message. - * [ng-switch-when="true"] - * @var string - */ - protected $completedMessage = '[ng-switch-when="true"]'; - - /** - * PHP Version successful check. - * - * @var string - */ - protected $phpVersionCheck = '#php-version'; - - /** - * PHP Extensions successful check. - * - * @var string - */ - protected $phpExtensionCheck = '#php-extensions'; - - /** - * File Permission check. - * - * @var string - */ - protected $filePermissionCheck = '#php-permissions'; - - /** - * Click on 'Start Readiness Check' button. - * - * @return void - */ - public function clickReadinessCheck() - { - $this->_rootElement->find($this->readinessCheck, Locator::SELECTOR_CSS)->click(); - $this->waitForElementVisible($this->completedMessage, Locator::SELECTOR_CSS); - } - - /** - * Click on 'Next' button. - * - * @return void - */ - public function clickNext() - { - $this->_rootElement->find($this->next, Locator::SELECTOR_CSS)->click(); - } - - /** - * Get File Permissions check result. - * - * @return string - */ - public function getFilePermissionCheck() - { - return $this->_rootElement->find($this->filePermissionCheck, Locator::SELECTOR_CSS)->getText(); - } - - /** - * Get PHP Version check result. - * - * @return string - */ - public function getPhpVersionCheck() - { - return $this->_rootElement->find($this->phpVersionCheck, Locator::SELECTOR_CSS)->getText(); - } - - /** - * Get PHP Extensions check result. - * - * @return string - */ - public function getPhpExtensionsCheck() - { - return $this->_rootElement->find($this->phpExtensionCheck, Locator::SELECTOR_CSS)->getText(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Block/WebConfiguration.php b/dev/tests/functional/tests/app/Magento/Install/Test/Block/WebConfiguration.php deleted file mode 100644 index 1590dc43652ff..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Block/WebConfiguration.php +++ /dev/null @@ -1,95 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Block; - -use Magento\Mtf\Block\Form; -use Magento\Mtf\Fixture\FixtureInterface; -use Magento\Mtf\Client\Element\SimpleElement; -use Magento\Mtf\Client\Locator; - -/** - * Web configuration block. - */ -class WebConfiguration extends Form -{ - /** - * 'Next' button. - * - * @var string - */ - protected $next = "[ng-click*='validateUrl']"; - - /** - * 'Advanced Options' locator. - * - * @var string - */ - protected $advancedOptions = "[ng-click*='advanced']"; - - /** - * Admin URI check. - * - * @var string - */ - protected $adminUriCheck = '#admin'; - - /** - * 'Advanced Options' block locator. - * - * @var string - */ - protected $extendedConfig = '[ng-show="config.advanced.expanded"]'; - - /** - * Fill web configuration form. - * - * @param FixtureInterface $fixture - * @param SimpleElement|null $element - * @return $this - */ - public function fill(FixtureInterface $fixture, SimpleElement $element = null) - { - $data = $fixture->getData(); - $webConfiguration = []; - foreach ($data as $key => $value) { - if (strpos($key, 'db') !== 0 && strpos($key, 'store') !== 0) { - $webConfiguration[$key] = $value; - } - } - $mapping = $this->dataMapping($webConfiguration); - $this->_fill($mapping, $element); - - return $this; - } - - /** - * Click on 'Next' button. - * - * @return void - */ - public function clickNext() - { - $this->_rootElement->find($this->next)->click(); - } - - /** - * Click on 'Advanced Options' button. - * - * @return void - */ - public function clickAdvancedOptions() - { - if (!$this->_rootElement->find($this->extendedConfig)->isVisible()) { - $this->_rootElement->find($this->advancedOptions)->click(); - } - } - - public function getAdminUriCheck() - { - return $this->_rootElement->find($this->adminUriCheck)->getAttribute('ng-init'); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Block/WebConfiguration.xml b/dev/tests/functional/tests/app/Magento/Install/Test/Block/WebConfiguration.xml deleted file mode 100644 index f256c97ea71c2..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Block/WebConfiguration.xml +++ /dev/null @@ -1,35 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<mapping strict="0"> - <fields> - <baseUrl> - <selector>[name="base_url"]</selector> - </baseUrl> - <admin /> - <keyOwn> - <selector>[value="user"]</selector> - <input>radiobutton</input> - </keyOwn> - <keyValue> - <selector>[name="key"]</selector> - </keyValue> - <apacheRewrites> - <selector>[ng-model*="rewrites"]</selector> - <input>checkbox</input> - </apacheRewrites> - <httpsFront> - <selector>[ng-model*="front"]</selector> - <input>radiobutton</input> - </httpsFront> - <https /> - <httpsAdmin> - <selector>[type="checkbox"][ng-model*="admin"]</selector> - <input>radiobutton</input> - </httpsAdmin> - </fields> -</mapping> diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertAdminUriAutogenerated.php b/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertAdminUriAutogenerated.php deleted file mode 100644 index f59ff908cc175..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertAdminUriAutogenerated.php +++ /dev/null @@ -1,46 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Constraint; - -use Magento\Install\Test\Page\Install; -use Magento\Mtf\Constraint\AbstractConstraint; - -/** - * Check that default Admin URI is generated according to the pattern - */ -class AssertAdminUriAutogenerated extends AbstractConstraint -{ - /** - * Admin URI pattern. - */ - const ADMIN_URI_PATTERN = '/config\.address\.admin = \'admin_[a-z0-9]{1,6}/'; - - /** - * Assert that default Admin URI is generated according to the pattern. - * - * @param Install $installPage - * @return void - */ - public function processAssert(Install $installPage) - { - \PHPUnit\Framework\Assert::assertRegExp( - self::ADMIN_URI_PATTERN, - $installPage->getWebConfigBlock()->getAdminUriCheck(), - 'Unexpected Backend Frontname pattern.' - ); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Default Admin URI is OK."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertAgreementTextPresent.php b/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertAgreementTextPresent.php deleted file mode 100644 index 600e97a545cca..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertAgreementTextPresent.php +++ /dev/null @@ -1,60 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Constraint; - -use Magento\Install\Test\Page\Install; -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\TestFramework\Inspection\Exception; - -/** - * Check that agreement text present on Terms & Agreement page during install. - */ -class AssertAgreementTextPresent extends AbstractConstraint -{ - /** - * Part of Default license agreement text. - */ - const DEFAULT_LICENSE_AGREEMENT_TEXT = 'Open Software License ("OSL") v. 3.0'; - - /** - * Part of Default license agreement text. - */ - const LICENSE_AGREEMENT_TEXT = 'END USER LICENSE AGREEMENT'; - - /** - * Assert that part of license agreement text is present on Terms & Agreement page. - * - * @param Install $installPage - * @return void - */ - public function processAssert(Install $installPage) - { - try { - \PHPUnit\Framework\Assert::assertContains( - self::LICENSE_AGREEMENT_TEXT, - $installPage->getLicenseBlock()->getLicense(), - 'License agreement text is absent.' - ); - } catch (\Exception $e) { - \PHPUnit\Framework\Assert::assertContains( - self::DEFAULT_LICENSE_AGREEMENT_TEXT, - $installPage->getLicenseBlock()->getLicense(), - 'License agreement text is absent.' - ); - } - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "License agreement text is present on Terms & Agreement page."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertCurrencySelected.php b/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertCurrencySelected.php deleted file mode 100644 index 9e6eb0159e743..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertCurrencySelected.php +++ /dev/null @@ -1,41 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Constraint; - -use Magento\Backend\Test\Page\Adminhtml\Dashboard; -use Magento\Mtf\Constraint\AbstractConstraint; - -/** - * Assert that selected currency symbol displays in admin. - */ -class AssertCurrencySelected extends AbstractConstraint -{ - /** - * Assert that selected currency symbol displays on dashboard. - * - * @param string $currencySymbol - * @param Dashboard $dashboardPage - * @return void - */ - public function processAssert($currencySymbol, Dashboard $dashboardPage) - { - \PHPUnit\Framework\Assert::assertTrue( - strpos($dashboardPage->getMainBlock()->getRevenuePrice(), $currencySymbol) !== false, - 'Selected currency symbol not displays on dashboard.' - ); - } - - /** - * Returns a string representation of the object. - * - * @return string - */ - public function toString() - { - return 'Selected currency displays in admin.'; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertDevdocsLink.php b/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertDevdocsLink.php deleted file mode 100644 index 3e5dfe62d527c..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertDevdocsLink.php +++ /dev/null @@ -1,46 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Constraint; - -use Magento\Install\Test\Page\DevdocsInstall; -use Magento\Mtf\Constraint\AbstractConstraint; - -/** - * Check Developer Documentation link. - */ -class AssertDevdocsLink extends AbstractConstraint -{ - /** - * Developer Documentation title. - */ - const DEVDOCS_TITLE_TEXT = 'Setup Wizard installation'; - - /** - * Check Developer Documentation link. - * - * @param DevdocsInstall $devdocsInstallPage - * @return void - */ - public function processAssert(DevdocsInstall $devdocsInstallPage) - { - \PHPUnit\Framework\Assert::assertEquals( - self::DEVDOCS_TITLE_TEXT, - $devdocsInstallPage->getDevdocsBlock()->getDevdocsTitle(), - 'Developer Documentation link is wrong.' - ); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Developer Documentation link is correct."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertGenerationFilePathCheck.php b/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertGenerationFilePathCheck.php deleted file mode 100644 index 6afe876525f13..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertGenerationFilePathCheck.php +++ /dev/null @@ -1,64 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Install\Test\Constraint; - -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Mtf\Util\Command\PathChecker; - -/** - * Assert that path of generated files is correct. - */ -class AssertGenerationFilePathCheck extends AbstractConstraint -{ - /** - * Assert that path of generated files is correct. - * - * @param PathChecker $pathChecker - * @return void - */ - public function processAssert(PathChecker $pathChecker) - { - $existsPaths = [ - 'generated/code', - 'generated/metadata', - 'generated/metadata/global.ser', - 'generated/metadata/adminhtml.ser', - 'generated/metadata/crontab.ser', - 'generated/metadata/frontend.ser', - 'generated/metadata/webapi_rest.ser', - 'generated/metadata/webapi_soap.ser', - ]; - - $nonExistsPaths = [ - 'var/di', - 'var/generation' - ]; - - foreach ($existsPaths as $path) { - \PHPUnit\Framework\Assert::assertTrue( - $pathChecker->pathExists($path), - 'Path "' . $path . '" does not exist.' - ); - } - - foreach ($nonExistsPaths as $path) { - \PHPUnit\Framework\Assert::assertFalse( - $pathChecker->pathExists($path), - 'Path "' . $path . '" exists.' - ); - } - } - - /** - * Returns a string representation of the object. - * - * @return string - */ - public function toString() - { - return 'Path of generated files is correct.'; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertKeyCreated.php b/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertKeyCreated.php deleted file mode 100644 index cec2921b2c080..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertKeyCreated.php +++ /dev/null @@ -1,43 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Constraint; - -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Install\Test\Page\Install; -use Magento\Install\Test\Fixture\Install as InstallConfig; - -/** - * Assert that selected encryption key displays on success full install page. - */ -class AssertKeyCreated extends AbstractConstraint -{ - /** - * Assert that selected encryption key displays on success full install page. - * - * @param Install $installPage - * @param InstallConfig $installConfig - * @return void - */ - public function processAssert(Install $installPage, InstallConfig $installConfig) - { - \PHPUnit\Framework\Assert::assertEquals( - $installConfig->getKeyValue(), - $installPage->getInstallBlock()->getAdminInfo()['encryption_key'], - 'Selected encryption key on install page not equals to data from fixture.' - ); - } - - /** - * Returns a string representation of the object. - * - * @return string - */ - public function toString() - { - return 'Selected encryption key displays on success full install page.'; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertLanguageSelected.php b/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertLanguageSelected.php deleted file mode 100644 index 236b9805ea1c6..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertLanguageSelected.php +++ /dev/null @@ -1,42 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Constraint; - -use Magento\Cms\Test\Page\CmsIndex; -use Magento\Mtf\Constraint\AbstractConstraint; - -/** - * Assert that selected language currently displays on frontend. - */ -class AssertLanguageSelected extends AbstractConstraint -{ - /** - * Assert that selected language currently displays on frontend. - * - * @param string $languageTemplate - * @param CmsIndex $indexPage - * @return void - */ - public function processAssert($languageTemplate, CmsIndex $indexPage) - { - $indexPage->open(); - \PHPUnit\Framework\Assert::assertTrue( - $indexPage->getFooterBlock()->isLinkVisible($languageTemplate), - 'Selected language not displays on frontend.' - ); - } - - /** - * Returns a string representation of the object. - * - * @return string - */ - public function toString() - { - return 'Selected language currently displays on frontend.'; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertRewritesEnabled.php b/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertRewritesEnabled.php deleted file mode 100644 index ca6180fc97dd1..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertRewritesEnabled.php +++ /dev/null @@ -1,47 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Constraint; - -use Magento\Cms\Test\Page\CmsIndex; -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Mtf\Client\BrowserInterface; -use Magento\Catalog\Test\Fixture\Category; - -/** - * Assert that apache redirect correct works. - */ -class AssertRewritesEnabled extends AbstractConstraint -{ - /** - * Assert that apache redirect works by opening category page and asserting index.php in its url - * - * @param Category $category - * @param CmsIndex $homePage - * @param BrowserInterface $browser - */ - public function processAssert(Category $category, CmsIndex $homePage, BrowserInterface $browser) - { - $category->persist(); - $homePage->open(); - $homePage->getTopmenu()->selectCategoryByName($category->getName()); - - \PHPUnit\Framework\Assert::assertTrue( - strpos($browser->getUrl(), 'index.php') === false, - 'Apache redirect for category does not work.' - ); - } - - /** - * Returns a string representation of the object. - * - * @return string - */ - public function toString() - { - return 'Apache redirect works correct.'; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertSecureUrlEnabled.php b/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertSecureUrlEnabled.php deleted file mode 100644 index f5d029620a32b..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertSecureUrlEnabled.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Constraint; - -use Magento\Mtf\Client\BrowserInterface; -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Backend\Test\Page\Adminhtml\Dashboard; -use Magento\Customer\Test\Page\CustomerAccountLogin; - -/** - * Assert that Secure Urls Enabled. - */ -class AssertSecureUrlEnabled extends AbstractConstraint -{ - /* tags */ - const SEVERITY = 'low'; - /* end tags */ - - /** - * Assert that Secure Urls Enabled. - * - * @param BrowserInterface $browser - * @param Dashboard $dashboard - * @param CustomerAccountLogin $customerAccountLogin - * @return void - */ - public function processAssert( - BrowserInterface $browser, - Dashboard $dashboard, - CustomerAccountLogin $customerAccountLogin - ) { - $dashboard->open(); - \PHPUnit\Framework\Assert::assertTrue( - strpos($browser->getUrl(), 'https://') !== false, - 'Secure Url is not displayed on backend.' - ); - - $customerAccountLogin->open(); - \PHPUnit\Framework\Assert::assertTrue( - strpos($browser->getUrl(), 'https://') !== false, - 'Secure Url is not displayed on frontend.' - ); - } - - /** - * Returns a string representation of the object. - * - * @return string - */ - public function toString() - { - return 'Secure Urls are displayed successful.'; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertSuccessInstall.php b/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertSuccessInstall.php deleted file mode 100644 index 3f0c240834aad..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertSuccessInstall.php +++ /dev/null @@ -1,106 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Constraint; - -use Magento\User\Test\Fixture\User; -use Magento\Install\Test\Page\Install; -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Install\Test\Fixture\Install as InstallConfig; - -/** - * Check that Magento successfully installed. - */ -class AssertSuccessInstall extends AbstractConstraint -{ - /** - * Admin info fields mapping. - * - * @var array - */ - protected $adminFieldsList = [ - ['pageData' => 'username', 'fixture' => 'username'], - ['pageData' => 'email', 'fixture' => 'email'], - ['pageData' => 'your_store_address', 'fixture' => 'baseUrl'], - ['pageData' => 'magento_admin_address', 'fixture' => 'admin'] - ]; - - /** - * Database info fields mapping. - * - * @var array - */ - protected $dbFieldsList = [ - ['pageData' => 'database_name', 'fixture' => 'dbName'], - ['pageData' => 'username', 'fixture' => 'dbUser'] - ]; - - /** - * Assert that Magento successfully installed. - * - * @param InstallConfig $installConfig - * @param User $user - * @param Install $installPage - * @return void - */ - public function processAssert(Install $installPage, InstallConfig $installConfig, User $user) - { - //TODO Nginx server does't make redirect after installation (random fail) - sleep(5); - if ($installPage->getInstallBlock()->isInstallationCompleted()) { - return; - } - $adminData = $installPage->getInstallBlock()->getAdminInfo(); - $dbData = $installPage->getInstallBlock()->getDbInfo(); - - $allData = array_merge($user->getData(), $installConfig->getData()); - - foreach ($installConfig->getData() as $key => $value) { - $allData[$key] = isset($value['value']) ? $value['value'] : $value; - } - - $allData['baseUrl'] = (isset($allData['https']) ? $allData['https'] : $allData['baseUrl']); - $allData['admin'] = $allData['baseUrl'] . $allData['admin'] . '/'; - - $this->checkInstallData($allData, $adminData, $dbData); - } - - /** - * Check data on success installation page. - * - * @param array $allData - * @param array $adminData - * @param array $dbData - * @return void - */ - private function checkInstallData(array $allData, array $adminData, array $dbData) - { - foreach ($this->adminFieldsList as $field) { - \PHPUnit\Framework\Assert::assertEquals( - $allData[$field['fixture']], - $adminData[$field['pageData']], - 'Wrong admin information is displayed.' - ); - } - foreach ($this->dbFieldsList as $field) { - \PHPUnit\Framework\Assert::assertEquals( - $allData[$field['fixture']], - $dbData[$field['pageData']], - 'Wrong database information is displayed.' - ); - } - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Install successfully finished."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertSuccessfulReadinessCheck.php b/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertSuccessfulReadinessCheck.php deleted file mode 100644 index 2c3e74ef873b3..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Constraint/AssertSuccessfulReadinessCheck.php +++ /dev/null @@ -1,66 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\Constraint; - -use Magento\Install\Test\Page\Install; -use Magento\Mtf\Constraint\AbstractConstraint; - -/** - * Check that PHP Version, PHP Extensions and File Permission are ok. - */ -class AssertSuccessfulReadinessCheck extends AbstractConstraint -{ - /** - * PHP version message. - */ - const PHP_VERSION_MESSAGE = 'Your PHP version is correct'; - - /** - * PHP extensions message. - */ - const PHP_EXTENSIONS_REGEXP = '/You meet (\d+) out of \1 PHP extensions requirements\./'; - - /** - * File permission message. - */ - const FILE_PERMISSION_REGEXP = '/You meet (\d+) out of \1 writable file permission requirements\./'; - - /** - * Assert that PHP Version, PHP Extensions and File Permission are ok. - * - * @param Install $installPage - * @return void - */ - public function processAssert(Install $installPage) - { - \PHPUnit\Framework\Assert::assertContains( - self::PHP_VERSION_MESSAGE, - $installPage->getReadinessBlock()->getPhpVersionCheck(), - 'PHP version is incorrect.' - ); - \PHPUnit\Framework\Assert::assertRegExp( - self::PHP_EXTENSIONS_REGEXP, - $installPage->getReadinessBlock()->getPhpExtensionsCheck(), - 'PHP extensions missed.' - ); - \PHPUnit\Framework\Assert::assertRegExp( - self::FILE_PERMISSION_REGEXP, - $installPage->getReadinessBlock()->getFilePermissionCheck(), - 'File permissions does not meet requirements.' - ); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "PHP Version, PHP Extensions and File Permission are ok."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Fixture/Install.xml b/dev/tests/functional/tests/app/Magento/Install/Test/Fixture/Install.xml deleted file mode 100644 index 4712f3d5068a6..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Fixture/Install.xml +++ /dev/null @@ -1,36 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/fixture.xsd"> - <fixture name="install" - module="Magento_Install" - type="virtual" - entity_type="install" - repository_class="Magento\Install\Test\Repository\Install" - handler_interface="Magento\Install\Test\Handler\Install\InstallInterface" - class="Magento\Install\Test\Fixture\Install"> - <field name="dbHost" /> - <field name="dbUser" /> - <field name="dbPassword" /> - <field name="dbName" /> - <field name="dbTablePrefix" /> - <field name="baseUrl" /> - <field name="admin" /> - <field name="adminUsername" /> - <field name="adminEmail" /> - <field name="adminPassword" /> - <field name="adminConfirm" /> - <field name="apacheRewrites" /> - <field name="keyOwn" /> - <field name="httpsAdmin" /> - <field name="https" /> - <field name="httpsFront" /> - <field name="keyValue" /> - <field name="storeLanguage" /> - <field name="storeCurrency" /> - </fixture> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Page/DevdocsInstall.xml b/dev/tests/functional/tests/app/Magento/Install/Test/Page/DevdocsInstall.xml deleted file mode 100644 index 4a396e634443c..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Page/DevdocsInstall.xml +++ /dev/null @@ -1,12 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/pages.xsd"> - <page name="DevdocsInstall" mca="https://devdocs.magento.com/guides/v2.3/install-gde/install/web/install-web.html" module="Magento_Install"> - <block name="devdocsBlock" class="Magento\Install\Test\Block\Devdocs" locator="body" strategy="css selector"/> - </page> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/Page/Install.xml b/dev/tests/functional/tests/app/Magento/Install/Test/Page/Install.xml deleted file mode 100644 index 69b694078e430..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/Page/Install.xml +++ /dev/null @@ -1,19 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/pages.xsd"> - <page name="Install" mca="setup/" module="Magento_Install"> - <block name="landingBlock" class="Magento\Install\Test\Block\Landing" locator="body" strategy="css selector"/> - <block name="licenseBlock" class="Magento\Install\Test\Block\License" locator="body" strategy="css selector"/> - <block name="readinessBlock" class="Magento\Install\Test\Block\Readiness" locator="body" strategy="css selector"/> - <block name="databaseBlock" class="Magento\Install\Test\Block\Database" locator="body" strategy="css selector"/> - <block name="webConfigBlock" class="Magento\Install\Test\Block\WebConfiguration" locator="body" strategy="css selector"/> - <block name="customizeStoreBlock" class="Magento\Install\Test\Block\CustomizeStore" locator="body" strategy="css selector"/> - <block name="createAdminBlock" class="Magento\Install\Test\Block\CreateAdmin" locator="body" strategy="css selector"/> - <block name="installBlock" class="Magento\Install\Test\Block\Install" locator="body" strategy="css selector"/> - </page> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/TestCase/InstallTest.php b/dev/tests/functional/tests/app/Magento/Install/Test/TestCase/InstallTest.php deleted file mode 100644 index b219305a7be65..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/TestCase/InstallTest.php +++ /dev/null @@ -1,220 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Install\Test\TestCase; - -use Magento\Install\Test\Page\Install; -use Magento\Install\Test\Page\DevdocsInstall; -use Magento\Install\Test\Fixture\Install as InstallConfig; -use Magento\User\Test\Fixture\User; -use Magento\Mtf\Fixture\FixtureFactory; -use Magento\Mtf\TestCase\Injectable; -use Magento\Install\Test\Constraint\AssertAgreementTextPresent; -use Magento\Install\Test\Constraint\AssertSuccessfulReadinessCheck; -use Magento\Install\Test\Constraint\AssertAdminUriAutogenerated; -use Magento\Install\Test\Constraint\AssertDevdocsLink; -use Magento\Mtf\Util\Command\Cli\Setup; -use Magento\Mtf\Util\Command\GeneratedCode; -use Magento\Mtf\Client\BrowserInterface; - -/** - * PLEASE ADD NECESSARY INFO BEFORE RUNNING TEST TO - * ../dev/tests/functional/config/config.xml - * - * Preconditions: - * 1. Uninstall Magento. - * - * Steps: - * 1. Go setup landing page. - * 2. Click on Developer Documentation link. - * 3. Check Developer Documentation title. - * 4. Click on "Terms and agreements" button. - * 5. Check license agreement text. - * 6. Return back to landing page and click "Agree and Setup" button. - * 7. Click "Start Readiness Check" button. - * 8. Make sure PHP Version, PHP Extensions and File Permission are ok. - * 9. Click "Next" and fill DB credentials. - * 10. Click "Test Connection and Authentication" and make sure connection successful. - * 11. Click "Next" and fill store address and admin path. - * 12. Click "Next" and leave all default values. - * 13. Click "Next" and fill admin user info. - * 14. Click "Next" and on the "Step 6: Install" page click "Install Now" button. - * 15. Perform assertions. - * - * @group Installer_and_Upgrade/Downgrade - * @ZephyrId MAGETWO-31431 - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class InstallTest extends Injectable -{ - /** - * Developer Documentation link text. - */ - const DEVDOCS_LINK_TEXT = 'Getting Started'; - - /** - * Developer Documentation install page. - * - * @var DevdocsInstall - */ - protected $devdocsInstallPage; - - /** - * Terms and agreement selector. - * - * @var string - */ - protected $termsLink = '.text-terms>a'; - - /** - * Install page. - * - * @var Install - */ - protected $installPage; - - /** - * Setup Magento for tests executions. - * - * @var Setup - */ - private $magentoSetup; - - /** - * Uninstall Magento before test. - * - * @return array - */ - public function __prepare() - { - $config = $this->objectManager->get(\Magento\Mtf\Config\DataInterface::class); - // Prepare config data - $configData['dbHost'] = $config->get('install/0/host/0'); - $configData['dbUser'] = $config->get('install/0/user/0'); - $configData['dbPassword'] = $config->get('install/0/password/0'); - $configData['dbName'] = $config->get('install/0/dbName/0'); - $configData['baseUrl'] = $config->get('install/0/baseUrl/0'); - $configData['admin'] = $config->get('install/0/backendName/0'); - - return ['configData' => $configData]; - } - - /** - * Uninstall Magento. - * - * @param Install $installPage - * @param Setup $magentoSetup - * @param DevdocsInstall $devdocsInstallPage - * @param GeneratedCode $generatedCode - * @return void - */ - public function __inject( - Install $installPage, - Setup $magentoSetup, - DevdocsInstall $devdocsInstallPage, - GeneratedCode $generatedCode - ) { - $generatedCode->delete(); - $this->magentoSetup = $magentoSetup; - $this->installPage = $installPage; - $this->devdocsInstallPage = $devdocsInstallPage; - } - - /** - * Install Magento via web interface. - * - * @param User $user - * @param array $configData - * @param FixtureFactory $fixtureFactory - * @param AssertAgreementTextPresent $assertLicense - * @param AssertSuccessfulReadinessCheck $assertReadiness - * @param AssertAdminUriAutogenerated $assertAdminUri - * @param AssertDevdocsLink $assertDevdocsLink - * @param BrowserInterface $browser - * @param bool $diCompile - * @param array $install [optional] - * @return array - * @SuppressWarnings(PHPMD.ExcessiveParameterList) - */ - public function test( - User $user, - array $configData, - FixtureFactory $fixtureFactory, - AssertAgreementTextPresent $assertLicense, - AssertSuccessfulReadinessCheck $assertReadiness, - AssertAdminUriAutogenerated $assertAdminUri, - AssertDevdocsLink $assertDevdocsLink, - BrowserInterface $browser, - $diCompile = false, - array $install = [] - ) { - $this->magentoSetup->uninstall(); - $dataConfig = array_merge($install, $configData); - if (isset($dataConfig['httpsFront'])) { - $dataConfig['https'] = str_replace('http', 'https', $dataConfig['baseUrl']); - } - /** @var InstallConfig $installConfig */ - $installConfig = $fixtureFactory->create(\Magento\Install\Test\Fixture\Install::class, ['data' => $dataConfig]); - // Steps - $this->installPage->open(); - // Verify Developer Documentation link. - $handle = $browser->getCurrentWindow(); - $this->installPage->getLandingBlock()->clickLink(self::DEVDOCS_LINK_TEXT); - $this->waitTillTermsLinkNotVisible($browser); - $docHandle = $browser->getCurrentWindow(); - $assertDevdocsLink->processAssert($this->devdocsInstallPage); - $browser->closeWindow($docHandle); - $browser->selectWindow($handle); - // Verify license agreement. - $this->installPage->getLandingBlock()->clickTermsAndAgreement(); - $assertLicense->processAssert($this->installPage); - $this->installPage->getLicenseBlock()->clickBack(); - $this->installPage->getLandingBlock()->clickAgreeAndSetup(); - // Step 1: Readiness Check. - $this->installPage->getReadinessBlock()->clickReadinessCheck(); - $assertReadiness->processAssert($this->installPage); - $this->installPage->getReadinessBlock()->clickNext(); - // Step 2: Add a Database. - $this->installPage->getDatabaseBlock()->fill($installConfig); - $this->installPage->getDatabaseBlock()->clickNext(); - // Step 3: Web Configuration. - $assertAdminUri->processAssert($this->installPage); - $this->installPage->getWebConfigBlock()->clickAdvancedOptions(); - $this->installPage->getWebConfigBlock()->fill($installConfig); - $this->installPage->getWebConfigBlock()->clickNext(); - // Step 4: Customize Your Store - $this->installPage->getCustomizeStoreBlock()->fill($installConfig); - $this->installPage->getCustomizeStoreBlock()->clickNext(); - // Step 5: Create Admin Account. - $this->installPage->getCreateAdminBlock()->fill($user); - $this->installPage->getCreateAdminBlock()->clickNext(); - // Step 6: Install. - $this->installPage->getInstallBlock()->clickInstallNow(); - - if ($diCompile) { - $this->magentoSetup->diCompile(); - } - - return ['installConfig' => $installConfig]; - } - - /** - * Wait till terms link is not visible. - * - * @param BrowserInterface $browser - * @return void - */ - private function waitTillTermsLinkNotVisible(BrowserInterface $browser) - { - $browser->waitUntil( - function () use ($browser) { - $browser->selectWindow(); - return $browser->find($this->termsLink)->isVisible() ? null : true; - } - ); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Install/Test/TestCase/InstallTest.xml b/dev/tests/functional/tests/app/Magento/Install/Test/TestCase/InstallTest.xml deleted file mode 100644 index ed0c4119dd825..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Install/Test/TestCase/InstallTest.xml +++ /dev/null @@ -1,62 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Install\Test\TestCase\InstallTest" summary="[Web Setup][Auto] Install CE Magento via Web Interface" ticketId="MAGETWO-31431"> - <variation name="InstallTestVariation1" firstConstraint="Magento\Install\Test\Constraint\AssertSuccessInstall" summary="Install with custom admin path"> - <data name="user/dataset" xsi:type="string">default</data> - <data name="install/admin" xsi:type="string">custom</data> - <data name="vertical" xsi:type="string">Apps and Games</data> - <constraint name="Magento\Install\Test\Constraint\AssertSuccessInstall" next="Magento\User\Test\Constraint\AssertUserSuccessLogin" /> - <constraint name="Magento\User\Test\Constraint\AssertUserSuccessLogin" prev="Magento\Install\Test\Constraint\AssertSuccessInstall" /> - </variation> - <variation name="InstallTestVariation2" firstConstraint="Magento\Install\Test\Constraint\AssertSuccessInstall" summary="Install with custom encryption key and changed currency and locale"> - <data name="user/dataset" xsi:type="string">default</data> - <data name="install/keyOwn" xsi:type="string">I want to use my own encryption key</data> - <data name="install/keyValue" xsi:type="string">I_want_to_use_my_own__encryption</data> - <data name="install/storeLanguage" xsi:type="string">German (Germany)</data> - <data name="install/storeCurrency" xsi:type="string">Euro (EUR)</data> - <data name="currencySymbol" xsi:type="string">€</data> - <data name="languageTemplate" xsi:type="string">Suchbegriffe</data> - <constraint name="Magento\Install\Test\Constraint\AssertSuccessInstall" next="Magento\Install\Test\Constraint\AssertKeyCreated" /> - <constraint name="Magento\Install\Test\Constraint\AssertKeyCreated" prev="Magento\Install\Test\Constraint\AssertSuccessInstall" next="Magento\User\Test\Constraint\AssertUserSuccessLogin" /> - <constraint name="Magento\User\Test\Constraint\AssertUserSuccessLogin" prev="Magento\Install\Test\Constraint\AssertKeyCreated" next="Magento\Install\Test\Constraint\AssertCurrencySelected" /> - <constraint name="Magento\Install\Test\Constraint\AssertCurrencySelected" prev="Magento\User\Test\Constraint\AssertUserSuccessLogin" /> - </variation> - <variation name="InstallTestVariation3" firstConstraint="Magento\Install\Test\Constraint\AssertSuccessInstall" summary="Install with table prefix"> - <data name="user/dataset" xsi:type="string">default</data> - <data name="install/dbTablePrefix" xsi:type="string">pref_</data> - <data name="install/storeLanguage" xsi:type="string">Chinese</data> - <constraint name="Magento\Install\Test\Constraint\AssertSuccessInstall" next="Magento\User\Test\Constraint\AssertUserSuccessLogin" /> - <constraint name="Magento\User\Test\Constraint\AssertUserSuccessLogin" prev="Magento\Install\Test\Constraint\AssertSuccessInstall" /> - </variation> - <variation name="InstallTestVariation4" summary="Install with enabled url rewrites"> - <data name="user/dataset" xsi:type="string">default</data> - <data name="install/apacheRewrites" xsi:type="string">Yes</data> - <constraint name="Magento\Install\Test\Constraint\AssertSuccessInstall" /> - <constraint name="Magento\User\Test\Constraint\AssertUserSuccessLogin" /> - <constraint name="Magento\Install\Test\Constraint\AssertRewritesEnabled" /> - </variation> - <variation name="InstallTestVariation5" summary="Install with enabled secure urls"> - <data name="user/dataset" xsi:type="string">default</data> - <data name="install/httpsFront" xsi:type="string">Use HTTPS for Magento Storefront</data> - <data name="install/httpsAdmin" xsi:type="string">Use HTTPS for Magento Admin</data> - <constraint name="Magento\Install\Test\Constraint\AssertSuccessInstall" /> - <constraint name="Magento\User\Test\Constraint\AssertUserSuccessLogin" /> - <constraint name="Magento\Install\Test\Constraint\AssertSecureUrlEnabled" /> - </variation> - <variation name="InstallTestVariation6" summary="Install with default values and check DI compile" ticketId="MAGETWO-62817"> - <data name="issue" xsi:type="string">MAGETWO-63314: Magento\Install\Test\TestCase\InstallTest test with data set "InstallTestVariation6" fails on Bamboo SampleData and Functional Acceptance Tests plan</data> - <data name="tag" xsi:type="string">to_maintain:yes</data> - <data name="user/dataset" xsi:type="string">default</data> - <data name="diCompile" xsi:type="boolean">true</data> - <constraint name="Magento\Install\Test\Constraint\AssertSuccessInstall" /> - <constraint name="Magento\User\Test\Constraint\AssertUserSuccessLogin" /> - <constraint name="Magento\Install\Test\Constraint\AssertGenerationFilePathCheck" /> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Payment/Test/TestCase/ConflictResolutionTest.xml b/dev/tests/functional/tests/app/Magento/Payment/Test/TestCase/ConflictResolutionTest.xml index 5609436fcc15b..b9ef50dac2a72 100644 --- a/dev/tests/functional/tests/app/Magento/Payment/Test/TestCase/ConflictResolutionTest.xml +++ b/dev/tests/functional/tests/app/Magento/Payment/Test/TestCase/ConflictResolutionTest.xml @@ -14,7 +14,6 @@ <data name="sections" xsi:type="array"> <item name="recommended_solutions" xsi:type="array"> <item name="PayPal Express Checkout" xsi:type="string">PayPal Express Checkout</item> - <item name="Braintree" xsi:type="string">Braintree</item> </item> <item name="other_paypal_payment_solutions" xsi:type="array"> <item name="paypal_group_all_in_one" xsi:type="array"> diff --git a/dev/tests/functional/tests/app/Magento/Paypal/Test/etc/testcase.xml b/dev/tests/functional/tests/app/Magento/Paypal/Test/etc/testcase.xml index d2f6e78be2d47..a331a949743a1 100644 --- a/dev/tests/functional/tests/app/Magento/Paypal/Test/etc/testcase.xml +++ b/dev/tests/functional/tests/app/Magento/Paypal/Test/etc/testcase.xml @@ -62,8 +62,7 @@ <step name="getPlacedOrderId" module="Magento_Checkout" /> </scenario> <scenario name="ConflictResolutionTest" firstStep="checkExpressConfig"> - <step name="checkExpressConfig" module="Magento_Paypal" next="checkBraintreeConfig" /> - <step name="checkBraintreeConfig" module="Magento_Braintree" next="checkPaymentsAdvancedConfig" /> + <step name="checkExpressConfig" module="Magento_Paypal" next="checkPaymentsAdvancedConfig" /> <step name="checkPaymentsAdvancedConfig" module="Magento_Paypal" next="checkPaymentsProConfig" /> <step name="checkPaymentsProConfig" module="Magento_Paypal" next="checkPayflowProConfig" /> <step name="checkPayflowProConfig" module="Magento_Paypal" next="checkPayflowLinkConfig" /> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Authentication.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Authentication.php deleted file mode 100644 index e33daa76ff9cc..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Authentication.php +++ /dev/null @@ -1,63 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Block; - -use Magento\Mtf\Block\Form; -use Magento\Mtf\Client\Element\SimpleElement; -use Magento\Mtf\Client\Locator; -use Magento\Mtf\Fixture\FixtureInterface; - -/** - * Perform Authentication block. - */ -class Authentication extends Form -{ - /** - * 'Save Config' button. - * - * @var string - */ - protected $save = "[ng-click*='saveAuthJson']"; - - /** - * First field selector - * - * @var string - */ - protected $firstField = '[name="username"]'; - - /** - * Popup Loading. - * - * @var string - */ - protected $popupLoading = '.popup popup-loading'; - - /** - * Click on 'Save Config' button. - * - * @return void - */ - public function clickSaveConfig() - { - $this->_rootElement->find($this->save, Locator::SELECTOR_CSS)->click(); - $this->waitForElementNotVisible($this->popupLoading); - } - - /** - * Ensure the form is loaded and fill the root form - * - * @param FixtureInterface $fixture - * @param SimpleElement|null $element - * @return $this - */ - public function fill(FixtureInterface $fixture, SimpleElement $element = null) - { - $this->waitForElementVisible($this->firstField); - return parent::fill($fixture, $element); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Authentication.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Authentication.xml deleted file mode 100644 index 25147ab9c85ff..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Authentication.xml +++ /dev/null @@ -1,17 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<mapping strict="1"> - <fields> - <publicKey> - <selector>[name='username']</selector> - </publicKey> - <privateKey> - <selector>[name='password']</selector> - </privateKey> - </fields> -</mapping> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/CreateBackup.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/CreateBackup.php deleted file mode 100644 index 45ced59e4877b..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/CreateBackup.php +++ /dev/null @@ -1,35 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Block; - -use Magento\Mtf\Block\Form; -use Magento\Mtf\Client\Element\SimpleElement; -use Magento\Mtf\Client\Locator; -use Magento\Mtf\Fixture\FixtureInterface; - -/** - * Create Backup block. - */ -class CreateBackup extends Form -{ - /** - * 'Start Update' button. - * - * @var string - */ - protected $startUpdate = "[ng-click*='goToStartUpdater']"; - - /** - * Click on 'Start Update/Next' button. - * - * @return void - */ - public function clickNext() - { - $this->_rootElement->find($this->startUpdate, Locator::SELECTOR_CSS)->click(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/CreateBackup.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/CreateBackup.xml deleted file mode 100644 index 9e2bd545c407e..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/CreateBackup.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<mapping strict="1"> - <fields> - <optionsCode> - <selector>#optionsCode</selector> - <input>checkbox</input> - </optionsCode> - <optionsMedia> - <selector>#optionsMedia</selector> - <input>checkbox</input> - </optionsMedia> - <optionsDb> - <selector>#optionsDb</selector> - <input>checkbox</input> - </optionsDb> - </fields> -</mapping> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/AbstractGrid.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/AbstractGrid.php deleted file mode 100644 index ae2fd893c20f4..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/AbstractGrid.php +++ /dev/null @@ -1,133 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Block\Extension; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; -use Magento\Setup\Test\Fixture\Extension; - -/** - * Abstract Extensions Grid block. - */ -abstract class AbstractGrid extends Block -{ - /** - * 'Next Page' button for grid. - * - * @var string - */ - protected $nextPageButton = '.action-next'; - - /** - * Grid that contains the list of extensions. - * - * @var string - */ - protected $dataGrid = '#installExtensionGrid'; - - /** - * Container that contains name of the extension. - * - * @var string - */ - protected $extensionName = "//*[contains(text(), '%s')]"; - - /** - * Checkbox for select extension. - * - * @var string - */ - protected $extensionCheckbox = "//tr[td/*[contains(text(), '%s')]]//*[contains(@ng-checked, 'selectedExtension')]"; - - /** - * Find Extension on the grid by name. - * - * @param Extension $extension - * @return boolean - */ - public function findExtensionOnGrid(Extension $extension) - { - $result = false; - while (true) { - if (($result = $this->isExtensionOnGrid($extension->getExtensionName())) || !$this->clickNextPageButton()) { - break; - } - } - - return $result; - } - - /** - * Check that there is extension on grid. - * - * @param string $name - * @return bool - */ - protected function isExtensionOnGrid($name) - { - $this->waitForElementVisible($this->dataGrid); - return $this->_rootElement->find( - sprintf($this->extensionName, $name), - Locator::SELECTOR_XPATH - )->isVisible(); - } - - /** - * Click 'Next Page' button. - * - * @return bool - */ - protected function clickNextPageButton() - { - $this->waitForElementVisible($this->nextPageButton); - $nextPageButton = $this->_rootElement->find($this->nextPageButton); - if (!$nextPageButton->isDisabled() && $nextPageButton->isVisible()) { - $nextPageButton->click(); - return true; - } - - return false; - } - - /** - * Select several extensions to install on grid. - * - * @param Extension[] $extensions - * @return Extension[] - */ - public function selectSeveralExtensions(array $extensions) - { - while (true) { - foreach ($extensions as $key => $extension) { - if ($this->isExtensionOnGrid($extension->getExtensionName())) { - $this->selectExtension($extension->getExtensionName()); - unset($extensions[$key]); - } - } - - if (empty($extensions) || !$this->clickNextPageButton()) { - break; - } - } - - return $extensions; - } - - /** - * Select extension on grid, check checkbox. - * - * @param string $extensionName - * @return void - */ - protected function selectExtension($extensionName) - { - $this->_rootElement->find( - sprintf($this->extensionCheckbox, $extensionName), - Locator::SELECTOR_XPATH - )->click(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/DataOption.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/DataOption.php deleted file mode 100644 index 789adbd118c67..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/DataOption.php +++ /dev/null @@ -1,33 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Block\Extension; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; - -/** - * Data Option block. - */ -class DataOption extends Block -{ - /** - * "Next" button. - * - * @var string - */ - protected $nextState = "[ng-click*='nextState']"; - - /** - * Click "Next" button. - * - * @return void - */ - public function clickNext() - { - $this->_rootElement->find($this->nextState, Locator::SELECTOR_CSS)->click(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/Grid.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/Grid.php deleted file mode 100644 index cbaaf06acac77..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/Grid.php +++ /dev/null @@ -1,199 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Block\Extension; - -use Magento\Mtf\Client\Locator; -use Magento\Setup\Test\Fixture\Extension; - -/** - * Extensions Grid block. - */ -class Grid extends AbstractGrid -{ - /** - * "Install" button that opens grid with extensions for installing. - * - * @var string - */ - protected $installButton = "//button[contains(@class, 'goInstall')]"; - - /** - * 'Review Updates' button that opens grid with extensions for update. - * - * @var string - */ - protected $updateButton = "//button[contains(@class, 'goUpdate')]"; - - /** - * Select action of extension on the grid. - * - * @var string - */ - protected $selectAction = "//tr[td/*[contains(text(), '%s')]]//*[contains(@class, 'action-select')]"; - - /** - * Uninstall action of extension. - * - * @var string - */ - protected $uninstallAction = "//tr[td/*[contains(text(), '%s')]]//*[contains(@ng-mousedown, 'uninstall')]"; - - /** - * Update action of extension. - * - * @var string - */ - protected $updateAction = "//tr[td/*[contains(text(), '%s')]]//*[contains(@ng-mousedown, 'update')]"; - - /** - * Container that contains version of extension. - * - * @var string - */ - protected $versionContainer = "//tr[td/*[contains(text(), '%s')]]//*[@data-type='version']"; - - /** - * Popup Loading. - * - * @var string - */ - protected $popupLoading = '.popup.popup-loading'; - - /** - * 'Not found any extensions' message. - * - * @var string - */ - protected $notFoundMessage = '.not-found'; - - /** - * Grid that contains the list of extensions. - * - * @var string - */ - protected $dataGrid = '#extensionGrid'; - - /** - * Click to 'Install' button. - * - * @return void - */ - public function clickInstallButton() - { - $this->_rootElement->find($this->installButton, Locator::SELECTOR_XPATH)->click(); - } - - /** - * Click 'Review Updates' button. - * - * @return void - */ - public function clickUpdateButton() - { - $this->_rootElement->find($this->updateButton, Locator::SELECTOR_XPATH)->click(); - } - - /** - * Click to uninstall button. - * - * @param Extension $extension - * @return void - */ - public function clickUninstallButton(Extension $extension) - { - $this->clickSelectActionButton($extension); - $button = $this->_rootElement->find( - sprintf($this->uninstallAction, $extension->getExtensionName()), - Locator::SELECTOR_XPATH - ); - - if ($button->isVisible()) { - $button->click(); - } - } - - /** - * Get version of extension. - * - * @param Extension $extension - * @return string - */ - public function getVersion(Extension $extension) - { - return $this->_rootElement->find( - sprintf($this->versionContainer, $extension->getExtensionName()), - Locator::SELECTOR_XPATH - )->getText(); - } - - /** - * Click to update button. - * - * @param Extension $extension - * @return void - */ - public function clickUpdateActionButton(Extension $extension) - { - $this->clickSelectActionButton($extension); - $button = $this->_rootElement->find( - sprintf($this->updateAction, $extension->getExtensionName()), - Locator::SELECTOR_XPATH - ); - - if ($button->isVisible()) { - $button->click(); - } - } - - /** - * {@inheritdoc} - */ - public function findExtensionOnGrid(Extension $extension) - { - sleep(3); - - $this->_rootElement->waitUntil( - function () { - $message = $this->_rootElement->find($this->notFoundMessage)->isVisible(); - $grid = $this->_rootElement->find($this->dataGrid)->isVisible(); - - return ($message && !$grid) || (!$message && $grid); - } - ); - - if ($this->_rootElement->find($this->notFoundMessage)->isVisible()) { - return false; - } - - return parent::findExtensionOnGrid($extension); - } - - /** - * Click to Select action - * - * @param Extension $extension - * @return void - */ - protected function clickSelectActionButton(Extension $extension) - { - $this->_rootElement->find( - sprintf($this->selectAction, $extension->getExtensionName()), - Locator::SELECTOR_XPATH - )->click(); - } - - /** - * Wait loader. - * - * @return void - */ - public function waitLoader() - { - $this->waitForElementVisible($this->popupLoading); - $this->waitForElementNotVisible($this->popupLoading); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/InstallGrid.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/InstallGrid.php deleted file mode 100644 index 8eec97bbbde00..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/InstallGrid.php +++ /dev/null @@ -1,71 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Block\Extension; - -use Magento\Mtf\Client\Locator; -use Magento\Setup\Test\Fixture\Extension; - -/** - * Extensions Install Grid. - */ -class InstallGrid extends AbstractGrid -{ - /** - * "Install" button of extension. - * - * @var string - */ - protected $extensionInstall = "//tr[td/*[contains(text(), '%s')]]//*[contains(@class, 'action-wrap')]//button"; - - /** - * Select version of extension. - * - * @var string - */ - protected $extensionSelectVersion = "//tr[td/*[contains(text(), '%s')]]//*[contains(@id, 'selectedVersion')]"; - - /** - * "Install All" button. - * - * @var string - */ - protected $installAllButton = "[ng-click*='installAll']"; - - /** - * Install extension. - * - * @param Extension $extension - * @return void - */ - public function install(Extension $extension) - { - $select = $this->_rootElement->find( - sprintf($this->extensionSelectVersion, $extension->getExtensionName()), - Locator::SELECTOR_XPATH, - 'strictselect' - ); - - if ($select->isVisible()) { - $select->setValue('Version ' . $extension->getVersion()); - } - - $this->_rootElement->find( - sprintf($this->extensionInstall, $extension->getExtensionName()), - Locator::SELECTOR_XPATH - )->click(); - } - - /** - * Click to "Install" button that starts installing of selected extensions. - * - * @return void - */ - public function clickInstallAll() - { - $this->_rootElement->find($this->installAllButton, Locator::SELECTOR_CSS)->click(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/UpdateGrid.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/UpdateGrid.php deleted file mode 100644 index e29b2cb9ff310..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/UpdateGrid.php +++ /dev/null @@ -1,41 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Test\Block\Extension; - -use Magento\Mtf\Client\Locator; -use Magento\Setup\Test\Fixture\Extension; - -/** - * Class UpdateGrid - * - * Grid with extension updates. - */ -class UpdateGrid extends AbstractGrid -{ - /** - * 'Update All' button. - * - * @var string - */ - protected $updateAllButton = "[ng-click*='updateAll']"; - - /** - * Grid that contains the list of extensions. - * - * @var string - */ - protected $dataGrid = '#updateExtensionGrid'; - - /** - * Click to update all button. - * - * @return void - */ - public function clickUpdateAllButton() - { - $this->_rootElement->find($this->updateAllButton, Locator::SELECTOR_CSS)->click(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/Updater.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/Updater.php deleted file mode 100644 index 488302057a19c..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Extension/Updater.php +++ /dev/null @@ -1,50 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Block\Extension; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; - -/** - * Updater Extension block for installing, updating and uninstalling of extensions. - */ -class Updater extends Block -{ - /** - * Container with a message about installation, updating or uninstalling. - * - * @var string - */ - protected $message = 'start-updater'; - - /** - * "Install" button that starts an installation. - * - * @var string - */ - protected $button = "[ng-click*='update']"; - - /** - * Click to 'Install'|'Update'|'Uninstall' button. - * - * @return void - */ - public function clickStartButton() - { - $this->_rootElement->find($this->button, Locator::SELECTOR_CSS)->click(); - } - - /** - * Get message. - * - * @return string - */ - public function getMessage() - { - return $this->_rootElement->find($this->message, Locator::SELECTOR_NAME)->getText(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Home.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Home.php deleted file mode 100644 index 1d0ad5288af7e..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Home.php +++ /dev/null @@ -1,65 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Block; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; - -/** - * Home block. - */ -class Home extends Block -{ - /** - * @var string - */ - protected $systemUpgrade = '.setup-home-item-upgrade'; - - /** - * Button that opens grid with installed extensions. - * - * @var string - */ - protected $extensionManager = '.setup-home-item-extension'; - - /** - * 'Module Manager' button. - * - * @var string - */ - protected $moduleManager = '.setup-home-item-module'; - - /** - * Click on 'System Upgrade' button. - * - * @return void - */ - public function clickSystemUpgrade() - { - $this->_rootElement->find($this->systemUpgrade, Locator::SELECTOR_CSS)->click(); - } - - /** - * Click on 'Extension Manager' button. - * - * @return void - */ - public function clickExtensionManager() - { - $this->_rootElement->find($this->extensionManager, Locator::SELECTOR_CSS)->click(); - } - - /** - * Click on 'Module Manager' section. - * - * @return void - */ - public function clickModuleManager() - { - $this->_rootElement->find($this->moduleManager, Locator::SELECTOR_CSS)->click(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Module/Grid.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Module/Grid.php deleted file mode 100644 index cd57aaf8164dd..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Module/Grid.php +++ /dev/null @@ -1,167 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Test\Block\Module; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; -use Magento\Mtf\Client\ElementInterface; - -/** - * Class Grid - * - * Table grid on backend. - */ -class Grid extends Block -{ - /** - * Select action toggle. - * - * @var string - */ - protected $selectAction = '.action-select'; - - /** - * Module name path. - * - * @var string - */ - protected $componentName = '//table//*//div[contains(text(), \'%s\')]'; - - /** - * Select path. - * - * @var string - */ - protected $select = '//div[contains(text(), \'%s\')]//..//..//td//div[contains(@class, \'action-select\')]'; - - /** - * Next button selector. - * - * @var string - */ - protected $next = '.action-next'; - - /** - * Item enable selector. - * - * @var string - */ - protected $itemEnable = '.item-enable'; - - /** - * Item disable selector. - * - * @var string - */ - protected $itemDisable = '.item-disable'; - - /** - * Button element. - * - * @var string - */ - protected $button = 'button'; - - /** - * Click Next button. - * - * @return void - */ - public function clickNext() - { - $this->_rootElement->find($this->next, Locator::SELECTOR_CSS)->click(); - } - - /** - * Check if Next page button is available. - * - * @return bool - */ - public function isClickNextAvailable() - { - return !$this->_rootElement->find($this->next, Locator::SELECTOR_CSS)->isDisabled(); - } - - /** - * Find module by it's name. - * - * @param string $name - * @return ElementInterface - */ - public function findModuleByName($name) - { - $element = $this->getModuleByName($name); - - while (!$element->isVisible() && $this->isClickNextAvailable()) { - $this->clickNext(); - - $element = $this->getModuleByName($name); - } - - return $element; - } - - /** - * Retrieve module by it's name. - * - * @param string $name - * @return ElementInterface - */ - private function getModuleByName($name) - { - $componentName = sprintf($this->componentName, $name); - - return $this->_rootElement->find($componentName, Locator::SELECTOR_XPATH); - } - - /** - * Check if Module is enabled.s - * - * @param string $name - * @return bool - */ - public function isModuleEnabled($name) - { - $element = $this->findModuleByName($name); - $select = sprintf($this->select, $name); - - $element->find($select, Locator::SELECTOR_XPATH)->find($this->button)->click(); - $isVisible = $element->find($select, Locator::SELECTOR_XPATH)->find($this->itemDisable)->isVisible(); - $element->find($select, Locator::SELECTOR_XPATH)->find($this->button)->click(); - - return $isVisible; - } - - /** - * Disable Module. - * - * @param string $name - * @return void - */ - public function disableModule($name) - { - $element = $this->findModuleByName($name); - $select = sprintf($this->select, $name); - - $element->find($select, Locator::SELECTOR_XPATH)->find($this->button)->click(); - $element->find($select, Locator::SELECTOR_XPATH)->find($this->itemDisable)->click(); - } - - /** - * Enable Module. - * - * @param string $name - * @return void - */ - public function enableModule($name) - { - $element = $this->findModuleByName($name); - $select = sprintf($this->select, $name); - - $element->find($select, Locator::SELECTOR_XPATH)->find($this->button)->click(); - $element->find($select, Locator::SELECTOR_XPATH)->find($this->itemEnable)->click(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Module/Status.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Module/Status.php deleted file mode 100644 index 39bd55f63d7b8..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Module/Status.php +++ /dev/null @@ -1,44 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Test\Block\Module; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; - -/** - * Class Status - * - * Contains action to manipulate with Module's actions. - */ -class Status extends Block -{ - /** - * Button selector. - * - * @var string - */ - protected $button = '.btn-large'; - - /** - * Click on Disable Element. - * - * @return void - */ - public function clickDisable() - { - $this->_rootElement->find($this->button, Locator::SELECTOR_CSS)->click(); - } - - /** - * Click en Enable element. - * - * @return void - */ - public function clickEnable() - { - $this->_rootElement->find($this->button, Locator::SELECTOR_CSS)->click(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Readiness.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Readiness.php deleted file mode 100644 index 3aa6fc8f2a84f..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/Readiness.php +++ /dev/null @@ -1,232 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Block; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; -use Magento\Setup\Test\Fixture\Extension; - -/** - * Readiness block. - */ -class Readiness extends Block -{ - /** - * 'Start Readiness Check' button. - * - * @var string - */ - protected $readinessCheck = "[ng-click*='state.go']"; - - /** - * 'Next' button. - * - * @var string - */ - protected $next = "[ng-click*='next']"; - - /** - * 'Try Again' button. - * - * @var string - */ - protected $tryAgain = "[ng-click*='forceReload']"; - - /** - * Trash Bin icon. - * - * @var string - */ - protected $removeExtension = '//li[contains(text(), \'%s\')]//button'; - - /** - * Remove button on modal. - * - * @var string - */ - protected $removeExtensionButtonOnModal = "[ng-click*='removeExtension']"; - - /** - * Remove popup modal. - * - * @var string - */ - protected $popupRemoveModal = '.modal-popup'; - - /** - * 'Completed!' message. - * [ng-switch-when="true"] - * @var string - */ - protected $completedMessage = '[ng-switch-when="true"]'; - - /** - * Updater application successful check. - * - * @var string - */ - protected $updaterApplicationCheck = '#updater-application'; - - /** - * Cron script successful check. - * - * @var string - */ - protected $cronScriptCheck = '#cron-script'; - - /** - * Dependency successful check. - * - * @var string - */ - protected $dependencyCheck = '#component-dependency'; - - /** - * PHP Version successful check. - * - * @var string - */ - protected $phpVersionCheck = '#php-version'; - - /** - * PHP Settings successful check. - * - * @var string - */ - protected $phpSettingsCheck = '#php-settings'; - - /** - * PHP Extensions successful check. - * - * @var string - */ - protected $phpExtensionCheck = '#php-extensions'; - - /** - * Click on 'Start Readiness Check' button. - * - * @return void - */ - public function clickReadinessCheck() - { - $this->_rootElement->find($this->readinessCheck, Locator::SELECTOR_CSS)->click(); - $this->waitForElementVisible($this->completedMessage, Locator::SELECTOR_CSS); - } - - /** - * Click on 'Next' button. - * - * @return void - */ - public function clickNext() - { - $this->_rootElement->find($this->next, Locator::SELECTOR_CSS)->click(); - } - - /** - * Click on 'Try Again' button. - * - * @return void - */ - public function clickTryAgain() - { - $this->_rootElement->find($this->tryAgain, Locator::SELECTOR_CSS)->click(); - $this->waitForElementVisible($this->completedMessage, Locator::SELECTOR_CSS); - } - - /** - * Click Trash Bin icon. - * - * @param Extension $extension - * @return void - */ - public function clickRemoveExtension(Extension $extension) - { - $removeExtension = sprintf($this->removeExtension, $extension->getExtensionName()); - - $this->_rootElement->find($removeExtension, Locator::SELECTOR_XPATH)->click(); - } - - /** - * Click Remove button on modal. - * - * @return void - */ - public function clickRemoveExtensionOnModal() - { - $this->_rootElement->find($this->removeExtensionButtonOnModal, Locator::SELECTOR_CSS)->click(); - $this->waitForElementNotVisible($this->popupRemoveModal, Locator::SELECTOR_CSS); - } - - /** - * Get Updater application check result. - * - * @return string - */ - public function getUpdaterApplicationCheck() - { - return $this->_rootElement->find($this->updaterApplicationCheck, Locator::SELECTOR_CSS)->getText(); - } - - /** - * Get cron script check result. - * - * @return string - */ - public function getCronScriptCheck() - { - return $this->_rootElement->find($this->cronScriptCheck, Locator::SELECTOR_CSS)->getText(); - } - - /** - * Get dependency check result. - * - * @return string - */ - public function getDependencyCheck() - { - return $this->_rootElement->find($this->dependencyCheck, Locator::SELECTOR_CSS)->getText(); - } - - /** - * @return bool - */ - public function isPhpVersionCheckVisible() : bool - { - return $this->_rootElement->find($this->phpVersionCheck)->isVisible(); - } - - /** - * Get PHP Version check result. - * - * @return string - */ - public function getPhpVersionCheck() - { - return $this->_rootElement->find($this->phpVersionCheck, Locator::SELECTOR_CSS)->getText(); - } - - /** - * Get setting check result. - * - * @return string - */ - public function getSettingsCheck() - { - return $this->_rootElement->find($this->phpSettingsCheck, Locator::SELECTOR_CSS)->getText(); - } - - /** - * Get PHP Extensions check result. - * - * @return string - */ - public function getPhpExtensionsCheck() - { - return $this->_rootElement->find($this->phpExtensionCheck, Locator::SELECTOR_CSS)->getText(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SelectVersion.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SelectVersion.php deleted file mode 100644 index 5cb71d85a51ce..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SelectVersion.php +++ /dev/null @@ -1,158 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Block; - -use Magento\Mtf\Block\Form; -use Magento\Mtf\Client\Element\SimpleElement; -use Magento\Mtf\Client\Locator; -use Magento\Mtf\Fixture\FixtureInterface; -use Magento\Setup\Test\Block\SelectVersion\OtherComponentsGrid; - -/** - * Select version block. - */ -class SelectVersion extends Form -{ - /** - * 'Next' button. - * - * @var string - */ - protected $next = "[ng-click*='update']"; - - /** - * First field selector - * - * @var string - */ - protected $firstField = '#selectVersion'; - - /** - * Show all versions checkbox - * - * @var string - */ - private $showAllVersions = '#showUnstable'; - - /** - * CSS selector for Other Components Grid Block. - * - * @var string - */ - private $otherComponentsGrid = '.admin__data-grid-outer-wrap'; - - /** - * @var string - */ - private $empty = '[ng-show="componentsProcessed && total == 0"]'; - - /** - * @var string - */ - private $waitEmpty = - '//div[contains(@ng-show, "componentsProcessed && total") and not(contains(@class,"ng-hide"))]'; - - /** - * @var OtherComponentsGrid - */ - private $otherComponentGrid; - - /** - * Click on 'Next' button. - * - * @return void - */ - public function clickNext() - { - $this->_rootElement->find($this->next, Locator::SELECTOR_CSS)->click(); - } - - /** - * Ensure the form is loaded and fill the root form - * - * @param FixtureInterface $fixture - * @param SimpleElement|null $element - * @return $this - */ - public function fill(FixtureInterface $fixture, SimpleElement $element = null) - { - $this->waitForElementVisible($this->firstField); - $this->chooseShowAllVersions(); - - return parent::fill($fixture, $element); - } - - /** - * Show all versions include unstable - * - * @return void - */ - private function chooseShowAllVersions() - { - $element = $this->_rootElement->find($this->showAllVersions, Locator::SELECTOR_CSS); - if ($element->isVisible()) { - $element->click(); - } - } - - /** - * Choose 'yes' for upgrade option called 'Other components'. - * - * @param array $packages - * @return void - */ - public function chooseUpgradeOtherComponents(array $packages) :void - { - $this->_rootElement->find("[for=yesUpdateComponents]")->click(); - $this->waitForElementNotVisible("[ng-show=\"!componentsProcessed\""); - - if (!$this->isComponentsEmpty()) { - $otherComponentGrid = $this->getOtherComponentsGrid(); - $otherComponentGrid->setItemsPerPage(200); - $otherComponentGrid->setVersions($packages); - } - } - - /** - * Check that grid is empty. - * - * @return bool - */ - public function isComponentsEmpty() - { - $this->waitForElementVisible($this->waitEmpty, Locator::SELECTOR_XPATH); - - return $this->_rootElement->find($this->empty)->isVisible(); - } - - /** - * Returns selected packages. - * - * @return array - */ - public function getSelectedPackages() - { - return $this->getOtherComponentsGrid()->getSelectedPackages(); - } - - /** - * Get grid block for other components. - * - * @return OtherComponentsGrid - */ - private function getOtherComponentsGrid() : OtherComponentsGrid - { - if (!isset($this->otherComponentGrid)) { - $this->otherComponentGrid = $this->blockFactory->create( - OtherComponentsGrid::class, - ['element' => $this->_rootElement->find($this->otherComponentsGrid)] - ); - } - - return $this->otherComponentGrid; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SelectVersion.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SelectVersion.xml deleted file mode 100644 index 94d9c3e437388..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SelectVersion.xml +++ /dev/null @@ -1,15 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<mapping strict="1"> - <fields> - <upgradeVersion> - <selector>#selectVersion</selector> - <input>select</input> - </upgradeVersion> - </fields> -</mapping> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SelectVersion/OtherComponentsGrid.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SelectVersion/OtherComponentsGrid.php deleted file mode 100644 index 8ca2c0654e28c..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SelectVersion/OtherComponentsGrid.php +++ /dev/null @@ -1,88 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Block\SelectVersion; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\ElementInterface; -use Magento\Mtf\Client\Locator; -use Magento\Setup\Test\Block\SelectVersion\OtherComponentsGrid\Item; - -/** - * Perform OtherComponentsGrid block. - */ -class OtherComponentsGrid extends Block -{ - /** - * @var string - */ - private $itemComponent = '//tr[contains(@ng-repeat,"component") and ./td[contains(.,"%s")]]'; - - /** - * @var string - */ - private $perPage = '#perPage'; - - /** - * @var array - */ - private $selectedPackages = []; - - /** - * Set version of the packages. - * - * @param array $packages - * @return void - */ - public function setVersions(array $packages) : void - { - foreach ($packages as $package) { - $selector = sprintf($this->itemComponent, $package['name']); - $elements = $this->_rootElement->getElements($selector, Locator::SELECTOR_XPATH); - foreach ($elements as $element) { - $row = $this->getComponentRow($element); - $row->setVersion($package['version']); - $this->selectedPackages[$row->getPackageName()] = $package['version']; - } - } - } - - /** - * Returns selected packages. - * - * @return array - */ - public function getSelectedPackages() : array - { - return $this->selectedPackages; - } - - /** - * Set pager size. - * - * @param int $count - * @return void - */ - public function setItemsPerPage(int $count) : void - { - $this->_rootElement->find($this->perPage, Locator::SELECTOR_CSS, 'select')->setValue($count); - } - - /** - * Get component block. - * - * @param ElementInterface $element - * @return Item - */ - private function getComponentRow(ElementInterface $element) : Item - { - return $this->blockFactory->create( - Item::class, - ['element' => $element] - ); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SelectVersion/OtherComponentsGrid/Item.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SelectVersion/OtherComponentsGrid/Item.php deleted file mode 100644 index 8c24323f37618..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SelectVersion/OtherComponentsGrid/Item.php +++ /dev/null @@ -1,51 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Block\SelectVersion\OtherComponentsGrid; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; - -/** - * Block for each component. - */ -class Item extends Block -{ - /** - * CSS selector for version element. - * - * @var string - */ - private $version = '[ng-change*="setComponentVersion"]'; - - /** - * CSS selector for package name element. - * - * @var string - */ - private $packageName = 'td:nth-child(2)'; - - /** - * Set version for particular component. - * - * @param string $version - */ - public function setVersion(string $version) - { - $this->_rootElement->find($this->version, Locator::SELECTOR_CSS, 'select')->setValue($version); - } - - /** - * Returns package name of element. - * - * @return array|string - */ - public function getPackageName() - { - return $this->_rootElement->find($this->packageName)->getText(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SuccessMessage.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SuccessMessage.php deleted file mode 100644 index f853c48815391..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SuccessMessage.php +++ /dev/null @@ -1,57 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Block; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; - -/** - * Success Message block. - */ -class SuccessMessage extends Block -{ - /** - * Success message block class. - * - * @var string - */ - protected $successMessage = 'content-success'; - - /** - * Retrieve Updater Status. - * - * @return string - */ - public function getUpdaterStatus() - { - $this->waitForElementVisible($this->successMessage, Locator::SELECTOR_CLASS_NAME); - - return $this->_rootElement->find($this->successMessage, Locator::SELECTOR_CLASS_NAME)->getText(); - } - - /** - * Retrieve status of Module. - * - * @return array|string - */ - public function getDisableModuleStatus() - { - $this->waitForElementVisible($this->successMessage, Locator::SELECTOR_CLASS_NAME); - - return $this->_rootElement->find($this->successMessage, Locator::SELECTOR_CLASS_NAME)->getText(); - } - - /** - * Click Back to Setup button. - * - * @return void - */ - public function clickBackToSetup() - { - $this->_rootElement->find('btn-prime', Locator::SELECTOR_CLASS_NAME)->click(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SystemConfig.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SystemConfig.php deleted file mode 100644 index b5168a233501b..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SystemConfig.php +++ /dev/null @@ -1,31 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Block; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; - -/** - * System Config block. - */ -class SystemConfig extends Block -{ - /** - * @var string - */ - protected $systemConfig = '.setup-home-item-configuration'; - - /** - * Click on 'System Configuration' button. - * - * @return void - */ - public function clickSystemConfig() - { - $this->_rootElement->find($this->systemConfig, Locator::SELECTOR_CSS)->click(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SystemUpgrade.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SystemUpgrade.php deleted file mode 100644 index a1903a01c22f1..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Block/SystemUpgrade.php +++ /dev/null @@ -1,48 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Block; - -use Magento\Mtf\Block\Block; -use Magento\Mtf\Client\Locator; - -/** - * System Upgrade block. - */ -class SystemUpgrade extends Block -{ - /** - * @var string - */ - protected $systemUpgradeMessage = 'start-updater'; - - /** - * 'Upgrade' button. - * - * @var string - */ - protected $upgrade = "[ng-click*='update']"; - - /** - * Get upgrade message. - * - * @return string - */ - public function getUpgradeMessage() - { - return $this->_rootElement->find($this->systemUpgradeMessage, Locator::SELECTOR_NAME)->getText(); - } - - /** - * Click on 'Upgrade' button. - * - * @return void - */ - public function clickSystemUpgrade() - { - $this->_rootElement->find($this->upgrade, Locator::SELECTOR_CSS)->click(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/AssertApplicationVersion.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/AssertApplicationVersion.php deleted file mode 100644 index dd47c30c4a991..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/AssertApplicationVersion.php +++ /dev/null @@ -1,43 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Constraint; - -use Magento\Backend\Test\Page\Adminhtml\Dashboard; -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Mtf\Fixture\FixtureInterface; - -/** - * Check application version - */ -class AssertApplicationVersion extends AbstractConstraint -{ - /** - * Assert upgrade is successfully - * - * @param Dashboard $dashboard - * @param string $version - * @return void - */ - public function processAssert(Dashboard $dashboard, $version) - { - \PHPUnit\Framework\Assert::assertContains( - $version, - $dashboard->getApplicationVersion()->getVersion(), - 'Application version is incorrect.' - ); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Application new version is correct."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/AssertSuccessMessage.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/AssertSuccessMessage.php deleted file mode 100644 index 4a2ff92412b66..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/AssertSuccessMessage.php +++ /dev/null @@ -1,48 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Constraint; - -use Magento\Setup\Test\Page\Adminhtml\SetupWizard; -use Magento\Mtf\Constraint\AbstractConstraint; - -/** - * Check upgrade is successfully - */ -class AssertSuccessMessage extends AbstractConstraint -{ - /** - * Assert upgrade is successfully - * - * @param SetupWizard $setupWizard - * @param string $package - * @return void - */ - public function processAssert(SetupWizard $setupWizard, $package) - { - $message = "You upgraded"; - \PHPUnit\Framework\Assert::assertContains( - $message, - $setupWizard->getSuccessMessage()->getUpdaterStatus(), - 'Success message is incorrect.' - ); - \PHPUnit\Framework\Assert::assertContains( - $package, - $setupWizard->getSuccessMessage()->getUpdaterStatus(), - 'Updated package is incorrect.' - ); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "System Upgrade success message is correct."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/AssertSuccessfulReadinessCheck.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/AssertSuccessfulReadinessCheck.php deleted file mode 100644 index 676703924e59a..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/AssertSuccessfulReadinessCheck.php +++ /dev/null @@ -1,98 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Constraint; - -use Magento\Setup\Test\Page\Adminhtml\SetupWizard; -use Magento\Mtf\Constraint\AbstractConstraint; - -/** - * Check that Updater, Dependency, PHP Version, PHP Extensions and File Permission are ok. - */ -class AssertSuccessfulReadinessCheck extends AbstractConstraint -{ - /** - * Updater application message - */ - const UPDATER_APPLICATION_MESSAGE = 'Updater application is available'; - - /** - * Cron script message - */ - const CRON_SCRIPT_MESSAGE = 'Cron script readiness check passed'; - - /** - * Dependency check message - */ - const DEPENDENCY_CHECK_MESSAGE = 'Component dependency is correct'; - - /** - * PHP version message. - */ - const PHP_VERSION_MESSAGE = 'Your PHP version is correct'; - - /** - * PHP extensions message. - */ - const PHP_SETTING_REGEXP = 'Your PHP settings are correct'; - - /** - * PHP extensions message. - */ - const PHP_EXTENSIONS_REGEXP = '/You meet (\d+) out of \1 PHP extensions requirements\./'; - - /** - * Assert that readiness check items are passed. - * - * @param SetupWizard $setupWizard - * @return void - */ - public function processAssert(SetupWizard $setupWizard) - { - \PHPUnit\Framework\Assert::assertContains( - self::UPDATER_APPLICATION_MESSAGE, - $setupWizard->getReadiness()->getUpdaterApplicationCheck(), - 'Updater application check is incorrect.' - ); - \PHPUnit\Framework\Assert::assertContains( - self::CRON_SCRIPT_MESSAGE, - $setupWizard->getReadiness()->getCronScriptCheck(), - 'Cron scripts are incorrect.' - ); - \PHPUnit\Framework\Assert::assertContains( - self::DEPENDENCY_CHECK_MESSAGE, - $setupWizard->getReadiness()->getDependencyCheck(), - 'Dependency check is incorrect.' - ); - if ($setupWizard->getReadiness()->isPhpVersionCheckVisible()) { - \PHPUnit\Framework\Assert::assertContains( - self::PHP_VERSION_MESSAGE, - $setupWizard->getReadiness()->getPhpVersionCheck(), - 'PHP version is incorrect.' - ); - } - \PHPUnit\Framework\Assert::assertContains( - self::PHP_SETTING_REGEXP, - $setupWizard->getReadiness()->getSettingsCheck(), - 'PHP settings check failed.' - ); - \PHPUnit\Framework\Assert::assertRegExp( - self::PHP_EXTENSIONS_REGEXP, - $setupWizard->getReadiness()->getPhpExtensionsCheck(), - 'PHP extensions missed.' - ); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "System Upgrade readiness check passed."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/AssertVersionAndEditionCheck.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/AssertVersionAndEditionCheck.php deleted file mode 100644 index caafa814a871a..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/AssertVersionAndEditionCheck.php +++ /dev/null @@ -1,51 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Constraint; - -use Magento\Setup\Test\Page\Adminhtml\SetupWizard; -use Magento\Mtf\Constraint\AbstractConstraint; - -/** - * Check that package and version is correct - */ -class AssertVersionAndEditionCheck extends AbstractConstraint -{ - /** - * Assert that package and version is correct - * - * @param SetupWizard $setupWizard - * @param array $upgrade - * @return void - */ - public function processAssert(SetupWizard $setupWizard, array $upgrade) :void - { - $message = "We're ready to upgrade {$upgrade['package']} to {$upgrade['version']}."; - if ($upgrade['otherComponents'] === 'Yes' && isset($upgrade['selectedPackages'])) { - foreach ($upgrade['selectedPackages'] as $name => $version) { - $message .= "\nWe're ready to upgrade {$name} to {$version}."; - } - } - $actualMessage = $setupWizard->getSystemUpgrade()->getUpgradeMessage(); - \PHPUnit\Framework\Assert::assertContains( - $message, - $actualMessage, - "Updater application check is incorrect: \n" - . "Expected: '$message' \n" - . "Actual: '$actualMessage'" - ); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "System Upgrade edition and version check passed."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertExtensionAndVersionCheck.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertExtensionAndVersionCheck.php deleted file mode 100644 index 1b8550845e0cd..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertExtensionAndVersionCheck.php +++ /dev/null @@ -1,71 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Constraint\Extension; - -use Magento\Setup\Test\Page\Adminhtml\SetupWizard; -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Setup\Test\Fixture\Extension; - -/** - * Check that extension and version is correct. - */ -class AssertExtensionAndVersionCheck extends AbstractConstraint -{ - /**#@+ - * Types of the job on extensions. - */ - const TYPE_INSTALL = 1; - const TYPE_UNINSTALL = 2; - const TYPE_UPDATE = 3; - /*#@-*/ - - /** - * Assert that extension and version is correct. - * - * @param SetupWizard $setupWizard - * @param Extension $extension - * @param int $type - * @return void - */ - public function processAssert(SetupWizard $setupWizard, Extension $extension, $type) - { - switch ($type) { - case self::TYPE_INSTALL: - $message = "We're ready to install " . $extension->getExtensionName() - . " to " . $extension->getVersion(); - break; - - case self::TYPE_UNINSTALL: - $message = "We're ready to uninstall " . $extension->getExtensionName(); - break; - - case self::TYPE_UPDATE: - $message = "We're ready to update " . $extension->getExtensionName() - . " to " . $extension->getVersionToUpdate(); - break; - - default: - $message = ''; - } - - \PHPUnit\Framework\Assert::assertContains( - $message, - $setupWizard->getUpdaterExtension()->getMessage(), - 'Extension name and version check is incorrect.' - ); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Extension name and version check passed."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertFindExtensionOnGrid.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertFindExtensionOnGrid.php deleted file mode 100644 index 68c0cd1960180..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertFindExtensionOnGrid.php +++ /dev/null @@ -1,42 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Constraint\Extension; - -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Setup\Test\Block\Extension\AbstractGrid; -use Magento\Setup\Test\Fixture\Extension; - -/** - * Check that there is extension on grid. - */ -class AssertFindExtensionOnGrid extends AbstractConstraint -{ - /** - * Assert that there is extension on grid. - * - * @param AbstractGrid $grid - * @param Extension $extension - * @return void - */ - public function processAssert(AbstractGrid $grid, Extension $extension) - { - \PHPUnit\Framework\Assert::assertTrue( - $grid->findExtensionOnGrid($extension), - 'Extension is not found on the grid.' - ); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Extension is found on the grid."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertMultipleExtensionAndVersionCheck.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertMultipleExtensionAndVersionCheck.php deleted file mode 100644 index 79ed17f5d2284..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertMultipleExtensionAndVersionCheck.php +++ /dev/null @@ -1,43 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Constraint\Extension; - -use Magento\Setup\Test\Page\Adminhtml\SetupWizard; -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Setup\Test\Fixture\Extension; - -/** - * Check that extension and version is correct for several extensions. - */ -class AssertMultipleExtensionAndVersionCheck extends AbstractConstraint -{ - /** - * Assert that extensions and versions are correct. - * - * @param SetupWizard $setupWizard - * @param Extension[] $extensions - * @param int $type - * @return void - */ - public function processAssert(SetupWizard $setupWizard, array $extensions, $type) - { - $assertExtensionAndVersionCheck = $this->objectManager->get(AssertExtensionAndVersionCheck::class); - foreach ($extensions as $extension) { - $assertExtensionAndVersionCheck->processAssert($setupWizard, $extension, $type); - } - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Extension name and version check passed."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertMultipleSuccessMessage.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertMultipleSuccessMessage.php deleted file mode 100644 index 3ba87757a875c..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertMultipleSuccessMessage.php +++ /dev/null @@ -1,43 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Constraint\Extension; - -use Magento\Setup\Test\Page\Adminhtml\SetupWizard; -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Setup\Test\Fixture\Extension; - -/** - * Check installing of extensions is successfully. - */ -class AssertMultipleSuccessMessage extends AbstractConstraint -{ - /** - * Assert installing of extensions is successfully. - * - * @param SetupWizard $setupWizard - * @param Extension[] $extensions - * @param int $type - * @return void - */ - public function processAssert(SetupWizard $setupWizard, array $extensions, $type) - { - $assertSuccessMessage = $this->objectManager->get(AssertSuccessMessage::class); - foreach ($extensions as $extension) { - $assertSuccessMessage->processAssert($setupWizard, $extension, $type); - } - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Extension Updater success message is correct."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertSelectSeveralExtensions.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertSelectSeveralExtensions.php deleted file mode 100644 index 945e345d2851f..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertSelectSeveralExtensions.php +++ /dev/null @@ -1,59 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Constraint\Extension; - -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Setup\Test\Block\Extension\AbstractGrid; -use Magento\Setup\Test\Fixture\Extension; - -/** - * Check that several extensions were selected on the grid. - */ -class AssertSelectSeveralExtensions extends AbstractConstraint -{ - /** - * Assert that extensions were selected on the grid. - * - * @param AbstractGrid $grid - * @param Extension[] $extensions - * @return void - */ - public function processAssert(AbstractGrid $grid, array $extensions) - { - $extensions = $grid->selectSeveralExtensions($extensions); - \PHPUnit\Framework\Assert::assertEmpty( - $extensions, - 'Next extensions are not found on the grid: ' . $this->getExtensionsNames($extensions) - ); - } - - /** - * Get names of extensions. - * - * @param Extension[] $extensions - * @return string - */ - protected function getExtensionsNames(array $extensions) - { - $result = []; - foreach ($extensions as $extension) { - $result[] = $extension->getExtensionName(); - } - - return implode(', ', $result); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Extensions are found and selected on the grid."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertSuccessMessage.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertSuccessMessage.php deleted file mode 100644 index 0e1d1be3855dc..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertSuccessMessage.php +++ /dev/null @@ -1,74 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Constraint\Extension; - -use Magento\Setup\Test\Page\Adminhtml\SetupWizard; -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Setup\Test\Fixture\Extension; - -/** - * Check extension installing, updating or uninstalling is successfully. - */ -class AssertSuccessMessage extends AbstractConstraint -{ - /**#@+ - * Types of the job on extensions. - */ - const TYPE_INSTALL = 1; - const TYPE_UNINSTALL = 2; - const TYPE_UPDATE = 3; - /*#@-*/ - - /** - * Assert extension installing, updating or uninstalling is successfully. - * - * @param SetupWizard $setupWizard - * @param Extension $extension - * @param int $type - * @return void - */ - public function processAssert(SetupWizard $setupWizard, Extension $extension, $type) - { - switch ($type) { - case self::TYPE_INSTALL: - $message = "You installed:"; - break; - - case self::TYPE_UNINSTALL: - $message = "You uninstalled:"; - break; - - case self::TYPE_UPDATE: - $message = "You updated:"; - break; - - default: - $message = ''; - } - - \PHPUnit\Framework\Assert::assertContains( - $message, - $setupWizard->getSuccessMessage()->getUpdaterStatus(), - 'Success message is incorrect.' - ); - \PHPUnit\Framework\Assert::assertContains( - $extension->getExtensionName(), - $setupWizard->getSuccessMessage()->getUpdaterStatus(), - 'Extension name is incorrect.' - ); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Extension Updater success message is correct."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertVersionOnGrid.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertVersionOnGrid.php deleted file mode 100644 index 21ed8a24345f4..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Extension/AssertVersionOnGrid.php +++ /dev/null @@ -1,63 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\Constraint\Extension; - -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Setup\Test\Block\Extension\Grid; -use Magento\Setup\Test\Fixture\Extension; - -/** - * Check that version of extension is correct. - */ -class AssertVersionOnGrid extends AbstractConstraint -{ - /**#@+ - * Types of the job on extensions. - */ - const TYPE_INSTALL = 1; - const TYPE_UPDATE = 2; - /*#@-*/ - - /** - * Assert that version of extension is correct. - * - * @param Grid $grid - * @param Extension $extension - * @param int $type - * @return void - */ - public function processAssert(Grid $grid, Extension $extension, $type) - { - switch ($type) { - case self::TYPE_INSTALL: - $version = $extension->getVersion(); - break; - - case self::TYPE_UPDATE: - $version = $extension->getVersionToUpdate(); - break; - - default: - $version = ''; - } - - \PHPUnit\Framework\Assert::assertTrue( - $grid->getVersion($extension) === $version, - 'Version of extension is not correct.' - ); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Version of extension is correct."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Module/AssertModuleInGrid.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Module/AssertModuleInGrid.php deleted file mode 100644 index 236888fbe9583..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Module/AssertModuleInGrid.php +++ /dev/null @@ -1,42 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Test\Constraint\Module; - -use Magento\Mtf\Constraint\AbstractConstraint; -use Magento\Setup\Test\Page\Adminhtml\SetupWizard; - -/** - * Class AssertGrid - * - * Checks whether Module presents in the grid. - */ -class AssertModuleInGrid extends AbstractConstraint -{ - /** - * Recursively search for the Module name. - * - * @param SetupWizard $setupWizard - * @param string $moduleName - * @return void - */ - public function processAssert(SetupWizard $setupWizard, $moduleName) - { - \PHPUnit\Framework\Assert::assertTrue( - $setupWizard->getModuleGrid()->findModuleByName($moduleName)->isVisible(), - 'Module was not found in grid.' - ); - } - - /** - * Returns a string representation of the object. - * - * @return string - */ - public function toString() - { - return 'Module was found in grid.'; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Module/AssertSuccessMessage.php b/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Module/AssertSuccessMessage.php deleted file mode 100644 index 07d8564f47ef3..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Constraint/Module/AssertSuccessMessage.php +++ /dev/null @@ -1,43 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Test\Constraint\Module; - -use Magento\Setup\Test\Page\Adminhtml\SetupWizard; - -/** - * Class AssertSuccessMessage - * - * Checks whether Module manipulation was succeed. - */ -class AssertSuccessMessage -{ - const SUCCESS_MESSAGE = 'Success'; - - /** - * Assert module action is successful. - * - * @param SetupWizard $setupWizard - * @return void - */ - public function processAssert(SetupWizard $setupWizard) - { - \PHPUnit\Framework\Assert::assertContains( - static::SUCCESS_MESSAGE, - $setupWizard->getSuccessMessage()->getDisableModuleStatus(), - 'Success message is incorrect.' - ); - } - - /** - * Returns a string representation of successful assertion. - * - * @return string - */ - public function toString() - { - return "Success message is correct."; - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Fixture/BackupOptions.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/Fixture/BackupOptions.xml deleted file mode 100644 index 6ff0bddcab19e..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Fixture/BackupOptions.xml +++ /dev/null @@ -1,19 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/fixture.xsd"> - <fixture name="backupOptions" - module="Magento_Setup" - type="virtual" - entity_type="backup_options" - class="Magento\Setup\Test\Fixture\BackupOptions" - repository_class="Magento\Setup\Test\Repository\BackupOptions"> - <field name="optionsCode" /> - <field name="optionsMedia" /> - <field name="optionsDb" /> - </fixture> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Fixture/Extension.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/Fixture/Extension.xml deleted file mode 100644 index 62a064e4ec782..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Fixture/Extension.xml +++ /dev/null @@ -1,19 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/fixture.xsd"> - <fixture name="extension" - module="Magento_Setup" - type="virtual" - entity_type="extension" - class="Magento\Setup\Test\Fixture\Extension" - repository_class="Magento\Setup\Test\Repository\Extension"> - <field name="extensionName" /> - <field name="version" /> - <field name="versionToUpdate" /> - </fixture> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Fixture/Module.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/Fixture/Module.xml deleted file mode 100644 index bafb4800b75e6..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Fixture/Module.xml +++ /dev/null @@ -1,16 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/fixture.xsd"> - <fixture name="module" - module="Magento_Setup" - type="virtual" - entity_type="moduleConfig" - class="Magento\Setup\Test\Fixture\Module"> - <field name="moduleName" /> - </fixture> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Fixture/RepoCredentials.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/Fixture/RepoCredentials.xml deleted file mode 100644 index 6c81a245e0688..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Fixture/RepoCredentials.xml +++ /dev/null @@ -1,18 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/fixture.xsd"> - <fixture name="repoCredentials" - module="Magento_Setup" - type="virtual" - entity_type="repo_credentials" - class="Magento\Setup\Test\Fixture\RepoCredentials" - repository_class="Magento\Setup\Test\Repository\RepoCredentials"> - <field name="publicKey" /> - <field name="privateKey" /> - </fixture> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Fixture/Upgrade.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/Fixture/Upgrade.xml deleted file mode 100644 index a33ae68d482ee..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Fixture/Upgrade.xml +++ /dev/null @@ -1,22 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/fixture.xsd"> - <fixture name="upgrade" - module="Magento_Setup" - type="virtual" - entity_type="upgrade" - handler_interface="Magento\Setup\Test\Handler\Upgrade\UpgradeInterface" - class="Magento\Setup\Test\Fixture\Upgrade"> - <field name="upgradeVersion" /> - <field name="publicKey" /> - <field name="privateKey" /> - <field name="optionsCode" /> - <field name="optionsMedia" /> - <field name="optionsDb" /> - </fixture> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Page/Adminhtml/SetupWizard.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/Page/Adminhtml/SetupWizard.xml deleted file mode 100644 index cbc6ab848a6f0..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Page/Adminhtml/SetupWizard.xml +++ /dev/null @@ -1,26 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../vendor/magento/mtf/etc/pages.xsd"> - <page name="setupWizard" area="Adminhtml" mca="admin/backendapp/redirect/app/setup/" module="Magento_Setup"> - <block name="setupHome" class="Magento\Setup\Test\Block\Home" locator="body" strategy="css selector"/> - <block name="extensionsGrid" class="Magento\Setup\Test\Block\Extension\Grid" locator="#main" strategy="css selector"/> - <block name="extensionsInstallGrid" class="Magento\Setup\Test\Block\Extension\InstallGrid" locator="#main" strategy="css selector"/> - <block name="updaterExtension" class="Magento\Setup\Test\Block\Extension\Updater" locator="body" strategy="css selector"/> - <block name="dataOption" class="Magento\Setup\Test\Block\Extension\DataOption" locator="#anchor-content" strategy="css selector"/> - <block name="systemConfig" class="Magento\Setup\Test\Block\SystemConfig" locator="body" strategy="css selector"/> - <block name="authentication" class="Magento\Setup\Test\Block\Authentication" locator="body" strategy="css selector"/> - <block name="selectVersion" class="Magento\Setup\Test\Block\SelectVersion" locator="body" strategy="css selector"/> - <block name="readiness" class="Magento\Setup\Test\Block\Readiness" locator="body" strategy="css selector"/> - <block name="createBackup" class="Magento\Setup\Test\Block\CreateBackup" locator="body" strategy="css selector"/> - <block name="systemUpgrade" class="Magento\Setup\Test\Block\SystemUpgrade" locator="body" strategy="css selector"/> - <block name="successMessage" class="Magento\Setup\Test\Block\SuccessMessage" locator="body" strategy="css selector"/> - <block name="moduleGrid" class="Magento\Setup\Test\Block\Module\Grid" locator=".admin__data-grid-outer-wrap" strategy="css selector"/> - <block name="moduleStatus" class="Magento\Setup\Test\Block\Module\Status" locator="body" strategy="css selector"/> - <block name="extensionsUpdateGrid" class="Magento\Setup\Test\Block\Extension\UpdateGrid" locator="#main" strategy="css selector"/> - </page> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Repository/BackupOptions.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/Repository/BackupOptions.xml deleted file mode 100644 index 5452dfc3746e2..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Repository/BackupOptions.xml +++ /dev/null @@ -1,16 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/Magento/Mtf/Repository/etc/repository.xsd"> - <repository class="Magento\Setup\Test\Repository\BackupOptions"> - <dataset name="default"> - <field name="optionsCode" xsi:type="string">No</field> - <field name="optionsMedia" xsi:type="string">No</field> - <field name="optionsDb" xsi:type="string">No</field> - </dataset> - </repository> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Repository/Extension.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/Repository/Extension.xml deleted file mode 100644 index 4a786a2352df8..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Repository/Extension.xml +++ /dev/null @@ -1,36 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/Magento/Mtf/Repository/etc/repository.xsd"> - <repository class="Magento\Setup\Test\Repository\Extension"> - <dataset name="default"> - <field name="extensionName" xsi:type="string">magento/module-customer-sample-data</field> - <field name="version" xsi:type="string">100.1.0-rc3</field> - <field name="versionToUpdate" xsi:type="string">100.1.0</field> - </dataset> - - <dataset name="firstExtension"> - <field name="extensionName" xsi:type="string">magento/module-customer-sample-data</field> - </dataset> - - <dataset name="secondExtension"> - <field name="extensionName" xsi:type="string">magento/module-theme-sample-data</field> - </dataset> - - <dataset name="thirdExtension"> - <field name="extensionName" xsi:type="string">magento/module-customer-sample-data</field> - <field name="version" xsi:type="string">100.1.0-rc3</field> - <field name="versionToUpdate" xsi:type="string">100.1.0</field> - </dataset> - - <dataset name="fourthExtension"> - <field name="extensionName" xsi:type="string">magento/module-theme-sample-data</field> - <field name="version" xsi:type="string">100.1.0-rc3</field> - <field name="versionToUpdate" xsi:type="string">100.1.0</field> - </dataset> - </repository> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/Repository/RepoCredentials.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/Repository/RepoCredentials.xml deleted file mode 100644 index 159f34692ac27..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/Repository/RepoCredentials.xml +++ /dev/null @@ -1,15 +0,0 @@ -<?xml version="1.0" ?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/Magento/Mtf/Repository/etc/repository.xsd"> - <repository class="Magento\Setup\Test\Repository\RepoCredentials"> - <dataset name="default"> - <field name="publicKey" xsi:type="string">{publicKey}</field> - <field name="privateKey" xsi:type="string">{privateKey}</field> - </dataset> - </repository> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/AbstractExtensionTest.php b/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/AbstractExtensionTest.php deleted file mode 100644 index c7d96e3481f44..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/AbstractExtensionTest.php +++ /dev/null @@ -1,210 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\TestCase; - -use Magento\Mtf\TestCase\Injectable; -use Magento\Setup\Test\Page\Adminhtml\SetupWizard; -use Magento\Backend\Test\Page\Adminhtml\Dashboard; -use Magento\Setup\Test\Fixture\Extension; -use Magento\Setup\Test\Fixture\BackupOptions; -use Magento\Setup\Test\Fixture\RepoCredentials; -use Magento\Setup\Test\Constraint\Extension\AssertFindExtensionOnGrid; -use Magento\Setup\Test\Constraint\Extension\AssertSuccessMessage; -use Magento\Setup\Test\Constraint\Extension\AssertExtensionAndVersionCheck; -use Magento\Setup\Test\Constraint\AssertSuccessfulReadinessCheck; - -/** - * AbstractExtensionTest for testing of extension manager. - */ -abstract class AbstractExtensionTest extends Injectable -{ - /** - * Page System Upgrade Index. - * - * @var SetupWizard - */ - protected $setupWizard; - - /** - * Admin Dashboard - * - * @var Dashboard - */ - protected $adminDashboard; - - /** - * Injection data. - * - * @param Dashboard $adminDashboard - * @param SetupWizard $setupWizard - * @return void - */ - public function __inject( - Dashboard $adminDashboard, - SetupWizard $setupWizard - ) { - $this->adminDashboard = $adminDashboard; - $this->setupWizard = $setupWizard; - } - - /** - * Set credentials for connecting to repo.magento.com - * - * @param bool $needAuthentication - * @param RepoCredentials $repoCredentials - * @return void - */ - protected function repoAuthentication($needAuthentication, RepoCredentials $repoCredentials) - { - if ($needAuthentication) { - $this->setupWizard->getSystemConfig()->clickSystemConfig(); - $this->setupWizard->getAuthentication()->fill($repoCredentials); - $this->setupWizard->getAuthentication()->clickSaveConfig(); - $this->setupWizard->open(); - } - } - - /** - * Readiness check and Create Backup steps. - * - * @param AssertSuccessfulReadinessCheck $assertReadiness - * @param BackupOptions $backupOptions - * @return void - */ - protected function readinessCheckAndBackup( - AssertSuccessfulReadinessCheck $assertReadiness, - BackupOptions $backupOptions - ) { - $this->readinessCheck($assertReadiness); - $this->setupWizard->getReadiness()->clickNext(); - $this->backup($backupOptions); - $this->setupWizard->getCreateBackup()->clickNext(); - } - - /** - * Perform Readiness check. - * - * @param AssertSuccessfulReadinessCheck $assertReadiness - */ - protected function readinessCheck(AssertSuccessfulReadinessCheck $assertReadiness) - { - // Readiness Check - $this->setupWizard->getReadiness()->clickReadinessCheck(); - - $assertReadiness->processAssert($this->setupWizard); - } - - /** - * Perform Backup. - * - * @param BackupOptions $backupOptions - */ - protected function backup(BackupOptions $backupOptions) - { - // Create Backup page - $this->setupWizard->getCreateBackup()->fill($backupOptions); - } - - /** - * Uninstall extension. - * - * @param Extension $extension - * @param BackupOptions $backupOptions - * @param AssertSuccessfulReadinessCheck $assertReadiness - * @param AssertFindExtensionOnGrid $assertFindExtensionOnGrid - * @param AssertExtensionAndVersionCheck $assertExtensionAndVersionCheck - * @param AssertSuccessMessage $assertSuccessMessage - */ - protected function uninstallExtension( - Extension $extension, - BackupOptions $backupOptions, - AssertSuccessfulReadinessCheck $assertReadiness, - AssertFindExtensionOnGrid $assertFindExtensionOnGrid, - AssertExtensionAndVersionCheck $assertExtensionAndVersionCheck, - AssertSuccessMessage $assertSuccessMessage - ) { - // Open Extension Grid with installed extensions and find installed extension - $this->setupWizard->open(); - $this->setupWizard->getSetupHome()->clickExtensionManager(); - $this->setupWizard->getExtensionsGrid()->waitLoader(); - $assertFindExtensionOnGrid->processAssert($this->setupWizard->getExtensionsGrid(), $extension); - - // Click to uninstall extension - $this->setupWizard->getExtensionsGrid()->clickUninstallButton($extension); - - $this->readinessCheckAndBackup($assertReadiness, $backupOptions); - - // Data Option (keep or remove data of extension) - $this->setupWizard->getDataOption()->clickNext(); - - // Uninstall extension - $assertExtensionAndVersionCheck->processAssert( - $this->setupWizard, - $extension, - AssertExtensionAndVersionCheck::TYPE_UNINSTALL - ); - $this->setupWizard->getUpdaterExtension()->clickStartButton(); - $assertSuccessMessage->processAssert( - $this->setupWizard, - $extension, - AssertSuccessMessage::TYPE_UNINSTALL - ); - - // Check that extension is uninstalled - $this->setupWizard->open(); - $this->setupWizard->getSetupHome()->clickExtensionManager(); - $this->setupWizard->getExtensionsGrid()->waitLoader(); - - if ($this->setupWizard->getExtensionsGrid()->findExtensionOnGrid($extension)) { - $this->fail('Extension is not uninstalled!'); - } - } - - /** - * @param Extension $extension - * @param BackupOptions $backupOptions - * @param AssertFindExtensionOnGrid $assertFindExtensionOnGrid - * @param AssertSuccessfulReadinessCheck $assertReadiness - * @param AssertExtensionAndVersionCheck $assertExtensionAndVersionCheck - * @param AssertSuccessMessage $assertSuccessMessage - */ - protected function installExtension( - Extension $extension, - BackupOptions $backupOptions, - AssertFindExtensionOnGrid $assertFindExtensionOnGrid, - AssertSuccessfulReadinessCheck $assertReadiness, - AssertExtensionAndVersionCheck $assertExtensionAndVersionCheck, - AssertSuccessMessage $assertSuccessMessage - ) { - // Open Extension Grid with extensions to install - $this->setupWizard->getSetupHome()->clickExtensionManager(); - $this->setupWizard->getExtensionsGrid()->waitLoader(); - $this->setupWizard->getExtensionsGrid()->clickInstallButton(); - - // Find extension on grid and install - $assertFindExtensionOnGrid->processAssert($this->setupWizard->getExtensionsInstallGrid(), $extension); - $this->setupWizard->getExtensionsInstallGrid()->install($extension); - - $this->readinessCheckAndBackup($assertReadiness, $backupOptions); - - // Install Extension - $assertExtensionAndVersionCheck->processAssert( - $this->setupWizard, - $extension, - AssertExtensionAndVersionCheck::TYPE_INSTALL - ); - $this->setupWizard->getUpdaterExtension()->clickStartButton(); - $assertSuccessMessage->processAssert( - $this->setupWizard, - $extension, - AssertSuccessMessage::TYPE_INSTALL - ); - - // Open Web Setup Wizard - $this->setupWizard->open(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/EnableDisableModuleTest.php b/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/EnableDisableModuleTest.php deleted file mode 100644 index 9b96c0c387c6c..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/EnableDisableModuleTest.php +++ /dev/null @@ -1,148 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Test\TestCase; - -use Magento\Mtf\TestCase\Injectable; -use Magento\Backend\Test\Page\Adminhtml\Dashboard; -use Magento\Setup\Test\Constraint\Module\AssertModuleInGrid; -use Magento\Setup\Test\Constraint\AssertSuccessfulReadinessCheck; -use Magento\Setup\Test\Constraint\Module\AssertSuccessMessage; -use Magento\Setup\Test\Fixture\BackupOptions; -use Magento\Setup\Test\Fixture\Module; -use Magento\Setup\Test\Page\Adminhtml\SetupWizard; - -/** - * Preconditions: - * 1. Appropriate Module must be installed and enabled. - * - * Steps: - * 1. Open Backend. - * 2. Go to System > Web Setup Wizard. - * 3. Click "Module Manager" button. - * 4. Find Module in the Grid and click Select > Disable module. - * 5. Perform Readiness Checks. - * 6. Perform DB Backup. - * 7. Click "Disable" button. - * 8. Check for Success message - * 9. Return to "Web Setup Wizard". - * 10. Click "Module Manager" button. - * 11. Find appropriate Module in the Grid. - * 12. Find Module in the Grid and click Select > Enable module. - * 13. Perform Readiness Checks. - * 14. Perform DB Backup. - * 15. Click "Enable" button. - * 16. Check for Success message - * 17. Return to "Web Setup Wizard". - * - * @group Setup - * @ZephyrId MAGETWO-43202 - */ -class EnableDisableModuleTest extends Injectable -{ - /** - * Dashboard page. - * - * @var Dashboard - */ - private $adminDashboard; - - /** - * Web Setup Wizard page. - * - * @var SetupWizard - */ - private $setupWizard; - - /** - * Injection of pages. - * - * @param Dashboard $dashboard - * @param SetupWizard $setupWizard - */ - public function __inject(Dashboard $dashboard, SetupWizard $setupWizard) - { - $this->adminDashboard = $dashboard; - $this->setupWizard = $setupWizard; - } - - /** - * Test root method. - * - * @param Module $module - * @param BackupOptions $backupOptions - * @param AssertModuleInGrid $assertModuleInGrid - * @param AssertSuccessfulReadinessCheck $assertReadiness - * @param AssertSuccessMessage $assertSuccessMessage - */ - public function test( - Module $module, - BackupOptions $backupOptions, - AssertModuleInGrid $assertModuleInGrid, - AssertSuccessfulReadinessCheck $assertReadiness, - AssertSuccessMessage $assertSuccessMessage - ) { - // Open Backend - $this->adminDashboard->open(); - - // Go to System > Web Setup Wizard - $this->setupWizard->open(); - - // Click "Module Manager" button - $this->setupWizard->getSetupHome()->clickModuleManager(); - - // Find appropriate Module in the grid - $assertModuleInGrid->processAssert($this->setupWizard, $module->getModuleName()); - - if (!$this->setupWizard->getModuleGrid()->isModuleEnabled($module->getModuleName())) { - $this->fail('Module is already disabled.'); - } - - // Find Module in the Grid and click Select > Disable module - $this->setupWizard->getModuleGrid()->disableModule($module->getModuleName()); - - // Perform Readiness Checks - $this->setupWizard->getReadiness()->clickReadinessCheck(); - $assertReadiness->processAssert($this->setupWizard); - $this->setupWizard->getReadiness()->clickNext(); - - // Perform DB Backup - $this->setupWizard->getCreateBackup()->fill($backupOptions); - $this->setupWizard->getCreateBackup()->clickNext(); - - // Click "Disable" button - $this->setupWizard->getModuleStatus()->clickDisable(); - - // Check for Success message - $assertSuccessMessage->processAssert($this->setupWizard); - - // Return to "Web Setup Wizard" - $this->setupWizard->getSuccessMessage()->clickBackToSetup(); - - // Find appropriate Module in the Grid - $assertModuleInGrid->processAssert($this->setupWizard, $module->getModuleName()); - - // Find Module in the Grid and click Select > Enable module - $this->setupWizard->getModuleGrid()->enableModule($module->getModuleName()); - - // Perform Readiness Checks - $this->setupWizard->getReadiness()->clickReadinessCheck(); - $assertReadiness->processAssert($this->setupWizard); - $this->setupWizard->getReadiness()->clickNext(); - - // Perform DB Backup - $this->setupWizard->getCreateBackup()->fill($backupOptions); - $this->setupWizard->getCreateBackup()->clickNext(); - - // Click "Enable" button - $this->setupWizard->getModuleStatus()->clickEnable(); - - // Check for Success message - $assertSuccessMessage->processAssert($this->setupWizard); - - // Return to "Web Setup Wizard" - $this->setupWizard->getSuccessMessage()->clickBackToSetup(); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/EnableDisableModuleTest.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/EnableDisableModuleTest.xml deleted file mode 100644 index 7c2817ede93ed..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/EnableDisableModuleTest.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Setup\Test\TestCase\EnableDisableModuleTest" summary="Enable/Disable Module" ticketId="MAGETWO-43202"> - <variation name="variation1" summary="Disable Module Magento_Sitemap"> - <data name="module/data/moduleName" xsi:type="string">magento/module-sitemap</data> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionMultipleTest.php b/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionMultipleTest.php deleted file mode 100644 index 94e741156880e..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionMultipleTest.php +++ /dev/null @@ -1,110 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\TestCase; - -use Magento\Setup\Test\Constraint\Extension\AssertFindExtensionOnGrid; -use Magento\Mtf\Fixture\FixtureFactory; -use Magento\Setup\Test\Fixture\Extension; -use Magento\Setup\Test\Fixture\BackupOptions; -use Magento\Setup\Test\Fixture\RepoCredentials; -use Magento\Setup\Test\Constraint\AssertSuccessfulReadinessCheck; -use Magento\Setup\Test\Constraint\Extension\AssertSuccessMessage; -use Magento\Setup\Test\Constraint\Extension\AssertMultipleSuccessMessage; -use Magento\Setup\Test\Constraint\Extension\AssertMultipleExtensionAndVersionCheck; -use Magento\Setup\Test\Constraint\Extension\AssertExtensionAndVersionCheck; -use Magento\Setup\Test\Constraint\Extension\AssertSelectSeveralExtensions; - -/** - * ExtensionMultipleTest checks installing of several extensions - */ -class ExtensionMultipleTest extends AbstractExtensionTest -{ - /** - * @param FixtureFactory $fixtureFactory - * @param AssertExtensionAndVersionCheck $assertExtensionAndVersionCheck - * @param AssertMultipleExtensionAndVersionCheck $assertMultipleExtensionAndVersionCheck - * @param AssertSuccessMessage $assertSuccessMessage - * @param AssertMultipleSuccessMessage $assertMultipleSuccessMessage - * @param AssertSuccessfulReadinessCheck $assertReadiness - * @param AssertSelectSeveralExtensions $assertSelectSeveralExtensions - * @param AssertFindExtensionOnGrid $assertFindExtensionOnGrid - * @param bool $needAuthentication - * @param RepoCredentials $repoCredentials - * @param BackupOptions $backupOptions - * @param Extension[] $extensions - * @SuppressWarnings(PHPMD.ExcessiveParameterList) - */ - public function test( - FixtureFactory $fixtureFactory, - AssertExtensionAndVersionCheck $assertExtensionAndVersionCheck, - AssertMultipleExtensionAndVersionCheck $assertMultipleExtensionAndVersionCheck, - AssertSuccessMessage $assertSuccessMessage, - AssertMultipleSuccessMessage $assertMultipleSuccessMessage, - AssertSuccessfulReadinessCheck $assertReadiness, - AssertSelectSeveralExtensions $assertSelectSeveralExtensions, - AssertFindExtensionOnGrid $assertFindExtensionOnGrid, - $needAuthentication, - RepoCredentials $repoCredentials, - BackupOptions $backupOptions, - array $extensions - ) { - foreach ($extensions as $key => $options) { - $extensions[$key] = $fixtureFactory->create(Extension::class, $options); - } - - // Authenticate in admin area - $this->adminDashboard->open(); - - // Open Web Setup Wizard - $this->setupWizard->open(); - - // Authenticate on repo.magento.com - $this->repoAuthentication($needAuthentication, $repoCredentials); - - // Open Extension Grid with extensions to install - $this->setupWizard->getSetupHome()->clickExtensionManager(); - $this->setupWizard->getExtensionsGrid()->waitLoader(); - $this->setupWizard->getExtensionsGrid()->clickInstallButton(); - - // Select several extensions on grid and check it - $assertSelectSeveralExtensions->processAssert($this->setupWizard->getExtensionsInstallGrid(), $extensions); - - // Click general "Install" button - $this->setupWizard->getExtensionsInstallGrid()->clickInstallAll(); - - $this->readinessCheckAndBackup($assertReadiness, $backupOptions); - - // Check selected extensions - $assertMultipleExtensionAndVersionCheck->processAssert( - $this->setupWizard, - $extensions, - AssertExtensionAndVersionCheck::TYPE_INSTALL - ); - - // Start installing - $this->setupWizard->getUpdaterExtension()->clickStartButton(); - - // Check success message - $assertMultipleSuccessMessage->processAssert( - $this->setupWizard, - $extensions, - AssertSuccessMessage::TYPE_INSTALL - ); - - // Uninstall installed extensions - foreach ($extensions as $extension) { - $this->uninstallExtension( - $extension, - $backupOptions, - $assertReadiness, - $assertFindExtensionOnGrid, - $assertExtensionAndVersionCheck, - $assertSuccessMessage - ); - } - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionMultipleTest.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionMultipleTest.xml deleted file mode 100644 index 783c0d7f00fe4..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionMultipleTest.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Setup\Test\TestCase\ExtensionMultipleTest" - summary="Multiple Install Extensions"> - <variation name="PerformMultipleInstallExtensions"> - <data name="needAuthentication" xsi:type="boolean">false</data> - <data name="extensions" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="dataset" xsi:type="string">firstExtension</item> - </item> - <item name="1" xsi:type="array"> - <item name="dataset" xsi:type="string">secondExtension</item> - </item> - </data> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionMultipleUpdateTest.php b/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionMultipleUpdateTest.php deleted file mode 100644 index f195d04191ada..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionMultipleUpdateTest.php +++ /dev/null @@ -1,132 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Test\TestCase; - -use Magento\Mtf\Fixture\FixtureFactory; -use Magento\Setup\Test\Constraint\AssertSuccessfulReadinessCheck; -use Magento\Setup\Test\Constraint\Extension\AssertExtensionAndVersionCheck; -use Magento\Setup\Test\Constraint\Extension\AssertFindExtensionOnGrid; -use Magento\Setup\Test\Constraint\Extension\AssertMultipleSuccessMessage; -use Magento\Setup\Test\Constraint\Extension\AssertSelectSeveralExtensions; -use Magento\Setup\Test\Constraint\Extension\AssertSuccessMessage; -use Magento\Setup\Test\Fixture\BackupOptions; -use Magento\Setup\Test\Fixture\Extension; -use Magento\Setup\Test\Fixture\RepoCredentials; - -/** - * @group Setup_(CS) - * @ZephyrId MAGETWO-56328, MAGETWO-56332 - */ -class ExtensionMultipleUpdateTest extends AbstractExtensionTest -{ - /** - * @param FixtureFactory $fixtureFactory - * @param RepoCredentials $repoCredentials - * @param BackupOptions $backupOptions - * @param AssertFindExtensionOnGrid $assertFindExtensionOnGrid - * @param AssertSuccessfulReadinessCheck $assertReadiness - * @param AssertExtensionAndVersionCheck $assertExtensionAndVersionCheck - * @param AssertSuccessMessage $assertSuccessMessage - * @param AssertMultipleSuccessMessage $assertMultipleSuccessMessage - * @param AssertSelectSeveralExtensions $assertSelectSeveralExtensions - * @param $needAuthentication - * @param array $extensions - * @param array $removeExtensions - * - * @SuppressWarnings(PHPMD.ExcessiveParameterList) - */ - public function test( - FixtureFactory $fixtureFactory, - RepoCredentials $repoCredentials, - BackupOptions $backupOptions, - AssertFindExtensionOnGrid $assertFindExtensionOnGrid, - AssertSuccessfulReadinessCheck $assertReadiness, - AssertExtensionAndVersionCheck $assertExtensionAndVersionCheck, - AssertSuccessMessage $assertSuccessMessage, - AssertMultipleSuccessMessage $assertMultipleSuccessMessage, - AssertSelectSeveralExtensions $assertSelectSeveralExtensions, - $needAuthentication, - array $extensions, - array $removeExtensions - ) { - foreach ($extensions as $key => $options) { - $extensions[$key] = $fixtureFactory->create(Extension::class, $options); - } - - foreach ($removeExtensions as $key => $options) { - $removeExtensions[$key] = $fixtureFactory->create(Extension::class, $options); - } - - // Authenticate in admin area - $this->adminDashboard->open(); - - // Open Web Setup Wizard - $this->setupWizard->open(); - - // Authenticate on repo.magento.com - $this->repoAuthentication($needAuthentication, $repoCredentials); - - foreach ($extensions as $extension) { - $this->installExtension( - $extension, - $backupOptions, - $assertFindExtensionOnGrid, - $assertReadiness, - $assertExtensionAndVersionCheck, - $assertSuccessMessage - ); - } - - // Open Extension Grid with extensions to update - $this->setupWizard->getSetupHome()->clickExtensionManager(); - $this->setupWizard->getExtensionsGrid()->waitLoader(); - $this->setupWizard->getExtensionsGrid()->clickUpdateButton(); - - // Select several extensions on grid and check it - $assertSelectSeveralExtensions->processAssert($this->setupWizard->getExtensionsUpdateGrid(), $extensions); - - // Click general "Update" button - $this->setupWizard->getExtensionsUpdateGrid()->clickUpdateAllButton(); - - $this->readinessCheck($assertReadiness); - - /** @var Extension $removeExtension */ - foreach ($removeExtensions as $removeExtension) { - $this->setupWizard->getReadiness()->clickRemoveExtension($removeExtension); - $this->setupWizard->getReadiness()->clickRemoveExtensionOnModal(); - } - - $this->setupWizard->getReadiness()->clickTryAgain(); - $assertReadiness->processAssert($this->setupWizard); - $this->setupWizard->getReadiness()->clickNext(); - $this->backup($backupOptions); - $this->setupWizard->getCreateBackup()->clickNext(); - - // Start updating - $this->setupWizard->getUpdaterExtension()->clickStartButton(); - - $updatedExtensions = array_diff_key($extensions, $removeExtensions); - - // Check success message - $assertMultipleSuccessMessage->processAssert( - $this->setupWizard, - $updatedExtensions, - AssertSuccessMessage::TYPE_UPDATE - ); - - // Uninstall installed extensions - foreach ($extensions as $extension) { - $this->uninstallExtension( - $extension, - $backupOptions, - $assertReadiness, - $assertFindExtensionOnGrid, - $assertExtensionAndVersionCheck, - $assertSuccessMessage - ); - } - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionMultipleUpdateTest.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionMultipleUpdateTest.xml deleted file mode 100644 index be21f644b5e29..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionMultipleUpdateTest.xml +++ /dev/null @@ -1,27 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Setup\Test\TestCase\ExtensionMultipleUpdateTest" summary="Multiple Update Extensions"> - <variation name="PerformMultipleUpdateExtensions"> - <data name="needAuthentication" xsi:type="boolean">false</data> - <data name="extensions" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="dataset" xsi:type="string">thirdExtension</item> - </item> - <item name="1" xsi:type="array"> - <item name="dataset" xsi:type="string">fourthExtension</item> - </item> - </data> - <data name="removeExtensions" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="dataset" xsi:type="string">thirdExtension</item> - </item> - </data> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionTest.php b/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionTest.php deleted file mode 100644 index bc7d8741436ef..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionTest.php +++ /dev/null @@ -1,133 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\TestCase; - -use Magento\Setup\Test\Fixture\Extension; -use Magento\Setup\Test\Fixture\BackupOptions; -use Magento\Setup\Test\Fixture\RepoCredentials; -use Magento\Setup\Test\Constraint\Extension\AssertFindExtensionOnGrid; -use Magento\Setup\Test\Constraint\Extension\AssertSuccessMessage; -use Magento\Setup\Test\Constraint\Extension\AssertExtensionAndVersionCheck; -use Magento\Setup\Test\Constraint\Extension\AssertVersionOnGrid; -use Magento\Setup\Test\Constraint\AssertSuccessfulReadinessCheck; - -/** - * ExtensionTest checks installing, updating and uninstalling of extensions. - */ -class ExtensionTest extends AbstractExtensionTest -{ - /** - * @param AssertFindExtensionOnGrid $assertFindExtensionOnGrid - * @param AssertSuccessfulReadinessCheck $assertReadiness - * @param AssertExtensionAndVersionCheck $assertExtensionAndVersionCheck - * @param AssertSuccessMessage $assertSuccessMessage - * @param AssertVersionOnGrid $assertVersionOnGrid - * @param bool $needAuthentication - * @param Extension $extension - * @param RepoCredentials $repoCredentials - * @param BackupOptions $backupOptions - * @return void - */ - public function test( - AssertFindExtensionOnGrid $assertFindExtensionOnGrid, - AssertSuccessfulReadinessCheck $assertReadiness, - AssertExtensionAndVersionCheck $assertExtensionAndVersionCheck, - AssertSuccessMessage $assertSuccessMessage, - AssertVersionOnGrid $assertVersionOnGrid, - $needAuthentication, - Extension $extension, - RepoCredentials $repoCredentials, - BackupOptions $backupOptions - ) { - // Authenticate in admin area - $this->adminDashboard->open(); - - // Open Web Setup Wizard - $this->setupWizard->open(); - - // Authenticate on repo.magento.com - $this->repoAuthentication($needAuthentication, $repoCredentials); - - // Open Extension Grid with extensions to install - $this->setupWizard->getSetupHome()->clickExtensionManager(); - $this->setupWizard->getExtensionsGrid()->waitLoader(); - $this->setupWizard->getExtensionsGrid()->clickInstallButton(); - - // Find extension on grid and install - $assertFindExtensionOnGrid->processAssert($this->setupWizard->getExtensionsInstallGrid(), $extension); - $this->setupWizard->getExtensionsInstallGrid()->install($extension); - - $this->readinessCheckAndBackup($assertReadiness, $backupOptions); - - // Install Extension - $assertExtensionAndVersionCheck->processAssert( - $this->setupWizard, - $extension, - AssertExtensionAndVersionCheck::TYPE_INSTALL - ); - $this->setupWizard->getUpdaterExtension()->clickStartButton(); - $assertSuccessMessage->processAssert( - $this->setupWizard, - $extension, - AssertSuccessMessage::TYPE_INSTALL - ); - - // Open Extension Grid with installed extensions and find installed extension - $this->setupWizard->open(); - $this->setupWizard->getSetupHome()->clickExtensionManager(); - $this->setupWizard->getExtensionsGrid()->waitLoader(); - $assertFindExtensionOnGrid->processAssert($this->setupWizard->getExtensionsGrid(), $extension); - - // Check version of installed extension - $assertVersionOnGrid->processAssert( - $this->setupWizard->getExtensionsGrid(), - $extension, - AssertVersionOnGrid::TYPE_INSTALL - ); - - // Update extension - $this->setupWizard->getExtensionsGrid()->clickUpdateButton($extension); - - $this->readinessCheckAndBackup($assertReadiness, $backupOptions); - - // Update extension - $assertExtensionAndVersionCheck->processAssert( - $this->setupWizard, - $extension, - AssertExtensionAndVersionCheck::TYPE_UPDATE - ); - $this->setupWizard->getUpdaterExtension()->clickStartButton(); - $assertSuccessMessage->processAssert( - $this->setupWizard, - $extension, - AssertSuccessMessage::TYPE_UPDATE - ); - - // Open Extension Grid with updated extensions and find updated extension - $this->setupWizard->open(); - $this->setupWizard->getSetupHome()->clickExtensionManager(); - $this->setupWizard->getExtensionsGrid()->waitLoader(); - $assertFindExtensionOnGrid->processAssert($this->setupWizard->getExtensionsGrid(), $extension); - - // Check version of updated extension - $assertVersionOnGrid->processAssert( - $this->setupWizard->getExtensionsGrid(), - $extension, - AssertVersionOnGrid::TYPE_UPDATE - ); - - // Uninstall extension - $this->uninstallExtension( - $extension, - $backupOptions, - $assertReadiness, - $assertFindExtensionOnGrid, - $assertExtensionAndVersionCheck, - $assertSuccessMessage - ); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionTest.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionTest.xml deleted file mode 100644 index a7c4a6a6331ba..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/ExtensionTest.xml +++ /dev/null @@ -1,14 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Setup\Test\TestCase\ExtensionTest" summary="Install, Update and Uninstall Extension" ticketId="MAGETWO-47925"> - <variation name="PerformInstallUpdateUninstallExtension"> - <data name="needAuthentication" xsi:type="boolean">false</data> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/UpgradeSystemTest.php b/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/UpgradeSystemTest.php deleted file mode 100644 index 7a82b43dba76d..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/UpgradeSystemTest.php +++ /dev/null @@ -1,139 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Test\TestCase; - -use Magento\Mtf\TestCase\Injectable; -use Magento\Setup\Test\Fixture\Upgrade; -use Magento\Setup\Test\Page\Adminhtml\SetupWizard; -use Magento\Backend\Test\Page\Adminhtml\Dashboard; -use Magento\Mtf\Fixture\FixtureFactory; -use Magento\Setup\Test\Constraint\AssertSuccessfulReadinessCheck; -use Magento\Setup\Test\Constraint\AssertVersionAndEditionCheck; -use Magento\Setup\Test\Constraint\AssertSuccessMessage; -use Magento\Setup\Test\Constraint\AssertApplicationVersion; - -class UpgradeSystemTest extends Injectable -{ - /** - * Page System Upgrade Index. - * - * @var SetupWizard - */ - protected $setupWizard; - - /** - * @var Dashboard - */ - protected $adminDashboard; - - /** - * Injection data. - * - * @param Dashboard $adminDashboard - * @param SetupWizard $setupWizard - * @return void - */ - public function __inject( - Dashboard $adminDashboard, - SetupWizard $setupWizard - ) { - $this->adminDashboard = $adminDashboard; - $this->setupWizard = $setupWizard; - } - - /** - * @param FixtureFactory $fixtureFactory - * @param AssertSuccessfulReadinessCheck $assertReadiness - * @param AssertVersionAndEditionCheck $assertVersionAndEdition - * @param AssertSuccessMessage $assertSuccessMessage - * @param AssertApplicationVersion $assertApplicationVersion - * @param array $upgrade - * @return void - */ - public function test( - FixtureFactory $fixtureFactory, - AssertSuccessfulReadinessCheck $assertReadiness, - AssertVersionAndEditionCheck $assertVersionAndEdition, - AssertSuccessMessage $assertSuccessMessage, - AssertApplicationVersion $assertApplicationVersion, - array $upgrade = [] - ) { - // Create fixture - $upgradeFixture = $fixtureFactory->create(Upgrade::class, ['data' => $upgrade]); - $createBackupConfig = array_intersect_key( - $upgrade, - ['optionsCode' => '', 'optionsMedia' => '', 'optionsDb' => ''] - ); - $createBackupFixture = $fixtureFactory->create( - Upgrade::class, - ['data' => $createBackupConfig] - ); - $version = $upgrade['upgradeVersion']; - - $suffix = "( (CE|EE|B2B))$"; - $normalVersion = '(0|[1-9]\d*)'; - $preReleaseVersion = "((0(?!\\d+(\\.|\\+|{$suffix}))|[1-9A-Za-z])[0-9A-Za-z-]*)"; - $buildVersion = '([0-9A-Za-z][0-9A-Za-z-]*)'; - $versionPattern = "/^{$normalVersion}(\\.{$normalVersion}){2}" - . "(-{$preReleaseVersion}(\\.{$preReleaseVersion})*)?" - . "(\\+{$buildVersion}(\\.{$buildVersion})*)?{$suffix}/"; - - if (preg_match($versionPattern, $version)) { - preg_match("/(.*){$suffix}/", $version, $matches); - $version = $matches[1]; - } else { - $this->fail( - "Provided version format does not comply with semantic versioning specification. Got '{$version}'" - ); - } - - // Authenticate in admin area - $this->adminDashboard->open(); - - // Open Web Setup Wizard - $this->setupWizard->open(); - - // Authenticate on repo.magento.com - if ($upgrade['needAuthentication'] === 'Yes') { - $this->setupWizard->getSystemConfig()->clickSystemConfig(); - $this->setupWizard->getAuthentication()->fill($upgradeFixture); - $this->setupWizard->getAuthentication()->clickSaveConfig(); - $this->setupWizard->open(); - } - - // Select upgrade to version - $this->setupWizard->getSetupHome()->clickSystemUpgrade(); - $this->setupWizard->getSelectVersion()->fill($upgradeFixture); - if ($upgrade['otherComponents'] === 'Yes') { - $this->setupWizard->getSelectVersion()->chooseUpgradeOtherComponents($upgrade['otherComponentsList']); - } - $this->setupWizard->getSelectVersion()->clickNext(); - - // Readiness Check - $this->setupWizard->getReadiness()->clickReadinessCheck(); - $assertReadiness->processAssert($this->setupWizard); - $this->setupWizard->getReadiness()->clickNext(); - - // Create Backup page - $this->setupWizard->getCreateBackup()->fill($createBackupFixture); - $this->setupWizard->getCreateBackup()->clickNext(); - - // Check info and press 'Upgrade' button - $upgrade['version'] = $version; - $upgrade['selectedPackages'] = $this->setupWizard->getSelectVersion()->getSelectedPackages(); - $assertVersionAndEdition->processAssert($this->setupWizard, $upgrade); - $this->setupWizard->getSystemUpgrade()->clickSystemUpgrade(); - - $assertSuccessMessage->processAssert($this->setupWizard, $upgrade['package']); - - // Check application version - $this->adminDashboard->open(); - $this->adminDashboard->getModalMessage()->dismissIfModalAppears(); - $this->adminDashboard->getModalMessage()->waitModalWindowToDisappear(); - $assertApplicationVersion->processAssert($this->adminDashboard, $version); - } -} diff --git a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/UpgradeSystemTest.xml b/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/UpgradeSystemTest.xml deleted file mode 100644 index 95193dbf6c097..0000000000000 --- a/dev/tests/functional/tests/app/Magento/Setup/Test/TestCase/UpgradeSystemTest.xml +++ /dev/null @@ -1,30 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?> -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - --> -<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/variations.xsd"> - <testCase name="Magento\Setup\Test\TestCase\UpgradeSystemTest" summary="System Upgrade" ticketId="MAGETWO-45592"> - <variation name="PerformSystemUpgrade"> - <data name="description" xsi:type="string">System Upgrade Page</data> - <data name="upgrade/upgradeVersion" xsi:type="string">{version}</data> - <data name="upgrade/package" xsi:type="string">{package}</data> - <data name="upgrade/needAuthentication" xsi:type="string">No</data> - <data name="upgrade/publicKey" xsi:type="string">{publicKey}</data> - <data name="upgrade/privateKey" xsi:type="string">{privateKey}</data> - <data name="upgrade/optionsCode" xsi:type="string">No</data> - <data name="upgrade/optionsMedia" xsi:type="string">No</data> - <data name="upgrade/optionsDb" xsi:type="string">No</data> - <data name="upgrade/otherComponents" xsi:type="string">{otherComponents}</data> - <!-- If otherComponents value is Yes specify otherComponentsList items--> - <data name="upgrade/otherComponentsList" xsi:type="array"> - <item name="0" xsi:type="array"> - <item name="name" xsi:type="string">{package_0_name}</item> - <item name="version" xsi:type="string">{package_0_version}</item> - </item> - </data> - </variation> - </testCase> -</config> diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/Page/CheckoutOnepage.xml b/dev/tests/functional/tests/app/Magento/Vault/Test/Page/CheckoutOnepage.xml index b5e5bdf33b1b6..fe0caebf8c097 100644 --- a/dev/tests/functional/tests/app/Magento/Vault/Test/Page/CheckoutOnepage.xml +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/Page/CheckoutOnepage.xml @@ -8,8 +8,10 @@ <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../vendor/magento/mtf/etc/pages.xsd"> <page name="CheckoutOnepage" mca="checkout/index"> <block name="vaultPaymentBlock" class="Magento\Vault\Test\Block\Onepage\Payment\Method\Vault" locator="#checkout-step-payment" strategy="css selector" /> + <!-- <block name="paymentBlock"> <render name="braintree" class="Magento\Braintree\Test\Block\Form\BraintreeCc" /> </block> + --> </page> </config> diff --git a/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/DeleteSavedCreditCardTest.xml b/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/DeleteSavedCreditCardTest.xml index bd8c470ca1f2b..8eb17cfdcc87e 100644 --- a/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/DeleteSavedCreditCardTest.xml +++ b/dev/tests/functional/tests/app/Magento/Vault/Test/TestCase/DeleteSavedCreditCardTest.xml @@ -16,18 +16,6 @@ <data name="shipping/shipping_method" xsi:type="string">Fixed</data> <data name="payments" xsi:type="array"> <item name="0" xsi:type="array"> - <item name="method" xsi:type="string">braintree</item> - <item name="arguments" xsi:type="array"> - <item name="paymentForm" xsi:type="string">braintree</item> - </item> - <item name="creditCard" xsi:type="array"> - <item name="dataset" xsi:type="string">visa_default</item> - <item name="data" xsi:type="array"> - <item name="payment_code" xsi:type="string">braintree</item> - </item> - </item> - </item> - <item name="1" xsi:type="array"> <item name="method" xsi:type="string">payflowpro</item> <item name="creditCard" xsi:type="array"> <item name="dataset" xsi:type="string">visa_alt</item> @@ -36,22 +24,7 @@ </item> </item> </item> - <item name="2" xsi:type="array"> - <item name="method" xsi:type="string">braintree</item> - <item name="arguments" xsi:type="array"> - <item name="paymentForm" xsi:type="string">braintree</item> - </item> - <item name="creditCard" xsi:type="array"> - <item name="dataset" xsi:type="string">visa_default</item> - <item name="data" xsi:type="array"> - <item name="payment_code" xsi:type="string">braintree</item> - </item> - </item> - <item name="vault" xsi:type="array"> - <item name="method" xsi:type="string">braintree_cc_vault</item> - </item> - </item> - <item name="3" xsi:type="array"> + <item name="1" xsi:type="array"> <item name="method" xsi:type="string">payflowpro</item> <item name="creditCard" xsi:type="array"> <item name="dataset" xsi:type="string">visa_alt</item> @@ -65,7 +38,7 @@ </item> </data> <data name="creditCardSave" xsi:type="string">Yes</data> - <data name="configData" xsi:type="string">braintree, payflowpro, braintree_use_vault, payflowpro_use_vault</data> + <data name="configData" xsi:type="string">payflowpro, payflowpro_use_vault</data> <data name="tag" xsi:type="string">test_type:3rd_party_test, severity:S1</data> </variation> </testCase> diff --git a/dev/tests/integration/framework/Magento/TestFramework/Db/Mysql.php b/dev/tests/integration/framework/Magento/TestFramework/Db/Mysql.php index 6900f89a55f9d..7627d78df12dc 100644 --- a/dev/tests/integration/framework/Magento/TestFramework/Db/Mysql.php +++ b/dev/tests/integration/framework/Magento/TestFramework/Db/Mysql.php @@ -9,15 +9,17 @@ */ namespace Magento\TestFramework\Db; +use Magento\Framework\Exception\LocalizedException; + class Mysql extends \Magento\TestFramework\Db\AbstractDb { /** - * Default port + * Mysql default Port. */ const DEFAULT_PORT = 3306; /** - * Defaults extra file name + * Name of configuration file. */ const DEFAULTS_EXTRA_FILE_NAME = 'defaults_extra.cnf'; @@ -42,8 +44,20 @@ class Mysql extends \Magento\TestFramework\Db\AbstractDb */ private $_port; + /** + * @var bool + */ + private $mysqlDumpVersionIs8; + /** * {@inheritdoc} + * + * @param string $host + * @param string $user + * @param string $password + * @param string $schema + * @param string $varPath + * @param \Magento\Framework\Shell $shell */ public function __construct($host, $user, $password, $schema, $varPath, \Magento\Framework\Shell $shell) { @@ -102,15 +116,35 @@ public function isDbDumpExists() public function storeDbDump() { $this->ensureDefaultsExtraFile(); + $additionalArguments = ''; + + if ($this->isMysqlDumpVersion8()) { + $additionalArguments = '--column-statistics=0'; + } + + $format = sprintf( + '%s %s %s', + 'mysqldump --defaults-file=%s --host=%s --port=%s', + $additionalArguments, + '%s > %s' + ); + $this->_shell->execute( - 'mysqldump --defaults-file=%s --host=%s --port=%s %s > %s', - [$this->_defaultsExtraFile, $this->_host, $this->_port, $this->_schema, $this->getSetupDbDumpFilename()] + $format, + [ + $this->_defaultsExtraFile, + $this->_host, + $this->_port, + $this->_schema, + $this->getSetupDbDumpFilename() + ] ); } /** - * {@inheritdoc} - * @throws \LogicException + * @inheritdoc + * + * @throws LocalizedException */ public function restoreFromDbDump() { @@ -125,7 +159,7 @@ public function restoreFromDbDump() } /** - * {@inheritdoc} + * @inheritdoc */ public function getVendorName() { @@ -141,9 +175,32 @@ private function ensureDefaultsExtraFile() { if (!file_exists($this->_defaultsExtraFile)) { $this->assertVarPathWritable(); - $extraConfig = ['[client]', 'user=' . $this->_user, 'password="' . $this->_password . '"']; + $extraConfig = [ + '[client]', + 'user=' . $this->_user, + 'password="' . $this->_password . '"' + ]; file_put_contents($this->_defaultsExtraFile, implode(PHP_EOL, $extraConfig)); chmod($this->_defaultsExtraFile, 0640); } } + + /** + * Check if mysql dump is version 8. + * + * @return bool + * @throws LocalizedException + */ + private function isMysqlDumpVersion8(): bool + { + if (!$this->mysqlDumpVersionIs8) { + $version = $this->_shell->execute( + 'mysqldump --version' + ); + + $this->mysqlDumpVersionIs8 = (bool) preg_match('/8\.0\./', $version); + } + + return $this->mysqlDumpVersionIs8; + } } diff --git a/dev/tests/integration/framework/Magento/TestFramework/HTTP/AsyncClientInterfaceMock.php b/dev/tests/integration/framework/Magento/TestFramework/HTTP/AsyncClientInterfaceMock.php index caef011267bc7..ab0020917a9e9 100644 --- a/dev/tests/integration/framework/Magento/TestFramework/HTTP/AsyncClientInterfaceMock.php +++ b/dev/tests/integration/framework/Magento/TestFramework/HTTP/AsyncClientInterfaceMock.php @@ -33,6 +33,11 @@ class AsyncClientInterfaceMock implements AsyncClientInterface */ private $lastRequest; + /** + * @var Request[] + */ + private $requests = []; + /** * AsyncClientInterfaceMock constructor. * @param GuzzleAsyncClient $client @@ -63,12 +68,34 @@ public function getLastRequest(): ?Request return $this->lastRequest; } + /** + * Returns all requests made. + * + * @return Request[]|null + */ + public function getRequests(): array + { + return $this->requests; + } + + /** + * Clear requests. + * + * @return void + */ + public function clearRequests() + { + $this->requests = []; + $this->lastRequest = null; + } + /** * @inheritDoc */ public function request(Request $request): HttpResponseDeferredInterface { $this->lastRequest = $request; + $this->requests[] = $request; if ($mockResponse = array_shift($this->mockResponses)) { return new MockDeferredResponse($mockResponse); } diff --git a/dev/tests/integration/testsuite/Magento/Analytics/Controller/Adminhtml/Reports/ShowTest.php b/dev/tests/integration/testsuite/Magento/Analytics/Controller/Adminhtml/Reports/ShowTest.php new file mode 100644 index 0000000000000..f492e2cd09570 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Analytics/Controller/Adminhtml/Reports/ShowTest.php @@ -0,0 +1,35 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Analytics\Controller\Adminhtml\Reports; + +use Magento\TestFramework\TestCase\AbstractBackendController; + +/** + * @magentoAppArea adminhtml + */ +class ShowTest extends AbstractBackendController +{ + private const REPORT_HOST = 'advancedreporting.rjmetrics.com'; + /** + * @inheritDoc + */ + protected $resource = 'Magento_Analytics::advanced_reporting'; + /** + * @inheritDoc + */ + protected $uri = 'backend/analytics/reports/show'; + /** + * @inheritDoc + */ + public function testAclHasAccess() + { + parent::testAclHasAccess(); + $this->assertSame(302, $this->getResponse()->getHttpResponseCode()); + $this->assertSame(self::REPORT_HOST, $this->getResponse()->getHeader('location')->uri()->getHost()); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Block/Form/ContainerTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Block/Form/ContainerTest.php deleted file mode 100644 index 8f9a800237c51..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Block/Form/ContainerTest.php +++ /dev/null @@ -1,64 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Block\Form; - -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider as PayPalConfigProvider; -use Magento\Framework\App\Area; -use Magento\Framework\ObjectManagerInterface; -use Magento\Payment\Block\Form\Container; -use Magento\Payment\Model\MethodInterface; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\TestFramework\Helper\Bootstrap; - -/** - * Class ContainerTest - */ -class ContainerTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var ObjectManagerInterface - */ - private $objectManager; - - /** - * @var Bootstrap - */ - private $bootstrap; - - /** - * @var Container - */ - private $container; - - protected function setUp(): void - { - $this->bootstrap = Bootstrap::getInstance(); - $this->bootstrap->loadArea(Area::AREA_ADMINHTML); - $this->objectManager = Bootstrap::getObjectManager(); - - $this->container = $this->objectManager->create(Container::class); - } - - /** - * @covers \Magento\Payment\Block\Form\Container::getMethods - * @magentoDataFixture Magento/Braintree/_files/paypal_quote.php - */ - public function testGetMethods() - { - $customerId = 1; - /** @var CartRepositoryInterface $quoteRepository */ - $quoteRepository = $this->objectManager->get(CartRepositoryInterface::class); - $quote = $quoteRepository->getForCustomer($customerId); - $this->container->setData('quote', $quote); - $actual = $this->container->getMethods(); - /** @var MethodInterface $paymentMethod */ - foreach ($actual as $paymentMethod) { - static::assertNotContains($paymentMethod->getCode(), [ - PayPalConfigProvider::PAYPAL_VAULT_CODE, PayPalConfigProvider::PAYPAL_CODE - ]); - } - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Block/VaultTokenRendererTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Block/VaultTokenRendererTest.php deleted file mode 100644 index 5816971f77192..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Block/VaultTokenRendererTest.php +++ /dev/null @@ -1,67 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Block; - -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider; -use Magento\Customer\Model\Session; -use Magento\Framework\App\Area; -use Magento\Framework\ObjectManagerInterface; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\Vault\Api\Data\PaymentTokenInterface; -use Magento\Vault\Block\Customer\AccountTokens; -use Magento\Vault\Model\AccountPaymentTokenFactory; - -/** - * Class VaultTokenRendererTest - */ -class VaultTokenRendererTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var AccountTokens - */ - private $tokenBlock; - - /** - * @var ObjectManagerInterface - */ - private $objectManager; - - protected function setUp(): void - { - $bootstrap = Bootstrap::getInstance(); - $bootstrap->loadArea(Area::AREA_FRONTEND); - $this->objectManager = Bootstrap::getObjectManager(); - - $this->tokenBlock = $this->objectManager->get(AccountTokens::class); - } - - /** - * @covers \Magento\Vault\Block\Customer\AccountTokens::getPaymentTokens - * @magentoDataFixture Magento/Braintree/_files/paypal_vault_token.php - */ - public function testGetPaymentTokens() - { - $customerId = 1; - $token = 'mx29vk'; - - /** @var Session $session */ - $session = $this->objectManager->get(Session::class); - $session->setCustomerId($customerId); - - $tokens = $this->tokenBlock->getPaymentTokens(); - - static::assertCount(1, $tokens); - - /** @var PaymentTokenInterface $vaultToken */ - $vaultToken = array_pop($tokens); - - static::assertTrue($vaultToken->getIsActive()); - static::assertTrue($vaultToken->getIsVisible()); - static::assertEquals($token, $vaultToken->getGatewayToken()); - static::assertEquals(ConfigProvider::PAYPAL_CODE, $vaultToken->getPaymentMethodCode()); - static::assertEquals(AccountPaymentTokenFactory::TOKEN_TYPE_ACCOUNT, $vaultToken->getType()); - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Invoice/CreateTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Invoice/CreateTest.php deleted file mode 100644 index 626f166c72c6d..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Invoice/CreateTest.php +++ /dev/null @@ -1,154 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Controller\Adminhtml\Invoice; - -use Braintree\Result\Successful; -use Braintree\Transaction; -use Magento\Braintree\Model\Adapter\BraintreeAdapter; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Framework\Data\Form\FormKey; -use Magento\Framework\Message\MessageInterface; -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\TestFramework\TestCase\AbstractBackendController; -use PHPUnit\Framework\MockObject\MockObject as MockObject; - -/** - * @magentoAppArea adminhtml - */ -class CreateTest extends AbstractBackendController -{ - /** - * @var BraintreeAdapter|MockObject - */ - private $adapter; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - parent::setUp(); - - $adapterFactory = $this->getMockBuilder(BraintreeAdapterFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->adapter = $this->getMockBuilder(BraintreeAdapter::class) - ->disableOriginalConstructor() - ->getMock(); - $adapterFactory->method('create') - ->willReturn($this->adapter); - - $this->_objectManager->addSharedInstance($adapterFactory, BraintreeAdapterFactory::class); - } - - /** - * @inheritdoc - */ - protected function tearDown(): void - { - $this->_objectManager->removeSharedInstance(BraintreeAdapterFactory::class); - parent::tearDown(); - } - - /** - * Checks a case when non default Merchant Account ID should be send to Braintree - * during creation second partial invoice. - * - * @return void - * @magentoConfigFixture default_store payment/braintree/merchant_account_id Magento - * @magentoConfigFixture current_store payment/braintree/merchant_account_id USA_Merchant - * @magentoDataFixture Magento/Braintree/Fixtures/partial_invoice.php - */ - public function testCreatePartialInvoiceWithNonDefaultMerchantAccount(): void - { - $order = $this->getOrder('100000002'); - - $this->adapter->method('sale') - ->with( - self::callback( - function ($request) { - self::assertEquals('USA_Merchant', $request['merchantAccountId']); - return true; - } - ) - )->willReturn($this->getTransactionStub()); - - $uri = 'backend/sales/order_invoice/save/order_id/' . $order->getEntityId(); - $this->prepareRequest($uri); - $this->dispatch($uri); - - self::assertSessionMessages( - self::equalTo(['The invoice has been created.']), - MessageInterface::TYPE_SUCCESS - ); - } - - /** - * Creates stub for Braintree capture Transaction. - * - * @return Successful - */ - private function getTransactionStub(): Successful - { - $transaction = $this->getMockBuilder(Transaction::class) - ->disableOriginalConstructor() - ->getMock(); - $transaction->status = 'submitted_for_settlement'; - $response = new Successful(); - $response->success = true; - $response->transaction = $transaction; - - return $response; - } - - /** - * Gets order by increment ID. - * - * @param string $incrementId - * @return OrderInterface - */ - private function getOrder(string $incrementId): OrderInterface - { - /** @var SearchCriteriaBuilder $searchCriteriaBuilder */ - $searchCriteriaBuilder = $this->_objectManager->get(SearchCriteriaBuilder::class); - $searchCriteria = $searchCriteriaBuilder->addFilter('increment_id', $incrementId) - ->create(); - - /** @var OrderRepositoryInterface $repository */ - $repository = $this->_objectManager->get(OrderRepositoryInterface::class); - $items = $repository->getList($searchCriteria) - ->getItems(); - - return array_pop($items); - } - - /** - * Prepares POST request for invoice creation. - * - * @param string $uri - * @return void - */ - private function prepareRequest(string $uri): void - { - /** @var FormKey $formKey */ - $formKey = $this->_objectManager->get(FormKey::class); - $request = $this->getRequest(); - $request->setMethod('POST'); - $request->setParam('form_key', $formKey->getFormKey()); - $request->setRequestUri($uri); - $request->setPostValue( - [ - 'invoice' => [ - 'capture_case' => 'online' - ] - ] - ); - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Order/PaymentReviewTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Order/PaymentReviewTest.php deleted file mode 100644 index 5d7dfc62b26be..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Order/PaymentReviewTest.php +++ /dev/null @@ -1,112 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Controller\Adminhtml\Order; - -use Magento\Framework\Api\FilterBuilder; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Framework\Message\MessageInterface; -use Magento\Payment\Model\Method\Adapter; -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\Order; -use Magento\TestFramework\TestCase\AbstractBackendController; - -/** - * Class PaymentReviewTest - */ -class PaymentReviewTest extends AbstractBackendController -{ - /** - * @var Order - */ - private $order; - - /** - * @var OrderRepositoryInterface - */ - private $orderRepository; - - protected function setUp(): void - { - parent::setUp(); - - /** @var FilterBuilder $filterBuilder */ - $filterBuilder = $this->_objectManager->get(FilterBuilder::class); - $filters = [ - $filterBuilder->setField(OrderInterface::INCREMENT_ID) - ->setValue('100000002') - ->create() - ]; - - /** @var SearchCriteriaBuilder $searchCriteriaBuilder */ - $searchCriteriaBuilder = $this->_objectManager->get(SearchCriteriaBuilder::class); - $searchCriteria = $searchCriteriaBuilder->addFilters($filters) - ->create(); - - $this->orderRepository = $this->_objectManager->get(OrderRepositoryInterface::class); - $orders = $this->orderRepository->getList($searchCriteria) - ->getItems(); - /** @var OrderInterface $order */ - $this->order = array_pop($orders); - } - - /** - * @covers \Magento\Sales\Controller\Adminhtml\Order\ReviewPayment::execute - * @magentoDataFixture Magento/Braintree/_files/fraud_order.php - * @magentoAppArea adminhtml - */ - public function testExecuteAccept() - { - $orderId = $this->order->getEntityId(); - $this->dispatch('backend/sales/order/reviewPayment/action/accept/order_id/' . $orderId); - - static::assertRedirect(static::stringContains('sales/order/view/order_id/' . $orderId)); - static::assertSessionMessages( - static::equalTo(['The payment has been accepted.']), - MessageInterface::TYPE_SUCCESS - ); - - $order = $this->orderRepository->get($orderId); - static::assertEquals(Order::STATE_COMPLETE, $order->getState()); - static::assertEquals(Order::STATE_COMPLETE, $order->getStatus()); - } - - /** - * @covers \Magento\Sales\Controller\Adminhtml\Order\ReviewPayment::execute - * @magentoDataFixture Magento/Braintree/_files/fraud_order.php - * @magentoAppArea adminhtml - */ - public function testExecuteDeny() - { - $orderId = $this->order->getEntityId(); - $payment = $this->order->getPayment(); - - $adapter = $this->getMockBuilder(Adapter::class) - ->disableOriginalConstructor() - ->setMethods(['denyPayment']) - ->getMock(); - // uses the mock instead a real adapter to avoid api calls to Braintree gateway - $payment->setMethodInstance($adapter); - $this->orderRepository->save($this->order); - - $adapter->expects(static::once()) - ->method('denyPayment') - ->with($payment) - ->willReturn(true); - - $this->dispatch('backend/sales/order/reviewPayment/action/deny/order_id/' . $orderId); - - static::assertRedirect(static::stringContains('sales/order/view/order_id/' . $orderId)); - static::assertSessionMessages( - static::equalTo(['The payment has been denied.']), - MessageInterface::TYPE_SUCCESS - ); - - $order = $this->orderRepository->get($orderId); - static::assertEquals(Order::STATE_CANCELED, $order->getState()); - static::assertEquals(Order::STATE_CANCELED, $order->getStatus()); - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Payment/GetClientTokenTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Payment/GetClientTokenTest.php deleted file mode 100644 index 181edc53fa31e..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Adminhtml/Payment/GetClientTokenTest.php +++ /dev/null @@ -1,171 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Controller\Adminhtml\Payment; - -use Braintree\Configuration; -use Magento\Backend\Model\Session\Quote; -use Magento\Braintree\Gateway\Config\Config; -use Magento\Braintree\Model\Adapter\BraintreeAdapter; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\Serialize\SerializerInterface; -use Magento\Store\Api\StoreRepositoryInterface; -use Magento\TestFramework\TestCase\AbstractBackendController; -use PHPUnit\Framework\MockObject\MockObject as MockObject; - -/** - * Tests \Magento\Braintree\Controller\Adminhtml\Payment\GetClientToken - */ -class GetClientTokenTest extends AbstractBackendController -{ - /** - * @var Quote - */ - private $quoteSession; - - /** - * @var ObjectManager|MockObject $stubObjectManager - */ - private $stubObjectManager; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - parent::setUp(); - - $this->quoteSession = $this->_objectManager->get(Quote::class); - - $this->stubObjectManager = $this->getMockBuilder(ObjectManager::class) - ->disableOriginalConstructor() - ->getMock(); - - $adapterFactory = new BraintreeAdapterFactory( - $this->stubObjectManager, - $this->_objectManager->get(Config::class) - ); - - $this->_objectManager->addSharedInstance($adapterFactory, BraintreeAdapterFactory::class); - } - - /** - * @inheritdoc - */ - protected function tearDown(): void - { - $this->_objectManager->removeSharedInstance(BraintreeAdapterFactory::class); - parent::tearDown(); - } - - /** - * Checks if client token will retrieved from Braintree initialized with default scope. - * - * @magentoDataFixture Magento/Braintree/_files/payment_configuration.php - * @magentoAppArea adminhtml - */ - public function testExecute() - { - $this->perform( - 'def_merchant_id', - 'def_public_key', - 'def_private_key' - ); - } - - /** - * Checks if client token will be retrieved from Braintree initialized per store. - * - * @magentoDataFixture Magento/Braintree/_files/payment_configuration.php - * @magentoAppArea adminhtml - */ - public function testExecuteWithStoreConfiguration() - { - /** @var StoreRepositoryInterface $storeRepository */ - $storeRepository = $this->_objectManager->get(StoreRepositoryInterface::class); - $store = $storeRepository->get('test'); - $this->quoteSession->setStoreId($store->getId()); - - $this->perform( - 'store_merchant_id', - 'store_public_key', - 'def_private_key' // should be read from default scope - ); - } - - /** - * Checks if client token will be retrieved from Braintree initialized per website. - * - * @magentoDataFixture Magento/Braintree/_files/payment_configuration.php - * @magentoAppArea adminhtml - */ - public function testExecuteWithWebsiteConfiguration() - { - /** @var StoreRepositoryInterface $storeRepository */ - $storeRepository = $this->_objectManager->get(StoreRepositoryInterface::class); - $store = $storeRepository->get('fixture_second_store'); - $this->quoteSession->setStoreId($store->getId()); - - $this->perform( - 'website_merchant_id', - 'def_public_key', // should be read from default scope - 'website_private_key' - ); - } - - /** - * Perform test. - * - * @param string $merchantId - * @param string $publicKey - * @param string $privateKey - * @return void - */ - private function perform($merchantId, $publicKey, $privateKey) - { - $args = [ - 'merchantId' => $merchantId, - 'publicKey' => $publicKey, - 'privateKey' => $privateKey, - 'environment' => 'sandbox', - ]; - - $adapter = $this->getMockBuilder(BraintreeAdapter::class) - ->setConstructorArgs($args) - ->setMethods(['generate']) - ->getMock(); - $adapter->method('generate') - ->willReturn('client_token'); - - $this->stubObjectManager->method('create') - ->with(BraintreeAdapter::class, $args) - ->willReturn($adapter); - - $this->dispatch('backend/braintree/payment/getClientToken'); - - /** @var SerializerInterface $serializer */ - $serializer = $this->_objectManager->get(SerializerInterface::class); - $decoded = $serializer->unserialize($this->getResponse()->getBody()); - $this->performAsserts($decoded['clientToken'], $merchantId, $publicKey, $privateKey); - } - - /** - * Perform Asserts. - * - * @param string $clientToken - * @param string $merchantId - * @param string $publicKey - * @param string $privateKey - * @return void - */ - private function performAsserts($clientToken, $merchantId, $publicKey, $privateKey) - { - self::assertEquals('client_token', $clientToken); - self::assertEquals(Configuration::merchantId(), $merchantId); - self::assertEquals(Configuration::publicKey(), $publicKey); - self::assertEquals(Configuration::privateKey(), $privateKey); - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Cards/DeleteActionTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Cards/DeleteActionTest.php deleted file mode 100644 index 325f02bd621c1..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Cards/DeleteActionTest.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Controller\Cards; - -use Magento\Customer\Model\Session; -use Magento\Framework\Data\Form\FormKey; -use Magento\TestFramework\TestCase\AbstractController; -use Magento\Vault\Model\CustomerTokenManagement; -use Laminas\Http\Request; - -/** - * Test for \Magento\Vault\Controller\Cards\DeleteAction - */ -class DeleteActionTest extends AbstractController -{ - /** - * @covers \Magento\Vault\Controller\Cards\DeleteAction::execute - * @magentoDataFixture Magento/Braintree/_files/paypal_vault_token.php - */ - public function testExecute() - { - $customerId = 1; - /** @var Session $session */ - $session = $this->_objectManager->get(Session::class); - $session->setCustomerId($customerId); - - /** @var CustomerTokenManagement $tokenManagement */ - $tokenManagement = $this->_objectManager->get(CustomerTokenManagement::class); - $tokens = $tokenManagement->getCustomerSessionTokens(); - - static::assertCount(1, $tokens); - - $vaultToken = array_pop($tokens); - - /** @var FormKey $formKey */ - $formKey = $this->_objectManager->get(FormKey::class); - $this->getRequest() - ->setPostValue([ - 'public_hash' => $vaultToken->getPublicHash(), - 'form_key' => $formKey->getFormKey() - ]) - ->setMethod(Request::METHOD_POST); - $this->dispatch('vault/cards/deleteaction'); - - static::assertTrue($this->getResponse()->isRedirect()); - static::assertRedirect(static::stringContains('vault/cards/listaction')); - static::assertSessionMessages(static::equalTo(['Stored Payment Method was successfully removed'])); - static::assertEmpty($tokenManagement->getCustomerSessionTokens()); - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Paypal/PlaceOrderTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Paypal/PlaceOrderTest.php deleted file mode 100644 index f1ccdf4cc6f0e..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Paypal/PlaceOrderTest.php +++ /dev/null @@ -1,214 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Controller\Paypal; - -use Braintree\Result\Successful; -use Braintree\Transaction; -use Magento\Braintree\Model\Adapter\BraintreeAdapter; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Checkout\Model\Session; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Framework\App\Request\Http as HttpRequest; -use Magento\Framework\Message\MessageInterface; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Quote\Api\Data\CartInterface; -use Magento\Sales\Api\Data\OrderInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\TestFramework\TestCase\AbstractController; -use PHPUnit\Framework\MockObject\MockObject; - -/** - * PlaceOrderTest - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class PlaceOrderTest extends AbstractController -{ - /** - * @var Session|MockObject - */ - private $session; - - /** - * @var BraintreeAdapter|MockObject - */ - private $adapter; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - parent::setUp(); - - $this->session = $this->getMockBuilder(Session::class) - ->disableOriginalConstructor() - ->setMethods(['getQuote', 'setLastOrderStatus', 'unsLastBillingAgreementReferenceId', 'getQuoteId']) - ->getMock(); - - $adapterFactory = $this->getMockBuilder(BraintreeAdapterFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->adapter = $this->getMockBuilder(BraintreeAdapter::class) - ->disableOriginalConstructor() - ->getMock(); - $adapterFactory->method('create') - ->willReturn($this->adapter); - - $this->_objectManager->addSharedInstance($this->session, Session::class); - $this->_objectManager->addSharedInstance($adapterFactory, BraintreeAdapterFactory::class); - } - - /** - * @inheritdoc - */ - protected function tearDown(): void - { - $this->_objectManager->removeSharedInstance(Session::class); - $this->_objectManager->removeSharedInstance(BraintreeAdapterFactory::class); - parent::tearDown(); - } - - /** - * Tests a negative scenario for a place order flow when exception throws after placing an order. - * - * @magentoAppArea frontend - * @magentoAppIsolation enabled - * @magentoDataFixture Magento/Braintree/Fixtures/paypal_quote.php - */ - public function testExecuteWithFailedOrder() - { - $reservedOrderId = 'test01'; - $quote = $this->getQuote($reservedOrderId); - - $this->session->method('getQuote') - ->willReturn($quote); - $this->session->method('getQuoteId') - ->willReturn($quote->getId()); - - $this->adapter->method('sale') - ->willReturn($this->getTransactionStub('authorized')); - $this->adapter->method('void') - ->willReturn($this->getTransactionStub('voided')); - - // emulates an error after placing the order - $this->session->method('setLastOrderStatus') - ->willThrowException(new \Exception('Test Exception')); - - $this->getRequest()->setMethod(HttpRequest::METHOD_POST); - $this->dispatch('braintree/paypal/placeOrder'); - - self::assertRedirect(self::stringContains('checkout/cart')); - self::assertSessionMessages( - self::equalTo(['The order #' . $reservedOrderId . ' cannot be processed.']), - MessageInterface::TYPE_ERROR - ); - - $order = $this->getOrder($reservedOrderId); - self::assertEquals('canceled', $order->getState()); - } - - /** - * Tests a negative scenario for a place order flow when exception throws before order creation. - * - * @magentoAppArea frontend - * @magentoAppIsolation enabled - * @magentoDataFixture Magento/Braintree/Fixtures/paypal_quote.php - */ - public function testExecuteWithFailedQuoteValidation() - { - $reservedOrderId = null; - $quote = $this->getQuote('test01'); - $quote->setReservedOrderId($reservedOrderId); - - $this->session->method('getQuote') - ->willReturn($quote); - $this->session->method('getQuoteId') - ->willReturn($quote->getId()); - - $this->adapter->method('sale') - ->willReturn($this->getTransactionStub('authorized')); - $this->adapter->method('void') - ->willReturn($this->getTransactionStub('voided')); - - // emulates an error after placing the order - $this->session->method('setLastOrderStatus') - ->willThrowException(new \Exception('Test Exception')); - - $this->getRequest()->setMethod(HttpRequest::METHOD_POST); - $this->dispatch('braintree/paypal/placeOrder'); - - self::assertRedirect(self::stringContains('checkout/cart')); - self::assertSessionMessages( - self::equalTo(['The order #' . $reservedOrderId . ' cannot be processed.']), - MessageInterface::TYPE_ERROR - ); - } - - /** - * Gets quote by reserved order ID. - * - * @param string $reservedOrderId - * @return CartInterface - */ - private function getQuote(string $reservedOrderId): CartInterface - { - $searchCriteria = $this->_objectManager->get(SearchCriteriaBuilder::class) - ->addFilter('reserved_order_id', $reservedOrderId) - ->create(); - - /** @var CartRepositoryInterface $quoteRepository */ - $quoteRepository = $this->_objectManager->get(CartRepositoryInterface::class); - $items = $quoteRepository->getList($searchCriteria) - ->getItems(); - - return array_pop($items); - } - - /** - * Gets order by increment ID. - * - * @param string $incrementId - * @return OrderInterface - */ - private function getOrder(string $incrementId): OrderInterface - { - $searchCriteria = $this->_objectManager->get(SearchCriteriaBuilder::class) - ->addFilter('increment_id', $incrementId) - ->create(); - - /** @var OrderRepositoryInterface $repository */ - $repository = $this->_objectManager->get(OrderRepositoryInterface::class); - $items = $repository->getList($searchCriteria) - ->getItems(); - - return array_pop($items); - } - - /** - * Creates stub for Braintree Transaction. - * - * @param string $status - * @return Successful - */ - private function getTransactionStub(string $status): Successful - { - $transaction = $this->getMockBuilder(Transaction::class) - ->disableOriginalConstructor() - ->getMock(); - $transaction->status = $status; - $transaction->paypal = [ - 'paymentId' => 'pay-001', - 'payerEmail' => 'test@test.com' - ]; - $response = new Successful(); - $response->success = true; - $response->transaction = $transaction; - - return $response; - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Paypal/ReviewTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Controller/Paypal/ReviewTest.php deleted file mode 100644 index caa610b6ee7f4..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Controller/Paypal/ReviewTest.php +++ /dev/null @@ -1,43 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Controller\Paypal; - -use Magento\Framework\App\Action\HttpGetActionInterface; -use Magento\Framework\App\Action\HttpPostActionInterface; -use Magento\TestFramework\TestCase\AbstractController; - -/** - * ReviewTest - */ -class ReviewTest extends AbstractController -{ - /** - * @var Review - */ - private $controller; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - parent::setUp(); - - $this->controller = $this->_objectManager->create(Review::class); - } - - /** - * Test controller implements correct interfaces - * - */ - public function testInterfaceImplementation() - { - $this->assertInstanceOf(HttpGetActionInterface::class, $this->controller); - $this->assertInstanceOf(HttpPostActionInterface::class, $this->controller); - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/order.php b/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/order.php deleted file mode 100644 index 7675e749d852f..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/order.php +++ /dev/null @@ -1,81 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Catalog\Api\ProductRepositoryInterface; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\Order; -use Magento\Sales\Model\Order\Address; -use Magento\Sales\Model\Order\Item as OrderItem; -use Magento\Store\Model\StoreManagerInterface; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\ObjectManager; -use Magento\TestFramework\Workaround\Override\Fixture\Resolver; -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Sales\Api\Data\OrderPaymentExtensionInterfaceFactory; -use Magento\Sales\Model\Order\Payment; -use Magento\Vault\Model\PaymentToken; - -Resolver::getInstance()->requireDataFixture('Magento/Catalog/_files/product_simple.php'); -/** @var ObjectManager $objectManager */ -$objectManager = Bootstrap::getObjectManager(); -/** @var ProductRepositoryInterface $productRepository */ -$productRepository = $objectManager->create(ProductRepositoryInterface::class); -$product = $productRepository->get('simple'); -$addressData = include __DIR__ . '/../../Sales/_files/address_data.php'; - -$billingAddress = $objectManager->create(Address::class, ['data' => $addressData]); -$billingAddress->setAddressType('billing'); - -$shippingAddress = clone $billingAddress; -$shippingAddress->setId(null) - ->setAddressType('shipping'); - -/** @var OrderItem $orderItem */ -$orderItem = $objectManager->create(OrderItem::class); -$orderItem->setProductId($product->getId()) - ->setQtyOrdered(2) - ->setBasePrice($product->getPrice()) - ->setPrice($product->getPrice()) - ->setRowTotal($product->getPrice()) - ->setProductType('simple'); - -Resolver::getInstance()->requireDataFixture('Magento/Vault/_files/token.php'); -/** @var ObjectManager $objectManager */ -$objectManager = Bootstrap::getObjectManager(); -/** @var PaymentToken $token */ -$token = $objectManager->create(PaymentToken::class); -$token->load('vault_payment', 'payment_method_code'); -$token->setPaymentMethodCode(ConfigProvider::CODE); -/** @var OrderPaymentExtensionInterfaceFactory $paymentExtensionFactory */ -$paymentExtensionFactory = $objectManager->get(OrderPaymentExtensionInterfaceFactory::class); -$extensionAttributes = $paymentExtensionFactory->create(); -$extensionAttributes->setVaultPaymentToken($token); - -/** @var Payment $payment */ -$payment = $objectManager->create(Payment::class); -$payment->setMethod(ConfigProvider::CODE); -$payment->setExtensionAttributes($extensionAttributes); -$payment->setAuthorizationTransaction(true); - -$order = $objectManager->create(Order::class); -$order->setIncrementId('100000002') - ->setSubtotal($product->getPrice() * 2) - ->setBaseSubtotal($product->getPrice() * 2) - ->setCustomerEmail('admin@example.com') - ->setCustomerIsGuest(true) - ->setBillingAddress($billingAddress) - ->setShippingAddress($shippingAddress) - ->setStoreId( - $objectManager->get(StoreManagerInterface::class)->getStore() - ->getId() - ) - ->addItem($orderItem) - ->setPayment($payment); - -/** @var OrderRepositoryInterface $orderRepository */ -$orderRepository = $objectManager->get(OrderRepositoryInterface::class); -$orderRepository->save($order); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/order_rollback.php b/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/order_rollback.php deleted file mode 100644 index 68fd4b0e58532..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/order_rollback.php +++ /dev/null @@ -1,29 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\TestFramework\ObjectManager; -use Magento\TestFramework\Workaround\Override\Fixture\Resolver; - -$objectManager = ObjectManager::getInstance(); - -/** @var SearchCriteriaBuilder $searchCriteriaBuilder */ -$searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class); -$searchCriteria = $searchCriteriaBuilder->addFilter('increment_id', '100000002') - ->create(); - -/** @var OrderRepositoryInterface $orderRepository */ -$orderRepository = $objectManager->get(OrderRepositoryInterface::class); -$items = $orderRepository->getList($searchCriteria) - ->getItems(); - -foreach ($items as $item) { - $orderRepository->delete($item); -} - -Resolver::getInstance()->requireDataFixture('Magento/Catalog/_files/product_simple_rollback.php'); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/partial_invoice.php b/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/partial_invoice.php deleted file mode 100644 index 3aaea849365df..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/partial_invoice.php +++ /dev/null @@ -1,49 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Sales\Api\Data\OrderInterfaceFactory; -use Magento\Sales\Api\InvoiceRepositoryInterface; -use Magento\Sales\Api\TransactionRepositoryInterface; -use Magento\Sales\Model\Order; -use Magento\Sales\Model\Service\InvoiceService; -use Magento\TestFramework\ObjectManager; -use Magento\TestFramework\Workaround\Override\Fixture\Resolver; - -/** @var Order $order */ -Resolver::getInstance()->requireDataFixture('Magento/Braintree/Fixtures/order.php'); - -$objectManager = ObjectManager::getInstance(); -/** @var Order $order */ -$order = $objectManager->get(OrderInterfaceFactory::class)->create()->loadByIncrementId('100000002'); -/** @var InvoiceService $invoiceService */ -$invoiceService = $objectManager->get(InvoiceService::class); -$invoice = $invoiceService->prepareInvoice($order); -$invoice->setIncrementId('100000002'); -$invoice->register(); - -$items = $invoice->getAllItems(); -$item = array_pop($items); -$item->setQty(1); -$invoice->setTotalQty(1); - -$items = $order->getAllItems(); -/** @var \Magento\Sales\Api\Data\OrderItemInterface $item */ -$item = array_pop($items); -$item->setQtyInvoiced(1); -$invoice->collectTotals(); - -/** @var InvoiceRepositoryInterface $invoiceRepository */ -$invoiceRepository = $objectManager->get(InvoiceRepositoryInterface::class); -$invoice = $invoiceRepository->save($invoice); - -/** @var TransactionRepositoryInterface $transactionRepository */ -$transactionRepository = $objectManager->get(TransactionRepositoryInterface::class); -$transaction = $transactionRepository->create(); -$transaction->setTxnType('capture'); -$transaction->setPaymentId($order->getPayment()->getEntityId()); -$transaction->setOrderId($order->getEntityId()); -$transactionRepository->save($transaction); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/partial_invoice_rollback.php b/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/partial_invoice_rollback.php deleted file mode 100644 index c8f3beb043ce2..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/partial_invoice_rollback.php +++ /dev/null @@ -1,29 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Sales\Api\InvoiceRepositoryInterface; -use Magento\TestFramework\ObjectManager; -use Magento\TestFramework\Workaround\Override\Fixture\Resolver; - -$objectManager = ObjectManager::getInstance(); - -/** @var SearchCriteriaBuilder $searchCriteriaBuilder */ -$searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class); -$searchCriteria = $searchCriteriaBuilder->addFilter('increment_id', '%10000000%', 'like') - ->create(); - -/** @var InvoiceRepositoryInterface $invoiceRepository */ -$invoiceRepository = $objectManager->get(InvoiceRepositoryInterface::class); -$items = $invoiceRepository->getList($searchCriteria) - ->getItems(); - -foreach ($items as $item) { - $invoiceRepository->delete($item); -} - -Resolver::getInstance()->requireDataFixture('Magento/Braintree/Fixtures/order_rollback.php'); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/payment.php b/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/payment.php deleted file mode 100644 index f673f16b06c78..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/payment.php +++ /dev/null @@ -1,32 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Sales\Api\Data\OrderPaymentExtensionInterfaceFactory; -use Magento\Sales\Model\Order\Payment; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\ObjectManager; -use Magento\TestFramework\Workaround\Override\Fixture\Resolver; -use Magento\Vault\Model\PaymentToken; - -Resolver::getInstance()->requireDataFixture('Magento/Vault/_files/token.php'); -/** @var ObjectManager $objectManager */ -$objectManager = Bootstrap::getObjectManager(); -/** @var PaymentToken $token */ -$token = $objectManager->create(PaymentToken::class); -$token->load('vault_payment', 'payment_method_code'); -$token->setPaymentMethodCode(ConfigProvider::CODE); -/** @var OrderPaymentExtensionInterfaceFactory $paymentExtensionFactory */ -$paymentExtensionFactory = $objectManager->get(OrderPaymentExtensionInterfaceFactory::class); -$extensionAttributes = $paymentExtensionFactory->create(); -$extensionAttributes->setVaultPaymentToken($token); - -/** @var Payment $payment */ -$payment = $objectManager->create(Payment::class); -$payment->setMethod(ConfigProvider::CODE); -$payment->setExtensionAttributes($extensionAttributes); -$payment->setAuthorizationTransaction(true); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/payment_braintree_paypal.php b/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/payment_braintree_paypal.php deleted file mode 100644 index e4bba222078b0..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/payment_braintree_paypal.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Quote\Model\Quote\Payment; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\ObjectManager; -use Magento\Quote\Api\Data\PaymentInterface; -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider; - -/** - * @var Magento\Quote\Model\Quote $quote - */ - -if (empty($quote)) { - throw new \Exception('$quote should be defined in the parent fixture'); -} - -/** @var ObjectManager $objectManager */ -$objectManager = Bootstrap::getObjectManager(); - -/** @var PaymentInterface $payment */ -$payment = $objectManager->create(Payment::class); -$payment->setMethod(ConfigProvider::PAYPAL_CODE); -$quote->setPayment($payment); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/paypal_quote.php b/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/paypal_quote.php deleted file mode 100644 index 06806918accb9..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/paypal_quote.php +++ /dev/null @@ -1,42 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Quote\Model\Quote; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\Workaround\Override\Fixture\Resolver; -use Magento\Vault\Model\PaymentTokenManagement; - -Resolver::getInstance()->requireDataFixture('Magento/Braintree/_files/paypal_vault_token.php'); -Resolver::getInstance()->requireDataFixture('Magento/Sales/_files/quote_with_customer.php'); - -$objectManager = Bootstrap::getObjectManager(); -/** @var PaymentTokenManagement $tokenManagement */ -$tokenManagement = $objectManager->get(PaymentTokenManagement::class); -$paymentToken = $tokenManagement->getByGatewayToken('mx29vk', ConfigProvider::PAYPAL_CODE, 1); -/** @var $quote Quote */ -$quote = $objectManager->create(Quote::class); -$quote->load('test01', 'reserved_order_id'); -$quote->getShippingAddress() - ->setShippingMethod('flatrate_flatrate') - ->setCollectShippingRates(true); -$quote->getPayment() - ->setMethod(ConfigProvider::PAYPAL_VAULT_CODE) - ->setAdditionalInformation( - [ - 'customer_id' => $quote->getCustomerId(), - 'public_hash' => $paymentToken->getPublicHash() - ] - ); - -$quote->collectTotals(); - -/** @var CartRepositoryInterface $quoteRepository */ -$quoteRepository = $objectManager->get(CartRepositoryInterface::class); -$quoteRepository->save($quote); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/paypal_quote_rollback.php b/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/paypal_quote_rollback.php deleted file mode 100644 index 159ca1e7d7924..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/paypal_quote_rollback.php +++ /dev/null @@ -1,11 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -declare(strict_types=1); - -use Magento\TestFramework\Workaround\Override\Fixture\Resolver; - -Resolver::getInstance()->requireDataFixture('Magento/Sales/_files/quote_with_customer_rollback.php'); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/quote_with_split_items_braintree.php b/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/quote_with_split_items_braintree.php deleted file mode 100644 index 7169249712797..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/quote_with_split_items_braintree.php +++ /dev/null @@ -1,113 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Quote\Model\Quote; -use Magento\Quote\Model\QuoteFactory; -use Magento\Quote\Model\ResourceModel\Quote as QuoteResource; -use Magento\Store\Model\StoreManagerInterface; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\ObjectManager; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Quote\Model\Quote\Payment; -use Magento\Quote\Api\Data\PaymentInterface; -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Quote\Api\Data\AddressInterface; -use Magento\Quote\Model\Quote\Address\Rate; -use Magento\TestFramework\Workaround\Override\Fixture\Resolver; - -/** @var ObjectManager $objectManager */ -$objectManager = Bootstrap::getObjectManager(); -/** @var QuoteFactory $quoteFactory */ -$quoteFactory = Bootstrap::getObjectManager()->get(QuoteFactory::class); -/** @var QuoteResource $quoteResource */ -$quoteResource = Bootstrap::getObjectManager()->get(QuoteResource::class); -/** @var StoreManagerInterface $storeManager */ -$storeManager = $objectManager->get(StoreManagerInterface::class); -/** @var CartRepositoryInterface $quoteRepository */ -$quoteRepository = $objectManager->get(CartRepositoryInterface::class); -$store = $storeManager->getStore(); -/** @var Quote $quote */ -$quote = $objectManager->create(Quote::class); -$quote->setReservedOrderId('multishipping_quote_id') - ->setStoreId($store->getId()); - -$addressList = [ - [ - 'firstname' => 'Jonh', - 'lastname' => 'Doe', - 'telephone' => '0333-233-221', - 'street' => ['Main Division 1'], - 'city' => 'Culver City', - 'region' => 'CA', - 'postcode' => 90800, - 'country_id' => 'US', - 'email' => 'customer001@shipping.test', - 'address_type' => 'shipping', - ], - [ - 'firstname' => 'Antoni', - 'lastname' => 'Holmes', - 'telephone' => '0333-233-221', - 'street' => ['Second Division 2'], - 'city' => 'Denver', - 'region' => 'CO', - 'postcode' => 80203, - 'country_id' => 'US', - 'email' => 'customer002@shipping.test', - 'address_type' => 'shipping' - ] -]; -$methodCode = 'flatrate_flatrate'; -foreach ($addressList as $data) { - /** @var Rate $rate */ - $rate = $objectManager->create(Rate::class); - $rate->setCode($methodCode) - ->setPrice(5.00); - - $address = $objectManager->create(AddressInterface::class, ['data' => $data]); - $address->setShippingMethod($methodCode) - ->addShippingRate($rate) - ->setShippingAmount(5.00) - ->setBaseShippingAmount(5.00); - - $quote->addAddress($address); -} -$quote->setIsMultiShipping(1); -$quoteRepository->save($quote); - -Resolver::getInstance()->requireDataFixture('Magento/Multishipping/Fixtures/billing_address.php'); -Resolver::getInstance()->requireDataFixture('Magento/Multishipping/Fixtures/items.php'); - -$quote = $quoteFactory->create(); -$quoteResource->load($quote, 'multishipping_quote_id', 'reserved_order_id'); -/** @var PaymentInterface $payment */ -$payment = $objectManager->create(Payment::class); -$payment->setMethod(ConfigProvider::CODE); -$quote->setPayment($payment); - -$items = $quote->getAllItems(); -$addressList = $quote->getAllShippingAddresses(); - -foreach ($addressList as $key => $address) { - $item = $items[$key]; - // set correct quantity per shipping address - $item->setQty(1); - $address->setTotalQty(1); - $address->addItem($item); -} - -// assign virtual product to the billing address -$billingAddress = $quote->getBillingAddress(); -$virtualItem = $items[count($items) - 1]; -$billingAddress->setTotalQty(1); -$billingAddress->addItem($virtualItem); - -// need to recollect totals -$quote->setTotalsCollectedFlag(false) - ->setCustomerEmail('customer001@test.com') - ->collectTotals(); -$quoteRepository->save($quote); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/quote_with_split_items_braintree_paypal.php b/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/quote_with_split_items_braintree_paypal.php deleted file mode 100644 index c193ab6a2273e..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Fixtures/quote_with_split_items_braintree_paypal.php +++ /dev/null @@ -1,113 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -use Magento\Quote\Model\Quote; -use Magento\Quote\Model\QuoteFactory; -use Magento\Quote\Model\ResourceModel\Quote as QuoteResource; -use Magento\Store\Model\StoreManagerInterface; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\ObjectManager; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Quote\Model\Quote\Payment; -use Magento\Quote\Api\Data\PaymentInterface; -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider; -use Magento\Quote\Api\Data\AddressInterface; -use Magento\Quote\Model\Quote\Address\Rate; -use Magento\TestFramework\Workaround\Override\Fixture\Resolver; - -/** @var ObjectManager $objectManager */ -$objectManager = Bootstrap::getObjectManager(); -/** @var QuoteFactory $quoteFactory */ -$quoteFactory = Bootstrap::getObjectManager()->get(QuoteFactory::class); -/** @var QuoteResource $quoteResource */ -$quoteResource = Bootstrap::getObjectManager()->get(QuoteResource::class); -/** @var StoreManagerInterface $storeManager */ -$storeManager = $objectManager->get(StoreManagerInterface::class); -/** @var CartRepositoryInterface $quoteRepository */ -$quoteRepository = $objectManager->get(CartRepositoryInterface::class); -$store = $storeManager->getStore(); -/** @var Quote $quote */ -$quote = $objectManager->create(Quote::class); -$quote->setReservedOrderId('multishipping_quote_id') - ->setStoreId($store->getId()); - -$addressList = [ - [ - 'firstname' => 'Jonh', - 'lastname' => 'Doe', - 'telephone' => '0333-233-221', - 'street' => ['Main Division 1'], - 'city' => 'Culver City', - 'region' => 'CA', - 'postcode' => 90800, - 'country_id' => 'US', - 'email' => 'customer001@shipping.test', - 'address_type' => 'shipping', - ], - [ - 'firstname' => 'Antoni', - 'lastname' => 'Holmes', - 'telephone' => '0333-233-221', - 'street' => ['Second Division 2'], - 'city' => 'Denver', - 'region' => 'CO', - 'postcode' => 80203, - 'country_id' => 'US', - 'email' => 'customer002@shipping.test', - 'address_type' => 'shipping' - ] -]; -$methodCode = 'flatrate_flatrate'; -foreach ($addressList as $data) { - /** @var Rate $rate */ - $rate = $objectManager->create(Rate::class); - $rate->setCode($methodCode) - ->setPrice(5.00); - - $address = $objectManager->create(AddressInterface::class, ['data' => $data]); - $address->setShippingMethod($methodCode) - ->addShippingRate($rate) - ->setShippingAmount(5.00) - ->setBaseShippingAmount(5.00); - - $quote->addAddress($address); -} -$quote->setIsMultiShipping(1); -$quoteRepository->save($quote); - -Resolver::getInstance()->requireDataFixture('Magento/Multishipping/Fixtures/billing_address.php'); -Resolver::getInstance()->requireDataFixture('Magento/Multishipping/Fixtures/items.php'); - -$quote = $quoteFactory->create(); -$quoteResource->load($quote, 'multishipping_quote_id', 'reserved_order_id'); -/** @var PaymentInterface $payment */ -$payment = $objectManager->create(Payment::class); -$payment->setMethod(ConfigProvider::PAYPAL_CODE); -$quote->setPayment($payment); - -$items = $quote->getAllItems(); -$addressList = $quote->getAllShippingAddresses(); - -foreach ($addressList as $key => $address) { - $item = $items[$key]; - // set correct quantity per shipping address - $item->setQty(1); - $address->setTotalQty(1); - $address->addItem($item); -} - -// assign virtual product to the billing address -$billingAddress = $quote->getBillingAddress(); -$virtualItem = $items[count($items) - 1]; -$billingAddress->setTotalQty(1); -$billingAddress->addItem($virtualItem); - -// need to recollect totals -$quote->setTotalsCollectedFlag(false) - ->setCustomerEmail('customer001@test.com') - ->collectTotals(); -$quoteRepository->save($quote); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Gateway/Config/ConfigTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Gateway/Config/ConfigTest.php deleted file mode 100644 index 71b34de8778e6..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Gateway/Config/ConfigTest.php +++ /dev/null @@ -1,70 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Gateway\Config; - -use Magento\Config\Model\Config as SystemConfig; -use Magento\TestFramework\Helper\Bootstrap; - -class ConfigTest extends \PHPUnit\Framework\TestCase -{ - const METHOD_CODE = 'braintree'; - - /** @var Config */ - private $config; - - /** @var SystemConfig */ - private $systemConfig; - - protected function setUp(): void - { - $objectManager = Bootstrap::getObjectManager(); - $this->config = $objectManager->create(Config::class, [ - 'methodCode' => self::METHOD_CODE - ]); - $this->systemConfig = $objectManager->create(SystemConfig::class); - } - - /** - * Test methods that load Braintree configuration, and verify that values were json decoded correctly - * by the serializer dependency. - * - * @magentoDbIsolation enabled - * @dataProvider countryCreditRetrievalProvider - * @param string $value - * @param array $expected - */ - public function testCountryCreditRetrieval($value, array $expected) - { - $this->systemConfig->setDataByPath('payment/' . self::METHOD_CODE . '/countrycreditcard', $value); - $this->systemConfig->save(); - - $countrySpecificCardTypeConfig = $this->config->getCountrySpecificCardTypeConfig(); - $this->assertEquals($expected, $countrySpecificCardTypeConfig); - - foreach ($expected as $country => $expectedCreditCardTypes) { - $countryAvailableCardTypes = $this->config->getCountryAvailableCardTypes($country); - $this->assertEquals($expectedCreditCardTypes, $countryAvailableCardTypes); - } - } - - public function countryCreditRetrievalProvider() - { - return [ - 'empty_array' => [ - 'value' => '[]', - 'expected' => [] - ], - 'valid_data' => [ - 'value' => '{"AF":["AE","VI"],"US":["AE","VI","MA"]}', - 'expected' => [ - 'AF' => ['AE', 'VI'], - 'US' => ['AE', 'VI', 'MA'] - ] - ] - ]; - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Model/Adminhtml/System/Config/CountryCreditCardTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Model/Adminhtml/System/Config/CountryCreditCardTest.php deleted file mode 100644 index 5b674c675f301..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Model/Adminhtml/System/Config/CountryCreditCardTest.php +++ /dev/null @@ -1,69 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Braintree\Model\Adminhtml\System\Config; - -use Magento\TestFramework\Helper\Bootstrap; - -class CountryCreditCardTest extends \PHPUnit\Framework\TestCase -{ - /** @var CountryCreditCard */ - private $countryCreditCardConfig; - - protected function setUp(): void - { - $objectManager = Bootstrap::getObjectManager(); - $this->countryCreditCardConfig = $objectManager->get(CountryCreditCard::class); - $this->countryCreditCardConfig->setPath('payment/braintree/countrycreditcard'); - } - - /** - * Test save and load lifecycle of the Braintree configuration value. Save should trigger the passed - * array to be json encoded by the serializer. Load should trigger json decode of that value, and it - * should match what was originally passed in. - * - * @magentoAppArea adminhtml - * @magentoDbIsolation enabled - * @dataProvider saveAndLoadDataProvider - * @param array $value - * @param string $encodedExpectedValue - */ - public function testSaveAndLoad($value, $encodedExpectedValue) - { - $this->countryCreditCardConfig->setValue($value); - $this->countryCreditCardConfig->save(); - $this->assertEquals($encodedExpectedValue, $this->countryCreditCardConfig->getValue()); - - $this->countryCreditCardConfig->load($this->countryCreditCardConfig->getId()); - $loadedHashedArray = $this->countryCreditCardConfig->getValue(); - // strip the random hashes added by routine before assertion - $loadedIndexedArray = array_values($loadedHashedArray); - $this->assertEquals($value, $loadedIndexedArray); - } - - public function saveAndLoadDataProvider() - { - return [ - 'empty_array' => [ - 'value' => [], - 'expected' => '[]' - ], - 'valid_data' => [ - 'value' => [ - [ - 'country_id' => 'AF', - 'cc_types' => ['AE', 'VI'] - ], - [ - 'country_id' => 'US', - 'cc_types' => ['AE', 'VI', 'MA'] - ] - ], - 'expected' => '{"AF":["AE","VI"],"US":["AE","VI","MA"]}' - ] - ]; - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Model/MultishippingTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Model/MultishippingTest.php deleted file mode 100644 index b6350cfb2a4c3..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Model/MultishippingTest.php +++ /dev/null @@ -1,254 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree\Model; - -use Braintree\Result\Successful; -use Braintree\Transaction; -use Magento\Braintree\Gateway\Command\GetPaymentNonceCommand; -use Magento\Braintree\Model\Adapter\BraintreeAdapter; -use Magento\Braintree\Model\Adapter\BraintreeAdapterFactory; -use Magento\Checkout\Model\Session as CheckoutSession; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Multishipping\Model\Checkout\Type\Multishipping; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Quote\Model\Quote; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\Order\Email\Sender\OrderSender; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\ObjectManager; -use PHPUnit\Framework\MockObject\MockObject as MockObject; -use Magento\Payment\Gateway\Command\ResultInterface as CommandResultInterface; - -/** - * Tests Magento\Multishipping\Model\Checkout\Type\Multishipping with Braintree and BraintreePayPal payments. - * - * @magentoAppArea frontend - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class MultishippingTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var ObjectManager - */ - private $objectManager; - - /** - * @var BraintreeAdapter|MockObject - */ - private $adapter; - - /** - * @var Multishipping - */ - private $model; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->objectManager = Bootstrap::getObjectManager(); - - $orderSender = $this->getMockBuilder(OrderSender::class) - ->disableOriginalConstructor() - ->getMock(); - - $adapterFactory = $this->getMockBuilder(BraintreeAdapterFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $this->adapter = $this->getMockBuilder(BraintreeAdapter::class) - ->disableOriginalConstructor() - ->getMock(); - $adapterFactory->method('create') - ->willReturn($this->adapter); - - $this->objectManager->addSharedInstance($adapterFactory, BraintreeAdapterFactory::class); - $this->objectManager->addSharedInstance($this->getPaymentNonceMock(), GetPaymentNonceCommand::class); - - $this->model = $this->objectManager->create( - Multishipping::class, - ['orderSender' => $orderSender] - ); - } - - /** - * Checks a case when multiple orders are created successfully using Braintree payment method. - * - * @magentoAppIsolation enabled - * @magentoDataFixture Magento/Braintree/Fixtures/quote_with_split_items_braintree.php - * @magentoConfigFixture current_store payment/braintree/active 1 - * @return void - */ - public function testCreateOrdersWithBraintree() - { - $this->adapter->method('sale') - ->willReturn( - $this->getTransactionStub() - ); - $this->createOrders(); - } - - /** - * Checks a case when multiple orders are created successfully using Braintree PayPal payment method. - * - * @magentoAppIsolation enabled - * @magentoDataFixture Magento/Braintree/Fixtures/quote_with_split_items_braintree_paypal.php - * @magentoConfigFixture current_store payment/braintree_paypal/active 1 - * @return void - */ - public function testCreateOrdersWithBraintreePaypal() - { - $this->adapter->method('sale') - ->willReturn( - $this->getTransactionPaypalStub() - ); - $this->createOrders(); - } - - /** - * Creates orders for multishipping checkout flow. - * - * @return void - */ - private function createOrders() - { - $expectedPlacedOrdersNumber = 3; - $quote = $this->getQuote('multishipping_quote_id'); - - /** @var CheckoutSession $session */ - $session = $this->objectManager->get(CheckoutSession::class); - $session->replaceQuote($quote); - - $this->model->createOrders(); - - $orderList = $this->getOrderList((int)$quote->getId()); - self::assertCount( - $expectedPlacedOrdersNumber, - $orderList, - 'Total successfully placed orders number mismatch' - ); - } - - /** - * Creates stub for Braintree capture Transaction. - * - * @return Successful - */ - private function getTransactionStub(): Successful - { - $transaction = $this->getMockBuilder(Transaction::class) - ->disableOriginalConstructor() - ->getMock(); - $transaction->status = 'submitted_for_settlement'; - $transaction->creditCard = [ - 'last4' => '1111', - 'cardType' => 'Visa', - 'expirationMonth' => '12', - 'expirationYear' => '2021' - ]; - - $creditCardDetails = new \stdClass(); - $creditCardDetails->token = '4fdg'; - $creditCardDetails->expirationMonth = '12'; - $creditCardDetails->expirationYear = '2021'; - $creditCardDetails->cardType = 'Visa'; - $creditCardDetails->last4 = '1111'; - $creditCardDetails->expirationDate = '12/2021'; - $transaction->creditCardDetails = $creditCardDetails; - - $response = new Successful(); - $response->success = true; - $response->transaction = $transaction; - - return $response; - } - - /** - * Creates stub for BraintreePaypal capture Transaction. - * - * @return Successful - */ - private function getTransactionPaypalStub(): Successful - { - $transaction = $this->getMockBuilder(Transaction::class) - ->disableOriginalConstructor() - ->getMock(); - $transaction->status = 'submitted_for_settlement'; - $transaction->paypal = [ - 'token' => 'fchxqx', - 'payerEmail' => 'payer@example.com', - 'paymentId' => 'PAY-33ac47a28e7f54791f6cda45', - ]; - $paypalDetails = new \stdClass(); - $paypalDetails->token = 'fchxqx'; - $paypalDetails->payerEmail = 'payer@example.com'; - $paypalDetails->paymentId = '33ac47a28e7f54791f6cda45'; - $transaction->paypalDetails = $paypalDetails; - - $response = new Successful(); - $response->success = true; - $response->transaction = $transaction; - - return $response; - } - - /** - * Retrieves quote by reserved order id. - * - * @param string $reservedOrderId - * @return Quote - */ - private function getQuote(string $reservedOrderId): Quote - { - /** @var SearchCriteriaBuilder $searchCriteriaBuilder */ - $searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class); - $searchCriteria = $searchCriteriaBuilder->addFilter('reserved_order_id', $reservedOrderId) - ->create(); - - /** @var CartRepositoryInterface $quoteRepository */ - $quoteRepository = $this->objectManager->get(CartRepositoryInterface::class); - $items = $quoteRepository->getList($searchCriteria)->getItems(); - - return array_pop($items); - } - - /** - * Get list of orders by quote id. - * - * @param int $quoteId - * @return array - */ - private function getOrderList(int $quoteId): array - { - /** @var SearchCriteriaBuilder $searchCriteriaBuilder */ - $searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class); - $searchCriteria = $searchCriteriaBuilder->addFilter('quote_id', $quoteId) - ->create(); - - /** @var OrderRepositoryInterface $orderRepository */ - $orderRepository = $this->objectManager->get(OrderRepositoryInterface::class); - return $orderRepository->getList($searchCriteria)->getItems(); - } - - /** - * Returns GetPaymentNonceCommand command mock. - * - * @return MockObject - */ - private function getPaymentNonceMock(): MockObject - { - $commandResult = $this->getMockForAbstractClass(CommandResultInterface::class); - $commandResult->method('get') - ->willReturn(['paymentMethodNonce' => 'testNonce']); - $paymentNonce = $this->createMock(GetPaymentNonceCommand::class); - $paymentNonce->method('execute') - ->willReturn($commandResult); - - return $paymentNonce; - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Model/PaymentMethodListTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Model/PaymentMethodListTest.php deleted file mode 100644 index 3e5ffb0c222ab..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Model/PaymentMethodListTest.php +++ /dev/null @@ -1,72 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model; - -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider as PayPalConfigProvider; -use Magento\Store\Model\StoreManagerInterface; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\Vault\Api\PaymentMethodListInterface; -use Magento\Vault\Model\VaultPaymentInterface; - -/** - * Contains tests for vault payment list methods - */ -class PaymentMethodListTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var PaymentMethodListInterface - */ - private $paymentMethodList; - - /** - * @var int - */ - private $storeId; - - protected function setUp(): void - { - $objectManager = Bootstrap::getObjectManager(); - $this->storeId = $objectManager->get(StoreManagerInterface::class) - ->getStore() - ->getId(); - $this->paymentMethodList = $objectManager->get(PaymentMethodListInterface::class); - } - - /** - * @magentoDataFixture Magento/Braintree/_files/payments.php - */ - public function testGetList() - { - $vaultPayments = $this->paymentMethodList->getList($this->storeId); - - static::assertNotEmpty($vaultPayments); - - $paymentCodes = array_map(function (VaultPaymentInterface $payment) { - return $payment->getCode(); - }, $vaultPayments); - - $expectedCodes = [ - PayPalConfigProvider::PAYPAL_VAULT_CODE, - ConfigProvider::CC_VAULT_CODE - ]; - static::assertNotEmpty(array_intersect($expectedCodes, $paymentCodes)); - } - - /** - * @magentoDataFixture Magento/Braintree/_files/payments.php - */ - public function testGetActiveList() - { - $vaultPayments = $this->paymentMethodList->getActiveList($this->storeId); - - static::assertNotEmpty($vaultPayments); - $paymentCodes = array_map(function ($payment) { - return $payment->getCode(); - }, $vaultPayments); - static::assertContains(PayPalConfigProvider::PAYPAL_VAULT_CODE, $paymentCodes); - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php deleted file mode 100644 index 1af94ea4518b5..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/Adminhtml/PayPal/TokenUiComponentProviderTest.php +++ /dev/null @@ -1,62 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Ui\Adminhtml\PayPal; - -use Magento\Braintree\Model\Ui\Adminhtml\PayPal\TokenUiComponentProvider; -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider; -use Magento\Framework\ObjectManagerInterface; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\Vault\Model\PaymentTokenManagement; -use Magento\Vault\Model\Ui\TokenUiComponentProviderInterface; - -/** - * Contains tests for PayPal token Ui component provider - */ -class TokenUiComponentProviderTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var ObjectManagerInterface - */ - private $objectManager; - - /** - * @var TokenUiComponentProvider - */ - private $tokenComponentProvider; - - protected function setUp(): void - { - $this->objectManager = Bootstrap::getObjectManager(); - $this->tokenComponentProvider = $this->objectManager->get(TokenUiComponentProvider::class); - } - - /** - * @covers \Magento\Braintree\Model\Ui\Adminhtml\PayPal\TokenUiComponentProvider::getComponentForToken - * @magentoDataFixture Magento/Braintree/_files/paypal_vault_token.php - * @magentoAppArea adminhtml - */ - public function testGetComponentForToken() - { - $customerId = 1; - $token = 'mx29vk'; - $payerEmail = 'john.doe@example.com'; - - /** @var PaymentTokenManagement $tokenManagement */ - $tokenManagement = $this->objectManager->get(PaymentTokenManagement::class); - $paymentToken = $tokenManagement->getByGatewayToken($token, ConfigProvider::PAYPAL_CODE, $customerId); - - $component = $this->tokenComponentProvider->getComponentForToken($paymentToken); - $config = $component->getConfig(); - - static::assertNotEmpty($config[TokenUiComponentProviderInterface::COMPONENT_DETAILS]); - static::assertNotEmpty($config[TokenUiComponentProviderInterface::COMPONENT_PUBLIC_HASH]); - static::assertEquals(ConfigProvider::PAYPAL_VAULT_CODE, $config['code']); - - $details = $config[TokenUiComponentProviderInterface::COMPONENT_DETAILS]; - static::assertEquals($payerEmail, $details['payerEmail']); - static::assertNotEmpty($details['icon']); - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/TokensConfigProviderTest.php b/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/TokensConfigProviderTest.php deleted file mode 100644 index 94b3570fb2ea3..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/Model/Ui/TokensConfigProviderTest.php +++ /dev/null @@ -1,87 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Braintree\Model\Ui; - -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider as PayPalConfigProvider; -use Magento\Braintree\Model\Ui\PayPal\TokenUiComponentProvider; -use Magento\Customer\Model\Session; -use Magento\Framework\App\Area; -use Magento\Framework\ObjectManagerInterface; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\Vault\Model\PaymentTokenManagement; -use Magento\Vault\Model\Ui\TokensConfigProvider; -use Magento\Vault\Model\Ui\TokenUiComponentProviderInterface; -use PHPUnit\Framework\MockObject_MockObject as MockObject; - -/** - * Class TokensConfigProviderTest - */ -class TokensConfigProviderTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var ObjectManagerInterface - */ - private $objectManager; - - /** - * @var TokenUiComponentProviderInterface|MockObject - */ - private $tokenComponentProvider; - - /** - * @var TokensConfigProvider - */ - private $configProvider; - - /** - * @var Bootstrap - */ - private $bootstrap; - - protected function setUp(): void - { - $this->bootstrap = Bootstrap::getInstance(); - $this->bootstrap->loadArea(Area::AREA_FRONTEND); - $this->objectManager = Bootstrap::getObjectManager(); - - $this->tokenComponentProvider = $this->objectManager->get(TokenUiComponentProvider::class); - - $this->configProvider = $this->objectManager->create( - TokensConfigProvider::class, - [ - 'tokenUiComponentProviders' => [ - PayPalConfigProvider::PAYPAL_CODE => $this->tokenComponentProvider - ] - ] - ); - } - - /** - * @covers \Magento\Vault\Model\Ui\TokensConfigProvider::getConfig - * @magentoDataFixture Magento/Braintree/_files/paypal_vault_token.php - */ - public function testGetConfig() - { - $customerId = 1; - $token = 'mx29vk'; - $payerEmail = 'john.doe@example.com'; - - /** @var PaymentTokenManagement $tokenManagement */ - $tokenManagement = $this->objectManager->get(PaymentTokenManagement::class); - $paymentToken = $tokenManagement->getByGatewayToken($token, PayPalConfigProvider::PAYPAL_CODE, $customerId); - $item = PayPalConfigProvider::PAYPAL_VAULT_CODE . '_' . $paymentToken->getEntityId(); - - /** @var Session $session */ - $session = $this->objectManager->get(Session::class); - $session->setCustomerId($customerId); - - $actual = $this->configProvider->getConfig()['payment']['vault']; - static::assertCount(1, $actual); - static::assertNotEmpty($actual[$item]); - static::assertEquals(PayPalConfigProvider::PAYPAL_VAULT_CODE, $actual[$item]['config']['code']); - static::assertEquals($payerEmail, $actual[$item]['config']['details']['payerEmail']); - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/PaymentInformationManagementTest.php b/dev/tests/integration/testsuite/Magento/Braintree/PaymentInformationManagementTest.php deleted file mode 100644 index 839236d23826a..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/PaymentInformationManagementTest.php +++ /dev/null @@ -1,315 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Braintree; - -use Braintree\Result\Error; -use Braintree\Result\Successful; -use Braintree\Transaction; -use Braintree\Transaction\CreditCardDetails; -use Magento\Braintree\Gateway\Http\Client\TransactionSale; -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Checkout\Api\PaymentInformationManagementInterface; -use Magento\Framework\Api\SearchCriteriaBuilder; -use Magento\Framework\App\State; -use Magento\Framework\App\Area; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Quote\Api\Data\CartInterface; -use Magento\Quote\Api\Data\PaymentInterface; -use Magento\Sales\Api\Data\TransactionInterface; -use Magento\Sales\Api\TransactionRepositoryInterface; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\ObjectManager; -use PHPUnit\Framework\TestCase; -use PHPUnit\Framework\MockObject\MockObject as MockObject; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class PaymentInformationManagementTest extends TestCase -{ - /** - * @var ObjectManager - */ - private $objectManager; - - /** - * @var TransactionSale|MockObject - */ - private $client; - - /** - * @var PaymentInformationManagementInterface - */ - private $management; - - /** - * @inheritdoc - */ - protected function setUp(): void - { - $this->objectManager = Bootstrap::getObjectManager(); - - $this->client = $this->getMockBuilder(TransactionSale::class) - ->disableOriginalConstructor() - ->getMock(); - $this->objectManager->addSharedInstance($this->client, TransactionSale::class); - $this->management = $this->objectManager->get(PaymentInformationManagementInterface::class); - } - - /** - * @inheritdoc - */ - protected function tearDown(): void - { - $this->objectManager->removeSharedInstance(TransactionSale::class); - parent::tearDown(); - } - - /** - * Checks a case when payment method triggers an error during place order flow and - * error messages from payment gateway should be mapped. - * Error messages might be specific for different areas. - * - * @magentoAppIsolation enabled - * @magentoDataFixture Magento/Checkout/_files/quote_with_shipping_method.php - * @magentoConfigFixture current_store payment/braintree/active 1 - * @dataProvider getErrorPerAreaDataProvider - * @param string $area - * @param array $testErrorCodes - * @param string $expectedOutput - * @throws \Magento\Framework\Exception\LocalizedException - */ - public function testSavePaymentInformationAndPlaceOrderWithErrors( - string $area, - array $testErrorCodes, - string $expectedOutput - ) { - $this->expectException(\Magento\Framework\Exception\CouldNotSaveException::class); - - /** @var State $state */ - $state = $this->objectManager->get(State::class); - $state->setAreaCode($area); - - $quote = $this->getQuote('test_order_1'); - $payment = $this->getPayment(); - - $errors = ['errors' => []]; - - foreach ($testErrorCodes as $testErrorCode) { - array_push($errors['errors'], ['code' => $testErrorCode]); - } - - $response = new Error(['errors' => $errors, 'transaction' => ['status' => 'declined']]); - - $this->client->method('placeRequest') - ->willReturn(['object' => $response]); - - $this->expectExceptionMessage($expectedOutput); - - $this->management->savePaymentInformationAndPlaceOrder( - $quote->getId(), - $payment - ); - } - - /** - * Gets list of areas with specific error messages. - * - * @return array - */ - public function getErrorPerAreaDataProvider() - { - $testErrorGlobal = ['code' => 81802, 'message' => 'Company is too long.']; - $testErrorAdmin = ['code' => 91511, 'message' => 'Customer does not have any credit cards.']; - $testErrorFake = ['code' => 'fake_code', 'message' => 'Error message should not be mapped.']; - - return [ - [ - Area::AREA_FRONTEND, - [$testErrorAdmin['code'], $testErrorFake['code']], - 'Transaction has been declined. Please try again later.' - ], [ - Area::AREA_FRONTEND, - [$testErrorGlobal['code'], $testErrorAdmin['code'], $testErrorFake['code']], - $testErrorGlobal['message'] - ], [ - Area::AREA_ADMINHTML, - [$testErrorGlobal['code'], $testErrorAdmin['code'], $testErrorFake['code']], - $testErrorGlobal['message'] . PHP_EOL . $testErrorAdmin['message'] - ], - ]; - } - - /** - * Checks a case when order should be placed with "Sale" payment action. - * - * @magentoAppIsolation enabled - * @magentoDataFixture Magento/Checkout/_files/quote_with_shipping_method.php - * @magentoConfigFixture current_store payment/braintree/active 1 - * @magentoConfigFixture current_store payment/braintree/payment_action authorize_capture - */ - public function testPlaceOrderWithSaleAction() - { - $response = $this->getSuccessfulResponse(Transaction::SUBMITTED_FOR_SETTLEMENT); - $this->client->method('placeRequest') - ->willReturn($response); - - $quote = $this->getQuote('test_order_1'); - $payment = $this->getPayment(); - - $orderId = $this->management->savePaymentInformationAndPlaceOrder($quote->getId(), $payment); - self::assertNotEmpty($orderId); - - $transactions = $this->getPaymentTransactionList((int) $orderId); - self::assertCount(1, $transactions, 'Only one transaction should be present.'); - - /** @var TransactionInterface $transaction */ - $transaction = array_pop($transactions); - self::assertEquals( - 'capture', - $transaction->getTxnType(), - 'Order should contain only the "capture" transaction.' - ); - self::assertFalse((bool) $transaction->getIsClosed(), 'Transaction should not be closed.'); - } - - /** - * Checks a case when order should be placed with "Authorize" payment action. - * - * @magentoAppIsolation enabled - * @magentoDataFixture Magento/Checkout/_files/quote_with_shipping_method.php - * @magentoConfigFixture current_store payment/braintree/active 1 - * @magentoConfigFixture current_store payment/braintree/payment_action authorize - */ - public function testPlaceOrderWithAuthorizeAction() - { - $response = $this->getSuccessfulResponse(Transaction::AUTHORIZED); - $this->client->method('placeRequest') - ->willReturn($response); - - $quote = $this->getQuote('test_order_1'); - $payment = $this->getPayment(); - - $orderId = $this->management->savePaymentInformationAndPlaceOrder($quote->getId(), $payment); - self::assertNotEmpty($orderId); - - $transactions = $this->getPaymentTransactionList((int) $orderId); - self::assertCount(1, $transactions, 'Only one transaction should be present.'); - - /** @var TransactionInterface $transaction */ - $transaction = array_pop($transactions); - self::assertEquals( - 'authorization', - $transaction->getTxnType(), - 'Order should contain only the "authorization" transaction.' - ); - self::assertFalse((bool) $transaction->getIsClosed(), 'Transaction should not be closed.'); - } - - /** - * Retrieves quote by provided order ID. - * - * @param string $reservedOrderId - * @return CartInterface - */ - private function getQuote(string $reservedOrderId): CartInterface - { - /** @var SearchCriteriaBuilder $searchCriteriaBuilder */ - $searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class); - $searchCriteria = $searchCriteriaBuilder->addFilter('reserved_order_id', $reservedOrderId) - ->create(); - - /** @var CartRepositoryInterface $quoteRepository */ - $quoteRepository = $this->objectManager->get(CartRepositoryInterface::class); - $items = $quoteRepository->getList($searchCriteria) - ->getItems(); - - return array_pop($items); - } - - /** - * Creates Braintree payment method. - * - * @return PaymentInterface - */ - private function getPayment(): PaymentInterface - { - /** @var PaymentInterface $payment */ - $payment = $this->objectManager->create(PaymentInterface::class); - $payment->setMethod(ConfigProvider::CODE); - - return $payment; - } - - /** - * Get list of order transactions. - * - * @param int $orderId - * @return TransactionInterface[] - */ - private function getPaymentTransactionList(int $orderId): array - { - /** @var SearchCriteriaBuilder $searchCriteriaBuilder */ - $searchCriteriaBuilder = $this->objectManager->get(SearchCriteriaBuilder::class); - $searchCriteria = $searchCriteriaBuilder->addFilter('order_id', $orderId) - ->create(); - - /** @var TransactionRepositoryInterface $transactionRepository */ - $transactionRepository = $this->objectManager->get(TransactionRepositoryInterface::class); - return $transactionRepository->getList($searchCriteria) - ->getItems(); - } - - /** - * Returns successful Braintree response. - * - * @param string $transactionStatus - * @return array - */ - private function getSuccessfulResponse(string $transactionStatus): array - { - $successResponse = new Successful(); - $successResponse->success = true; - $successResponse->transaction = $this->getBraintreeTransaction($transactionStatus); - - $response = [ - 'object' => $successResponse, - ]; - - return $response; - } - - /** - * Returns Braintree transaction. - * - * @param string $transactionStatus - * @return Transaction - */ - private function getBraintreeTransaction(string $transactionStatus) - { - $cardData = [ - 'token' => '73nrjn', - 'bin' => '411111', - 'cardType' => 'Visa', - 'expirationMonth' => '12', - 'expirationYear' => '2025', - 'last4' => '1111' - ]; - - $transactionData = [ - 'id' => 'c0n6gvjb', - 'status' => $transactionStatus, - 'creditCard' => $cardData, - 'creditCardDetails' => new CreditCardDetails($cardData) - ]; - - $transaction = Transaction::factory($transactionData); - - return $transaction; - } -} diff --git a/dev/tests/integration/testsuite/Magento/Braintree/_files/fraud_order.php b/dev/tests/integration/testsuite/Magento/Braintree/_files/fraud_order.php deleted file mode 100644 index e6f92928e9644..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/_files/fraud_order.php +++ /dev/null @@ -1,38 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -use Magento\Braintree\Model\Ui\ConfigProvider; -use Magento\Config\Model\Config; -use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Sales\Model\Order; -use Magento\Sales\Model\Order\Payment; -use Magento\TestFramework\Helper\Bootstrap; - -$objectManager = Bootstrap::getObjectManager(); - -/** @var Config $config */ -$config = $objectManager->get(Config::class); -$config->setDataByPath('payment/' . ConfigProvider::CODE . '/active', 1); -$config->save(); - -/** @var Payment $payment */ -$payment = $objectManager->create(Payment::class); -$payment->setMethod(ConfigProvider::CODE) - ->setLastTransId('000001'); - -$amount = 100; - -/** @var Order $order */ -$order = $objectManager->create(Order::class); -$order->setIncrementId('100000002') - ->setState(Order::STATE_PAYMENT_REVIEW) - ->setStatus(Order::STATUS_FRAUD) - ->setBaseGrandTotal($amount) - ->setPayment($payment); - -/** @var OrderRepositoryInterface $orderRepository */ -$orderRepository = $objectManager->get(OrderRepositoryInterface::class); -$orderRepository->save($order); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/_files/payment_configuration.php b/dev/tests/integration/testsuite/Magento/Braintree/_files/payment_configuration.php deleted file mode 100644 index 276700a83ccc0..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/_files/payment_configuration.php +++ /dev/null @@ -1,62 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -use Magento\Config\Model\Config; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\Encryption\EncryptorInterface; -use Magento\Store\Api\WebsiteRepositoryInterface; -use Magento\Store\Model\ScopeInterface; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\Workaround\Override\Fixture\Resolver; - -$objectManager = Bootstrap::getObjectManager(); -/** @var WebsiteRepositoryInterface $websiteRepository */ -$websiteRepository = $objectManager->get(WebsiteRepositoryInterface::class); -/** @var EncryptorInterface $encryptor */ -$encryptor = $objectManager->get(EncryptorInterface::class); - -$processConfigData = function (Config $config, array $data) { - foreach ($data as $key => $value) { - $config->setDataByPath($key, $value); - $config->save(); - } -}; - -// save payment configuration for the default scope -$configData = [ - 'payment/braintree/merchant_id' => 'def_merchant_id', - 'payment/braintree/public_key' => $encryptor->encrypt('def_public_key'), - 'payment/braintree/private_key' => $encryptor->encrypt('def_private_key'), -]; -/** @var Config $defConfig */ -$defConfig = $objectManager->create(Config::class); -$defConfig->setScope(ScopeConfigInterface::SCOPE_TYPE_DEFAULT); -$processConfigData($defConfig, $configData); - -// save payment configuration per store -Resolver::getInstance()->requireDataFixture('Magento/Store/_files/store.php'); -$storeConfigData = [ - 'payment/braintree/merchant_id' => 'store_merchant_id', - 'payment/braintree/public_key' => $encryptor->encrypt('store_public_key'), -]; -/** @var Config $storeConfig */ -$storeConfig = $objectManager->create(Config::class); -$storeConfig->setScope(ScopeInterface::SCOPE_STORES); -$storeConfig->setStore('test'); -$processConfigData($storeConfig, $storeConfigData); - -// save payment website config data -Resolver::getInstance()->requireDataFixture('Magento/Store/_files/second_website_with_two_stores.php'); -$websiteId = $websiteRepository->get('test')->getCode(); -$websiteConfigData = [ - 'payment/braintree/merchant_id' => 'website_merchant_id', - 'payment/braintree/private_key' => $encryptor->encrypt('website_private_key'), -]; -/** @var Config $websiteConfig */ -$websiteConfig = $objectManager->create(Config::class); -$websiteConfig->setScope(ScopeInterface::SCOPE_WEBSITES); -$websiteConfig->setWebsite($websiteId); -$processConfigData($websiteConfig, $websiteConfigData); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/_files/payment_configuration_rollback.php b/dev/tests/integration/testsuite/Magento/Braintree/_files/payment_configuration_rollback.php deleted file mode 100644 index 44914fe7abe2a..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/_files/payment_configuration_rollback.php +++ /dev/null @@ -1,43 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\App\Config\Storage\WriterInterface; -use Magento\Store\Api\StoreRepositoryInterface; -use Magento\Store\Api\WebsiteRepositoryInterface; -use Magento\Store\Model\ScopeInterface; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\Workaround\Override\Fixture\Resolver; - -$objectManager = Bootstrap::getObjectManager(); - -$deleteConfigData = function (WriterInterface $writer, $scope, $scopeId) { - $configData = [ - 'payment/braintree/merchant_id', - 'payment/braintree/public_key', - 'payment/braintree/private_key', - ]; - foreach ($configData as $path) { - $writer->delete($path, $scope, $scopeId); - } -}; - -/** @var WriterInterface $configWriter */ -$configWriter = $objectManager->get(WriterInterface::class); -$deleteConfigData($configWriter, ScopeConfigInterface::SCOPE_TYPE_DEFAULT, null); - -/** @var StoreRepositoryInterface $storeRepository */ -$storeRepository = $objectManager->get(StoreRepositoryInterface::class); -$store = $storeRepository->get('test'); -$deleteConfigData($configWriter, ScopeInterface::SCOPE_STORES, $store->getId()); - -/** @var WebsiteRepositoryInterface $websiteRepository */ -$websiteRepository = $objectManager->get(WebsiteRepositoryInterface::class); -$website = $websiteRepository->get('test'); -$deleteConfigData($configWriter, ScopeInterface::SCOPE_WEBSITES, $website->getId()); - -Resolver::getInstance()->requireDataFixture('Magento/Store/_files/second_website_with_two_stores_rollback.php'); -Resolver::getInstance()->requireDataFixture('Magento/Store/_files/store_rollback.php'); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/_files/payments.php b/dev/tests/integration/testsuite/Magento/Braintree/_files/payments.php deleted file mode 100644 index 93fdf078ca453..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/_files/payments.php +++ /dev/null @@ -1,16 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider; -use Magento\Config\Model\Config; -use Magento\TestFramework\Helper\Bootstrap; - -$objectManager = Bootstrap::getObjectManager(); -/** @var Config $config */ -$config = $objectManager->get(Config::class); -$config->setDataByPath('payment/' . ConfigProvider::PAYPAL_CODE . '/active', 1); -$config->save(); -$config->setDataByPath('payment/' . ConfigProvider::PAYPAL_VAULT_CODE . '/active', 1); -$config->save(); diff --git a/dev/tests/integration/testsuite/Magento/Braintree/_files/paypal_quote.php b/dev/tests/integration/testsuite/Magento/Braintree/_files/paypal_quote.php deleted file mode 100644 index 0dcc7b49da20b..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Braintree/_files/paypal_quote.php +++ /dev/null @@ -1,31 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -use Magento\Customer\Model\CustomerRegistry; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Quote\Api\Data\CartInterface; -use Magento\Store\Model\StoreManagerInterface; -use Magento\TestFramework\Helper\Bootstrap; -use Magento\TestFramework\Workaround\Override\Fixture\Resolver; - -Resolver::getInstance()->requireDataFixture('Magento/Braintree/_files/paypal_vault_token.php'); - -$objectManager = Bootstrap::getObjectManager(); -/** @var CustomerRegistry $customerRegistry */ -$customerRegistry = Bootstrap::getObjectManager()->create(CustomerRegistry::class); -$customer = $customerRegistry->retrieve(1); -/** @var StoreManagerInterface $storeManager */ -$storeManager = $objectManager->get(StoreManagerInterface::class); - -/** @var CartInterface $quote */ -$quote = $objectManager->get(CartInterface::class); -$quote->setStoreId($storeManager->getStore()->getId()) - ->setCustomerIsGuest(false) - ->setCustomerId($customer->getId()); - -/** @var CartRepositoryInterface $quoteRepository */ -$quoteRepository = $objectManager->get(CartRepositoryInterface::class); -$quoteRepository->save($quote); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/WeightTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/WeightTest.php index 7c57440fdb29d..1ab700ed58948 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/WeightTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Adminhtml/Product/Helper/Form/WeightTest.php @@ -71,7 +71,7 @@ public function testProductHasWeight($type) $form = $this->_formFactory->create(); $form->setDataObject($currentProduct); $block->setForm($form); - $this->assertNotRegExp( + $this->assertDoesNotMatchRegularExpression( '/value="0".*checked="checked"/', $block->getElementHtml(), '"Does this have a weight" is set to "No" for physical products' diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/CheckProductPriceTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/CheckProductPriceTest.php index d3287ae492d37..4526a83bb0bce 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/CheckProductPriceTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/ListProduct/CheckProductPriceTest.php @@ -140,7 +140,7 @@ public function testCheckFixedTierPriceForLoggedUser(): void { $priceHtml = $this->getProductPriceHtml('simple-product-tax-none'); $this->assertFinalPrice($priceHtml, 205.00); - $this->assertNotRegExp('/\$10/', $priceHtml); + $this->assertDoesNotMatchRegularExpression('/\$10/', $priceHtml); $this->customerSession->setCustomerId(1); try { $priceHtml = $this->getProductPriceHtml('simple-product-tax-none'); diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Options/AbstractRenderCustomOptionsTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Options/AbstractRenderCustomOptionsTest.php index 5e5834304f107..eb34696c70dbf 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Options/AbstractRenderCustomOptionsTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Block/Product/View/Options/AbstractRenderCustomOptionsTest.php @@ -160,7 +160,7 @@ protected function assertSelectOptionRenderingOnProduct( if (isset($checkArray['not_contain_arr'])) { foreach ($checkArray['not_contain_arr'] as $notContainPattern) { - $this->assertNotRegExp($notContainPattern, $optionHtml); + $this->assertDoesNotMatchRegularExpression($notContainPattern, $optionHtml); } } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Gallery/UploadTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Gallery/UploadTest.php index 3aa6c79a35ef1..b88980181fb63 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Gallery/UploadTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Controller/Adminhtml/Product/Gallery/UploadTest.php @@ -167,7 +167,7 @@ public function testUploadActionWithErrors(array $file, array $expectation): voi $this->assertEquals($expectation['errorcode'], $jsonBody['errorcode']); if (!empty($expectation['tmp_media_path'])) { - $this->assertFileNotExists( + $this->assertFileDoesNotExist( $this->getFileAbsolutePath($expectation['tmp_media_path']) ); } diff --git a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/ResourceModel/Product/ConditionsToCollectionApplierTest.php b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/ResourceModel/Product/ConditionsToCollectionApplierTest.php index 1b2485e20fc9d..0bef038b5f7e5 100644 --- a/dev/tests/integration/testsuite/Magento/CatalogRule/Model/ResourceModel/Product/ConditionsToCollectionApplierTest.php +++ b/dev/tests/integration/testsuite/Magento/CatalogRule/Model/ResourceModel/Product/ConditionsToCollectionApplierTest.php @@ -78,6 +78,9 @@ function (Product $product) { asort($expectedSkuList); asort($resultSkuList); + $expectedSkuList = array_values($expectedSkuList); + $resultSkuList = array_values($resultSkuList); + $this->assertEquals($expectedSkuList, $resultSkuList, sprintf('%s failed', $variationName)); } } @@ -416,6 +419,19 @@ private function conditionProvider() 'simple-product-12' ] ], + + // test filter for case "If ALL/ANY of these conditions are FALSE" with multiple levels + 'variation 22' => [ + 'condition' => $this->getConditionsForVariation22(), + 'expected-sku' => [ + 'simple-product-1', + 'simple-product-2', + 'simple-product-3', + 'simple-product-4', + 'simple-product-7', + 'simple-product-8' + ] + ], ]; } @@ -1008,6 +1024,39 @@ private function getConditionsForVariation21() return $this->getCombineConditionFromArray($conditions); } + private function getConditionsForVariation22() + { + $category1Name = 'Category 1'; + + $category1Id = $this->categoryCollectionFactory + ->create() + ->addAttributeToFilter('name', $category1Name) + ->getAllIds(); + + $conditions = [ + 'type' => \Magento\CatalogRule\Model\Rule\Condition\Combine::class, + 'aggregator' => 'all', + 'value' => 0, + 'conditions' => [ + [ + 'type' => \Magento\CatalogRule\Model\Rule\Condition\Combine::class, + 'aggregator' => 'all', + 'value' => 1, + 'conditions' => [ + [ + 'type' => \Magento\CatalogRule\Model\Rule\Condition\Product::class, + 'operator' => '==', + 'value' => implode(',', $category1Id), + 'attribute' => 'category_ids' + ] + ] + ] + ] + ]; + + return $this->getCombineConditionFromArray($conditions); + } + private function getCombineConditionFromArray(array $data) { $combinedCondition = $this->combinedConditionFactory->create(); diff --git a/dev/tests/integration/testsuite/Magento/Checkout/Block/Checkout/LayoutProcessorTest.php b/dev/tests/integration/testsuite/Magento/Checkout/Block/Checkout/LayoutProcessorTest.php new file mode 100644 index 0000000000000..31a96d1584392 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Checkout/Block/Checkout/LayoutProcessorTest.php @@ -0,0 +1,66 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Checkout\Block\Checkout; + +use Magento\Framework\App\Config\MutableScopeConfigInterface; +use Magento\Store\Model\ScopeInterface; +use Magento\TestFramework\Helper\Bootstrap; +use PHPUnit\Framework\TestCase; + +class LayoutProcessorTest extends TestCase +{ + /** + * Tests default country for shipping address. + * + * @param string $defaultCountryId + * @param bool $isCountryValueExpected + * @magentoConfigFixture default_store checkout/options/display_billing_address_on 1 + * @magentoDataFixture Magento/Backend/_files/allowed_countries_fr.php + * @dataProvider defaultCountryDataProvider + */ + public function testShippingAddressCountryId(string $defaultCountryId, bool $isCountryValueExpected): void + { + /** @var MutableScopeConfigInterface $mutableConfig */ + $mutableConfig = Bootstrap::getObjectManager()->get(MutableScopeConfigInterface::class); + $mutableConfig->setValue('general/country/default', $defaultCountryId, ScopeInterface::SCOPE_STORE, 'default'); + + /** @var $layoutProcessor LayoutProcessor */ + $layoutProcessor = Bootstrap::getObjectManager()->get(LayoutProcessor::class); + + $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step'] + ['children']['shippingAddress']['children']['shipping-address-fieldset']['children'] = []; + $data = $layoutProcessor->process($jsLayout); + + $countryId = $data["components"]["checkout"]["children"]["steps"]["children"]["shipping-step"]["children"] + ["shippingAddress"]["children"]["shipping-address-fieldset"]["children"]["country_id"]; + + $isCountryValueExists = array_key_exists('value', $countryId); + + $this->assertEquals($isCountryValueExpected, $isCountryValueExists); + if ($isCountryValueExpected) { + $this->assertEquals($defaultCountryId, $countryId['value']); + } + } + + /** + * @return array[] + */ + public function defaultCountryDataProvider(): array + { + return [ + 'Default country isn\'t in allowed country list' => [ + 'defaultCountryId' => 'US', + 'isCountryValueExpected' => false + ], + 'Default country is in allowed country list' => [ + 'defaultCountryId' => 'FR', + 'isCountryValueExpected' => true + ], + ]; + } +} diff --git a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/product_configurable.php b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/product_configurable.php index 02a3e77663991..35439a24cd2db 100644 --- a/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/product_configurable.php +++ b/dev/tests/integration/testsuite/Magento/ConfigurableProduct/_files/product_configurable.php @@ -23,7 +23,7 @@ /** @var ProductRepositoryInterface $productRepository */ $productRepository = Bootstrap::getObjectManager() - ->create(ProductRepositoryInterface::class); + ->get(ProductRepositoryInterface::class); /** @var $installer CategorySetup */ $installer = Bootstrap::getObjectManager()->create(CategorySetup::class); $eavConfig = Bootstrap::getObjectManager()->get(Config::class); diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/SaveTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/SaveTest.php index 8030b63051001..2ec87f758b812 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/SaveTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/Adminhtml/Index/SaveTest.php @@ -22,6 +22,7 @@ use Magento\Store\Model\Store; use Magento\Store\Model\StoreManagerInterface; use Magento\TestFramework\TestCase\AbstractBackendController; +use PHPUnit\Framework\MockObject\MockObject; /** * Tests for save customer via backend/customer/index/save controller. @@ -224,6 +225,32 @@ public function createCustomerErrorsProvider(): array ]; } + /** + * Update customer with exceptions + * + * @magentoDbIsolation enabled + * + * @return void + */ + public function testUpdateCustomerErrors(): void + { + $postData = [ + 'customer' => [ + CustomerData::FIRSTNAME => 'John', + CustomerData::LASTNAME => 'Doe', + ], + 'subscription' => '1', + ]; + $expectedMessages = [(string)__('Something went wrong while saving the customer.')]; + $postData['customer']['entity_id'] = -1; + $params = ['back' => true]; + $this->dispatchCustomerSave($postData, $params); + $this->assertSessionMessages( + $this->equalTo($expectedMessages), + MessageInterface::TYPE_ERROR + ); + } + /** * Update customer with subscription and redirect to edit page. * @@ -512,7 +539,7 @@ private function assertCustomerSubscription( * @param array $sender * @param int $customerId * @param string|null $newEmail - * @return \PHPUnit\Framework\MockObject\MockObject + * @return MockObject */ private function prepareEmailMock( int $occurrenceNumber, @@ -520,7 +547,7 @@ private function prepareEmailMock( array $sender, int $customerId, $newEmail = null - ) : \PHPUnit\Framework\MockObject\MockObject { + ) : MockObject { $area = Area::AREA_FRONTEND; $customer = $this->customerRepository->getById($customerId); $storeId = $customer->getStoreId(); @@ -568,12 +595,12 @@ private function prepareEmailMock( /** * Add email mock to class * - * @param \PHPUnit\Framework\MockObject\MockObject $transportBuilderMock + * @param MockObject $transportBuilderMock * @param string $className * @return void */ private function addEmailMockToClass( - \PHPUnit\Framework\MockObject\MockObject $transportBuilderMock, + MockObject $transportBuilderMock, $className ): void { $mocked = $this->_objectManager->create( diff --git a/dev/tests/integration/testsuite/Magento/Customer/Ui/Component/DataProviderTest.php b/dev/tests/integration/testsuite/Magento/Customer/Ui/Component/DataProviderTest.php new file mode 100644 index 0000000000000..8529d7baa744a --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/Ui/Component/DataProviderTest.php @@ -0,0 +1,98 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Customer\Ui\Component; + +use Magento\Backend\Model\Locale\Resolver; +use Magento\Framework\Api\Filter; +use Magento\Framework\Locale\ResolverInterface; +use Magento\TestFramework\Helper\Bootstrap; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * Class to test Data Provider for customer listing + * + * @magentoAppArea adminhtml + */ +class DataProviderTest extends TestCase +{ + /** + * @var ResolverInterface|MockObject + */ + private $localeResolverMock; + + /** + * @var DataProvider + */ + private $dataProvider; + + /** + * @inheritdoc + */ + protected function setUp(): void + { + $this->initLocaleResolverMock(); + } + + /** + * Test to filter by region name in custom locale + * + * @param array $filterData + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoDataFixture Magento/Customer/_files/customer_address.php + * @magentoDataFixture Magento/Directory/_files/region_name_jp.php + * @dataProvider getDataByRegionDataProvider + * @magentoDbIsolation disabled + */ + public function testGetDataByRegion(array $filterData) + { + $locale = 'JA_jp'; + $this->localeResolverMock->method('getLocale')->willReturn($locale); + $this->dataProvider = Bootstrap::getObjectManager()->create( + DataProvider::class, + [ + 'name' => 'customer_listing_data_source', + 'requestFieldName' => 'id', + 'primaryFieldName' => 'entity_id', + ] + ); + + $filter = Bootstrap::getObjectManager()->create( + Filter::class, + ['data' => $filterData] + ); + $this->dataProvider->addFilter($filter); + $data = $this->dataProvider->getData(); + $this->assertEquals(1, $data['totalRecords']); + $this->assertCount(1, $data['items']); + $this->assertEquals($filterData['value'], $data['items'][0]['billing_region']); + } + + /** + * @return array + */ + public function getDataByRegionDataProvider(): array + { + return [ + [['condition_type' => 'fulltext', 'field' => 'fulltext', 'value' => 'アラバマ']], + [['condition_type' => 'regular', 'field' => 'billing_region', 'value' => 'アラバマ']], + ]; + } + + /** + * Mock locale resolver + */ + private function initLocaleResolverMock(): void + { + $this->localeResolverMock = $this->createMock(ResolverInterface::class); + Bootstrap::getObjectManager()->removeSharedInstance(ResolverInterface::class); + Bootstrap::getObjectManager()->removeSharedInstance(Resolver::class); + Bootstrap::getObjectManager()->addSharedInstance($this->localeResolverMock, ResolverInterface::class); + Bootstrap::getObjectManager()->addSharedInstance($this->localeResolverMock, Resolver::class); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Customer/Ui/Component/Listing/Address/DataProviderTest.php b/dev/tests/integration/testsuite/Magento/Customer/Ui/Component/Listing/Address/DataProviderTest.php new file mode 100644 index 0000000000000..12e7b1bd3d0e9 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Customer/Ui/Component/Listing/Address/DataProviderTest.php @@ -0,0 +1,116 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Customer\Ui\Component\Listing\Address; + +use Magento\Backend\Model\Locale\Resolver; +use Magento\Framework\Api\Filter; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\Locale\ResolverInterface; +use Magento\TestFramework\Helper\Bootstrap; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * Class to test Data Provider for customer address listing + * + * @magentoAppArea adminhtml + */ +class DataProviderTest extends TestCase +{ + /** + * @var ResolverInterface|MockObject + */ + private $localeResolverMock; + + /** + * @var RequestInterface|MockObject + */ + private $requestMock; + + /** + * @var DataProvider + */ + private $dataProvider; + + /** + * @inheritdoc + */ + protected function setUp(): void + { + $this->initLocaleResolverMock(); + $this->requestMock = $this->createMock(RequestInterface::class); + $this->dataProvider = Bootstrap::getObjectManager()->create( + DataProvider::class, + [ + 'name' => 'customer_address_listing_data_source', + 'requestFieldName' => 'id', + 'primaryFieldName' => 'entity_id', + 'request' => $this->requestMock, + ] + ); + } + + /** + * Test to filter by region name in custom locale + * + * @param array $filterData + * @magentoDataFixture Magento/Customer/_files/customer.php + * @magentoDataFixture Magento/Customer/_files/customer_address.php + * @magentoDataFixture Magento/Directory/_files/region_name_jp.php + * @dataProvider getDataByRegionDataProvider + */ + public function testGetDataByRegion(array $filterData) + { + $customerId = 1; + $locale = 'JA_jp'; + $this->localeResolverMock->method('getLocale')->willReturn($locale); + $this->requestMock->method('getParam')->with('parent_id')->willReturn($customerId); + $this->dataProvider = Bootstrap::getObjectManager()->create( + DataProvider::class, + [ + 'name' => 'customer_address_listing_data_source', + 'requestFieldName' => 'id', + 'primaryFieldName' => 'entity_id', + 'request' => $this->requestMock, + ] + ); + + $filter = Bootstrap::getObjectManager()->create( + Filter::class, + ['data' => $filterData] + ); + $this->dataProvider->addFilter($filter); + $data = $this->dataProvider->getData(); + $this->assertEquals(1, $data['totalRecords']); + $this->assertCount(1, $data['items']); + $this->assertEquals($filterData['value'], $data['items'][0]['region']); + } + + /** + * @return array + */ + public function getDataByRegionDataProvider(): array + { + return [ + [['condition_type' => 'fulltext', 'field' => 'fulltext', 'value' => 'アラバマ']], + [['condition_type' => 'regular', 'field' => 'region', 'value' => 'アラバマ']], + ]; + } + + /** + * Mock locale resolver + */ + private function initLocaleResolverMock() + { + $this->localeResolverMock = $this->createMock(ResolverInterface::class); + Bootstrap::getObjectManager()->removeSharedInstance(ResolverInterface::class); + Bootstrap::getObjectManager()->removeSharedInstance(Resolver::class); + Bootstrap::getObjectManager()->addSharedInstance($this->localeResolverMock, ResolverInterface::class); + Bootstrap::getObjectManager()->addSharedInstance($this->localeResolverMock, Resolver::class); + } +} diff --git a/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/AddressTest.php b/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/AddressTest.php index 16e2f03bf49a4..832aabe6b6a78 100644 --- a/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/AddressTest.php +++ b/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/AddressTest.php @@ -9,10 +9,15 @@ */ namespace Magento\CustomerImportExport\Model\Import; +use Magento\Customer\Api\AddressRepositoryInterface; +use Magento\Customer\Api\CustomerRepositoryInterface; +use Magento\Customer\Api\Data\AddressInterface; +use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Filesystem; use Magento\ImportExport\Model\Import as ImportModel; use Magento\ImportExport\Model\Import\Adapter as ImportAdapter; +use Magento\ImportExport\Model\Import\Source\Csv; use Magento\TestFramework\Helper\Bootstrap; use Magento\Framework\Indexer\StateInterface; use ReflectionClass; @@ -483,4 +488,54 @@ public function testCustomerIndexer(): void $this->assertEquals(StateInterface::STATUS_VALID, $statusBeforeImport); $this->assertEquals(StateInterface::STATUS_INVALID, $statusAfterImport); } + + /** + * Test import address with region for a country that does not have regions defined + * + * @magentoDataFixture Magento/Customer/_files/import_export/customer_with_addresses.php + */ + public function testImportAddressWithOptionalRegion() + { + $objectManager = Bootstrap::getObjectManager(); + $customerRepository = $objectManager->get(CustomerRepositoryInterface::class); + $customer = $customerRepository->get('BetsyParker@example.com'); + $file = __DIR__ . '/_files/import_uk_address.csv'; + $filesystem = Bootstrap::getObjectManager()->create(Filesystem::class); + $directoryWrite = $filesystem->getDirectoryWrite(DirectoryList::ROOT); + $source = new Csv($file, $directoryWrite); + $errors = $this->_entityAdapter + ->setParameters(['behavior' => ImportModel::BEHAVIOR_ADD_UPDATE]) + ->setSource($source) + ->validateData(); + $this->assertEmpty($errors->getAllErrors(), 'Import validation failed'); + $this->_entityAdapter->importData(); + $address = $this->getAddresses( + [ + 'parent_id' => $customer->getId(), + 'country_id' => 'GB', + ] + ); + $this->assertCount(1, $address); + $this->assertNull($address[0]->getRegionId()); + $this->assertEquals('Liverpool', $address[0]->getRegion()->getRegion()); + } + + /** + * Get Addresses by filter + * + * @param array $filter + * @return AddressInterface[] + */ + private function getAddresses(array $filter): array + { + $objectManager = Bootstrap::getObjectManager(); + /** @var AddressRepositoryInterface $repository */ + $repository = $objectManager->create(AddressRepositoryInterface::class); + /** @var SearchCriteriaBuilder $searchCriteriaBuilder */ + $searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class); + foreach ($filter as $attr => $value) { + $searchCriteriaBuilder->addFilter($attr, $value); + } + return $repository->getList($searchCriteriaBuilder->create())->getItems(); + } } diff --git a/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/_files/import_uk_address.csv b/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/_files/import_uk_address.csv new file mode 100644 index 0000000000000..861f71fd43770 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/CustomerImportExport/Model/Import/_files/import_uk_address.csv @@ -0,0 +1,2 @@ +_website,_email,_entity_id,city,company,country_id,fax,firstname,lastname,middlename,postcode,prefix,region,region_id,street,suffix,telephone,vat_id,vat_is_valid,vat_request_date,vat_request_id,vat_request_success,_address_default_billing_,_address_default_shipping_ +base,"BetsyParker@example.com",,Liverpool,,GB,,Mike,Miller,,"L2 2AY",,"Liverpool",0,"Moorfields, Vernon St",," +443450507080",,,,,,, diff --git a/dev/tests/integration/testsuite/Magento/Deploy/_files/scopes/config_with_changed_stores.php b/dev/tests/integration/testsuite/Magento/Deploy/_files/scopes/config_with_changed_stores.php index e9e754d15da9c..a3e95fcb34bc8 100644 --- a/dev/tests/integration/testsuite/Magento/Deploy/_files/scopes/config_with_changed_stores.php +++ b/dev/tests/integration/testsuite/Magento/Deploy/_files/scopes/config_with_changed_stores.php @@ -14,9 +14,9 @@ 'default_group_id' => '0', 'is_default' => '0', ], - 'base' => [ + 'base_code_changed' => [ 'website_id' => '1', - 'code' => 'base', + 'code' => 'base_code_changed', 'name' => 'Main Website', 'sort_order' => '0', 'default_group_id' => '1', diff --git a/dev/tests/integration/testsuite/Magento/Directory/_files/region_name_jp.php b/dev/tests/integration/testsuite/Magento/Directory/_files/region_name_jp.php new file mode 100644 index 0000000000000..9d6c952fddff3 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Directory/_files/region_name_jp.php @@ -0,0 +1,23 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +use Magento\Framework\App\ResourceConnection; +use Magento\TestFramework\Helper\Bootstrap; + +/** @var ResourceConnection $resource */ +$resource = Bootstrap::getObjectManager()->get(ResourceConnection::class); +$connection = $resource->getConnection(); +/** Add japan name of Alabama State */ +$alabamaOnJP = [ + 'locale' => 'JA_jp', + 'region_id' => 1, + 'name' => 'アラバマ' +]; +$connection->insert( + $resource->getTableName('directory_country_region_name'), + $alabamaOnJP +); diff --git a/dev/tests/integration/testsuite/Magento/Directory/_files/region_name_jp_rollback.php b/dev/tests/integration/testsuite/Magento/Directory/_files/region_name_jp_rollback.php new file mode 100644 index 0000000000000..2a565dc52258f --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Directory/_files/region_name_jp_rollback.php @@ -0,0 +1,16 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +use Magento\Framework\App\ResourceConnection; +use Magento\TestFramework\Helper\Bootstrap; + +/** @var ResourceConnection $resource */ +$resource = Bootstrap::getObjectManager()->get(ResourceConnection::class); +$resource->getConnection()->delete( + $resource->getTableName('directory_country_region_name'), + "locale='JA_jp'" +); diff --git a/dev/tests/integration/testsuite/Magento/Framework/Backup/DbTest.php b/dev/tests/integration/testsuite/Magento/Framework/Backup/DbTest.php index 4cdec5b8ea720..f25880e10c811 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/Backup/DbTest.php +++ b/dev/tests/integration/testsuite/Magento/Framework/Backup/DbTest.php @@ -57,18 +57,10 @@ public function testBackupIncludesCustomTriggers() $tableName = Bootstrap::getObjectManager()->get(Setup::class) ->getTable('test_table_with_custom_trigger'); $this->assertMatchesRegularExpression( - '/CREATE TRIGGER test_custom_trigger AFTER INSERT ON '. $tableName . ' FOR EACH ROW/', + '/CREATE TRIGGER `?test_custom_trigger`? AFTER INSERT ON `?'. $tableName . '`? FOR EACH ROW/', $content ); //Clean up. $write->delete('/backups/' . $time . '_db_testbackup.sql'); } - - /** - * teardown - */ - protected function tearDown(): void - { - parent::tearDown(); - } } diff --git a/dev/tests/integration/testsuite/Magento/Framework/Composer/_files/testFromClone/composer.lock b/dev/tests/integration/testsuite/Magento/Framework/Composer/_files/testFromClone/composer.lock index 4dd3612ccb020..3ee5a290a7026 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/Composer/_files/testFromClone/composer.lock +++ b/dev/tests/integration/testsuite/Magento/Framework/Composer/_files/testFromClone/composer.lock @@ -6,53 +6,6 @@ ], "content-hash": "60007664938710edf52eadddd7551867", "packages": [ - { - "name": "braintree/braintree_php", - "version": "3.35.0", - "source": { - "type": "git", - "url": "https://github.com/braintree/braintree_php.git", - "reference": "6c4388199ce379432804a5c18b88585157ef2ed7" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/braintree/braintree_php/zipball/6c4388199ce379432804a5c18b88585157ef2ed7", - "reference": "6c4388199ce379432804a5c18b88585157ef2ed7", - "shasum": "" - }, - "require": { - "ext-curl": "*", - "ext-dom": "*", - "ext-hash": "*", - "ext-openssl": "*", - "ext-xmlwriter": "*", - "php": ">=5.4.0" - }, - "require-dev": { - "phpunit/phpunit": "3.7.*" - }, - "type": "library", - "autoload": { - "psr-0": { - "Braintree": "lib/" - }, - "psr-4": { - "Braintree\\": "lib/Braintree" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Braintree", - "homepage": "https://www.braintreepayments.com" - } - ], - "description": "Braintree PHP Client Library", - "time": "2018-07-26T14:37:38+00:00" - }, { "name": "colinmollenhour/cache-backend-file", "version": "v1.4.4", diff --git a/dev/tests/integration/testsuite/Magento/Framework/Composer/_files/testFromCreateProject/composer.lock b/dev/tests/integration/testsuite/Magento/Framework/Composer/_files/testFromCreateProject/composer.lock index fbcaf8d1600fb..1f6bc5acf739b 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/Composer/_files/testFromCreateProject/composer.lock +++ b/dev/tests/integration/testsuite/Magento/Framework/Composer/_files/testFromCreateProject/composer.lock @@ -289,53 +289,6 @@ ], "time": "2018-06-11T17:15:25+00:00" }, - { - "name": "braintree/braintree_php", - "version": "3.35.0", - "source": { - "type": "git", - "url": "https://github.com/braintree/braintree_php.git", - "reference": "6c4388199ce379432804a5c18b88585157ef2ed7" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/braintree/braintree_php/zipball/6c4388199ce379432804a5c18b88585157ef2ed7", - "reference": "6c4388199ce379432804a5c18b88585157ef2ed7", - "shasum": "" - }, - "require": { - "ext-curl": "*", - "ext-dom": "*", - "ext-hash": "*", - "ext-openssl": "*", - "ext-xmlwriter": "*", - "php": ">=5.4.0" - }, - "require-dev": { - "phpunit/phpunit": "3.7.*" - }, - "type": "library", - "autoload": { - "psr-0": { - "Braintree": "lib/" - }, - "psr-4": { - "Braintree\\": "lib/Braintree" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Braintree", - "homepage": "https://www.braintreepayments.com" - } - ], - "description": "Braintree PHP Client Library", - "time": "2018-07-26T14:37:38+00:00" - }, { "name": "christian-riesen/base32", "version": "1.3.2", @@ -2319,7 +2272,6 @@ "shasum": "7877828bb63a7cfca5c62c6c6caf6a9c05ab154b" }, "require": { - "braintree/braintree_php": "3.35.0", "composer/composer": "^1.6", "ext-intl": "*", "ext-mbstring": "*", @@ -3202,53 +3154,6 @@ ], "description": "N/A" }, - { - "name": "magento/module-braintree", - "version": "100.3.1", - "dist": { - "type": "zip", - "url": "https://repo.magento.com/archives/magento/module-braintree/magento-module-braintree-100.3.1.0.zip", - "reference": null, - "shasum": "bc99da6e5eef549dc2542cfe914aa7742361e2c6" - }, - "require": { - "braintree/braintree_php": "3.35.0", - "magento/framework": "102.0.*", - "magento/magento-composer-installer": "*", - "magento/module-backend": "101.0.*", - "magento/module-catalog": "103.0.*", - "magento/module-checkout": "100.3.*", - "magento/module-config": "101.1.*", - "magento/module-customer": "102.0.*", - "magento/module-directory": "100.3.*", - "magento/module-instant-purchase": "100.3.*", - "magento/module-payment": "100.3.*", - "magento/module-paypal": "100.3.*", - "magento/module-quote": "101.1.*", - "magento/module-sales": "102.0.*", - "magento/module-ui": "101.1.*", - "magento/module-vault": "101.1.*", - "php": "~7.1.3||~7.2.0" - }, - "suggest": { - "magento/module-checkout-agreements": "100.3.*", - "magento/module-theme": "101.0.*" - }, - "type": "magento2-module", - "autoload": { - "files": [ - "registration.php" - ], - "psr-4": { - "Magento\\Braintree\\": "" - } - }, - "license": [ - "OSL-3.0", - "AFL-3.0" - ], - "description": "N/A" - }, { "name": "magento/module-bundle", "version": "100.3.1", @@ -9545,7 +9450,6 @@ "version": "2.3.1", "require": { "amzn/amazon-pay-and-login-magento-2-module": "3.1.4", - "braintree/braintree_php": "3.35.0", "colinmollenhour/cache-backend-file": "~1.4.1", "colinmollenhour/cache-backend-redis": "1.10.6", "colinmollenhour/credis": "1.10.0", @@ -9595,7 +9499,6 @@ "magento/module-authorization": "100.3.1", "magento/module-backend": "101.0.1", "magento/module-backup": "100.3.1", - "magento/module-braintree": "100.3.1", "magento/module-bundle": "100.3.1", "magento/module-bundle-graph-ql": "100.3.1", "magento/module-bundle-import-export": "100.3.1", diff --git a/dev/tests/integration/testsuite/Magento/Framework/Composer/_files/testSkeleton/composer.lock b/dev/tests/integration/testsuite/Magento/Framework/Composer/_files/testSkeleton/composer.lock index 6c51c6a2072e9..6705104d300b2 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/Composer/_files/testSkeleton/composer.lock +++ b/dev/tests/integration/testsuite/Magento/Framework/Composer/_files/testSkeleton/composer.lock @@ -289,53 +289,6 @@ ], "time": "2018-06-11T17:15:25+00:00" }, - { - "name": "braintree/braintree_php", - "version": "3.35.0", - "source": { - "type": "git", - "url": "https://github.com/braintree/braintree_php.git", - "reference": "6c4388199ce379432804a5c18b88585157ef2ed7" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/braintree/braintree_php/zipball/6c4388199ce379432804a5c18b88585157ef2ed7", - "reference": "6c4388199ce379432804a5c18b88585157ef2ed7", - "shasum": "" - }, - "require": { - "ext-curl": "*", - "ext-dom": "*", - "ext-hash": "*", - "ext-openssl": "*", - "ext-xmlwriter": "*", - "php": ">=5.4.0" - }, - "require-dev": { - "phpunit/phpunit": "3.7.*" - }, - "type": "library", - "autoload": { - "psr-0": { - "Braintree": "lib/" - }, - "psr-4": { - "Braintree\\": "lib/Braintree" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Braintree", - "homepage": "https://www.braintreepayments.com" - } - ], - "description": "Braintree PHP Client Library", - "time": "2018-07-26T14:37:38+00:00" - }, { "name": "christian-riesen/base32", "version": "1.3.2", @@ -2319,7 +2272,6 @@ "shasum": "7877828bb63a7cfca5c62c6c6caf6a9c05ab154b" }, "require": { - "braintree/braintree_php": "3.35.0", "composer/composer": "^1.6", "ext-intl": "*", "ext-mbstring": "*", @@ -3202,53 +3154,6 @@ ], "description": "N/A" }, - { - "name": "magento/module-braintree", - "version": "100.3.1", - "dist": { - "type": "zip", - "url": "https://repo.magento.com/archives/magento/module-braintree/magento-module-braintree-100.3.1.0.zip", - "reference": null, - "shasum": "bc99da6e5eef549dc2542cfe914aa7742361e2c6" - }, - "require": { - "braintree/braintree_php": "3.35.0", - "magento/framework": "102.0.*", - "magento/magento-composer-installer": "*", - "magento/module-backend": "101.0.*", - "magento/module-catalog": "103.0.*", - "magento/module-checkout": "100.3.*", - "magento/module-config": "101.1.*", - "magento/module-customer": "102.0.*", - "magento/module-directory": "100.3.*", - "magento/module-instant-purchase": "100.3.*", - "magento/module-payment": "100.3.*", - "magento/module-paypal": "100.3.*", - "magento/module-quote": "101.1.*", - "magento/module-sales": "102.0.*", - "magento/module-ui": "101.1.*", - "magento/module-vault": "101.1.*", - "php": "~7.1.3||~7.2.0" - }, - "suggest": { - "magento/module-checkout-agreements": "100.3.*", - "magento/module-theme": "101.0.*" - }, - "type": "magento2-module", - "autoload": { - "files": [ - "registration.php" - ], - "psr-4": { - "Magento\\Braintree\\": "" - } - }, - "license": [ - "OSL-3.0", - "AFL-3.0" - ], - "description": "N/A" - }, { "name": "magento/module-bundle", "version": "100.3.1", @@ -9545,7 +9450,6 @@ "version": "2.3.1", "require": { "amzn/amazon-pay-and-login-magento-2-module": "3.1.4", - "braintree/braintree_php": "3.35.0", "colinmollenhour/cache-backend-file": "~1.4.1", "colinmollenhour/cache-backend-redis": "1.10.6", "colinmollenhour/credis": "1.10.0", @@ -9595,7 +9499,6 @@ "magento/module-authorization": "100.3.1", "magento/module-backend": "101.0.1", "magento/module-backup": "100.3.1", - "magento/module-braintree": "100.3.1", "magento/module-bundle": "100.3.1", "magento/module-bundle-graph-ql": "100.3.1", "magento/module-bundle-import-export": "100.3.1", diff --git a/dev/tests/integration/testsuite/Magento/Framework/DB/Adapter/Pdo/MysqlTest.php b/dev/tests/integration/testsuite/Magento/Framework/DB/Adapter/Pdo/MysqlTest.php index ce3141ffc571a..345302a374081 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/DB/Adapter/Pdo/MysqlTest.php +++ b/dev/tests/integration/testsuite/Magento/Framework/DB/Adapter/Pdo/MysqlTest.php @@ -187,7 +187,11 @@ public function testCreateTableColumnWithExpressionAsColumnDefaultValue() //Test default value with expression $this->assertEquals('created_at', $dateColumn['COLUMN_NAME'], 'Incorrect column name'); $this->assertEquals(Table::TYPE_DATETIME, $dateColumn['DATA_TYPE'], 'Incorrect column type'); - $this->assertEquals('CURRENT_TIMESTAMP', $dateColumn['DEFAULT'], 'Incorrect column default expression value'); + $this->assertMatchesRegularExpression( + '/(CURRENT_TIMESTAMP|current_timestamp\(\))/', + $dateColumn['DEFAULT'], + 'Incorrect column default expression value' + ); //Test default value with integer value $this->assertEquals('integer_column', $intColumn['COLUMN_NAME'], 'Incorrect column name'); diff --git a/dev/tests/integration/testsuite/Magento/Framework/View/LayoutTestWithExceptions.php b/dev/tests/integration/testsuite/Magento/Framework/View/LayoutTestWithExceptions.php index 7bb71a3d8b6b3..fdaa2d00db827 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/View/LayoutTestWithExceptions.php +++ b/dev/tests/integration/testsuite/Magento/Framework/View/LayoutTestWithExceptions.php @@ -5,21 +5,31 @@ */ namespace Magento\Framework\View; -use \Magento\Framework\App\State; +use Magento\Framework\App\State; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\View\Layout\Element; +use Magento\TestFramework\Helper\Bootstrap; +use PHPUnit\Framework\TestCase; -class LayoutTestWithExceptions extends \PHPUnit\Framework\TestCase +/** + * Class to test Layout model functionality with exceptions + */ +class LayoutTestWithExceptions extends TestCase { /** - * @var \Magento\Framework\View\Layout + * @var Layout */ protected $layout; - protected function setUp() + /** + * @inheritdoc + */ + protected function setUp(): void { - $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); - $layoutFactory = $objectManager->get(\Magento\Framework\View\LayoutFactory::class); + $objectManager = Bootstrap::getObjectManager(); + $layoutFactory = $objectManager->get(LayoutFactory::class); $this->layout = $layoutFactory->create(); - $layoutElement = new \Magento\Framework\View\Layout\Element( + $layoutElement = new Element( __DIR__ . '/_files/layout_with_exceptions/layout.xml', 0, true @@ -30,21 +40,24 @@ protected function setUp() } /** + * Test to Create structure of elements from the loaded XML configuration with exception */ public function testProcessWithExceptionsDeveloperMode() { - $this->expectException(\Magento\Framework\Exception\LocalizedException::class); + $this->expectException(LocalizedException::class); $this->expectExceptionMessage('Construction problem.'); $this->layout->generateElements(); } /** + * Test to Get all blocks marked for output with exceptions + * * @magentoAppIsolation enabled */ public function testProcessWithExceptions() { - \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\App\State::class) + Bootstrap::getObjectManager()->get(State::class) ->setMode(State::MODE_DEFAULT); $this->layout->generateElements(); diff --git a/dev/tests/integration/testsuite/Magento/GraphQl/Braintree/_files/token.php b/dev/tests/integration/testsuite/Magento/GraphQl/Braintree/_files/token.php deleted file mode 100644 index 8164e6d33e240..0000000000000 --- a/dev/tests/integration/testsuite/Magento/GraphQl/Braintree/_files/token.php +++ /dev/null @@ -1,45 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -use Magento\TestFramework\Helper\Bootstrap; -use Magento\Vault\Model\PaymentToken; -use Magento\Vault\Model\PaymentTokenRepository; - -$objectManager = Bootstrap::getObjectManager(); - -$adapterFactory = $objectManager->get(\Magento\Braintree\Model\Adapter\BraintreeAdapterFactory::class); -$adapter = $adapterFactory->create(); - -$result = $adapter->sale( - [ - 'amount' => '0.01', - 'customer' => [ - 'email' => 'customer@example.com', - 'firstName' => 'John', - 'lastName' => 'Smith' - ], - 'options' => ['storeInVaultOnSuccess' => true], - 'paymentMethodNonce' => 'fake-valid-nonce', - ] -); - -$braintreeToken = $result->transaction->creditCardDetails->token; - -/** @var PaymentToken $token */ -$token = $objectManager->create(PaymentToken::class); - -$token->setGatewayToken($braintreeToken) - ->setPublicHash('braintree_public_hash') - ->setPaymentMethodCode('braintree_vault') - ->setType('card') - ->setExpiresAt(strtotime('+1 year')) - ->setIsVisible(true) - ->setIsActive(true) - ->setCustomerId(1); - -/** @var PaymentTokenRepository $tokenRepository */ -$tokenRepository = $objectManager->create(PaymentTokenRepository::class); -$token = $tokenRepository->save($token); diff --git a/dev/tests/integration/testsuite/Magento/ImportExport/Controller/Adminhtml/Import/ValidateTest.php b/dev/tests/integration/testsuite/Magento/ImportExport/Controller/Adminhtml/Import/ValidateTest.php index 3f8c2852203a3..8675e2005535b 100644 --- a/dev/tests/integration/testsuite/Magento/ImportExport/Controller/Adminhtml/Import/ValidateTest.php +++ b/dev/tests/integration/testsuite/Magento/ImportExport/Controller/Adminhtml/Import/ValidateTest.php @@ -72,7 +72,7 @@ public function testValidationReturn(string $fileName, string $mimeType, string $this->assertStringContainsString($message, $this->getResponse()->getBody()); $this->assertStringNotContainsString('The file was not uploaded.', $this->getResponse()->getBody()); - $this->assertNotRegExp( + $this->assertDoesNotMatchRegularExpression( '/clear[^\[]*\[[^\]]*(import_file|import_image_archive)[^\]]*\]/m', $this->getResponse()->getBody() ); diff --git a/dev/tests/integration/testsuite/Magento/Review/_files/different_reviews.php b/dev/tests/integration/testsuite/Magento/Review/_files/different_reviews.php index ad1c0707e7896..51b642a11c7d9 100644 --- a/dev/tests/integration/testsuite/Magento/Review/_files/different_reviews.php +++ b/dev/tests/integration/testsuite/Magento/Review/_files/different_reviews.php @@ -29,6 +29,12 @@ ] )->save(); +/* + * Added a sleep because in a few tests the sql query orders by created at. Without the sleep the reviews + * have sometimes the same created at timestamp, that causes this tests randomly to fail. + */ +sleep(1); + $review = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Review\Model\Review::class, ['data' => ['nickname' => 'Nickname', 'title' => '2 filter first review', 'detail' => 'Review text']] @@ -51,6 +57,12 @@ ] )->save(); +/* + * Added a sleep because in a few tests the sql query orders by created at. Without the sleep the reviews + * have sometimes the same created at timestamp, that causes this tests randomly to fail. + */ +sleep(1); + $review = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( \Magento\Review\Model\Review::class, ['data' => ['nickname' => 'Nickname', 'title' => '1 filter second review', 'detail' => 'Review text']] diff --git a/dev/tests/integration/testsuite/Magento/SalesRule/_files/rules_group_any_categories_price_address.php b/dev/tests/integration/testsuite/Magento/SalesRule/_files/rules_group_any_categories_price_address.php index 1c18fb83d7c82..0b519fee6b46d 100644 --- a/dev/tests/integration/testsuite/Magento/SalesRule/_files/rules_group_any_categories_price_address.php +++ b/dev/tests/integration/testsuite/Magento/SalesRule/_files/rules_group_any_categories_price_address.php @@ -4,28 +4,38 @@ * See COPYING.txt for license details. */ -/** @var \Magento\SalesRule\Model\Rule $rule */ -$salesRule = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\SalesRule\Model\Rule::class); +use Magento\Customer\Model\GroupManagement; +use Magento\Framework\Registry; +use Magento\SalesRule\Model\Rule; +use Magento\SalesRule\Model\Rule\Condition\Address; +use Magento\SalesRule\Model\Rule\Condition\Combine; +use Magento\SalesRule\Model\Rule\Condition\Product; +use Magento\SalesRule\Model\Rule\Condition\Product\Found; +use Magento\Store\Model\StoreManagerInterface; +use Magento\TestFramework\Helper\Bootstrap; + +/** @var Rule $rule */ +$salesRule = Bootstrap::getObjectManager()->create(Rule::class); $salesRule->setData( [ 'name' => '50% Off on Large Orders', 'is_active' => 1, - 'customer_group_ids' => [\Magento\Customer\Model\GroupManagement::NOT_LOGGED_IN_ID], - 'coupon_type' => \Magento\SalesRule\Model\Rule::COUPON_TYPE_NO_COUPON, + 'customer_group_ids' => [GroupManagement::NOT_LOGGED_IN_ID], + 'coupon_type' => Rule::COUPON_TYPE_NO_COUPON, 'simple_action' => 'by_percent', 'discount_amount' => 50, 'discount_step' => 0, 'stop_rules_processing' => 1, 'website_ids' => [ - \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get( - \Magento\Store\Model\StoreManagerInterface::class + Bootstrap::getObjectManager()->get( + StoreManagerInterface::class )->getWebsite()->getId() ] ] ); $salesRule->getConditions()->loadArray([ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Combine::class, + 'type' => Combine::class, 'attribute' => null, 'operator' => null, 'value' => '1', @@ -34,7 +44,7 @@ 'conditions' => [ [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Product\Found::class, + 'type' => Found::class, 'attribute' => null, 'operator' => null, 'value' => '1', @@ -43,7 +53,7 @@ 'conditions' => [ [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Product::class, + 'type' => Product::class, 'attribute' => 'category_ids', 'operator' => '==', 'value' => '2', @@ -52,37 +62,36 @@ ], ], [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Address::class, + 'type' => Address::class, 'attribute' => 'payment_method', 'operator' => '==', - 'value' => 'braintree_paypal' - ], - [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Address::class, + 'value' => 'payflowpro' + ], [ + 'type' => Address::class, 'attribute' => 'shipping_method', 'operator' => '==', 'value' => 'fedex_FEDEX_2_DAY' ], [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Address::class, + 'type' => Address::class, 'attribute' => 'postcode', 'operator' => '==', 'value' => '78000' ], [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Address::class, + 'type' => Address::class, 'attribute' => 'region', 'operator' => '==', 'value' => 'HD' ], [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Address::class, + 'type' => Address::class, 'attribute' => 'region_id', 'operator' => '==', 'value' => '56' ], [ - 'type' => \Magento\SalesRule\Model\Rule\Condition\Address::class, + 'type' => Address::class, 'attribute' => 'country_id', 'operator' => '==', 'value' => 'US' @@ -93,7 +102,7 @@ $salesRule->save(); /** @var Magento\Framework\Registry $registry */ -$registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\Registry::class); +$registry = Bootstrap::getObjectManager()->get(Registry::class); $registry->unregister('_fixture/Magento_SalesRule_Group_Multiple_Categories'); $registry->register('_fixture/Magento_SalesRule_Group_Multiple_Categories', $salesRule); diff --git a/dev/tests/integration/testsuite/Magento/Setup/Controller/UrlCheckTest.php b/dev/tests/integration/testsuite/Magento/Setup/Controller/UrlCheckTest.php deleted file mode 100644 index 0eadfa156a2b5..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Setup/Controller/UrlCheckTest.php +++ /dev/null @@ -1,98 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Magento\TestFramework\Helper\Bootstrap; -use Laminas\Stdlib\RequestInterface as Request; -use Laminas\View\Model\JsonModel; - -class UrlCheckTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var UrlCheck - */ - private $controller; - - protected function setUp(): void - { - $this->controller = Bootstrap::getObjectManager()->create(UrlCheck::class); - } - - /** - * @param array $requestContent - * @param bool $successUrl - * @param bool $successSecureUrl - * @return void - * @dataProvider indexActionDataProvider - */ - public function testIndexAction($requestContent, $successUrl, $successSecureUrl) - { - $requestMock = $this->getMockBuilder(Request::class) - ->getMockForAbstractClass(); - $requestMock->expects($this->once()) - ->method('getContent') - ->willReturn(json_encode($requestContent)); - - $requestProperty = new \ReflectionProperty(get_class($this->controller), 'request'); - $requestProperty->setAccessible(true); - $requestProperty->setValue($this->controller, $requestMock); - - $resultModel = new JsonModel(['successUrl' => $successUrl, 'successSecureUrl' => $successSecureUrl]); - - $this->assertEquals($resultModel, $this->controller->indexAction()); - } - - /** - * @return array - */ - public function indexActionDataProvider() - { - return [ - [ - 'requestContent' => [ - 'address' => [ - 'actual_base_url' => 'http://example.com/' - ], - 'https' => [ - 'text' => 'https://example.com/', - 'admin' => true, - 'front' => false - ], - ], - 'successUrl' => true, - 'successSecureUrl' => true - ], - [ - 'requestContent' => [ - 'address' => [ - 'actual_base_url' => 'http://example.com/folder/' - ], - 'https' => [ - 'text' => 'https://example.com/folder_name/', - 'admin' => false, - 'front' => true - ], - ], - 'successUrl' => true, - 'successSecureUrl' => true - ], - [ - 'requestContent' => [ - 'address' => [ - 'actual_base_url' => 'ftp://example.com/' - ], - 'https' => [ - 'text' => 'https://example.com_test/', - 'admin' => true, - 'front' => true - ], - ], - 'successUrl' => false, - 'successSecureUrl' => false - ], - ]; - } -} diff --git a/dev/tests/integration/testsuite/Magento/Setup/Model/Cron/MultipleStreamOutputTest.php b/dev/tests/integration/testsuite/Magento/Setup/Model/Cron/MultipleStreamOutputTest.php deleted file mode 100644 index a88f8704e9d09..0000000000000 --- a/dev/tests/integration/testsuite/Magento/Setup/Model/Cron/MultipleStreamOutputTest.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Cron; - -class MultipleStreamOutputTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var MultipleStreamOutput - */ - private $multipleStreamOutput; - - protected function setUp(): void - { - $this->multipleStreamOutput = new MultipleStreamOutput( - [ - fopen(__DIR__ . '/_files/a.txt', 'a+'), - fopen(__DIR__ . '/_files/b.txt', 'a+') - ] - ); - } - - protected function tearDown(): void - { - file_put_contents(__DIR__ . '/_files/a.txt', ''); - file_put_contents(__DIR__ . '/_files/b.txt', ''); - } - - /** - */ - public function testCreateException() - { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('The StreamOutput class needs a stream as its first argument'); - - $this->multipleStreamOutput = new MultipleStreamOutput(['a', 'b']); - } - - public function testWriteln() - { - $this->multipleStreamOutput->writeln('Hello world'); - $this->assertEquals('Hello world' . PHP_EOL, file_get_contents(__DIR__ . '/_files/a.txt')); - $this->assertEquals('Hello world' . PHP_EOL, file_get_contents(__DIR__ . '/_files/b.txt')); - } - - public function testWrite() - { - $this->multipleStreamOutput->write('Hello world'); - $this->assertEquals('Hello world', file_get_contents(__DIR__ . '/_files/a.txt')); - $this->assertEquals('Hello world', file_get_contents(__DIR__ . '/_files/b.txt')); - } -} diff --git a/dev/tests/integration/testsuite/Magento/Setup/Model/Cron/_files/a.txt b/dev/tests/integration/testsuite/Magento/Setup/Model/Cron/_files/a.txt deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/dev/tests/integration/testsuite/Magento/Setup/Model/Cron/_files/b.txt b/dev/tests/integration/testsuite/Magento/Setup/Model/Cron/_files/b.txt deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/dev/tests/integration/testsuite/Magento/Tax/_files/scenarios/including_tax_apply_tax_after_discount.php b/dev/tests/integration/testsuite/Magento/Tax/_files/scenarios/including_tax_apply_tax_after_discount.php index e0cb82e50cbd4..028512a9eb142 100644 --- a/dev/tests/integration/testsuite/Magento/Tax/_files/scenarios/including_tax_apply_tax_after_discount.php +++ b/dev/tests/integration/testsuite/Magento/Tax/_files/scenarios/including_tax_apply_tax_after_discount.php @@ -73,14 +73,14 @@ 'base_shipping_incl_tax' => 5, 'shipping_tax_amount' => 0.25, 'base_shipping_tax_amount' => 0.25, - 'discount_amount' => -15.455, - 'base_discount_amount' => -15.455, + 'discount_amount' => -15.46, + 'base_discount_amount' => -15.46, 'discount_tax_compensation_amount' => 1.2, 'base_discount_tax_compensation_amount' => 1.2, 'shipping_discount_tax_compensation_amount' => 0.2, 'base_shipping_discount_tax_compensation_amount' => 0.2, - 'grand_total' => 18.545, - 'base_grand_total' => 18.545, + 'grand_total' => 18.54, + 'base_grand_total' => 18.54, 'applied_taxes' => [ SetupUtil::TAX_RATE_TX => [ 'percent' => 10, diff --git a/dev/tests/integration/testsuite/Magento/Test/Integrity/Modular/_files/skip_blocks_ce.php b/dev/tests/integration/testsuite/Magento/Test/Integrity/Modular/_files/skip_blocks_ce.php index 7a8f04d0160ff..4d53f168bc92e 100644 --- a/dev/tests/integration/testsuite/Magento/Test/Integrity/Modular/_files/skip_blocks_ce.php +++ b/dev/tests/integration/testsuite/Magento/Test/Integrity/Modular/_files/skip_blocks_ce.php @@ -15,8 +15,6 @@ \Magento\Config\Block\System\Config\Form::class, \Magento\Config\Block\System\Config\Tabs::class, \Magento\Review\Block\Form::class, - \Magento\Braintree\Block\Form::class, - \Magento\Braintree\Block\Payment::class, // Fails because of dependence on registry \Magento\Reminder\Block\Adminhtml\Reminder\Edit\Tab\Customers::class, \Magento\LayeredNavigation\Block\Navigation::class, diff --git a/dev/tests/integration/testsuite/Magento/Translation/Controller/AjaxTest.php b/dev/tests/integration/testsuite/Magento/Translation/Controller/AjaxTest.php index 5b3608fe8daf3..8c434e7e10cf7 100644 --- a/dev/tests/integration/testsuite/Magento/Translation/Controller/AjaxTest.php +++ b/dev/tests/integration/testsuite/Magento/Translation/Controller/AjaxTest.php @@ -27,7 +27,8 @@ public function testIndexAction(array $postData, string $expected): void { $this->getRequest()->setPostValue('translate', $postData); $this->dispatch('translation/ajax/index'); - $this->assertEquals($expected, $this->getResponse()->getBody()); + $result = $this->getResponse()->getBody(); + $this->assertEquals($expected, $result); } /** diff --git a/dev/tests/integration/testsuite/Magento/Ups/Model/CarrierTest.php b/dev/tests/integration/testsuite/Magento/Ups/Model/CarrierTest.php index e345e279a512f..4909a14f6f7d1 100644 --- a/dev/tests/integration/testsuite/Magento/Ups/Model/CarrierTest.php +++ b/dev/tests/integration/testsuite/Magento/Ups/Model/CarrierTest.php @@ -20,6 +20,8 @@ /** * Integration tests for Carrier model class + * + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class CarrierTest extends TestCase { @@ -208,6 +210,7 @@ public function collectRatesDataProvider() public function testRequestToShipment(): void { //phpcs:disable Magento2.Functions.DiscouragedFunction + $expectedShipmentRequest = file_get_contents(__DIR__ .'/../_files/ShipmentConfirmRequest.xml'); $shipmentResponse = file_get_contents(__DIR__ .'/../_files/ShipmentConfirmResponse.xml'); $acceptResponse = file_get_contents(__DIR__ .'/../_files/ShipmentAcceptResponse.xml'); //phpcs:enable Magento2.Functions.DiscouragedFunction @@ -217,6 +220,8 @@ public function testRequestToShipment(): void new Response(200, [], $acceptResponse) ] ); + $this->httpClient->clearRequests(); + $request = new Request( [ 'packages' => [ @@ -237,11 +242,37 @@ public function testRequestToShipment(): void ], ], ], + 'package2' => [ + 'params' => [ + 'width' => '4', + 'length' => '4', + 'height' => '4', + 'dimension_units' => 'INCH', + 'weight_units' => 'POUND', + 'weight' => '0.55', + 'customs_value' => '20.00', + 'container' => 'Large Express Box', + ], + 'items' => [ + 'item2' => [ + 'name' => 'item2_name', + ], + ], + ], ] ] ); $result = $this->carrier->requestToShipment($request); + + $requests = $this->httpClient->getRequests(); + $this->assertNotEmpty($requests); + $shipmentRequest = $this->extractShipmentRequest($requests[0]->getBody()); + $this->assertEquals( + $this->formatXml($expectedShipmentRequest), + $this->formatXml($shipmentRequest) + ); + $this->assertEmpty($result->getErrors()); $this->assertNotEmpty($result->getInfo()); $this->assertEquals( @@ -249,5 +280,44 @@ public function testRequestToShipment(): void $result->getInfo()[0]['tracking_number'], 'Tracking Number must match.' ); + $this->assertEquals( + '2V467W886398839541', + $result->getInfo()[1]['tracking_number'], + 'Tracking Number must match.' + ); + $this->httpClient->clearRequests(); + } + + /** + * Extracts shipment request. + * + * @param string $requestBody + * @return string + */ + private function extractShipmentRequest(string $requestBody): string + { + $resultXml = ''; + $pattern = '%(<\?xml version="1.0"\?>\n<ShipmentConfirmRequest)(.*)$%im'; + if (preg_match($pattern, $requestBody, $result)) { + $resultXml = array_shift($result); + } + + return $resultXml; + } + + /** + * Format XML string. + * + * @param string $xmlString + * @return string + */ + private function formatXml(string $xmlString): string + { + $xmlDocument = new \DOMDocument('1.0'); + $xmlDocument->preserveWhiteSpace = false; + $xmlDocument->formatOutput = true; + $xmlDocument->loadXML($xmlString); + + return $xmlDocument->saveXML(); } } diff --git a/dev/tests/integration/testsuite/Magento/Ups/_files/ShipmentAcceptResponse.xml b/dev/tests/integration/testsuite/Magento/Ups/_files/ShipmentAcceptResponse.xml index c15986f6502a5..03b6e1da659db 100644 --- a/dev/tests/integration/testsuite/Magento/Ups/_files/ShipmentAcceptResponse.xml +++ b/dev/tests/integration/testsuite/Magento/Ups/_files/ShipmentAcceptResponse.xml @@ -55,5 +55,19 @@ <HTMLImage>PCFET0NUWVBFI</HTMLImage> </LabelImage> </PackageResults> + <PackageResults> + <TrackingNumber>2V467W886398839541</TrackingNumber> + <ServiceOptionsCharges> + <CurrencyCode>USD</CurrencyCode> + <MonetaryValue>0.00</MonetaryValue> + </ServiceOptionsCharges> + <LabelImage> + <LabelImageFormat> + <Code>GIF</Code> + </LabelImageFormat> + <GraphicImage>R0lGODdheAUgA</GraphicImage> + <HTMLImage>PCFET0NUWVBFI</HTMLImage> + </LabelImage> + </PackageResults> </ShipmentResults> </ShipmentAcceptResponse> diff --git a/dev/tests/integration/testsuite/Magento/Ups/_files/ShipmentConfirmRequest.xml b/dev/tests/integration/testsuite/Magento/Ups/_files/ShipmentConfirmRequest.xml new file mode 100644 index 0000000000000..63463c087726c --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Ups/_files/ShipmentConfirmRequest.xml @@ -0,0 +1,94 @@ +<?xml version="1.0"?> +<ShipmentConfirmRequest xml:lang="en-US"> +<Request> + <RequestAction>ShipConfirm</RequestAction> + <RequestOption>nonvalidate</RequestOption> +</Request> +<Shipment> + <Description>item_name item2_name</Description> + <Shipper> + <Name /> + <AttentionName /> + <ShipperNumber>12345</ShipperNumber> + <PhoneNumber /> + <Address> + <AddressLine1 /> + <AddressLine2 /> + <City /> + <CountryCode /> + <PostalCode /> + </Address> + </Shipper> + <ShipTo> + <AttentionName /> + <CompanyName>N/A</CompanyName> + <PhoneNumber /> + <Address> + <AddressLine1 /> + <AddressLine2 /> + <City /> + <CountryCode /> + <PostalCode /> + <ResidentialAddress /> + </Address> + </ShipTo> + <Service> + <Code /> + </Service> + <Package> + <Description>item_name</Description> + <PackagingType> + <Code>Small Express Box</Code> + </PackagingType> + <PackageWeight> + <Weight>0.454000000001</Weight> + <UnitOfMeasurement> + <Code>LBS</Code> + </UnitOfMeasurement> + </PackageWeight> + <Dimensions> + <UnitOfMeasurement> + <Code>IN</Code> + </UnitOfMeasurement> + <Length>3</Length> + <Width>3</Width> + <Height>3</Height> + </Dimensions> + </Package> + <Package> + <Description>item2_name</Description> + <PackagingType> + <Code>Large Express Box</Code> + </PackagingType> + <PackageWeight> + <Weight>0.55</Weight> + <UnitOfMeasurement> + <Code>LBS</Code> + </UnitOfMeasurement> + </PackageWeight> + <Dimensions> + <UnitOfMeasurement> + <Code>IN</Code> + </UnitOfMeasurement> + <Length>4</Length> + <Width>4</Width> + <Height>4</Height> + </Dimensions> + </Package> + <PaymentInformation> + <Prepaid> + <BillShipper> + <AccountNumber>12345</AccountNumber> + </BillShipper> + </Prepaid> + </PaymentInformation> +</Shipment> +<LabelSpecification> + <LabelPrintMethod> + <Code>GIF</Code> + </LabelPrintMethod> + <LabelImageFormat> + <Code>GIF</Code> + </LabelImageFormat> +</LabelSpecification> +</ShipmentConfirmRequest> diff --git a/dev/tests/integration/testsuite/Magento/Vault/Model/ResourceModel/PaymentTokenTest.php b/dev/tests/integration/testsuite/Magento/Vault/Model/ResourceModel/PaymentTokenTest.php index 803158b638637..86f2275c85051 100644 --- a/dev/tests/integration/testsuite/Magento/Vault/Model/ResourceModel/PaymentTokenTest.php +++ b/dev/tests/integration/testsuite/Magento/Vault/Model/ResourceModel/PaymentTokenTest.php @@ -5,7 +5,6 @@ */ namespace Magento\Vault\Model\ResourceModel; -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider as PayPalConfigProvider; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\ObjectManagerInterface; @@ -13,12 +12,14 @@ use Magento\TestFramework\Helper\Bootstrap; use Magento\Vault\Model\PaymentTokenManagement; use Magento\Vault\Setup\InstallSchema; +use PHPUnit\Framework\TestCase; -class PaymentTokenTest extends \PHPUnit\Framework\TestCase +class PaymentTokenTest extends TestCase { const CUSTOMER_ID = 1; const TOKEN = 'mx29vk'; const ORDER_INCREMENT_ID = '100000001'; + const PAYFLOWPRO = 'payflowpro'; /** * @var ObjectManagerInterface @@ -63,13 +64,13 @@ protected function setUp(): void /** * @magentoDataFixture Magento/Sales/_files/order.php - * @magentoDataFixture Magento/Braintree/_files/paypal_vault_token.php + * @magentoDataFixture Magento/Vault/_files/payflowpro_vault_token.php */ public function testAddLinkToOrderPaymentExists() { $this->order->loadByIncrementId(self::ORDER_INCREMENT_ID); $paymentToken = $this->paymentTokenManagement - ->getByGatewayToken(self::TOKEN, PayPalConfigProvider::PAYPAL_CODE, self::CUSTOMER_ID); + ->getByGatewayToken(self::TOKEN, self::PAYFLOWPRO, self::CUSTOMER_ID); $this->connection->insert( $this->resource->getTableName('vault_payment_token_order_payment_link'), @@ -89,13 +90,13 @@ public function testAddLinkToOrderPaymentExists() /** * @magentoDataFixture Magento/Sales/_files/order.php - * @magentoDataFixture Magento/Braintree/_files/paypal_vault_token.php + * @magentoDataFixture Magento/Vault/_files/payflowpro_vault_token.php */ public function testAddLinkToOrderPaymentCreate() { $this->order->loadByIncrementId(self::ORDER_INCREMENT_ID); $paymentToken = $this->paymentTokenManagement - ->getByGatewayToken(self::TOKEN, PayPalConfigProvider::PAYPAL_CODE, self::CUSTOMER_ID); + ->getByGatewayToken(self::TOKEN, self::PAYFLOWPRO, self::CUSTOMER_ID); $select = $this->connection->select() ->from($this->resource->getTableName('vault_payment_token_order_payment_link')) diff --git a/dev/tests/integration/testsuite/Magento/Braintree/_files/paypal_vault_token.php b/dev/tests/integration/testsuite/Magento/Vault/_files/payflowpro_vault_token.php similarity index 85% rename from dev/tests/integration/testsuite/Magento/Braintree/_files/paypal_vault_token.php rename to dev/tests/integration/testsuite/Magento/Vault/_files/payflowpro_vault_token.php index 612243b999d31..ea36798c1d940 100644 --- a/dev/tests/integration/testsuite/Magento/Braintree/_files/paypal_vault_token.php +++ b/dev/tests/integration/testsuite/Magento/Vault/_files/payflowpro_vault_token.php @@ -4,7 +4,6 @@ * See COPYING.txt for license details. */ -use Magento\Braintree\Model\Ui\PayPal\ConfigProvider; use Magento\Config\Model\Config; use Magento\Framework\Encryption\EncryptorInterface; use Magento\TestFramework\Helper\Bootstrap; @@ -22,9 +21,9 @@ $customer = $customerRegistry->retrieve(1); /** @var Config $config */ $config = $objectManager->get(Config::class); -$config->setDataByPath('payment/' . ConfigProvider::PAYPAL_CODE . '/active', 1); +$config->setDataByPath('payment/payflowpro/active', 1); $config->save(); -$config->setDataByPath('payment/' . ConfigProvider::PAYPAL_VAULT_CODE . '/active', 1); +$config->setDataByPath('payment/payflowpro_cc_vault/active', 1); $config->save(); /** @var EncryptorInterface $encryptor */ @@ -34,7 +33,7 @@ $paymentToken = $objectManager->create(PaymentToken::class); $paymentToken ->setCustomerId($customer->getId()) - ->setPaymentMethodCode(ConfigProvider::PAYPAL_CODE) + ->setPaymentMethodCode('payflowpro') ->setType(AccountPaymentTokenFactory::TOKEN_TYPE_ACCOUNT) ->setGatewayToken('mx29vk') ->setPublicHash($encryptor->hash($customer->getId())) diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/column_modification.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/column_modification.php index f2a34c338edc2..8ca84c1638dc0 100644 --- a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/column_modification.php +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/column_modification.php @@ -5,13 +5,13 @@ */ return [ 'auto_increment_test' => 'CREATE TABLE `auto_increment_test` ( - `int_auto_increment_with_nullable` int(15) unsigned DEFAULT NULL, - `int_disabled_auto_increment` smallint(12) unsigned DEFAULT \'0\', + `int_auto_increment_with_nullable` int(10) unsigned DEFAULT NULL, + `int_disabled_auto_increment` smallint(5) unsigned DEFAULT \'0\', UNIQUE KEY `AUTO_INCREMENT_TEST_INT_AUTO_INCREMENT_WITH_NULLABLE` (`int_auto_increment_with_nullable`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8', 'reference_table' => 'CREATE TABLE `reference_table` ( `tinyint_ref` tinyint(7) NOT NULL AUTO_INCREMENT, - `tinyint_without_padding` tinyint(2) NOT NULL, + `tinyint_without_padding` tinyint(4) NOT NULL, `bigint_without_padding` bigint(20) NOT NULL DEFAULT \'0\', `smallint_without_padding` smallint(5) NOT NULL DEFAULT \'0\', `integer_without_padding` int(11) NOT NULL DEFAULT \'0\', @@ -42,7 +42,7 @@ `boolean` tinyint(1) DEFAULT \'1\', UNIQUE KEY `TEST_TABLE_SMALLINT_BIGINT` (`smallint`,`bigint`), KEY `TEST_TABLE_TINYINT_BIGINT` (`tinyint`,`bigint`), - CONSTRAINT `TEST_TABLE_TINYINT_REFERENCE_TABLE_TINYINT_REF` FOREIGN KEY (`tinyint`) + CONSTRAINT `TEST_TABLE_TINYINT_REFERENCE_TABLE_TINYINT_REF` FOREIGN KEY (`tinyint`) REFERENCES `reference_table` (`tinyint_ref`) ON DELETE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8', ]; diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/column_removal.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/column_removal.php index 0091b89845a73..8fcdf5db7d43f 100644 --- a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/column_removal.php +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/column_removal.php @@ -5,12 +5,12 @@ */ return [ 'auto_increment_test' => 'CREATE TABLE `auto_increment_test` ( - `int_auto_increment_with_nullable` int(12) unsigned NOT NULL AUTO_INCREMENT, + `int_auto_increment_with_nullable` int(10) unsigned NOT NULL AUTO_INCREMENT, UNIQUE KEY `AUTO_INCREMENT_TEST_INT_AUTO_INCREMENT_WITH_NULLABLE` (`int_auto_increment_with_nullable`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8', 'reference_table' => 'CREATE TABLE `reference_table` ( `tinyint_ref` tinyint(7) NOT NULL AUTO_INCREMENT, - `tinyint_without_padding` tinyint(2) NOT NULL DEFAULT \'0\', + `tinyint_without_padding` tinyint(4) NOT NULL DEFAULT \'0\', `bigint_without_padding` bigint(20) NOT NULL DEFAULT \'0\', `integer_without_padding` int(11) NOT NULL DEFAULT \'0\', `smallint_with_big_padding` smallint(254) NOT NULL DEFAULT \'0\', @@ -39,7 +39,7 @@ `varbinary_rename` varbinary(255) DEFAULT \'10101\', UNIQUE KEY `TEST_TABLE_SMALLINT_BIGINT` (`smallint`,`bigint`), KEY `TEST_TABLE_TINYINT_BIGINT` (`tinyint`,`bigint`), - CONSTRAINT `TEST_TABLE_TINYINT_REFERENCE_TABLE_TINYINT_REF` FOREIGN KEY (`tinyint`) + CONSTRAINT `TEST_TABLE_TINYINT_REFERENCE_TABLE_TINYINT_REF` FOREIGN KEY (`tinyint`) REFERENCES `reference_table` (`tinyint_ref`) ON DELETE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8', ]; diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/constraint_modification.mariadb10.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/constraint_modification.mariadb10.php new file mode 100644 index 0000000000000..f7a4b7caef6a8 --- /dev/null +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/constraint_modification.mariadb10.php @@ -0,0 +1,57 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +// @codingStandardsIgnoreFile +return [ + 'auto_increment_test' => 'CREATE TABLE `auto_increment_test` ( + `int_auto_increment_with_nullable` int(10) unsigned NOT NULL AUTO_INCREMENT, + `int_disabled_auto_increment` smallint(5) unsigned DEFAULT 0, + UNIQUE KEY `AUTO_INCREMENT_TEST_INT_AUTO_INCREMENT_WITH_NULLABLE` (`int_auto_increment_with_nullable`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8', + 'reference_table' => 'CREATE TABLE `reference_table` ( + `tinyint_ref` tinyint(4) NOT NULL AUTO_INCREMENT, + `tinyint_without_padding` tinyint(4) NOT NULL DEFAULT 0, + `bigint_without_padding` bigint(20) NOT NULL DEFAULT 0, + `smallint_without_padding` smallint(6) NOT NULL DEFAULT 0, + `integer_without_padding` int(11) NOT NULL DEFAULT 0, + `smallint_with_big_padding` smallint(6) NOT NULL DEFAULT 0, + `smallint_without_default` smallint(6) DEFAULT NULL, + `int_without_unsigned` int(11) DEFAULT NULL, + `int_unsigned` int(10) unsigned DEFAULT NULL, + `bigint_default_nullable` bigint(20) unsigned DEFAULT 1, + `bigint_not_default_not_nullable` bigint(20) unsigned NOT NULL, + `smallint_ref` smallint(6) NOT NULL DEFAULT 0, + PRIMARY KEY (`tinyint_ref`,`smallint_ref`), + UNIQUE KEY `REFERENCE_TABLE_SMALLINT_REF` (`smallint_ref`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8', + 'test_table' => 'CREATE TABLE `test_table` ( + `smallint` smallint(6) DEFAULT NULL, + `tinyint` tinyint(4) DEFAULT NULL, + `bigint` bigint(20) DEFAULT 0, + `float` float(12,10) DEFAULT 0.0000000000, + `double` double(245,10) DEFAULT 11111111.1111110000, + `decimal` decimal(15,4) DEFAULT 0.0000, + `date` date DEFAULT NULL, + `timestamp` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), + `datetime` datetime DEFAULT \'0000-00-00 00:00:00\', + `longtext` longtext DEFAULT NULL, + `mediumtext` mediumtext DEFAULT NULL, + `varchar` varchar(254) DEFAULT NULL, + `char` char(255) DEFAULT NULL, + `mediumblob` mediumblob DEFAULT NULL, + `blob` blob DEFAULT NULL, + `boolean` tinyint(1) DEFAULT NULL, + `integer_main` int(10) unsigned DEFAULT NULL, + `smallint_main` smallint(6) NOT NULL DEFAULT 0, + UNIQUE KEY `TEST_TABLE_SMALLINT_FLOAT` (`smallint`,`float`), + UNIQUE KEY `TEST_TABLE_DOUBLE` (`double`), + KEY `TEST_TABLE_TINYINT_BIGINT` (`tinyint`,`bigint`), + KEY `TEST_TABLE_SMALLINT_MAIN_REFERENCE_TABLE_SMALLINT_REF` (`smallint_main`), + KEY `FK_FB77604C299EB8612D01E4AF8D9931F2` (`integer_main`), + CONSTRAINT `FK_FB77604C299EB8612D01E4AF8D9931F2` FOREIGN KEY (`integer_main`) REFERENCES `auto_increment_test` (`int_auto_increment_with_nullable`) ON DELETE CASCADE, + CONSTRAINT `TEST_TABLE_SMALLINT_MAIN_REFERENCE_TABLE_SMALLINT_REF` FOREIGN KEY (`smallint_main`) REFERENCES `reference_table` (`smallint_ref`) ON DELETE CASCADE, + CONSTRAINT `TEST_TABLE_TINYINT_REFERENCE_TABLE_TINYINT_REF` FOREIGN KEY (`tinyint`) REFERENCES `reference_table` (`tinyint_ref`) ON DELETE SET NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8', +]; diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/constraint_modification.mysql8.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/constraint_modification.mysql8.php new file mode 100644 index 0000000000000..6f0ed86f942bc --- /dev/null +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/constraint_modification.mysql8.php @@ -0,0 +1,57 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +// @codingStandardsIgnoreFile +return [ + 'auto_increment_test' => 'CREATE TABLE `auto_increment_test` ( + `int_auto_increment_with_nullable` int unsigned NOT NULL AUTO_INCREMENT, + `int_disabled_auto_increment` smallint unsigned DEFAULT \'0\', + UNIQUE KEY `AUTO_INCREMENT_TEST_INT_AUTO_INCREMENT_WITH_NULLABLE` (`int_auto_increment_with_nullable`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8', + 'reference_table' => 'CREATE TABLE `reference_table` ( + `tinyint_ref` tinyint NOT NULL AUTO_INCREMENT, + `tinyint_without_padding` tinyint NOT NULL DEFAULT \'0\', + `bigint_without_padding` bigint NOT NULL DEFAULT \'0\', + `smallint_without_padding` smallint NOT NULL DEFAULT \'0\', + `integer_without_padding` int NOT NULL DEFAULT \'0\', + `smallint_with_big_padding` smallint NOT NULL DEFAULT \'0\', + `smallint_without_default` smallint DEFAULT NULL, + `int_without_unsigned` int DEFAULT NULL, + `int_unsigned` int unsigned DEFAULT NULL, + `bigint_default_nullable` bigint unsigned DEFAULT \'1\', + `bigint_not_default_not_nullable` bigint unsigned NOT NULL, + `smallint_ref` smallint NOT NULL DEFAULT \'0\', + PRIMARY KEY (`tinyint_ref`,`smallint_ref`), + UNIQUE KEY `REFERENCE_TABLE_SMALLINT_REF` (`smallint_ref`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8', + 'test_table' => 'CREATE TABLE `test_table` ( + `smallint` smallint DEFAULT NULL, + `tinyint` tinyint DEFAULT NULL, + `bigint` bigint DEFAULT \'0\', + `float` float(12,10) DEFAULT \'0.0000000000\', + `double` double(245,10) DEFAULT \'11111111.1111110000\', + `decimal` decimal(15,4) DEFAULT \'0.0000\', + `date` date DEFAULT NULL, + `timestamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + `datetime` datetime DEFAULT \'0000-00-00 00:00:00\', + `longtext` longtext, + `mediumtext` mediumtext, + `varchar` varchar(254) DEFAULT NULL, + `char` char(255) DEFAULT NULL, + `mediumblob` mediumblob, + `blob` blob, + `boolean` tinyint(1) DEFAULT NULL, + `integer_main` int unsigned DEFAULT NULL, + `smallint_main` smallint NOT NULL DEFAULT \'0\', + UNIQUE KEY `TEST_TABLE_SMALLINT_FLOAT` (`smallint`,`float`), + UNIQUE KEY `TEST_TABLE_DOUBLE` (`double`), + KEY `TEST_TABLE_TINYINT_BIGINT` (`tinyint`,`bigint`), + KEY `TEST_TABLE_SMALLINT_MAIN_REFERENCE_TABLE_SMALLINT_REF` (`smallint_main`), + KEY `FK_FB77604C299EB8612D01E4AF8D9931F2` (`integer_main`), + CONSTRAINT `FK_FB77604C299EB8612D01E4AF8D9931F2` FOREIGN KEY (`integer_main`) REFERENCES `auto_increment_test` (`int_auto_increment_with_nullable`) ON DELETE CASCADE, + CONSTRAINT `TEST_TABLE_SMALLINT_MAIN_REFERENCE_TABLE_SMALLINT_REF` FOREIGN KEY (`smallint_main`) REFERENCES `reference_table` (`smallint_ref`) ON DELETE CASCADE, + CONSTRAINT `TEST_TABLE_TINYINT_REFERENCE_TABLE_TINYINT_REF` FOREIGN KEY (`tinyint`) REFERENCES `reference_table` (`tinyint_ref`) ON DELETE SET NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8', +]; diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/constraint_modification.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/constraint_modification.php index 0b1ec6245478b..5794f0dcf2bfc 100644 --- a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/constraint_modification.php +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/constraint_modification.php @@ -3,32 +3,33 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +// @codingStandardsIgnoreFile return [ 'auto_increment_test' => 'CREATE TABLE `auto_increment_test` ( - `int_auto_increment_with_nullable` int(12) unsigned NOT NULL AUTO_INCREMENT, - `int_disabled_auto_increment` smallint(12) unsigned DEFAULT \'0\', + `int_auto_increment_with_nullable` int(10) unsigned NOT NULL AUTO_INCREMENT, + `int_disabled_auto_increment` smallint(5) unsigned DEFAULT \'0\', UNIQUE KEY `AUTO_INCREMENT_TEST_INT_AUTO_INCREMENT_WITH_NULLABLE` (`int_auto_increment_with_nullable`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8', 'reference_table' => 'CREATE TABLE `reference_table` ( - `tinyint_ref` tinyint(7) NOT NULL AUTO_INCREMENT, - `tinyint_without_padding` tinyint(2) NOT NULL DEFAULT \'0\', + `tinyint_ref` tinyint(4) NOT NULL AUTO_INCREMENT, + `tinyint_without_padding` tinyint(4) NOT NULL DEFAULT \'0\', `bigint_without_padding` bigint(20) NOT NULL DEFAULT \'0\', - `smallint_without_padding` smallint(5) NOT NULL DEFAULT \'0\', + `smallint_without_padding` smallint(6) NOT NULL DEFAULT \'0\', `integer_without_padding` int(11) NOT NULL DEFAULT \'0\', - `smallint_with_big_padding` smallint(254) NOT NULL DEFAULT \'0\', - `smallint_without_default` smallint(2) DEFAULT NULL, - `int_without_unsigned` int(2) DEFAULT NULL, - `int_unsigned` int(2) unsigned DEFAULT NULL, - `bigint_default_nullable` bigint(2) unsigned DEFAULT \'1\', - `bigint_not_default_not_nullable` bigint(2) unsigned NOT NULL, - `smallint_ref` smallint(254) NOT NULL DEFAULT \'0\', + `smallint_with_big_padding` smallint(6) NOT NULL DEFAULT \'0\', + `smallint_without_default` smallint(6) DEFAULT NULL, + `int_without_unsigned` int(11) DEFAULT NULL, + `int_unsigned` int(10) unsigned DEFAULT NULL, + `bigint_default_nullable` bigint(20) unsigned DEFAULT \'1\', + `bigint_not_default_not_nullable` bigint(20) unsigned NOT NULL, + `smallint_ref` smallint(6) NOT NULL DEFAULT \'0\', PRIMARY KEY (`tinyint_ref`,`smallint_ref`), UNIQUE KEY `REFERENCE_TABLE_SMALLINT_REF` (`smallint_ref`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8', 'test_table' => 'CREATE TABLE `test_table` ( - `smallint` smallint(3) DEFAULT NULL, - `tinyint` tinyint(7) DEFAULT NULL, - `bigint` bigint(13) DEFAULT \'0\', + `smallint` smallint(6) DEFAULT NULL, + `tinyint` tinyint(4) DEFAULT NULL, + `bigint` bigint(20) DEFAULT \'0\', `float` float(12,10) DEFAULT \'0.0000000000\', `double` double(245,10) DEFAULT \'11111111.1111110000\', `decimal` decimal(15,4) DEFAULT \'0.0000\', @@ -42,18 +43,15 @@ `mediumblob` mediumblob, `blob` blob, `boolean` tinyint(1) DEFAULT NULL, - `integer_main` int(12) unsigned DEFAULT NULL, - `smallint_main` smallint(254) NOT NULL DEFAULT \'0\', + `integer_main` int(10) unsigned DEFAULT NULL, + `smallint_main` smallint(6) NOT NULL DEFAULT \'0\', UNIQUE KEY `TEST_TABLE_SMALLINT_FLOAT` (`smallint`,`float`), UNIQUE KEY `TEST_TABLE_DOUBLE` (`double`), KEY `TEST_TABLE_TINYINT_BIGINT` (`tinyint`,`bigint`), KEY `TEST_TABLE_SMALLINT_MAIN_REFERENCE_TABLE_SMALLINT_REF` (`smallint_main`), KEY `FK_FB77604C299EB8612D01E4AF8D9931F2` (`integer_main`), - CONSTRAINT `FK_FB77604C299EB8612D01E4AF8D9931F2` FOREIGN KEY (`integer_main`) -REFERENCES `auto_increment_test` (`int_auto_increment_with_nullable`) ON DELETE CASCADE, - CONSTRAINT `TEST_TABLE_SMALLINT_MAIN_REFERENCE_TABLE_SMALLINT_REF` FOREIGN KEY (`smallint_main`) -REFERENCES `reference_table` (`smallint_ref`) ON DELETE CASCADE, - CONSTRAINT `TEST_TABLE_TINYINT_REFERENCE_TABLE_TINYINT_REF` FOREIGN KEY (`tinyint`) -REFERENCES `reference_table` (`tinyint_ref`) ON DELETE SET NULL + CONSTRAINT `FK_FB77604C299EB8612D01E4AF8D9931F2` FOREIGN KEY (`integer_main`) REFERENCES `auto_increment_test` (`int_auto_increment_with_nullable`) ON DELETE CASCADE, + CONSTRAINT `TEST_TABLE_SMALLINT_MAIN_REFERENCE_TABLE_SMALLINT_REF` FOREIGN KEY (`smallint_main`) REFERENCES `reference_table` (`smallint_ref`) ON DELETE CASCADE, + CONSTRAINT `TEST_TABLE_TINYINT_REFERENCE_TABLE_TINYINT_REF` FOREIGN KEY (`tinyint`) REFERENCES `reference_table` (`tinyint_ref`) ON DELETE SET NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8', ]; diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/installation.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/installation.php index 3e807c25e3519..7a285e8567996 100644 --- a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/installation.php +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/installation.php @@ -5,13 +5,13 @@ */ return [ 'auto_increment_test' => 'CREATE TABLE `auto_increment_test` ( - `int_auto_increment_with_nullable` int(12) unsigned NOT NULL AUTO_INCREMENT, - `int_disabled_auto_increment` smallint(12) unsigned DEFAULT \'0\', + `int_auto_increment_with_nullable` int(10) unsigned NOT NULL AUTO_INCREMENT, + `int_disabled_auto_increment` smallint(10) unsigned DEFAULT \'0\', UNIQUE KEY `AUTO_INCREMENT_TEST_INT_AUTO_INCREMENT_WITH_NULLABLE` (`int_auto_increment_with_nullable`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8', 'reference_table' => 'CREATE TABLE `reference_table` ( `tinyint_ref` tinyint(7) NOT NULL AUTO_INCREMENT, - `tinyint_without_padding` tinyint(2) NOT NULL DEFAULT \'0\', + `tinyint_without_padding` tinyint(4) NOT NULL DEFAULT \'0\', `bigint_without_padding` bigint(20) NOT NULL DEFAULT \'0\', `smallint_without_padding` smallint(5) NOT NULL DEFAULT \'0\', `integer_without_padding` int(11) NOT NULL DEFAULT \'0\', @@ -41,7 +41,7 @@ `boolean` tinyint(1) DEFAULT NULL, UNIQUE KEY `TEST_TABLE_SMALLINT_BIGINT` (`smallint`,`bigint`), KEY `TEST_TABLE_TINYINT_BIGINT` (`tinyint`,`bigint`), - CONSTRAINT `TEST_TABLE_TINYINT_REFERENCE_TABLE_TINYINT_REF` FOREIGN KEY (`tinyint`) + CONSTRAINT `TEST_TABLE_TINYINT_REFERENCE_TABLE_TINYINT_REF` FOREIGN KEY (`tinyint`) REFERENCES `reference_table` (`tinyint_ref`) ON DELETE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8', ]; diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/rollback.mysql8.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/rollback.mysql8.php new file mode 100644 index 0000000000000..fca11331318d6 --- /dev/null +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/rollback.mysql8.php @@ -0,0 +1,27 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +// @codingStandardsIgnoreFile +return [ + 'before' => [ + 'store' => 'CREATE TABLE `store` ( + `store_owner_id` smallint DEFAULT NULL COMMENT \'Store Owner Reference\', + KEY `STORE_STORE_OWNER_ID_STORE_OWNER_OWNER_ID` (`store_owner_id`), + CONSTRAINT `STORE_STORE_OWNER_ID_STORE_OWNER_OWNER_ID` FOREIGN KEY (`store_owner_id`) REFERENCES `store_owner` (`owner_id`) ON DELETE SET NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8', + 'store_owner' => 'CREATE TABLE `store_owner` ( + `owner_id` smallint NOT NULL AUTO_INCREMENT, + `store_owner_name` varchar(255) DEFAULT NULL COMMENT \'Store Owner Name\', + PRIMARY KEY (`owner_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=\'Store owner information\'' + ], + 'after' => [ + 'store' => 'CREATE TABLE `store` ( + `store_owner` varchar(255) DEFAULT NULL COMMENT \'Store Owner Name\' +) ENGINE=InnoDB DEFAULT CHARSET=utf8' + ] +]; diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/rollback.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/rollback.php index f5b98ce8a2735..61f4c5cd7fc61 100644 --- a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/rollback.php +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/rollback.php @@ -9,13 +9,13 @@ return [ 'before' => [ 'store' => 'CREATE TABLE `store` ( - `store_owner_id` smallint(5) DEFAULT NULL COMMENT \'Store Owner Reference\', + `store_owner_id` smallint(6) DEFAULT NULL COMMENT \'Store Owner Reference\', KEY `STORE_STORE_OWNER_ID_STORE_OWNER_OWNER_ID` (`store_owner_id`), CONSTRAINT `STORE_STORE_OWNER_ID_STORE_OWNER_OWNER_ID` FOREIGN KEY (`store_owner_id`) REFERENCES `store_owner` (`owner_id`) ON DELETE SET NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8', 'store_owner' => 'CREATE TABLE `store_owner` ( - `owner_id` smallint(5) NOT NULL AUTO_INCREMENT, + `owner_id` smallint(6) NOT NULL AUTO_INCREMENT, `store_owner_name` varchar(255) DEFAULT NULL COMMENT \'Store Owner Name\', PRIMARY KEY (`owner_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT=\'Store owner information\'' diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/table_removal.mariadb10.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/table_removal.mariadb10.php new file mode 100644 index 0000000000000..df7177284bd90 --- /dev/null +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/table_removal.mariadb10.php @@ -0,0 +1,12 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +return [ + 'auto_increment_test' => 'CREATE TABLE `auto_increment_test` ( + `int_auto_increment_with_nullable` int(10) unsigned NOT NULL AUTO_INCREMENT, + `int_disabled_auto_increment` smallint(5) unsigned DEFAULT 0, + UNIQUE KEY `AUTO_INCREMENT_TEST_INT_AUTO_INCREMENT_WITH_NULLABLE` (`int_auto_increment_with_nullable`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8' +]; diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/table_removal.mysql8.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/table_removal.mysql8.php new file mode 100644 index 0000000000000..6eef0bbc1603a --- /dev/null +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/table_removal.mysql8.php @@ -0,0 +1,12 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +return [ + 'auto_increment_test' => 'CREATE TABLE `auto_increment_test` ( + `int_auto_increment_with_nullable` int unsigned NOT NULL AUTO_INCREMENT, + `int_disabled_auto_increment` smallint unsigned DEFAULT \'0\', + UNIQUE KEY `AUTO_INCREMENT_TEST_INT_AUTO_INCREMENT_WITH_NULLABLE` (`int_auto_increment_with_nullable`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8' +]; diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/table_removal.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/table_removal.php index 7bd0213c6590d..224dda0d55dd3 100644 --- a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/table_removal.php +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/declarative_installer/table_removal.php @@ -5,8 +5,8 @@ */ return [ 'auto_increment_test' => 'CREATE TABLE `auto_increment_test` ( - `int_auto_increment_with_nullable` int(12) unsigned NOT NULL AUTO_INCREMENT, - `int_disabled_auto_increment` smallint(12) unsigned DEFAULT \'0\', + `int_auto_increment_with_nullable` int(10) unsigned NOT NULL AUTO_INCREMENT, + `int_disabled_auto_increment` smallint(5) unsigned DEFAULT \'0\', UNIQUE KEY `AUTO_INCREMENT_TEST_INT_AUTO_INCREMENT_WITH_NULLABLE` (`int_auto_increment_with_nullable`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8' ]; diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/dry_run_log.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/dry_run_log.php index 7735bd433d9d2..91406e57728b3 100644 --- a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/dry_run_log.php +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/dry_run_log.php @@ -5,30 +5,30 @@ */ // @codingStandardsIgnoreFile return ['CREATE TABLE `reference_table` ( -`tinyint_ref` tinyint(7) NOT NULL AUTO_INCREMENT , -`tinyint_without_padding` tinyint(2) NOT NULL DEFAULT 0 , -`bigint_without_padding` bigint(20) NOT NULL DEFAULT 0 , -`smallint_without_padding` smallint(5) NOT NULL DEFAULT 0 , -`integer_without_padding` int(11) NOT NULL DEFAULT 0 , -`smallint_with_big_padding` smallint(254) NOT NULL DEFAULT 0 , -`smallint_without_default` smallint(2) NULL , -`int_without_unsigned` int(2) NULL , -`int_unsigned` int(2) UNSIGNED NULL , -`bigint_default_nullable` bigint(2) UNSIGNED NULL DEFAULT 1 , -`bigint_not_default_not_nullable` bigint(2) UNSIGNED NOT NULL , +`tinyint_ref` tinyint NOT NULL AUTO_INCREMENT , +`tinyint_without_padding` tinyint NOT NULL DEFAULT 0 , +`bigint_without_padding` bigint NOT NULL DEFAULT 0 , +`smallint_without_padding` smallint NOT NULL DEFAULT 0 , +`integer_without_padding` int NOT NULL DEFAULT 0 , +`smallint_with_big_padding` smallint NOT NULL DEFAULT 0 , +`smallint_without_default` smallint NULL , +`int_without_unsigned` int NULL , +`int_unsigned` int UNSIGNED NULL , +`bigint_default_nullable` bigint UNSIGNED NULL DEFAULT 1 , +`bigint_not_default_not_nullable` bigint UNSIGNED NOT NULL , CONSTRAINT PRIMARY KEY (`tinyint_ref`) ) ENGINE=innodb DEFAULT CHARSET=utf8 DEFAULT COLLATE=utf8_general_ci CREATE TABLE `auto_increment_test` ( -`int_auto_increment_with_nullable` int(12) UNSIGNED NOT NULL AUTO_INCREMENT , -`int_disabled_auto_increment` smallint(12) UNSIGNED NULL DEFAULT 0 , +`int_auto_increment_with_nullable` int UNSIGNED NOT NULL AUTO_INCREMENT , +`int_disabled_auto_increment` smallint UNSIGNED NULL DEFAULT 0 , CONSTRAINT `AUTO_INCREMENT_TEST_INT_AUTO_INCREMENT_WITH_NULLABLE` UNIQUE KEY (`int_auto_increment_with_nullable`) ) ENGINE=innodb DEFAULT CHARSET=utf8 DEFAULT COLLATE=utf8_general_ci CREATE TABLE `test_table` ( -`smallint` smallint(3) NOT NULL AUTO_INCREMENT , -`tinyint` tinyint(7) NULL , -`bigint` bigint(13) NULL DEFAULT 0 , +`smallint` smallint NOT NULL AUTO_INCREMENT , +`tinyint` tinyint NULL , +`bigint` bigint NULL DEFAULT 0 , `float` float(12, 4) NULL DEFAULT 0 , `double` decimal(14, 6) NULL DEFAULT 11111111.111111 , `decimal` decimal(15, 4) NULL DEFAULT 0 , @@ -48,7 +48,7 @@ ) ENGINE=innodb DEFAULT CHARSET=utf8 DEFAULT COLLATE=utf8_general_ci CREATE TABLE `patch_list` ( -`patch_id` int(11) NOT NULL AUTO_INCREMENT COMMENT "Patch Auto Increment", +`patch_id` int NOT NULL AUTO_INCREMENT COMMENT "Patch Auto Increment", `patch_name` varchar(1024) NOT NULL COMMENT "Patch Class Name", CONSTRAINT PRIMARY KEY (`patch_id`) ) ENGINE=innodb DEFAULT CHARSET=utf8 DEFAULT COLLATE=utf8_general_ci COMMENT="List of data/schema patches" diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/dry_run_log_on_upgrade.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/dry_run_log_on_upgrade.php index ccc2d5b792917..1f903aab42792 100644 --- a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/dry_run_log_on_upgrade.php +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule1/fixture/dry_run_log_on_upgrade.php @@ -4,9 +4,9 @@ * See COPYING.txt for license details. */ // @codingStandardsIgnoreFile -return ['ALTER TABLE `reference_table` MODIFY COLUMN `tinyint_without_padding` tinyint(2) NOT NULL , MODIFY COLUMN `bigint_default_nullable` bigint(2) UNSIGNED NULL DEFAULT 123 , MODIFY COLUMN `bigint_not_default_not_nullable` bigint(20) NOT NULL +return ['ALTER TABLE `reference_table` MODIFY COLUMN `tinyint_without_padding` tinyint NOT NULL , MODIFY COLUMN `bigint_default_nullable` bigint UNSIGNED NULL DEFAULT 123 , MODIFY COLUMN `bigint_not_default_not_nullable` bigint NOT NULL -ALTER TABLE `auto_increment_test` MODIFY COLUMN `int_auto_increment_with_nullable` int(15) UNSIGNED NULL +ALTER TABLE `auto_increment_test` MODIFY COLUMN `int_auto_increment_with_nullable` int UNSIGNED NULL ALTER TABLE `test_table` MODIFY COLUMN `float` float(12, 10) NULL DEFAULT 0 , MODIFY COLUMN `double` double(245, 10) NULL , MODIFY COLUMN `timestamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP , MODIFY COLUMN `varchar` varchar(100) NULL , MODIFY COLUMN `boolean` BOOLEAN NULL DEFAULT 1 diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule9/fixture/declarative_installer/disabling_tables.mariadb10.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule9/fixture/declarative_installer/disabling_tables.mariadb10.php new file mode 100644 index 0000000000000..b21dca7d28b7e --- /dev/null +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule9/fixture/declarative_installer/disabling_tables.mariadb10.php @@ -0,0 +1,14 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +return [ + 'auto_increment_test' => 'CREATE TABLE `auto_increment_test` ( + `int_auto_increment_with_nullable` int(10) unsigned NOT NULL AUTO_INCREMENT, + `int_disabled_auto_increment` smallint(5) unsigned DEFAULT 0, + UNIQUE KEY `AUTO_INCREMENT_TEST_INT_AUTO_INCREMENT_WITH_NULLABLE` (`int_auto_increment_with_nullable`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8' +]; diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule9/fixture/declarative_installer/disabling_tables.mysql8.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule9/fixture/declarative_installer/disabling_tables.mysql8.php new file mode 100644 index 0000000000000..bd1f8a215297c --- /dev/null +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule9/fixture/declarative_installer/disabling_tables.mysql8.php @@ -0,0 +1,14 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +return [ + 'auto_increment_test' => 'CREATE TABLE `auto_increment_test` ( + `int_auto_increment_with_nullable` int unsigned NOT NULL AUTO_INCREMENT, + `int_disabled_auto_increment` smallint unsigned DEFAULT \'0\', + UNIQUE KEY `AUTO_INCREMENT_TEST_INT_AUTO_INCREMENT_WITH_NULLABLE` (`int_auto_increment_with_nullable`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8' +]; diff --git a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule9/fixture/declarative_installer/disabling_tables.php b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule9/fixture/declarative_installer/disabling_tables.php index 633185390ae84..8a0c4dc50df37 100644 --- a/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule9/fixture/declarative_installer/disabling_tables.php +++ b/dev/tests/setup-integration/_files/Magento/TestSetupDeclarationModule9/fixture/declarative_installer/disabling_tables.php @@ -7,8 +7,8 @@ return [ 'auto_increment_test' => 'CREATE TABLE `auto_increment_test` ( - `int_auto_increment_with_nullable` int(12) unsigned NOT NULL AUTO_INCREMENT, - `int_disabled_auto_increment` smallint(12) unsigned DEFAULT \'0\', + `int_auto_increment_with_nullable` int(10) unsigned NOT NULL AUTO_INCREMENT, + `int_disabled_auto_increment` smallint(5) unsigned DEFAULT \'0\', UNIQUE KEY `AUTO_INCREMENT_TEST_INT_AUTO_INCREMENT_WITH_NULLABLE` (`int_auto_increment_with_nullable`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8' ]; diff --git a/dev/tests/setup-integration/framework/Magento/TestFramework/Annotation/DataProviderFromFile.php b/dev/tests/setup-integration/framework/Magento/TestFramework/Annotation/DataProviderFromFile.php index 6bc513b659074..d34a5b2d40828 100644 --- a/dev/tests/setup-integration/framework/Magento/TestFramework/Annotation/DataProviderFromFile.php +++ b/dev/tests/setup-integration/framework/Magento/TestFramework/Annotation/DataProviderFromFile.php @@ -6,6 +6,7 @@ namespace Magento\TestFramework\Annotation; +use Magento\Framework\DB\Adapter\SqlVersionProvider; use Magento\TestFramework\Deploy\CliCommand; use Magento\TestFramework\Deploy\TestModuleManager; use Magento\TestFramework\TestCase\MutableDataInterface; @@ -15,6 +16,19 @@ */ class DataProviderFromFile { + /** + * @var string + */ + const FALLBACK_VALUE = 'default'; + + /** + * @var array + */ + const POSSIBLE_SUFFIXES = [ + SqlVersionProvider::MYSQL_8_0_VERSION => 'mysql8', + SqlVersionProvider::MARIA_DB_10_VERSION => 'mariadb10', + ]; + /** * @var TestModuleManager */ @@ -45,9 +59,10 @@ public function startTest(\PHPUnit\Framework\TestCase $test) $annotations = $test->getAnnotations(); //This annotation can be declared only on method level if (isset($annotations['method']['dataProviderFromFile']) && $test instanceof MutableDataInterface) { - $data = include TESTS_MODULES_PATH . "/" . $annotations['method']['dataProviderFromFile'][0]; - $test->setData($data); - } else if (!$test instanceof MutableDataInterface) { + $test->setData( + $this->loadAllFiles(TESTS_MODULES_PATH . "/" . $annotations['method']['dataProviderFromFile'][0]) + ); + } elseif (!$test instanceof MutableDataInterface) { throw new \Exception("Test type do not supports @dataProviderFromFile annotation"); } } @@ -64,4 +79,63 @@ public function endTest(\PHPUnit\Framework\TestCase $test) $test->flushData(); } } + + /** + * Load different db version files for different databases. + * + * @param string $path The path of the inital file. + * + * @return array + */ + private function loadAllFiles(string $path): array + { + $result = []; + $pathWithoutExtension = $this->removeFileExtension($path); + + foreach (glob($pathWithoutExtension . '.*') as $file) { + /* Search database string in file name like mysql8 with + possibility to use version until patch level. */ + preg_match('/\.([\D]*[\d]*(?:\.[\d]+){0,2})/', $file, $splitedParts); + $dbKey = self::FALLBACK_VALUE; + + if (count($splitedParts) > 1) { + $database = array_pop($splitedParts); + + if ($this->isValidDatabaseSuffix($database)) { + $dbKey = $database; + } + } + + $result[$dbKey] = include $file; + } + + return $result; + } + + /** + * Remove the file extension from path. + * + * @param string $path The file path. + * + * @return string + */ + private function removeFileExtension(string $path) + { + $result = explode('.', $path); + array_pop($result); + + return implode('.', $result); + } + + /** + * Check if database suffix is valid. + * + * @param string $databaseSuffix The suffix of the database from the file + * + * @return bool + */ + private function isValidDatabaseSuffix(string $databaseSuffix): bool + { + return in_array($databaseSuffix, self::POSSIBLE_SUFFIXES); + } } diff --git a/dev/tests/setup-integration/framework/Magento/TestFramework/TestCase/SetupTestCase.php b/dev/tests/setup-integration/framework/Magento/TestFramework/TestCase/SetupTestCase.php index e1efe5738910a..95f7e5b463160 100644 --- a/dev/tests/setup-integration/framework/Magento/TestFramework/TestCase/SetupTestCase.php +++ b/dev/tests/setup-integration/framework/Magento/TestFramework/TestCase/SetupTestCase.php @@ -3,10 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\TestFramework\TestCase; -use Magento\Framework\App\DesignInterface; -use Magento\Framework\View\DesignExceptions; +use Magento\Framework\DB\Adapter\ConnectionException; +use Magento\Framework\DB\Adapter\SqlVersionProvider; +use Magento\TestFramework\Annotation\DataProviderFromFile; +use Magento\TestFramework\Helper\Bootstrap; /** * Instance of Setup test case. Used in order to tweak dataProviders functionality. @@ -18,6 +22,29 @@ class SetupTestCase extends \PHPUnit\Framework\TestCase implements MutableDataIn */ private $data = []; + /** + * @var string + */ + private $dbKey; + + /** + * @var SqlVersionProvider + */ + private $sqlVersionProvider; + + /** + * @inheritDoc + */ + public function __construct( + $name = null, + array $data = [], + $dataName = '' + ) { + parent::__construct($name, $data, $dataName); + + $this->sqlVersionProvider = Bootstrap::getObjectManager()->get(SqlVersionProvider::class); + } + /** * @inheritdoc */ @@ -39,6 +66,43 @@ public function flushData() */ public function getData() { - return $this->data; + if (array_key_exists($this->getDbKey(), $this->data)) { + return $this->data[$this->getDbKey()]; + } + + return $this->data[DataProviderFromFile::FALLBACK_VALUE]; + } + + /** + * Get database version. + * + * @return string + * @throws ConnectionException + */ + protected function getDatabaseVersion(): string + { + return $this->sqlVersionProvider->getSqlVersion(); + } + + /** + * Get db key to decide which file to use. + * + * @return string + */ + private function getDbKey(): string + { + if ($this->dbKey) { + return $this->dbKey; + } + + $this->dbKey = DataProviderFromFile::FALLBACK_VALUE; + foreach (DataProviderFromFile::POSSIBLE_SUFFIXES as $possibleVersion => $suffix) { + if (strpos($this->getDatabaseVersion(), (string)$possibleVersion) !== false) { + $this->dbKey = $suffix; + break; + } + } + + return $this->dbKey; } } diff --git a/dev/tests/setup-integration/testsuite/Magento/Setup/DeclarativeInstallerTest.php b/dev/tests/setup-integration/testsuite/Magento/Setup/DeclarativeInstallerTest.php index 3082ca01899c6..e88d47a02c0d8 100644 --- a/dev/tests/setup-integration/testsuite/Magento/Setup/DeclarativeInstallerTest.php +++ b/dev/tests/setup-integration/testsuite/Magento/Setup/DeclarativeInstallerTest.php @@ -423,7 +423,7 @@ public function testDisableIndexByExternalModule() $this->cliCommand->upgrade(); $tableStatements = $this->describeTable->describeShard('default'); $tableSql = $tableStatements['test_table']; - $this->assertNotRegExp( + $this->assertDoesNotMatchRegularExpression( '/KEY\s+`TEST_TABLE_VARCHAR`\s+\(`varchar`\)/', $tableSql, 'Index is not being disabled by external module' diff --git a/dev/tests/setup-integration/testsuite/Magento/Setup/DiffOldSchemaTest.php b/dev/tests/setup-integration/testsuite/Magento/Setup/DiffOldSchemaTest.php index 3a4eb3216bd88..329ad0dca556d 100644 --- a/dev/tests/setup-integration/testsuite/Magento/Setup/DiffOldSchemaTest.php +++ b/dev/tests/setup-integration/testsuite/Magento/Setup/DiffOldSchemaTest.php @@ -156,7 +156,7 @@ private function getBigIntKeyDbSensitiveData() return [ 'type' => 'bigint', 'nullable' => true, - 'padding' => 20, + 'padding' => null, 'unsigned' => false, 'identity' => false, 'default' => 0, @@ -172,7 +172,7 @@ private function getBigIntKeyXmlSensitiveData() return [ 'type' => 'bigint', 'nullable' => true, - 'padding' => 20, + 'padding' => null, 'unsigned' => false, 'identity' => false, 'default' => 1, diff --git a/dev/tests/setup-integration/testsuite/Magento/Setup/DryRunTest.php b/dev/tests/setup-integration/testsuite/Magento/Setup/DryRunTest.php index ca6882a7d7cda..191ba635a35b6 100644 --- a/dev/tests/setup-integration/testsuite/Magento/Setup/DryRunTest.php +++ b/dev/tests/setup-integration/testsuite/Magento/Setup/DryRunTest.php @@ -47,7 +47,7 @@ public function testDryRunOnCleanDatabase() ); self::assertFileExists($logFileName); $data = file_get_contents($logFileName); - self::assertEquals($data, $this->getData()[0]); + self::assertEquals($this->getData()[0], $data); } /** @@ -67,6 +67,6 @@ public function testDryRunOnUpgrade() $this->cliCommad->upgrade(['dry-run' => true]); self::assertFileExists($logFileName); $data = file_get_contents($logFileName); - self::assertEquals($data, $this->getData()[0]); + self::assertEquals($this->getData()[0], $data); } } diff --git a/dev/tests/setup-integration/testsuite/Magento/Setup/ValidationRulesTest.php b/dev/tests/setup-integration/testsuite/Magento/Setup/ValidationRulesTest.php index d21925ab74439..1d7d006869583 100644 --- a/dev/tests/setup-integration/testsuite/Magento/Setup/ValidationRulesTest.php +++ b/dev/tests/setup-integration/testsuite/Magento/Setup/ValidationRulesTest.php @@ -6,6 +6,7 @@ namespace Magento\Setup; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Setup\Declaration\Schema\SchemaConfig; use Magento\TestFramework\Deploy\CliCommand; use Magento\TestFramework\Deploy\TestModuleManager; @@ -45,7 +46,7 @@ protected function setUp(): void */ public function testFailOnInvalidPrimaryKey() { - $this->expectException(\Magento\Framework\Setup\Exception::class); + $this->expectException(LocalizedException::class); $this->expectExceptionMessageMatches( '/Primary key can`t be applied on table "test_table". All columns should be not nullable/' ); @@ -68,7 +69,7 @@ public function testFailOnInvalidPrimaryKey() */ public function testFailOnIncosistentReferenceDefinition() { - $this->expectException(\Magento\Framework\Setup\Exception::class); + $this->expectException(LocalizedException::class); $this->expectExceptionMessageMatches( '/Column definition "page_id_on" and reference column definition "page_id"' . ' are different in tables "dependent" and "test_table"/' @@ -91,7 +92,7 @@ public function testFailOnIncosistentReferenceDefinition() */ public function testFailOnInvalidAutoIncrementField() { - $this->expectException(\Magento\Framework\Setup\Exception::class); + $this->expectException(LocalizedException::class); $this->expectExceptionMessageMatches('/Auto Increment column do not have index. Column - "page_id"/'); $this->cliCommad->install( diff --git a/dev/tests/static/testsuite/Magento/Test/Integrity/Magento/Backend/_files/controller_acl_test_whitelist_ce.txt b/dev/tests/static/testsuite/Magento/Test/Integrity/Magento/Backend/_files/controller_acl_test_whitelist_ce.txt index 8561818022112..9d3d7ad8e35d7 100644 --- a/dev/tests/static/testsuite/Magento/Test/Integrity/Magento/Backend/_files/controller_acl_test_whitelist_ce.txt +++ b/dev/tests/static/testsuite/Magento/Test/Integrity/Magento/Backend/_files/controller_acl_test_whitelist_ce.txt @@ -5,7 +5,6 @@ Magento\Backend\Controller\Adminhtml\Noroute\Index Magento\Directory\Controller\Adminhtml\Json\CountryRegion Magento\Tax\Controller\Adminhtml\Rule\AjaxLoadRates # List of classes that locates in controllers folder but don't inherit base admin controller MAGETWO-70433. -Magento\Braintree\Controller\Adminhtml\Payment\GetNonce Magento\Bundle\Controller\Adminhtml\Product\Initialization\Helper\Plugin\Bundle Magento\CatalogUrlRewrite\Plugin\Catalog\Controller\Adminhtml\Product\Initialization\Helper Magento\Catalog\Controller\Adminhtml\Product\Builder diff --git a/dev/tests/static/testsuite/Magento/Test/Legacy/ClassesTest.php b/dev/tests/static/testsuite/Magento/Test/Legacy/ClassesTest.php index 271aa26ee56f0..0081c4081bbb8 100644 --- a/dev/tests/static/testsuite/Magento/Test/Legacy/ClassesTest.php +++ b/dev/tests/static/testsuite/Magento/Test/Legacy/ClassesTest.php @@ -106,7 +106,7 @@ protected function _assertNonFactoryName($names, $file, $softComparison = false, foreach ($names as $name) { try { if ($softComparison) { - $this->assertNotRegExp('/\//', $name); + $this->assertDoesNotMatchRegularExpression('/\//', $name); } elseif ($moduleBlock) { $this->assertFalse(false === strpos($name, '_')); $this->assertMatchesRegularExpression('/^([A-Z][A-Za-z\d_]+)+$/', $name); diff --git a/dev/tests/static/testsuite/Magento/Test/Legacy/EmailTemplateTest.php b/dev/tests/static/testsuite/Magento/Test/Legacy/EmailTemplateTest.php index b02820bae901b..9775cdc2b9e20 100644 --- a/dev/tests/static/testsuite/Magento/Test/Legacy/EmailTemplateTest.php +++ b/dev/tests/static/testsuite/Magento/Test/Legacy/EmailTemplateTest.php @@ -19,13 +19,13 @@ public function testObsoleteDirectives() * @param string $file */ function ($file) { - $this->assertNotRegExp( + $this->assertDoesNotMatchRegularExpression( '/\{\{htmlescape.*?\}\}/i', file_get_contents($file), 'Directive {{htmlescape}} is obsolete. Use {{var}} instead.' ); - $this->assertNotRegExp( + $this->assertDoesNotMatchRegularExpression( '/\{\{escapehtml.*?\}\}/i', file_get_contents($file), 'Directive {{escapehtml}} is obsolete. Use {{var}} instead.' diff --git a/dev/tests/static/testsuite/Magento/Test/Legacy/Magento/Widget/XmlTest.php b/dev/tests/static/testsuite/Magento/Test/Legacy/Magento/Widget/XmlTest.php index b57f2b5bb2e5c..cabe4f91a0ef4 100644 --- a/dev/tests/static/testsuite/Magento/Test/Legacy/Magento/Widget/XmlTest.php +++ b/dev/tests/static/testsuite/Magento/Test/Legacy/Magento/Widget/XmlTest.php @@ -26,7 +26,7 @@ function ($file) { /** @var \SimpleXMLElement $node */ foreach ($nodes as $node) { $type = (string)$node['type']; - $this->assertNotRegExp('/\//', $type, "Factory name detected: {$type}."); + $this->assertDoesNotMatchRegularExpression('/\//', $type, "Factory name detected: {$type}."); } }, \Magento\Framework\App\Utility\Files::init()->getConfigFiles('widget.xml') diff --git a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/copyright/blacklist.php b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/copyright/blacklist.php index 48eb64ffea27e..50397b70ea925 100644 --- a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/copyright/blacklist.php +++ b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/copyright/blacklist.php @@ -10,5 +10,6 @@ '/setup\/src\/Zend\/Mvc\/Controller\/LazyControllerAbstractFactory\.php/', '/app\/code\/(?!Magento)[^\/]*/', '#dev/tests/setup-integration/testsuite/Magento/Developer/_files/\S*\.xml$#', - '/lib\/internal\/Magento\/Framework\/File\/Test\/Unit\/_files\/blank.html$/' + '/lib\/internal\/Magento\/Framework\/File\/Test\/Unit\/_files\/blank.html$/', + '/dev\/tests\/integration\/testsuite\/Magento\/Ups\/_files\/ShipmentConfirmRequest.xml$/' ]; diff --git a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/initialize_javascript/data_mage_init/whitelist.php b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/initialize_javascript/data_mage_init/whitelist.php deleted file mode 100644 index a77b7b28864ec..0000000000000 --- a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/initialize_javascript/data_mage_init/whitelist.php +++ /dev/null @@ -1,14 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -/** - * List of templates with data-mage-init attribute where JS component is not correctly called. - * - * JS component is initialized in php here. These templates cannot be refactored easily. This list consists of - * module name and template path within module. - */ -return [ - ['Magento_Braintree', 'view/frontend/templates/paypal/button_shopping_cart.phtml'] -]; diff --git a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/obsolete_classes.php b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/obsolete_classes.php index aebb08363e5d6..c4ae253fe7499 100644 --- a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/obsolete_classes.php +++ b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/obsolete_classes.php @@ -4261,4 +4261,57 @@ ['Magento\Elasticsearch\Model\Adapter\Container\Attribute'], ['PHPUnit_Framework_MockObject_MockObject', 'PHPUnit\Framework\MockObject\MockObject'], ['PHPUnit\Framework\BaseTestListener'], + ['Magento\Backend\Model\Setup\MenuBuilder'], + ['Magento\Setup\Controller\AddDatabase'], + ['Magento\Setup\Controller\BackupActionItems'], + ['Magento\Setup\Controller\CompleteBackup'], + ['Magento\Setup\Controller\ConfigureCatalogSearch'], + ['Magento\Setup\Controller\CreateAdminAccount'], + ['Magento\Setup\Controller\CreateBackup'], + ['Magento\Setup\Controller\CustomizeYourStore'], + ['Magento\Setup\Controller\DatabaseCheck'], + ['Magento\Setup\Controller\DataOption'], + ['Magento\Setup\Controller\DependencyCheck'], + ['Magento\Setup\Controller\Environment'], + ['Magento\Setup\Controller\ExtensionGrid'], + ['Magento\Setup\Controller\Home'], + ['Magento\Setup\Controller\Install'], + ['Magento\Setup\Controller\InstallExtensionGrid'], + ['Magento\Setup\Controller\LandingUpdater'], + ['Magento\Setup\Controller\Maintenance'], + ['Magento\Setup\Controller\Marketplace'], + ['Magento\Setup\Controller\MarketplaceCredentials'], + ['Magento\Setup\Controller\ModuleGrid'], + ['Magento\Setup\Controller\Modules'], + ['Magento\Setup\Controller\OtherComponentsGrid'], + ['Magento\Setup\Controller\ReadinessCheckInstaller'], + ['Magento\Setup\Controller\ReadinessCheckUpdater'], + ['Magento\Setup\Controller\SearchEngineCheck'], + ['Magento\Setup\Controller\SelectVersion'], + ['Magento\Setup\Controller\StartUpdater'], + ['Magento\Setup\Controller\Success'], + ['Magento\Setup\Controller\SystemConfig'], + ['Magento\Setup\Controller\UpdateExtensionGrid'], + ['Magento\Setup\Controller\UpdaterSuccess'], + ['Magento\Setup\Controller\UrlCheck'], + ['Magento\Setup\Controller\ValidateAdminCredentials'], + ['Magento\Setup\Controller\WebConfiguration'], + ['Magento\Setup\Controller\Session'], + ['Magento\Setup\Model\Grid\Extension'], + ['Magento\Setup\Model\Grid\Module'], + ['Magento\Setup\Model\Installer\ProgressFactory'], + ['Magento\Setup\Model\CronScriptReadinessCheck'], + ['Magento\Setup\Model\DependencyReadinessCheck'], + ['Magento\Setup\Model\ModuleStatus'], + ['Magento\Setup\Model\ModuleStatusFactory'], + ['Magento\Setup\Model\PackagesData'], + ['Magento\Setup\Model\PayloadValidator'], + ['Magento\Setup\Model\RequestDataConverter'], + ['Magento\Setup\Model\SystemPackage'], + ['Magento\Setup\Model\UninstallDependencyCheck'], + ['Magento\Setup\Model\UpdaterTaskCreator'], + ['Magento\Setup\Model\WebLogger'], + ['Magento\Setup\Validator\AdminCredentialsValidator'], + ['Magento\Setup\Model\Updater'], + ['Magento\Setup\Console\Command\CronRunCommand'], ]; diff --git a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/obsolete_namespaces.php b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/obsolete_namespaces.php index 2849e61c0208c..9cc654a64ff99 100644 --- a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/obsolete_namespaces.php +++ b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/obsolete_namespaces.php @@ -206,4 +206,7 @@ ['Magento\AuthorizenetAcceptjs'], ['Magento\AuthorizenetCardinal'], ['Magento\AuthorizenetGraphQl'], + ['Magento\Braintree'], + ['Magento\BraintreeGraphQl'], + ['Magento\Setup\Model\Cron'], ]; diff --git a/dev/tests/static/testsuite/Magento/Test/Php/_files/phpstan/blacklist/common.txt b/dev/tests/static/testsuite/Magento/Test/Php/_files/phpstan/blacklist/common.txt index fd7650790ea4f..1bb13d553c754 100644 --- a/dev/tests/static/testsuite/Magento/Test/Php/_files/phpstan/blacklist/common.txt +++ b/dev/tests/static/testsuite/Magento/Test/Php/_files/phpstan/blacklist/common.txt @@ -18,6 +18,3 @@ dev/tests/api-functional/testsuite/Magento/Integration/Model/AdminTokenServiceTe dev/tests/api-functional/testsuite/Magento/Integration/Model/CustomerTokenServiceTest.php app/code/Magento/Developer/Test/Unit/Console/Command/DevTestsRunCommandTest.php app/code/Magento/OfflineShipping/Test/Unit/Model/ResourceModel/Carrier/Tablerate/CSV/ColumnResolverTest.php -app/code/Magento/Staging/Test/Unit/Model/Entity/Action/UpdateVersionTest.php -app/code/Magento/Staging/Test/Unit/Model/Operation/DeleteTest.php -app/code/Magento/Staging/Test/Unit/Model/Operation/Update/DefaultTemporaryUpdateProcessorTest.php diff --git a/dev/tests/static/testsuite/Magento/Test/Php/_files/phpstan/phpstan.neon b/dev/tests/static/testsuite/Magento/Test/Php/_files/phpstan/phpstan.neon index f4f6ff87f8175..408da608225b9 100644 --- a/dev/tests/static/testsuite/Magento/Test/Php/_files/phpstan/phpstan.neon +++ b/dev/tests/static/testsuite/Magento/Test/Php/_files/phpstan/phpstan.neon @@ -29,10 +29,10 @@ parameters: - '#Method (?:.*?) should return (?:.*?)void(?:.*?) but return statement is missing.#' services: - errorFormatter.filtered: - class: Magento\PhpStan\Formatters\FilteredErrorFormatter - arguments: - showTipsOfTheDay: false - checkThisOnly: false - inferPrivatePropertyTypeFromConstructor: true - checkMissingTypehints: %checkMissingTypehints% + errorFormatter.filtered: + class: Magento\PhpStan\Formatters\FilteredErrorFormatter + arguments: + showTipsOfTheDay: false + checkThisOnly: false + inferPrivatePropertyTypeFromConstructor: true + checkMissingTypehints: %checkMissingTypehints% diff --git a/lib/internal/Magento/Framework/Crontab/Test/Unit/CrontabManagerTest.php b/lib/internal/Magento/Framework/Crontab/Test/Unit/CrontabManagerTest.php index 636457989720d..904b76a1285e6 100644 --- a/lib/internal/Magento/Framework/Crontab/Test/Unit/CrontabManagerTest.php +++ b/lib/internal/Magento/Framework/Crontab/Test/Unit/CrontabManagerTest.php @@ -109,11 +109,9 @@ public function getTasksDataProvider(): array 'content' => '* * * * * /bin/php /var/www/cron.php' . PHP_EOL . CrontabManagerInterface::TASKS_BLOCK_START . ' ' . hash("sha256", BP) . PHP_EOL . '* * * * * /bin/php /var/www/magento/bin/magento cron:run' . PHP_EOL - . '* * * * * /bin/php /var/www/magento/bin/magento setup:cron:run' . PHP_EOL . CrontabManagerInterface::TASKS_BLOCK_END . ' ' . hash("sha256", BP) . PHP_EOL, 'tasks' => [ '* * * * * /bin/php /var/www/magento/bin/magento cron:run', - '* * * * * /bin/php /var/www/magento/bin/magento setup:cron:run', ], ], [ @@ -193,7 +191,6 @@ public function removeTasksDataProvider(): array 'contentBefore' => '* * * * * /bin/php /var/www/cron.php' . PHP_EOL . CrontabManagerInterface::TASKS_BLOCK_START . ' ' . hash("sha256", BP) . PHP_EOL . '* * * * * /bin/php /var/www/magento/bin/magento cron:run' . PHP_EOL - . '* * * * * /bin/php /var/www/magento/bin/magento setup:cron:run' . PHP_EOL . CrontabManagerInterface::TASKS_BLOCK_END . ' ' . hash("sha256", BP) . PHP_EOL, 'contentAfter' => '* * * * * /bin/php /var/www/cron.php' . PHP_EOL ], diff --git a/lib/internal/Magento/Framework/Crontab/Test/Unit/TasksProviderTest.php b/lib/internal/Magento/Framework/Crontab/Test/Unit/TasksProviderTest.php index bb47357885464..3ba76dd5d4822 100644 --- a/lib/internal/Magento/Framework/Crontab/Test/Unit/TasksProviderTest.php +++ b/lib/internal/Magento/Framework/Crontab/Test/Unit/TasksProviderTest.php @@ -25,7 +25,6 @@ public function testTasksProvider() { $tasks = [ 'magentoCron' => ['expressin' => '* * * * *', 'command' => 'bin/magento cron:run'], - 'magentoSetup' => ['command' => 'bin/magento setup:cron:run'], ]; /** @var $tasksProvider $tasksProvider */ diff --git a/lib/internal/Magento/Framework/DB/Adapter/Pdo/Mysql.php b/lib/internal/Magento/Framework/DB/Adapter/Pdo/Mysql.php index 80d8808ab1768..7db91c06d9649 100644 --- a/lib/internal/Magento/Framework/DB/Adapter/Pdo/Mysql.php +++ b/lib/internal/Magento/Framework/DB/Adapter/Pdo/Mysql.php @@ -25,9 +25,11 @@ use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Phrase; use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\Setup\SchemaListener; use Magento\Framework\Stdlib\DateTime; use Magento\Framework\Stdlib\StringUtils; -use Magento\Framework\Setup\SchemaListener; +use Zend_Db_Adapter_Exception; +use Zend_Db_Statement_Exception; // @codingStandardsIgnoreStart @@ -132,6 +134,13 @@ class Mysql extends \Zend_Db_Adapter_Pdo_Mysql implements AdapterInterface */ protected $_isDdlCacheAllowed = true; + /** + * Save if mysql engine is 8 or not. + * + * @var bool + */ + private $isMysql8Engine; + /** * MySQL column - Table DDL type pairs * @@ -206,7 +215,7 @@ class Mysql extends \Zend_Db_Adapter_Pdo_Mysql implements AdapterInterface /** * Map that links database error code to corresponding Magento exception * - * @var \Zend_Db_Adapter_Exception[] + * @var Zend_Db_Adapter_Exception[] */ private $exceptionMap; @@ -264,7 +273,7 @@ public function __construct( ]; try { parent::__construct($config); - } catch (\Zend_Db_Adapter_Exception $e) { + } catch (Zend_Db_Adapter_Exception $e) { throw new \InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } } @@ -375,8 +384,8 @@ public function convertDateTime($datetime) * @SuppressWarnings(PHPMD.NPathComplexity) * * @return void - * @throws \Zend_Db_Adapter_Exception - * @throws \Zend_Db_Statement_Exception + * @throws Zend_Db_Adapter_Exception + * @throws Zend_Db_Statement_Exception */ protected function _connect() { @@ -385,15 +394,15 @@ protected function _connect() } if (!extension_loaded('pdo_mysql')) { - throw new \Zend_Db_Adapter_Exception('pdo_mysql extension is not installed'); + throw new Zend_Db_Adapter_Exception('pdo_mysql extension is not installed'); } if (!isset($this->_config['host'])) { - throw new \Zend_Db_Adapter_Exception('No host configured to connect'); + throw new Zend_Db_Adapter_Exception('No host configured to connect'); } if (isset($this->_config['port'])) { - throw new \Zend_Db_Adapter_Exception('Port must be configured within host parameter (like localhost:3306'); + throw new Zend_Db_Adapter_Exception('Port must be configured within host parameter (like localhost:3306'); } unset($this->_config['port']); @@ -464,7 +473,7 @@ public function rawQuery($sql) { try { $result = $this->query($sql); - } catch (\Zend_Db_Statement_Exception $e) { + } catch (Zend_Db_Statement_Exception $e) { // Convert to \PDOException to maintain backwards compatibility with usage of MySQL adapter $e = $e->getPrevious(); if (!($e instanceof \PDOException)) { @@ -507,7 +516,7 @@ public function rawFetchRow($sql, $field = null) * * @param string|\Magento\Framework\DB\Select $sql * @return void - * @throws \Zend_Db_Adapter_Exception + * @throws Zend_Db_Adapter_Exception */ protected function _checkDdlTransaction($sql) { @@ -529,8 +538,8 @@ protected function _checkDdlTransaction($sql) * @param string|\Magento\Framework\DB\Select $sql The SQL statement with placeholders. * @param mixed $bind An array of data or data itself to bind to the placeholders. * @return \Zend_Db_Statement_Pdo|void - * @throws \Zend_Db_Adapter_Exception To re-throw \PDOException. - * @throws \Zend_Db_Statement_Exception + * @throws Zend_Db_Adapter_Exception To re-throw \PDOException. + * @throws Zend_Db_Statement_Exception * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ protected function _query($sql, $bind = []) @@ -561,7 +570,7 @@ protected function _query($sql, $bind = []) $pdoException = null; if ($e instanceof \PDOException) { $pdoException = $e; - } elseif (($e instanceof \Zend_Db_Statement_Exception) + } elseif (($e instanceof Zend_Db_Statement_Exception) && ($e->getPrevious() instanceof \PDOException) ) { $pdoException = $e->getPrevious(); @@ -584,7 +593,7 @@ protected function _query($sql, $bind = []) // rethrow custom exception if needed if ($pdoException && isset($this->exceptionMap[$pdoException->errorInfo[1]])) { $customExceptionClass = $this->exceptionMap[$pdoException->errorInfo[1]]; - /** @var \Zend_Db_Adapter_Exception $customException */ + /** @var Zend_Db_Adapter_Exception $customException */ $customException = new $customExceptionClass($e->getMessage(), $pdoException->errorInfo[1], $e); throw $customException; } @@ -602,7 +611,7 @@ protected function _query($sql, $bind = []) * @param string|\Magento\Framework\DB\Select $sql The SQL statement with placeholders. * @param mixed $bind An array of data or data itself to bind to the placeholders. * @return \Zend_Db_Statement_Pdo|void - * @throws \Zend_Db_Adapter_Exception To re-throw \PDOException. + * @throws Zend_Db_Adapter_Exception To re-throw \PDOException. * @throws LocalizedException In case multiple queries are attempted at once, to protect from SQL injection * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ @@ -627,7 +636,7 @@ public function query($sql, $bind = []) * @param string|\Magento\Framework\DB\Select $sql The SQL statement with placeholders. * @param mixed $bind An array of data or data itself to bind to the placeholders. * @return \Zend_Db_Statement_Pdo|void - * @throws \Zend_Db_Adapter_Exception To re-throw \PDOException. + * @throws Zend_Db_Adapter_Exception To re-throw \PDOException. * @throws LocalizedException In case multiple queries are attempted at once, to protect from SQL injection * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @deprecated 100.2.0 @@ -1175,6 +1184,9 @@ public function modifyColumn($tableName, $columnName, $definition, $flushData = * @param string $tableName * @param string $schemaName * @return mixed + * @throws LocalizedException + * @throws Zend_Db_Adapter_Exception + * @throws Zend_Db_Statement_Exception */ public function showTableStatus($tableName, $schemaName = null) { @@ -1183,8 +1195,32 @@ public function showTableStatus($tableName, $schemaName = null) $fromDbName = ' FROM ' . $this->quoteIdentifier($schemaName); } $query = sprintf('SHOW TABLE STATUS%s LIKE %s', $fromDbName, $this->quote($tableName)); + //checks which slq engine used + if (!$this->isMysql8EngineUsed()) { + //if it's not MySQl-8 we just fetch results + return $this->rawFetchRow($query); + } + // Run show table status query in different connection because DDL queries do it in transaction, + // and we don't have actual table statistic in this case + $connection = $this->_transactionLevel ? $this->createConnection() : $this; + $connection->query(sprintf('ANALYZE TABLE %s', $this->quoteIdentifier($tableName))); + + return $connection->query($query)->fetch(\PDO::FETCH_ASSOC); + } + + /** + * Checks if the engine is mysql 8 + * + * @return bool + */ + private function isMysql8EngineUsed(): bool + { + if (!$this->isMysql8Engine) { + $version = $this->fetchPairs("SHOW variables LIKE 'version'")['version']; + $this->isMysql8Engine = (bool) preg_match('/^(8\.)/', $version); + } - return $this->rawFetchRow($query); + return $this->isMysql8Engine; } /** diff --git a/lib/internal/Magento/Framework/DB/Adapter/SqlVersionProvider.php b/lib/internal/Magento/Framework/DB/Adapter/SqlVersionProvider.php new file mode 100644 index 0000000000000..def51db16454d --- /dev/null +++ b/lib/internal/Magento/Framework/DB/Adapter/SqlVersionProvider.php @@ -0,0 +1,119 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + */ +declare(strict_types=1); + +namespace Magento\Framework\DB\Adapter; + +use Magento\Framework\App\ResourceConnection; + +/** + * Class GetDbVersion provides sql engine version requesting version variable + * + * Rather then depending on this class, please implement this logic in your extension + */ +class SqlVersionProvider +{ + /**#@+ + * Database version specific templates + */ + public const MYSQL_8_0_VERSION = '8.0.'; + + public const MYSQL_5_7_VERSION = '5.7.'; + + public const MARIA_DB_10_VERSION = '10.'; + + /**#@-*/ + + /** + * Database version variable name + */ + private const VERSION_VAR_NAME = 'version'; + + /** + * @var ResourceConnection + */ + private $resourceConnection; + + /** + * @var string + */ + private $version; + + /** + * @var array + */ + private $supportedVersionPatterns; + + /** + * @param ResourceConnection $resourceConnection + * @param array $supportedVersionPatterns + */ + public function __construct( + ResourceConnection $resourceConnection, + array $supportedVersionPatterns = [] + ) { + $this->resourceConnection = $resourceConnection; + $this->supportedVersionPatterns = $supportedVersionPatterns; + } + + /** + * Provides SQL engine version (MariaDB, MySQL-8, MySQL-5.7) + * + * @param string $resource + * + * @return string + * @throws ConnectionException + */ + public function getSqlVersion(string $resource = ResourceConnection::DEFAULT_CONNECTION): string + { + if (!$this->version) { + $this->version = $this->getVersionString($resource); + } + + return $this->version; + } + + /** + * Provides Sql Engine Version string + * + * @param string $resource + * + * @return string + * @throws ConnectionException + */ + private function getVersionString(string $resource): string + { + $pattern = sprintf('/(%s)/', implode('|', $this->supportedVersionPatterns)); + $sqlVersionOutput = $this->fetchSqlVersion($resource); + preg_match($pattern, $sqlVersionOutput, $match); + if (empty($match)) { + throw new ConnectionException( + sprintf( + "Current version of RDBMS is not supported. Used Version: %s. Supported versions: %s", + $sqlVersionOutput, + implode(', ', array_keys($this->supportedVersionPatterns)) + ) + ); + } + + return reset($match); + } + + /** + * Fetch version from sql engine + * + * @param string $resource + * + * @return string + */ + private function fetchSqlVersion(string $resource): string + { + $versionOutput = $this->resourceConnection->getConnection($resource) + ->fetchPairs(sprintf('SHOW variables LIKE "%s"', self::VERSION_VAR_NAME)); + + return $versionOutput[self::VERSION_VAR_NAME]; + } +} diff --git a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/DefinitionAggregator.php b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/DefinitionAggregator.php index c1d3f9ebee751..57f49d62028d0 100644 --- a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/DefinitionAggregator.php +++ b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/DefinitionAggregator.php @@ -3,10 +3,11 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Framework\Setup\Declaration\Schema\Db; -use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\SqlVersionProvider; use Magento\Framework\Setup\Declaration\Schema\Dto\ElementInterface; /** @@ -20,27 +21,22 @@ class DefinitionAggregator implements DbDefinitionProcessorInterface private $definitionProcessors; /** - * @var ResourceConnection + * @var SqlVersionProvider */ - private $resourceConnection; - - /** - * @var string - */ - private $dbVersion; + private $sqlVersionProvider; /** * Constructor. * - * @param ResourceConnection $resourceConnection + * @param SqlVersionProvider $sqlVersionProvider * @param DbDefinitionProcessorInterface[] $definitionProcessors */ public function __construct( - ResourceConnection $resourceConnection, + SqlVersionProvider $sqlVersionProvider, array $definitionProcessors ) { $this->definitionProcessors = $definitionProcessors; - $this->resourceConnection = $resourceConnection; + $this->sqlVersionProvider = $sqlVersionProvider; } /** @@ -79,21 +75,6 @@ public function fromDefinition(array $data) return $definitionProcessor->fromDefinition($data); } - /** - * Get DB version - * - * @return string - */ - private function getDatabaseVersion(): string - { - if (!$this->dbVersion) { - $this->dbVersion = $this->resourceConnection->getConnection('default') - ->fetchPairs("SHOW variables LIKE 'version'")['version']; - } - - return $this->dbVersion; - } - /** * Processes `$value` to be compatible with MySQL. * @@ -109,7 +90,7 @@ protected function processDefaultValue(array $data) if ($defaultValue === "'NULL'") { return "NULL"; } - if ($defaultValue === "NULL" && strpos($this->getDatabaseVersion(), 'MariaDB') !== false) { + if ($defaultValue === "NULL" && $this->isMariaDbSqlConnection()) { return null; } /* @@ -129,4 +110,17 @@ protected function processDefaultValue(array $data) return $defaultValue; } + + /** + * Checks if MariaDB used as SQL engine + * + * @return bool + */ + private function isMariaDbSqlConnection(): bool + { + return strpos( + $this->sqlVersionProvider->getSqlVersion(), + SqlVersionProvider::MARIA_DB_10_VERSION + ) === 0; + } } diff --git a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/DbSchemaReader.php b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/DbSchemaReader.php index a95b1812e68f9..d8c85ea9e206d 100644 --- a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/DbSchemaReader.php +++ b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/DbSchemaReader.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Framework\Setup\Declaration\Schema\Db\MySQL; diff --git a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/DbSchemaWriter.php b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/DbSchemaWriter.php index 65998e7541111..94e8e5642cad0 100644 --- a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/DbSchemaWriter.php +++ b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/DbSchemaWriter.php @@ -61,9 +61,9 @@ class DbSchemaWriter implements DbSchemaWriterInterface /** * @param ResourceConnection $resourceConnection - * @param StatementFactory $statementFactory - * @param DryRunLogger $dryRunLogger - * @param array $tableOptions + * @param StatementFactory $statementFactory + * @param DryRunLogger $dryRunLogger + * @param array $tableOptions */ public function __construct( ResourceConnection $resourceConnection, @@ -101,8 +101,6 @@ public function createTable($tableName, $resource, array $definition, array $opt } /** - * Drop table from MySQL database. - * * @inheritdoc */ public function dropTable($tableName, $resource) @@ -127,24 +125,34 @@ public function dropTable($tableName, $resource) */ private function getDropElementSQL($type, $name) { + $result = sprintf('DROP COLUMN %s', $name); switch ($type) { case Constraint::PRIMARY_TYPE: - return 'DROP PRIMARY KEY'; + $result = 'DROP PRIMARY KEY'; + break; case Constraint::UNIQUE_TYPE: - return sprintf('DROP KEY %s', $name); + $result = sprintf('DROP KEY %s', $name); + break; case \Magento\Framework\Setup\Declaration\Schema\Dto\Index::TYPE: - return sprintf('DROP INDEX %s', $name); + $result = sprintf('DROP INDEX %s', $name); + break; case Reference::TYPE: - return sprintf('DROP FOREIGN KEY %s', $name); - default: - return sprintf('DROP COLUMN %s', $name); + $result = sprintf('DROP FOREIGN KEY %s', $name); + break; } + + return $result; } /** - * Add element to existing table: column, constraint or index. - * * @inheritdoc + * + * @param string $elementName + * @param string $resource + * @param string $tableName + * @param string $elementDefinition , for example: like CHAR(200) NOT NULL + * @param string $elementType + * @return Statement */ public function addElement($elementName, $resource, $tableName, $elementDefinition, $elementType) { @@ -165,6 +173,12 @@ public function addElement($elementName, $resource, $tableName, $elementDefiniti /** * @inheritdoc + * + * @param string $tableName + * @param string $resource + * @param string $optionName + * @param string $optionValue + * @return Statement */ public function modifyTableOption($tableName, $resource, $optionName, $optionValue) { @@ -178,9 +192,13 @@ public function modifyTableOption($tableName, $resource, $optionName, $optionVal } /** - * Modify column and change its definition. - * * @inheritdoc + * + * @param string $columnName + * @param string $resource + * @param string $tableName + * @param string $columnDefinition + * @return Statement */ public function modifyColumn($columnName, $resource, $tableName, $columnDefinition) { @@ -199,6 +217,12 @@ public function modifyColumn($columnName, $resource, $tableName, $columnDefiniti /** * @inheritdoc + * + * @param string $resource + * @param string $elementName + * @param string $tableName + * @param string $type + * @return Statement */ public function dropElement($resource, $elementName, $tableName, $type) { @@ -243,7 +267,11 @@ public function compile(StatementAggregator $statementAggregator, $dryRun) { foreach ($statementAggregator->getStatementsBank() as $statementBank) { $statementsSql = []; - /** @var Statement $statement */ + $statement = null; + + /** + * @var Statement $statement + */ foreach ($statementBank as $statement) { $statementsSql[] = $statement->getStatement(); } diff --git a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/Boolean.php b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/Boolean.php index 5b8c5e2d4a60b..c80b8ddba8032 100644 --- a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/Boolean.php +++ b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/Boolean.php @@ -66,6 +66,8 @@ public function __construct( } /** + * Get definition for given column. + * * @param \Magento\Framework\Setup\Declaration\Schema\Dto\Columns\Boolean $column * @inheritdoc */ @@ -85,11 +87,17 @@ public function toDefinition(ElementInterface $column) /** * Boolean is presented as tinyint(1). * - * @inheritdoc + * @param array $data + * @return array */ public function fromDefinition(array $data) { - if ($data['type'] === self::INTEGER_TYPE && $data['padding'] === self::INTEGER_PADDING) { + if ($data['type'] === self::INTEGER_TYPE && + ( + array_key_exists('padding', $data) && + $data['padding'] === self::INTEGER_PADDING + ) + ) { $data['type'] = strtolower(self::TYPE); if (isset($data['default'])) { $data['default'] = $data['default'] === null ? null : (bool) $data['default']; diff --git a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/Integer.php b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/Integer.php index 1d08c5bea4eb0..fcebb549a2e56 100644 --- a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/Integer.php +++ b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/Integer.php @@ -81,11 +81,15 @@ public function __construct( */ public function toDefinition(ElementInterface $column) { - return sprintf( - '%s %s(%s) %s %s %s %s %s', + $definition = sprintf( + '%s %s', $this->resourceConnection->getConnection()->quoteIdentifier($column->getName()), - $column->getType(), - $column->getPadding(), + $column->getType() + ); + + return sprintf( + '%s %s %s %s %s %s', + $definition, $this->unsigned->toDefinition($column), $this->nullable->toDefinition($column), $column->getDefault() !== null ? @@ -101,13 +105,18 @@ public function toDefinition(ElementInterface $column) public function fromDefinition(array $data) { $matches = []; - if (preg_match('/^(big|small|tiny|medium)?int\((\d+)\)/', $data['definition'], $matches)) { - /** - * match[1] - prefix - * match[2] - padding, like 5 or 11 - */ - //Use shortcut for mediuminteger - $data['padding'] = $matches[2]; + if (preg_match( + '/^(?<type>(?:big|small|tiny|medium)?int)(?:\((?<padding>\d+)\))?/', + $data['definition'], + $matches + )) { + // we have an agreement that tinyint(1) is Boolean + if (isset($matches['padding']) + && $matches['type'] === 'tinyint' + && $matches['padding'] === '1' + ) { + $data['padding'] = $matches['padding']; + } $data = $this->unsigned->fromDefinition($data); $data = $this->nullable->fromDefinition($data); $data = $this->identity->fromDefinition($data); diff --git a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/OnUpdate.php b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/OnUpdate.php index 187f710b40edf..3be8704b378d9 100644 --- a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/OnUpdate.php +++ b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/OnUpdate.php @@ -17,6 +17,8 @@ class OnUpdate implements DbDefinitionProcessorInterface { /** + * Get definition for given column. + * * @param \Magento\Framework\Setup\Declaration\Schema\Dto\Columns\Timestamp $column * @inheritdoc */ @@ -36,7 +38,7 @@ public function toDefinition(ElementInterface $column) public function fromDefinition(array $data) { $matches = []; - if (preg_match('/^(?:on update)\s([\_\-\s\w\d]+)/', $data['extra'], $matches)) { + if (preg_match('/(?:on update)\s([\_\-\s\w\d]+)/', $data['extra'], $matches)) { $data['on_update'] = true; } diff --git a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/StringBinary.php b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/StringBinary.php index c2fd270a8f949..ace3f81e0f453 100644 --- a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/StringBinary.php +++ b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/MySQL/Definition/Columns/StringBinary.php @@ -16,6 +16,16 @@ */ class StringBinary implements DbDefinitionProcessorInterface { + /** + * Constant to define the binary data types. + */ + private const BINARY_TYPES = ['binary', 'varbinary']; + + /** + * Constant to define the char data types. + */ + private const CHAR_TYPES = ['char', 'varchar']; + /** * @var Nullable */ @@ -44,6 +54,8 @@ public function __construct(Nullable $nullable, ResourceConnection $resourceConn } /** + * Get definition for given column. + * * @param \Magento\Framework\Setup\Declaration\Schema\Dto\Columns\StringBinary $column * @inheritdoc */ @@ -71,11 +83,47 @@ public function toDefinition(ElementInterface $column) */ public function fromDefinition(array $data) { - $matches = []; - if (preg_match('/^(char|binary|varchar|varbinary)\s*\((\d+)\)/', $data['definition'], $matches)) { - $data['length'] = $matches[2]; + preg_match($this->getStringBinaryPattern(), $data['definition'], $matches); + + if (array_key_exists('padding', $matches) && !empty($matches['padding'])) { + $data['length'] = $matches['padding']; + } + + if (!isset($data['default'])) { + return $data; + } + + $isHex = preg_match('`^0x([a-f0-9]+)$`i', $data['default'], $hexMatches); + + if ($this->isBinaryHex($matches['type'], (bool)$isHex)) { + $data['default'] = hex2bin($hexMatches[1]); } return $data; } + + /** + * Get the pattern to identify binary and char types. + * + * @return string + */ + private function getStringBinaryPattern(): string + { + return sprintf( + '/^(?<type>%s)\s*\(?(?<padding>\d*)\)?/', + implode('|', array_merge(self::CHAR_TYPES, self::BINARY_TYPES)) + ); + } + + /** + * Check if the type is binary and the value is a hex value. + * + * @param string $type + * @param bool $isHex + * @return bool + */ + private function isBinaryHex($type, bool $isHex): bool + { + return in_array($type, self::BINARY_TYPES) && $isHex; + } } diff --git a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/SchemaBuilder.php b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/SchemaBuilder.php index f7a2a0d91396d..1e60ab407d61a 100644 --- a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/SchemaBuilder.php +++ b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Db/SchemaBuilder.php @@ -3,16 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Framework\Setup\Declaration\Schema\Db; +use Magento\Framework\Exception\NotFoundException; use Magento\Framework\Phrase; use Magento\Framework\Setup\Declaration\Schema\Dto\Column; use Magento\Framework\Setup\Declaration\Schema\Dto\ElementFactory; use Magento\Framework\Setup\Declaration\Schema\Dto\Schema; use Magento\Framework\Setup\Declaration\Schema\Dto\Table; use Magento\Framework\Setup\Declaration\Schema\Sharding; -use Magento\Framework\Setup\Exception; /** * This type of builder is responsible for converting ENTIRE data, that comes from db @@ -50,9 +51,9 @@ class SchemaBuilder /** * Constructor. * - * @param ElementFactory $elementFactory + * @param ElementFactory $elementFactory * @param DbSchemaReaderInterface $dbSchemaReader - * @param Sharding $sharding + * @param Sharding $sharding */ public function __construct( ElementFactory $elementFactory, @@ -131,8 +132,8 @@ public function build(Schema $schema) /** * Process references for all tables. Schema validation required. * - * @param Table[] $tables - * @param Schema $schema + * @param Table[] $tables + * @param Schema $schema */ private function processReferenceKeys(array $tables, Schema $schema) { @@ -170,15 +171,15 @@ private function processReferenceKeys(array $tables, Schema $schema) /** * Retrieve column objects from names. * - * @param Column[] $columns - * @param array $data - * @return Column[] - * @throws Exception + * @param Column[] $columns + * @param array $data + * @return Column[] + * @throws NotFoundException */ private function resolveInternalRelations(array $columns, array $data) { if (!is_array($data['column'])) { - throw new Exception( + throw new NotFoundException( new Phrase("Cannot find columns for internal index") ); } @@ -188,7 +189,7 @@ private function resolveInternalRelations(array $columns, array $data) if (!isset($columns[$columnName])) { $tableName = isset($data['table']) ? $data['table']->getName() : ''; trigger_error( - new Phrase( + (string)new Phrase( 'Column %1 does not exist for index/constraint %2 in table %3.', [ $columnName, diff --git a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Declaration/SchemaBuilder.php b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Declaration/SchemaBuilder.php index 4c65d8a70bed5..d423e47c50c13 100644 --- a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Declaration/SchemaBuilder.php +++ b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Declaration/SchemaBuilder.php @@ -7,10 +7,9 @@ namespace Magento\Framework\Setup\Declaration\Schema\Declaration; +use Magento\Framework\App\ResourceConnection; use Magento\Framework\Phrase; use Magento\Framework\Setup\Declaration\Schema\Declaration\TableElement\ElementNameResolver; -use Magento\Framework\Stdlib\BooleanUtils; -use Magento\Framework\Setup\Exception; use Magento\Framework\Setup\Declaration\Schema\Dto\Column; use Magento\Framework\Setup\Declaration\Schema\Dto\Constraint; use Magento\Framework\Setup\Declaration\Schema\Dto\ElementFactory; @@ -18,6 +17,9 @@ use Magento\Framework\Setup\Declaration\Schema\Dto\Schema; use Magento\Framework\Setup\Declaration\Schema\Dto\Table; use Magento\Framework\Setup\Declaration\Schema\Sharding; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Stdlib\BooleanUtils; +use Magento\Framework\Validation\ValidationException; /** * This type of builder is responsible for converting ENTIRE data, that comes from XML into DTO`s format. @@ -64,7 +66,7 @@ class SchemaBuilder private $validationComposite; /** - * @var \Magento\Framework\App\ResourceConnection + * @var ResourceConnection */ private $resourceConnection; @@ -76,11 +78,11 @@ class SchemaBuilder /** * SchemaBuilder constructor. * - * @param ElementFactory $elementFactory - * @param BooleanUtils $booleanUtils - * @param Sharding $sharding - * @param ValidationComposite $validationComposite - * @param \Magento\Framework\App\ResourceConnection $resourceConnection + * @param ElementFactory $elementFactory + * @param BooleanUtils $booleanUtils + * @param Sharding $sharding + * @param ValidationComposite $validationComposite + * @param ResourceConnection $resourceConnection * @param ElementNameResolver $elementNameResolver */ public function __construct( @@ -88,7 +90,7 @@ public function __construct( BooleanUtils $booleanUtils, Sharding $sharding, ValidationComposite $validationComposite, - \Magento\Framework\App\ResourceConnection $resourceConnection, + ResourceConnection $resourceConnection, ElementNameResolver $elementNameResolver ) { $this->sharding = $sharding; @@ -116,8 +118,8 @@ public function addTablesData(array $tablesData) /** * Do schema validation and print all errors. * - * @param Schema $schema - * @throws Exception + * @param Schema $schema + * @throws LocalizedException */ private function validate(Schema $schema) { @@ -129,16 +131,16 @@ private function validate(Schema $schema) $messages .= sprintf("%s%s", PHP_EOL, $error['message']); } - throw new Exception(new Phrase($messages)); + throw new LocalizedException(new Phrase($messages)); } } /** * Build schema. * - * @param Schema $schema - * @throws Exception + * @param Schema $schema * @return Schema + * @throws ValidationException */ public function build(Schema $schema): Schema { @@ -184,10 +186,10 @@ private function isDisabled(array $structuralElementData): bool * * If column was renamed new key will be associated to it. * - * @param array $tableData - * @param string $resource - * @param Table $table - * @return array + * @param array $tableData + * @param string $resource + * @param Table $table + * @return array */ private function processColumns(array $tableData, string $resource, Table $table): array { @@ -209,10 +211,10 @@ private function processColumns(array $tableData, string $resource, Table $table /** * Process generic data that is support by all 3 child types: columns, constraints, indexes. * - * @param array $elementData - * @param string $resource - * @param Table $table - * @return array + * @param array $elementData + * @param string $resource + * @param Table $table + * @return array */ private function processGenericData(array $elementData, string $resource, Table $table): array { @@ -327,11 +329,11 @@ private function processIndexes(array $tableData, string $resource, Table $table /** * Convert and instantiate constraint objects. * - * @param array $tableData - * @param string $resource - * @param Schema $schema - * @param Table $table - * @return Constraint[] + * @param array $tableData + * @param string $resource + * @param Schema $schema + * @param Table $table + * @return Constraint[] */ private function processConstraints(array $tableData, string $resource, Schema $schema, Table $table): array { diff --git a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Dto/Columns/Integer.php b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Dto/Columns/Integer.php index 5c0c89dd0b4b8..401c2ad7c4f78 100644 --- a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Dto/Columns/Integer.php +++ b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Dto/Columns/Integer.php @@ -64,7 +64,7 @@ public function __construct( string $name, string $type, Table $table, - int $padding, + int $padding = null, bool $nullable = true, bool $unsigned = false, bool $identity = false, @@ -83,7 +83,7 @@ public function __construct( /** * Column padding. * - * @return int + * @return int | null */ public function getPadding() { @@ -102,6 +102,7 @@ public function isNullable() /** * Return default value. + * * Note: default value should be int. * * @return int | null diff --git a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Dto/Factories/Integer.php b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Dto/Factories/Integer.php index b35e2c9864e83..e2d43a33dd1f2 100644 --- a/lib/internal/Magento/Framework/Setup/Declaration/Schema/Dto/Factories/Integer.php +++ b/lib/internal/Magento/Framework/Setup/Declaration/Schema/Dto/Factories/Integer.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Framework\Setup\Declaration\Schema\Dto\Factories; @@ -13,18 +14,6 @@ */ class Integer implements FactoryInterface { - /** - * Describe default for different integer types. - * - * @var array - */ - private static $defaultPadding = [ - 'int' => '11', - 'tinyint' => '2', - 'smallint' => '5', - 'bigint' => '20' - ]; - /** * @var ObjectManagerInterface */ @@ -38,8 +27,8 @@ class Integer implements FactoryInterface /** * Constructor. * - * @param ObjectManagerInterface $objectManager - * @param string $className + * @param ObjectManagerInterface $objectManager + * @param string $className */ public function __construct( ObjectManagerInterface $objectManager, @@ -54,9 +43,8 @@ public function __construct( */ public function create(array $data) { - if (!isset($data['padding'])) { - $data['padding'] = self::$defaultPadding[$data['type']]; - } + unset($data['padding']); + //Auto increment field can`t be null if (isset($data['identity']) && $data['identity']) { $data['nullable'] = false; diff --git a/lib/internal/Magento/Framework/Setup/Declaration/Schema/etc/types/integers/integer.xsd b/lib/internal/Magento/Framework/Setup/Declaration/Schema/etc/types/integers/integer.xsd index ff68beb27191d..037cd8e086862 100644 --- a/lib/internal/Magento/Framework/Setup/Declaration/Schema/etc/types/integers/integer.xsd +++ b/lib/internal/Magento/Framework/Setup/Declaration/Schema/etc/types/integers/integer.xsd @@ -27,8 +27,8 @@ <xs:attribute name="padding"> <xs:annotation> <xs:documentation> - We can use padding only from 2, because padding 1 used for boolean type. - And we need to distinguish boolean and integer + This attribute is deprecated and the value is ignored. + See https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-19.html. </xs:documentation> </xs:annotation> <xs:simpleType> diff --git a/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Db/MySQL/Definition/Columns/IntegerTest.php b/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Db/MySQL/Definition/Columns/IntegerTest.php index d9a3ce02b1177..d60f4cba56629 100644 --- a/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Db/MySQL/Definition/Columns/IntegerTest.php +++ b/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Db/MySQL/Definition/Columns/IntegerTest.php @@ -145,7 +145,7 @@ public function testToDefinition() ->with($column) ->willReturn('COMMENT "Comment"'); $this->assertEquals( - '`int_column` int(10) UNSIGNED NOT NULL DEFAULT 0 AUTO_INCREMENT COMMENT "Comment"', + '`int_column` int UNSIGNED NOT NULL DEFAULT 0 AUTO_INCREMENT COMMENT "Comment"', $this->integer->toDefinition($column) ); } @@ -180,13 +180,15 @@ public function definitionDataProvider() { return [ ['int'], - ['int(10)', 10], + ['int(10)'], ['tinyint'], - ['mediumint(5)', 5], + ['tinyint(1)', 1], + ['tinyint(2)'], + ['mediumint(5)'], ['mediumint'], - ['smallint(3)', 3], + ['smallint(3)'], ['smallint'], - ['bigint(10)', 10], + ['bigint(10)'], ['bigint'], ]; } diff --git a/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Db/MySQL/Definition/Columns/StringBinaryTest.php b/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Db/MySQL/Definition/Columns/StringBinaryTest.php index 16200f600bf4b..202aeae58e903 100644 --- a/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Db/MySQL/Definition/Columns/StringBinaryTest.php +++ b/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Db/MySQL/Definition/Columns/StringBinaryTest.php @@ -113,6 +113,24 @@ public function testToDefinition() ); } + /** + * @param array $definition + * @param bool $expectedLength + * @dataProvider definitionDataProvider() + */ + public function testGetBinaryDefaultValueFromDefinition($definition) + { + $defaultValue = 'test'; + if (preg_match('/^(binary|varbinary)/', $definition)) { + $default = '0x' . bin2hex($defaultValue); + } else { + $default = $defaultValue; + } + + $result = $this->stringBinary->fromDefinition(['definition' => $definition, 'default' => $default]); + $this->assertEquals($result['default'], $defaultValue); + } + /** * Test from definition conversion. * diff --git a/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Db/SchemaBuilderTest.php b/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Db/SchemaBuilderTest.php index 508d3786652b5..f7b893c8d06e2 100644 --- a/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Db/SchemaBuilderTest.php +++ b/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Db/SchemaBuilderTest.php @@ -8,6 +8,8 @@ namespace Magento\Framework\Setup\Test\Unit\Declaration\Schema\Db; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\SqlVersionProvider; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\Setup\Declaration\Schema\Db\DbSchemaReaderInterface; use Magento\Framework\Setup\Declaration\Schema\Db\SchemaBuilder; use Magento\Framework\Setup\Declaration\Schema\Dto\Columns\Integer; @@ -19,7 +21,6 @@ use Magento\Framework\Setup\Declaration\Schema\Dto\Schema; use Magento\Framework\Setup\Declaration\Schema\Dto\Table; use Magento\Framework\Setup\Declaration\Schema\Sharding; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use PHPUnit\Framework\Exception; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -27,7 +28,6 @@ /** * Test for SchemaBuilder. * - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class SchemaBuilderTest extends TestCase @@ -57,6 +57,11 @@ class SchemaBuilderTest extends TestCase */ private $shardingMock; + /** + * @var \PHPUnit\Framework\MockObject\MockObject|\Magento\Framework\DB\Adapter\SqlVersionProvider + */ + private $sqlVersionProvider; + protected function setUp(): void { $this->elementFactoryMock = $this->getMockBuilder(ElementFactory::class) @@ -67,6 +72,9 @@ protected function setUp(): void $this->shardingMock = $this->getMockBuilder(Sharding::class) ->disableOriginalConstructor() ->getMock(); + $this->sqlVersionProvider = $this->getMockBuilder(SqlVersionProvider::class) + ->disableOriginalConstructor() + ->getMock(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( @@ -74,7 +82,8 @@ protected function setUp(): void [ 'elementFactory' => $this->elementFactoryMock, 'dbSchemaReader' => $this->dbSchemaReaderMock, - 'sharding' => $this->shardingMock + 'sharding' => $this->shardingMock, + 'getDbVersion' => $this->sqlVersionProvider ] ); } @@ -105,8 +114,7 @@ public function dataProvider() 'second_column' => [ 'name' => 'second_column', 'type' => 'timestamp', - 'default' => 'CURRENT_TIMESTAMP', - 'on_update' => true + 'default' => 'CURRENT_TIMESTAMP' ], ], 'second_table' => [ @@ -408,7 +416,7 @@ private function prepareSchemaMocks(array $columns, array $references, array $co 'table' => $table, 'padding' => 10, 'identity' => true, - 'nullable' => false, + 'nullable' => false ] ], [ @@ -418,7 +426,7 @@ private function prepareSchemaMocks(array $columns, array $references, array $co 'type' => 'int', 'table' => $table, 'padding' => 10, - 'nullable' => false, + 'nullable' => false ] ], [ @@ -427,8 +435,7 @@ private function prepareSchemaMocks(array $columns, array $references, array $co 'name' => 'second_column', 'type' => 'timestamp', 'table' => $table, - 'default' => 'CURRENT_TIMESTAMP', - 'on_update' => true, + 'default' => 'CURRENT_TIMESTAMP' ] ], [ @@ -460,7 +467,7 @@ private function prepareSchemaMocks(array $columns, array $references, array $co 'type' => 'int', 'table' => $refTable, 'padding' => 10, - 'nullable' => false, + 'nullable' => false ] ], [ diff --git a/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Declaration/SchemaBuilderTest.php b/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Declaration/SchemaBuilderTest.php index 2f6ec097913dd..28cb8e58fcc43 100644 --- a/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Declaration/SchemaBuilderTest.php +++ b/lib/internal/Magento/Framework/Setup/Test/Unit/Declaration/Schema/Declaration/SchemaBuilderTest.php @@ -8,6 +8,10 @@ namespace Magento\Framework\Setup\Test\Unit\Declaration\Schema\Declaration; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\SqlVersionProvider; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Stdlib\BooleanUtils; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Magento\Framework\Setup\Declaration\Schema\Declaration\SchemaBuilder; use Magento\Framework\Setup\Declaration\Schema\Declaration\ValidationComposite; use Magento\Framework\Setup\Declaration\Schema\Dto\Columns\Integer; @@ -19,16 +23,12 @@ use Magento\Framework\Setup\Declaration\Schema\Dto\Schema; use Magento\Framework\Setup\Declaration\Schema\Dto\Table; use Magento\Framework\Setup\Declaration\Schema\Sharding; -use Magento\Framework\Setup\Exception; -use Magento\Framework\Stdlib\BooleanUtils; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; /** * Test for SchemaBuilder. * - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class SchemaBuilderTest extends TestCase @@ -68,6 +68,11 @@ class SchemaBuilderTest extends TestCase */ private $resourceConnectionMock; + /** + * @var SqlVersionProvider|\PHPUnit\Framework\MockObject\MockObject + */ + private $sqlVersionProvider; + protected function setUp(): void { $this->elementFactoryMock = $this->getMockBuilder(ElementFactory::class) @@ -85,6 +90,9 @@ protected function setUp(): void $this->resourceConnectionMock = $this->getMockBuilder(ResourceConnection::class) ->disableOriginalConstructor() ->getMock(); + $this->sqlVersionProvider = $this->getMockBuilder(SqlVersionProvider::class) + ->disableOriginalConstructor() + ->getMock(); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->model = $this->objectManagerHelper->getObject( @@ -94,7 +102,8 @@ protected function setUp(): void 'booleanUtils' => new BooleanUtils(), 'sharding' => $this->shardingMock, 'validationComposite' => $this->validationCompositeMock, - 'resourceConnection' => $this->resourceConnectionMock + 'resourceConnection' => $this->resourceConnectionMock, + 'sqlVersionProvider' => $this->sqlVersionProvider ] ); } @@ -302,7 +311,7 @@ private function createTimestampColumn($name, Table $table) * @dataProvider tablesProvider * @param array $tablesData * @SuppressWarnings(PHPMD.ExcessiveMethodLength) - * @throws Exception + * @throws LocalizedException */ public function testBuild(array $tablesData) { diff --git a/lib/internal/Magento/Framework/Test/Unit/DB/Adapter/SqlVersionProviderTest.php b/lib/internal/Magento/Framework/Test/Unit/DB/Adapter/SqlVersionProviderTest.php new file mode 100644 index 0000000000000..13fbf30c99de8 --- /dev/null +++ b/lib/internal/Magento/Framework/Test/Unit/DB/Adapter/SqlVersionProviderTest.php @@ -0,0 +1,159 @@ +<?php +/** + * Copyright © Magento, Inc. All rights reserved. + * See COPYING.txt for license details. + * @noinspection PhpDeprecationInspection + */ +declare(strict_types=1); + +namespace Magento\Framework\Test\Unit\DB\Adapter; + +use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\ConnectionException; +use Magento\Framework\DB\Adapter\Pdo\Mysql; +use Magento\Framework\DB\Adapter\SqlVersionProvider; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use PHPUnit\Framework\MockObject\MockBuilder; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; + +/** + * Class SqlVersionProviderTest + * + * Tests SqlVersionProvider + */ +class SqlVersionProviderTest extends TestCase +{ + /** + * @var SqlVersionProvider + */ + private $sqlVersionProvider; + + /** + * @var MockBuilder|ResourceConnection + */ + private $resourceConnection; + + /** + * @var MockObject|Mysql + */ + private $mysqlAdapter; + + /** + * @var ObjectManager + */ + private $objectManager; + + /** + * @var array + */ + private $supportedVersionPatterns = [ + 'MySQL-8' => '^8\.0\.', + 'MySQL-5.7' => '^5\.7\.', + 'MariaDB-(10.2-10.4)' => '^10\.[2-4]\.' + ]; + + /** + * @return void + */ + protected function setUp(): void + { + $this->objectManager = new ObjectManager($this); + $this->resourceConnection = $this->getMockBuilder(ResourceConnection::class) + ->setMethods(['getConnection']) + ->disableOriginalConstructor() + ->getMock(); + $this->mysqlAdapter = $this->getMockBuilder(Mysql::class) + ->setMethods(['fetchPairs']) + ->disableOriginalConstructor() + ->getMock(); + $this->resourceConnection->expects($this->atLeastOnce()) + ->method('getConnection') + ->willReturn($this->mysqlAdapter); + } + + /** + * @dataProvider executeDataProvider + * + * @param array $versionVariableValue + * @param string $expectedResult + * + * @return void + * @throws ConnectionException + */ + public function testGetSqlVersionProviderReturnsRightResponse( + array $versionVariableValue, + string $expectedResult + ): void { + $this->prepareSqlProviderAndMySQLAdapter($versionVariableValue); + $this->assertEquals($expectedResult, $this->sqlVersionProvider->getSqlVersion()); + } + + /** + * @return void + */ + public function testSqlVersionProviderThrowsExceptionWhenNonSupportedEngineUsed(): void + { + $this->prepareSqlProviderAndMySQLAdapter(['version' => '10.5.0-MariaDB-1:10.5.0+maria~bionic']); + $this->expectExceptionMessage('Current version of RDBMS is not supported.'); + $this->expectException(ConnectionException::class); + $this->sqlVersionProvider->getSqlVersion(); + } + + /** + * @return array + */ + public function executeDataProvider(): array + { + return [ + 'MariaDB-10.4' => [ + ['version' => '10.4.12-MariaDB-1:10.4.12+maria~bionic'], + '10.4.' + ], + 'MariaDB-10.2' => [ + ['version' => '10.2.31-MariaDB-1:10.2.31+maria~bionic'], + '10.2.' + ], + 'MySQL-5.7' => [ + ['version' => '5.7.29'], + SqlVersionProvider::MYSQL_5_7_VERSION, + ], + 'MySQL-8' => [ + ['version' => '8.0.19'], + SqlVersionProvider::MYSQL_8_0_VERSION, + ], + 'Percona' => [ + ['version' => '5.7.29-32'], + SqlVersionProvider::MYSQL_5_7_VERSION, + ], + ]; + } + + /** + * @param array $versionVariableValue + * + * @return void + */ + private function prepareSqlProviderAndMySQLAdapter(array $versionVariableValue): void + { + $this->mysqlAdapter->expects($this->atLeastOnce()) + ->method('fetchPairs') + ->willReturn($versionVariableValue); + $this->sqlVersionProvider = $this->objectManager->getObject( + SqlVersionProvider::class, + [ + 'resourceConnection' => $this->resourceConnection, + 'supportedVersionPatterns' => $this->supportedVersionPatterns + ] + ); + } + + /** + * @return void + */ + protected function tearDown(): void + { + unset($this->sqlVersionProvider); + unset($this->mysqlAdapter); + } +} diff --git a/phpserver/README.md b/phpserver/README.md index a7466557310ac..2e8c8f2efd317 100644 --- a/phpserver/README.md +++ b/phpserver/README.md @@ -14,7 +14,7 @@ Without a router script, that is not possible via the php built-in server. ### How to install Magento -Magento's web-based Setup Wizard runs from the `setup` subdirectory, which PHP's built-in web server cannot route. Therefore, you must install Magento using the <a href="https://devdocs.magento.com/guides/v2.3/install-gde/install/cli/install-cli.html" target="_blank">command line</a>. An example follows: +Please read how to install Magento using the <a href="https://devdocs.magento.com/guides/v2.4/install-gde/install/cli/install-cli.html" target="_blank">command line</a>. An example follows: ``` php bin/magento setup:install --base-url=http://127.0.0.1:8082 diff --git a/setup/config/marketplace.config.php b/setup/config/marketplace.config.php deleted file mode 100644 index 6b3d1f8d01612..0000000000000 --- a/setup/config/marketplace.config.php +++ /dev/null @@ -1,7 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -return ['marketplace' => ['check_credentials_url' => 'repo.magento.com']]; diff --git a/setup/config/module.config.php b/setup/config/module.config.php index 7816c8e3599f3..9ed7b9b839131 100644 --- a/setup/config/module.config.php +++ b/setup/config/module.config.php @@ -9,13 +9,6 @@ 'display_not_found_reason' => false, 'display_exceptions' => false, 'doctype' => 'HTML5', - 'not_found_template' => 'error/404', - 'exception_template' => 'error/index', - 'template_map' => [ - 'layout/layout' => __DIR__ . '/../view/layout/layout.phtml', - 'error/404' => __DIR__ . '/../view/error/404.phtml', - 'error/index' => __DIR__ . '/../view/error/index.phtml', - ], 'template_path_stack' => [ 'setup' => __DIR__ . '/../view', ], diff --git a/setup/config/states.disable.config.php b/setup/config/states.disable.config.php deleted file mode 100644 index ba730e68ffea7..0000000000000 --- a/setup/config/states.disable.config.php +++ /dev/null @@ -1,79 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -$base = basename($_SERVER['SCRIPT_FILENAME']); - -return [ - 'navUpdaterTitles' => [ - 'disable' => 'Disable ', - ], - 'navUpdater' => [ - [ - 'id' => 'root.readiness-check-disable', - 'url' => 'readiness-check-disable', - 'templateUrl' => "{$base}/readiness-check-updater", - 'title' => "Readiness \n Check", - 'header' => 'Step 1: Readiness Check', - 'nav' => true, - 'order' => 2, - 'type' => 'disable' - ], - [ - 'id' => 'root.readiness-check-disable.progress', - 'url' => 'readiness-check-disable/progress', - 'templateUrl' => "$base/readiness-check-updater/progress", - 'title' => 'Readiness Check', - 'header' => 'Step 1: Readiness Check', - 'controller' => 'readinessCheckController', - 'nav' => false, - 'order' => 3, - 'type' => 'disable' - ], - [ - 'id' => 'root.create-backup-disable', - 'url' => 'create-backup', - 'templateUrl' => "$base/create-backup", - 'title' => "Create \n Backup", - 'header' => 'Step 2: Create Backup', - 'controller' => 'createBackupController', - 'nav' => true, - 'validate' => true, - 'order' => 4, - 'type' => 'disable' - ], - [ - 'id' => 'root.create-backup-disable.progress', - 'url' => 'create-backup/progress', - 'templateUrl' => "$base/complete-backup/progress", - 'title' => "Create \n Backup", - 'header' => 'Step 2: Create Backup', - 'controller' => 'completeBackupController', - 'nav' => false, - 'order' => 5, - 'type' => 'disable' - ], - [ - 'id' => 'root.start-updater-disable', - 'url' => 'disable', - 'templateUrl' => "$base/start-updater", - 'title' => "Disable", - 'controller' => 'startUpdaterController', - 'header' => 'Step 3: Disable', - 'nav' => true, - 'order' => 6, - 'type' => 'disable' - ], - [ - 'id' => 'root.disable-success', - 'url' => 'disable-success', - 'templateUrl' => "$base/updater-success", - 'controller' => 'updaterSuccessController', - 'order' => 7, - 'main' => true, - 'noMenu' => true - ], - ], -]; diff --git a/setup/config/states.enable.config.php b/setup/config/states.enable.config.php deleted file mode 100644 index 42f4e251c8cc7..0000000000000 --- a/setup/config/states.enable.config.php +++ /dev/null @@ -1,79 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -$base = basename($_SERVER['SCRIPT_FILENAME']); - -return [ - 'navUpdaterTitles' => [ - 'enable' => 'Enable ', - ], - 'navUpdater' => [ - [ - 'id' => 'root.readiness-check-enable', - 'url' => 'readiness-check-enable', - 'templateUrl' => "{$base}/readiness-check-updater", - 'title' => "Readiness \n Check", - 'header' => 'Step 1: Readiness Check', - 'nav' => true, - 'order' => 2, - 'type' => 'enable' - ], - [ - 'id' => 'root.readiness-check-enable.progress', - 'url' => 'readiness-check-enable/progress', - 'templateUrl' => "$base/readiness-check-updater/progress", - 'title' => 'Readiness Check', - 'header' => 'Step 1: Readiness Check', - 'controller' => 'readinessCheckController', - 'nav' => false, - 'order' => 3, - 'type' => 'enable' - ], - [ - 'id' => 'root.create-backup-enable', - 'url' => 'create-backup', - 'templateUrl' => "$base/create-backup", - 'title' => "Create \n Backup", - 'header' => 'Step 2: Create Backup', - 'controller' => 'createBackupController', - 'nav' => true, - 'validate' => true, - 'order' => 4, - 'type' => 'enable' - ], - [ - 'id' => 'root.create-backup-enable.progress', - 'url' => 'create-backup/progress', - 'templateUrl' => "$base/complete-backup/progress", - 'title' => "Create \n Backup", - 'header' => 'Step 2: Create Backup', - 'controller' => 'completeBackupController', - 'nav' => false, - 'order' => 5, - 'type' => 'enable' - ], - [ - 'id' => 'root.start-updater-enable', - 'url' => 'enable', - 'templateUrl' => "$base/start-updater", - 'title' => "Enable Module", - 'controller' => 'startUpdaterController', - 'header' => 'Step 3: Enable Module', - 'nav' => true, - 'order' => 6, - 'type' => 'enable' - ], - [ - 'id' => 'root.enable-success', - 'url' => 'enable-success', - 'templateUrl' => "$base/updater-success", - 'controller' => 'updaterSuccessController', - 'order' => 7, - 'main' => true, - 'noMenu' => true - ], - ], -]; diff --git a/setup/config/states.extensionManager.config.php b/setup/config/states.extensionManager.config.php deleted file mode 100644 index 78e7d8f090324..0000000000000 --- a/setup/config/states.extensionManager.config.php +++ /dev/null @@ -1,75 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -$base = basename($_SERVER['SCRIPT_FILENAME']); - -return [ - 'navUpdaterTitles' => [ - 'install' => 'New Purchases', - ], - 'navUpdater' => [ - [ - 'id' => 'root.readiness-check-install', - 'url' => 'readiness-check-updater', - 'templateUrl' => "{$base}/readiness-check-updater", - 'title' => "Readiness \n Check", - 'header' => 'Step 1: Readiness Check', - 'nav' => true, - 'order' => 2, - 'type' => 'install', - 'wrapper' => 1 - ], - [ - 'id' => 'root.readiness-check-install.progress', - 'url' => 'readiness-check-updater/progress', - 'templateUrl' => "$base/readiness-check-updater/progress", - 'title' => 'Readiness Check', - 'header' => 'Step 1: Readiness Check', - 'controller' => 'readinessCheckController', - 'nav' => false, - 'order' => 3, - 'type' => 'install', - 'wrapper' => 1 - ], - [ - 'id' => 'root.create-backup-install', - 'url' => 'create-backup', - 'templateUrl' => "$base/create-backup", - 'title' => "Create \n Backup", - 'header' => 'Step 2: Create Backup', - 'controller' => 'createBackupController', - 'nav' => true, - 'validate' => true, - 'order' => 4, - 'type' => 'install', - 'wrapper' => 1 - ], - [ - 'id' => 'root.create-backup-install.progress', - 'url' => 'create-backup/progress', - 'templateUrl' => "$base/complete-backup/progress", - 'title' => "Create \n Backup", - 'header' => 'Step 2: Create Backup', - 'controller' => 'completeBackupController', - 'nav' => false, - 'order' => 5, - 'type' => 'install', - 'wrapper' => 1 - ], - [ - 'id' => 'root.start-updater-install', - 'url' => 'start-updater', - 'templateUrl' => "$base/start-updater", - 'controller' => 'startUpdaterController', - 'title' => "Component \n Install", - 'header' => 'Step 3: Install', - 'nav' => true, - 'order' => 6, - 'type' => 'install', - 'wrapper' => 1 - ], - ], -]; diff --git a/setup/config/states.home.config.php b/setup/config/states.home.config.php deleted file mode 100644 index 7e687af5f91b9..0000000000000 --- a/setup/config/states.home.config.php +++ /dev/null @@ -1,98 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -$base = basename($_SERVER['SCRIPT_FILENAME']); - -return [ - 'navUpdater' => [ - [ - 'id' => 'root', - 'step' => 0, - 'views' => ['root' => []], - ], - [ - 'id' => 'root.home', - 'url' => 'home', - 'title' => 'Setup Wizard', - 'templateUrl' => "$base/home", - 'header' => 'Home', - 'nav' => false, - 'default' => true, - 'noMenu' => true, - 'order' => -1, - ], - [ - 'id' => 'root.module', - 'url' => 'module-grid', - 'templateUrl' => "$base/module-grid", - 'title' => 'Module Manager', - 'controller' => 'moduleGridController', - 'nav' => false, - 'noMenu' => true, - 'order' => 1, - 'type' => 'module' - ], - [ - 'id' => 'root.extension-auth', - 'url' => 'marketplace-credentials', - 'templateUrl' => "$base/marketplace-credentials", - 'title' => 'Extension Manager', - 'controller' => 'MarketplaceCredentialsController', - 'order' => 1, - 'nav' => false, - 'noMenu' => true, - 'type' => 'extension' - ], - [ - 'id' => 'root.extension', - 'url' => 'extension-grid', - 'templateUrl' => "$base/extension-grid", - 'title' => 'Extension Manager', - 'controller' => 'extensionGridController', - 'order' => 2, - 'nav' => false, - 'noMenu' => true, - 'type' => 'extension' - ], - [ - 'id' => 'root.install', - 'url' => 'install-extension-grid', - 'templateUrl' => "$base/install-extension-grid", - 'title' => "Extension Manager", - 'controller' => 'installExtensionGridController', - 'nav' => false, - 'noMenu' => true, - 'order' => 1, - 'type' => 'install', - 'wrapper' => 1, - 'header' => 'Ready to Install' - ], - [ - 'id' => 'root.update', - 'url' => 'update-extension-grid', - 'templateUrl' => "$base/update-extension-grid", - 'title' => "Extension Manager", - 'controller' => 'updateExtensionGridController', - 'nav' => false, - 'noMenu' => true, - 'order' => 1, - 'type' => 'update', - 'wrapper' => 1, - 'header' => 'New Updates' - ], - [ - 'id' => 'root.upgrade', - 'url' => 'marketplace-credentials', - 'templateUrl' => "$base/marketplace-credentials", - 'title' => 'System Upgrade', - 'controller' => 'MarketplaceCredentialsController', - 'order' => 1, - 'nav' => false, - 'noMenu' => true, - 'type' => 'upgrade' - ], - ], -]; diff --git a/setup/config/states.install.config.php b/setup/config/states.install.config.php index 0559961b6119a..5d1b7c8fa150f 100644 --- a/setup/config/states.install.config.php +++ b/setup/config/states.install.config.php @@ -8,10 +8,10 @@ $base = basename($_SERVER['SCRIPT_FILENAME']); return [ - 'navInstallerTitles' => [ - 'install' => 'Magento Installer', + 'navLandingTitles' => [ + 'install' => 'Magento', ], - 'navInstaller' => [ + 'navLanding' => [ [ 'id' => 'root', 'step' => 0, @@ -28,116 +28,15 @@ 'type' => 'install' ], [ - 'id' => 'root.landing-install', - 'url' => 'landing-install', - 'templateUrl' => "$base/landing-installer", - 'title' => 'Installation', + 'id' => 'root.landing', + 'url' => 'landing', + 'templateUrl' => "$base/landing", + 'title' => 'Magento', 'controller' => 'landingController', 'main' => true, 'default' => true, 'order' => 0, 'type' => 'install' ], - [ - 'id' => 'root.readiness-check-install', - 'url' => 'readiness-check-install', - 'templateUrl' => "{$base}/readiness-check-installer", - 'title' => "Readiness \n Check", - 'header' => 'Step 1: Readiness Check', - 'nav' => true, - 'order' => 1, - 'type' => 'install' - ], - [ - 'id' => 'root.readiness-check-install.progress', - 'url' => 'readiness-check-install/progress', - 'templateUrl' => "{$base}/readiness-check-installer/progress", - 'title' => 'Readiness Check', - 'header' => 'Step 1: Readiness Check', - 'controller' => 'readinessCheckController', - 'nav' => false, - 'order' => 2, - 'type' => 'install' - ], - [ - 'id' => 'root.add-database', - 'url' => 'add-database', - 'templateUrl' => "{$base}/add-database", - 'title' => "Add \n a Database", - 'header' => 'Step 2: Add a Database', - 'controller' => 'addDatabaseController', - 'nav' => true, - 'validate' => true, - 'order' => 3, - 'type' => 'install' - ], - [ - 'id' => 'root.web-configuration', - 'url' => 'web-configuration', - 'templateUrl' => "{$base}/web-configuration", - 'title' => "Web \n Configuration", - 'header' => 'Step 3: Web Configuration', - 'controller' => 'webConfigurationController', - 'nav' => true, - 'validate' => true, - 'order' => 4, - 'type' => 'install' - ], - [ - 'id' => 'root.customize-your-store', - 'url' => 'customize-your-store', - 'templateUrl' => "{$base}/customize-your-store", - 'title' => "Customize \n Your Store", - 'header' => 'Step 4: Customize Your Store', - 'controller' => 'customizeYourStoreController', - 'nav' => true, - 'order' => 5, - 'type' => 'install' - ], - [ - 'id' => 'root.configure-catalog-search', - 'url' => 'configure-catalog-search', - 'templateUrl' => "{$base}/configure-catalog-search", - 'title' => "Configure \n Search", - 'header' => 'Step 5: Configure Catalog Search', - 'controller' => 'configureCatalogSearchController', - 'nav' => true, - 'validate' => true, - 'order' => 6, - 'type' => 'install' - ], - [ - 'id' => 'root.create-admin-account', - 'url' => 'create-admin-account', - 'templateUrl' => "{$base}/create-admin-account", - 'title' => "Create \n Admin Account", - 'header' => 'Step 6: Create Admin Account', - 'controller' => 'createAdminAccountController', - 'nav' => true, - 'validate' => true, - 'order' => 7, - 'type' => 'install' - ], - [ - 'id' => 'root.install', - 'url' => 'install', - 'templateUrl' => "{$base}/install", - 'title' => 'Install', - 'header' => 'Step 7: Install', - 'controller' => 'installController', - 'nav' => true, - 'order' => 8, - 'type' => 'install' - ], - [ - 'id' => 'root.success', - 'url' => 'success', - 'templateUrl' => "{$base}/success", - 'title' => 'Success', - 'controller' => 'successController', - 'main' => true, - 'order' => 9, - 'type' => 'install' - ], ], ]; diff --git a/setup/config/states.uninstall.config.php b/setup/config/states.uninstall.config.php deleted file mode 100644 index dac3a1d39469f..0000000000000 --- a/setup/config/states.uninstall.config.php +++ /dev/null @@ -1,90 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -$base = basename($_SERVER['SCRIPT_FILENAME']); - -return [ - 'navUpdaterTitles' => [ - 'uninstall' => 'Uninstall ', - ], - 'navUpdater' => [ - [ - 'id' => 'root.readiness-check-uninstall', - 'url' => 'readiness-check-uninstall', - 'templateUrl' => "{$base}/readiness-check-updater", - 'title' => "Readiness \n Check", - 'header' => 'Step 1: Readiness Check', - 'nav' => true, - 'order' => 2, - 'type' => 'uninstall' - ], - [ - 'id' => 'root.readiness-check-uninstall.progress', - 'url' => 'readiness-check-uninstall/progress', - 'templateUrl' => "$base/readiness-check-updater/progress", - 'title' => 'Readiness Check', - 'header' => 'Step 1: Readiness Check', - 'controller' => 'readinessCheckController', - 'nav' => false, - 'order' => 3, - 'type' => 'uninstall' - ], - [ - 'id' => 'root.create-backup-uninstall', - 'url' => 'create-backup', - 'templateUrl' => "$base/create-backup", - 'title' => "Create \n Backup", - 'header' => 'Step 2: Create Backup', - 'controller' => 'createBackupController', - 'nav' => true, - 'validate' => true, - 'order' => 4, - 'type' => 'uninstall' - ], - [ - 'id' => 'root.create-backup-uninstall.progress', - 'url' => 'create-backup/progress', - 'templateUrl' => "$base/complete-backup/progress", - 'title' => "Create \n Backup", - 'header' => 'Step 2: Create Backup', - 'controller' => 'completeBackupController', - 'nav' => false, - 'order' => 5, - 'type' => 'uninstall' - ], - [ - 'id' => 'root.data-option', - 'url' => 'data-option', - 'templateUrl' => "$base/data-option", - 'title' => "Remove or \n Keep Data", - 'controller' => 'dataOptionController', - 'header' => 'Step 3: Remove or Keep Data', - 'nav' => true, - 'order' => 6, - 'type' => 'uninstall' - ], - [ - 'id' => 'root.start-updater-uninstall', - 'url' => 'uninstall', - 'templateUrl' => "$base/start-updater", - 'title' => "Uninstall", - 'controller' => 'startUpdaterController', - 'header' => 'Step 4: Uninstall', - 'nav' => true, - 'order' => 7, - 'type' => 'uninstall' - ], - [ - 'id' => 'root.uninstall-success', - 'url' => 'uninstall-success', - 'templateUrl' => "$base/updater-success", - 'controller' => 'updaterSuccessController', - 'order' => 8, - 'main' => true, - 'noMenu' => true - ], - ], -]; diff --git a/setup/config/states.update.config.php b/setup/config/states.update.config.php deleted file mode 100644 index 57f81332b1e1a..0000000000000 --- a/setup/config/states.update.config.php +++ /dev/null @@ -1,70 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -$base = basename($_SERVER['SCRIPT_FILENAME']); - -return [ - 'navUpdaterTitles' => [ - 'update' => 'Update ', - ], - 'navUpdater' => [ - [ - 'id' => 'root.readiness-check-update', - 'url' => 'readiness-check-updater', - 'templateUrl' => "{$base}/readiness-check-updater", - 'title' => "Readiness \n Check", - 'header' => 'Step 1: Readiness Check', - 'nav' => true, - 'order' => 2, - 'type' => 'update' - ], - [ - 'id' => 'root.readiness-check-update.progress', - 'url' => 'readiness-check-updater/progress', - 'templateUrl' => "$base/readiness-check-updater/progress", - 'title' => 'Readiness Check', - 'header' => 'Step 1: Readiness Check', - 'controller' => 'readinessCheckController', - 'nav' => false, - 'order' => 3, - 'type' => 'update' - ], - [ - 'id' => 'root.create-backup-update', - 'url' => 'create-backup', - 'templateUrl' => "$base/create-backup", - 'title' => "Create \n Backup", - 'header' => 'Step 2: Create Backup', - 'controller' => 'createBackupController', - 'nav' => true, - 'validate' => true, - 'order' => 4, - 'type' => 'update' - ], - [ - 'id' => 'root.create-backup-update.progress', - 'url' => 'create-backup/progress', - 'templateUrl' => "$base/complete-backup/progress", - 'title' => "Create \n Backup", - 'header' => 'Step 2: Create Backup', - 'controller' => 'completeBackupController', - 'nav' => false, - 'order' => 5, - 'type' => 'update' - ], - [ - 'id' => 'root.start-updater-update', - 'url' => 'start-updater', - 'templateUrl' => "$base/start-updater", - 'controller' => 'startUpdaterController', - 'title' => "Extension \n Update", - 'header' => 'Step 3: Extension Update', - 'nav' => true, - 'order' => 6, - 'type' => 'update' - ], - ], -]; diff --git a/setup/config/states.upgrade.config.php b/setup/config/states.upgrade.config.php deleted file mode 100644 index bf1cbe2c8c156..0000000000000 --- a/setup/config/states.upgrade.config.php +++ /dev/null @@ -1,99 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -$base = basename($_SERVER['SCRIPT_FILENAME']); - -return [ - 'navUpdaterTitles' => [ - 'upgrade' => 'System Upgrade', - ], - 'navUpdater' => [ - [ - 'id' => 'root.select-version', - 'url' => 'select-version', - 'templateUrl' => "$base/select-version", - 'title' => 'System Upgrade', - 'controller' => 'selectVersionController', - 'header' => 'Step 1: Select Version', - 'order' => 2, - 'nav' => true, - 'type' => 'upgrade' - ], - [ - 'id' => 'root.readiness-check-upgrade', - 'url' => 'readiness-check-updater', - 'templateUrl' => "$base/readiness-check-updater", - 'title' => "Readiness \n Check", - 'header' => 'Step 2: Readiness Check', - 'order' => 3, - 'nav' => true, - 'type' => 'upgrade' - ], - [ - 'id' => 'root.readiness-check-upgrade.progress', - 'url' => 'readiness-check-updater/progress', - 'templateUrl' => "$base/readiness-check-updater/progress", - 'title' => 'Readiness Check', - 'header' => 'Step 2: Readiness Check', - 'controller' => 'readinessCheckController', - 'nav' => false, - 'order' => 4, - 'type' => 'upgrade' - ], - [ - 'id' => 'root.create-backup-upgrade', - 'url' => 'create-backup', - 'templateUrl' => "$base/create-backup", - 'title' => 'Create Backup', - 'controller' => 'createBackupController', - 'header' => 'Step 3: Create Backup', - 'order' => 5, - 'nav' => true, - 'type' => 'upgrade' - ], - [ - 'id' => 'root.create-backup-upgrade.progress', - 'url' => 'create-backup/progress', - 'templateUrl' => "$base/complete-backup/progress", - 'title' => "Create \n Backup", - 'header' => 'Step 3: Create Backup', - 'controller' => 'completeBackupController', - 'nav' => false, - 'order' => 6, - 'type' => 'upgrade' - ], - [ - 'id' => 'root.start-updater-upgrade', - 'url' => 'start-updater', - 'templateUrl' => "$base/start-updater", - 'title' => "System \n Upgrade", - 'controller' => 'startUpdaterController', - 'header' => 'Step 4: System Upgrade', - 'order' => 7, - 'nav' => true, - 'type' => 'upgrade' - ], - [ - 'id' => 'root.updater-success', - 'url' => 'updater-success', - 'templateUrl' => "$base/updater-success", - 'controller' => 'updaterSuccessController', - 'order' => 8, - 'noMenu' => true - ], - [ - 'id' => 'root.system-config', - 'url' => 'system-config', - 'templateUrl' => "$base/system-config", - 'title' => 'System config', - 'controller' => 'systemConfigController', - 'default' => false, - 'nav-bar' => false, - 'noMenu' => true, - 'order' => -1, - ] - ], -]; diff --git a/setup/pub/magento/setup/add-database.js b/setup/pub/magento/setup/add-database.js deleted file mode 100644 index 229c13d11e279..0000000000000 --- a/setup/pub/magento/setup/add-database.js +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('add-database', ['ngStorage']) - .controller('addDatabaseController', ['$scope', '$state', '$localStorage', '$http', function ($scope, $state, $localStorage, $http) { - $scope.db = { - useExistingDb: 1, - useAccess: 1, - host: 'localhost', - user: 'root', - name: 'magento' - }; - - if ($localStorage.db) { - $scope.db = $localStorage.db; - } - - $scope.testConnection = function () { - $http.post('index.php/database-check', $scope.db) - .then(function successCallback(resp) { - $scope.testConnection.result = resp.data; - - if ($scope.testConnection.result.success) { - $scope.nextState(); - } - }, function errorCallback(resp) { - $scope.testConnection.failed = resp.data; - }); - }; - - $scope.$on('nextState', function () { - $localStorage.db = $scope.db; - }); - - // Listens on form validate event, dispatched by parent controller - $scope.$on('validate-' + $state.current.id, function() { - $scope.validate(); - }); - - // Dispatch 'validation-response' event to parent controller - $scope.validate = function() { - if ($scope.database.$valid) { - $scope.$emit('validation-response', true); - } else { - $scope.$emit('validation-response', false); - $scope.database.submitted = true; - } - } - - // Update 'submitted' flag - $scope.$watch(function() { return $scope.database.$valid }, function(valid) { - if (valid) { - $scope.database.submitted = false; - } - }); - }]); diff --git a/setup/pub/magento/setup/app.js b/setup/pub/magento/setup/app.js index 830ab04bfc6c5..8670c61792156 100644 --- a/setup/pub/magento/setup/app.js +++ b/setup/pub/magento/setup/app.js @@ -5,35 +5,12 @@ 'use strict'; var app = angular.module( - 'magentoSetup', + 'magento', [ 'ui.router', 'ui.bootstrap', 'main', - 'landing', - 'readiness-check', - 'add-database', - 'web-configuration', - 'customize-your-store', - 'configure-catalog-search', - 'create-admin-account', - 'install', - 'success', - 'module-grid', - 'extension-grid', - 'install-extension-grid', - 'update-extension-grid', - 'create-backup', - 'complete-backup', - 'data-option', - 'start-updater', - 'select-version', - 'updater-success', - 'home', - 'auth-dialog', - 'system-config', - 'marketplace-credentials', - 'ngSanitize' + 'landing' ]); app.config(['$httpProvider', '$stateProvider', function ($httpProvider, $stateProvider) { diff --git a/setup/pub/magento/setup/auth-dialog.js b/setup/pub/magento/setup/auth-dialog.js deleted file mode 100644 index 4f539d64272db..0000000000000 --- a/setup/pub/magento/setup/auth-dialog.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('auth-dialog', ['ngStorage']) - .controller('authDialogController', ['$rootScope', '$scope', '$state', '$http', '$localStorage', 'authService', - function ($rootScope, $scope, $state, $http, $localStorage, authService) { - $scope.user = { - username : $localStorage.marketplaceUsername ? $localStorage.marketplaceUsername : '', - password : '', - submitted : '' - }; - $scope.errors = false; - - if (!$rootScope.isMarketplaceAuthorized) { - authService.checkAuth({ - success: function(response) { - $scope.user.username = response.data.username; - }, - fail: function(response) {}, - error: function() {} - }); - } - - $scope.saveAuthJson = function () { - if ($scope.auth.$valid) { - authService.saveAuthJson({ - user: $scope.user, - success: function(response) { - $scope.saveAuthJson.result = response; - $scope.logout = false; - $scope.errors = false; - if (typeof($scope.$parent) != 'undefined') { - $scope.$parent.logout = false; - } - authService.closeAuthDialog(); - }, - fail: function(response) { - $scope.saveAuthJson.result = response; - $scope.errors = true; - }, - error: function(data) { - $scope.errors = true; - $scope.saveAuthJson.failed = data; - } - }); - } else { - $scope.validate(); - } - }; - - $scope.reset = function () { - authService.reset({ - success: function() { - $scope.logout = true; - authService.checkMarketplaceAuthorized(); - } - }) - }; - - $scope.validate = function() { - $scope.user.submitted = !$scope.user.$valid; - } - }]); diff --git a/setup/pub/magento/setup/complete-backup.js b/setup/pub/magento/setup/complete-backup.js deleted file mode 100644 index db7f6fdf8a176..0000000000000 --- a/setup/pub/magento/setup/complete-backup.js +++ /dev/null @@ -1,185 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('complete-backup', ['ngStorage']) - .constant('BACKUPCOUNTER', 1) - .controller('completeBackupController', ['$rootScope', '$scope', '$state', '$http', '$timeout', 'BACKUPCOUNTER', '$localStorage', '$q', function ($rootScope, $scope, $state, $http, $timeout, BACKUPCOUNTER, $localStorage, $q) { - if ($localStorage.backupInfo) { - $scope.backupInfoPassed = $localStorage.backupInfo; - } - - $scope.type = $state.current.type; - - $scope.progressCounter = BACKUPCOUNTER; - $scope.startProgress = function() { - ++$scope.progressCounter; - }; - $scope.stopProgress = function() { - --$scope.progressCounter; - if ($scope.progressCounter == BACKUPCOUNTER) { - $scope.resetProgress(); - } - }; - $scope.resetProgress = function() { - $scope.progressCounter = 0; - }; - $rootScope.checkingInProgress = function() { - return $scope.progressCounter > 0; - }; - - $scope.requestFailedHandler = function(obj) { - obj.processed = true; - obj.isRequestError = true; - $scope.hasErrors = true; - $rootScope.hasErrors = true; - $scope.stopProgress(); - } - - $scope.completed = false; - $scope.hasErrors = false; - - $scope.maintenance = { - visible: false, - processed: false, - isRequestError: false - }; - $scope.check = { - visible: false, - processed: false, - isRequestError: false - }; - $scope.create = { - visible: false, - processed: false, - isRequestError: false - }; - $scope.items = { - 'backup-check': { - url:'index.php/backup-action-items/check', - show: function() { - $scope.startProgress(); - $scope.check.visible = true; - }, - process: function(data) { - $scope.check.processed = true; - angular.extend($scope.check, data); - $scope.updateOnProcessed($scope.check.responseType); - $scope.stopProgress(); - }, - fail: function() { - $scope.requestFailedHandler($scope.check); - } - }, - 'store-maintenance': { - url:'index.php/maintenance/index', - show: function() { - $scope.startProgress(); - $scope.maintenance.visible = true; - }, - process: function(data) { - $scope.maintenance.processed = true; - angular.extend($scope.maintenance, data); - $scope.updateOnProcessed($scope.maintenance.responseType); - $scope.stopProgress(); - }, - fail: function() { - $scope.requestFailedHandler($scope.maintenance); - } - }, - 'backup-create': { - url:'index.php/backup-action-items/create', - show: function() { - $scope.startProgress(); - $scope.create.visible = true; - }, - process: function(data) { - $scope.create.processed = true; - angular.extend($scope.create, data); - var files = ''; - if (typeof $scope.create.files !== 'undefined') { - for (var i = 0; i < $scope.create.files.length; i++) { - if (i == 0) { - files = files + $scope.create.files[i]; - } else { - files = files + ", " + $scope.create.files[i]; - } - } - } - $scope.files = files; - $scope.updateOnProcessed($scope.create.responseType); - $scope.stopProgress(); - $scope.disableMeintenanceMode(); - }, - fail: function() { - $scope.requestFailedHandler($scope.create); - $scope.disableMeintenanceMode(); - } - } - }; - - $scope.disableMeintenanceMode = function() { - $http.post('index.php/maintenance/index', {'disable' : true}); - }; - - $scope.isCompleted = function() { - return $scope.maintenance.processed - && $scope.check.processed - && $scope.create.processed; - }; - - $scope.updateOnProcessed = function(value) { - if (!$rootScope.hasErrors) { - $rootScope.hasErrors = (value != 'success'); - $scope.hasErrors = $rootScope.hasErrors; - } - }; - - $scope.hasItem = function(haystack, needle) { - return haystack.indexOf(needle) > -1; - }; - - function endsWith(str, suffix) { - return str.indexOf(suffix, str.length - suffix.length) !== -1; - } - - $scope.query = function(item) { - if (!$rootScope.hasErrors) { - return $http.post(item.url, $scope.backupInfoPassed, {timeout: 3000000}) - .then(function successCallback(resp) { - item.process(resp.data); - }, function errorCallback() { - item.fail(); - }); - } else { - $scope.stopProgress(); - $scope.completed = true; - $scope.maintenance.processed = true; - $scope.check.processed = true; - $scope.create.processed = true; - return void (0); - } - }; - - $scope.progress = function() { - $rootScope.hasErrors = false; - $scope.hasErrors = false; - var promise = $q.all(null); - angular.forEach($scope.items, function(item) { - item.show(); - promise = promise.then(function() { - return $scope.query(item); - }, function() { - return void (0); - }); - }); - }; - - $scope.$on('$stateChangeSuccess', function (event, nextState) { - if (nextState.id == 'root.create-backup-' + nextState.type +'.progress') { - $scope.progress(); - } - }); - }]); diff --git a/setup/pub/magento/setup/configure-catalog-search.js b/setup/pub/magento/setup/configure-catalog-search.js deleted file mode 100644 index 10829225f4ed2..0000000000000 --- a/setup/pub/magento/setup/configure-catalog-search.js +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('configure-catalog-search', ['ngStorage', 'ngSanitize']) - .controller('configureCatalogSearchController', ['$scope', '$localStorage' , '$state', '$http', function ($scope, $localStorage, $state, $http) { - $scope.search = { - config: { - engine: null, - elasticsearch: {}, - }, - testConnection: { - result: {} - }, - }; - - if ($localStorage.search) { - $scope.search.config = $localStorage.search; - } - - $scope.$on('nextState', function () { - $localStorage.search = $scope.search.config; - }); - - // Listens on form validate event, dispatched by parent controller - $scope.$on('validate-' + $state.current.id, function() { - $scope.validate(); - }); - - // Dispatch 'validation-response' event to parent controller - $scope.validate = function() { - if ($scope.searchConfig.$valid) { - $scope.$emit('validation-response', true); - } else { - $scope.$emit('validation-response', false); - $scope.searchConfig.submitted = true; - } - }; - - // Update 'submitted' flag - $scope.$watch(function() { return $scope.searchConfig.$valid }, function(valid) { - if (valid) { - $scope.searchConfig.submitted = false; - } - }); - - if (!$scope.search.config.engine) { - $http.get('index.php/configure-catalog-search/default-parameters',{'responseType' : 'json'}) - .then(function successCallback(resp) { - $scope.search.config = resp.data; - }); - } - - $scope.testConnection = function(goNext) { - $scope.checking = true; - $scope.search.testConnection.result = {}; - $http.post('index.php/search-engine-check', $scope.search.config) - .then(function successCallback(resp) { - if (resp.data.success) { - $scope.search.testConnection.result.success = true; - if (goNext) { - $scope.nextState(); - } else { - $scope.search.testConnection.result.message = 'Test connection successful.'; - } - } else { - $scope.search.testConnection.result.success = false; - $scope.search.testConnection.result.message = resp.data.error; - } - $scope.checking = false; - }, function errorCallback() { - $scope.search.testConnection.result.success = false; - $scope.search.testConnection.result.message = - 'An unknown error occurred. Please check configuration and try again.'; - $scope.checking = false; - }); - }; - }]); diff --git a/setup/pub/magento/setup/create-admin-account.js b/setup/pub/magento/setup/create-admin-account.js deleted file mode 100644 index 6e8807bb7a2ae..0000000000000 --- a/setup/pub/magento/setup/create-admin-account.js +++ /dev/null @@ -1,156 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('create-admin-account', ['ngStorage']) - .controller('createAdminAccountController', ['$scope', '$state', '$localStorage', '$http', function ($scope, $state, $localStorage, $http) { - $scope.admin = { - 'passwordStatus': { - class: 'none', - label: 'None' - } - }; - - $scope.passwordStatusChange = function () { - if (angular.isUndefined($scope.admin.password)) { - return; - } - var p = $scope.admin.password; - var MIN_ADMIN_PASSWORD_LENGTH = 7; - if (p.length >= MIN_ADMIN_PASSWORD_LENGTH && p.match(/[\d]+/) && p.match(/[a-z]+/) && p.match(/[A-Z]+/) && p.match(/[!@#$%^*()_\/\\\-\+=]+/)) { - $scope.admin.passwordStatus.class = 'strong'; - $scope.admin.passwordStatus.label = 'Strong'; - } else if (p.length >= MIN_ADMIN_PASSWORD_LENGTH && p.match(/[\d]+/) && p.match(/[a-z]+/) && p.match(/[A-Z]+/)) { - $scope.admin.passwordStatus.class = 'good'; - $scope.admin.passwordStatus.label = 'Good'; - } else if (p.length >= MIN_ADMIN_PASSWORD_LENGTH && p.match(/[\d]+/) && p.match(/[a-zA-Z]+/)) { - $scope.admin.passwordStatus.class = 'fair'; - $scope.admin.passwordStatus.label = 'Fair'; - } else if (p.length >= MIN_ADMIN_PASSWORD_LENGTH) { - $scope.admin.passwordStatus.class = 'weak'; - $scope.admin.passwordStatus.label = 'Weak'; - } else { - $scope.admin.passwordStatus.class = 'too-short'; - $scope.admin.passwordStatus.label = 'Too Short'; - } - }; - - if ($localStorage.admin) { - $scope.admin = $localStorage.admin; - } - - $scope.validateCredentials = function () { - var data = { - 'db': $localStorage.db, - 'admin': $scope.admin, - 'store': $localStorage.store, - 'config': $localStorage.config - }; - $scope.validate(); - if ($scope.valid) { - $http.post('index.php/validate-admin-credentials', data) - .then(function successCallback(resp) { - $scope.validateCredentials.result = resp.data; - - if ($scope.validateCredentials.result.success) { - $scope.nextState(); - } - }, function errorCallback(resp) { - $scope.validateCredentials.failed = resp.data; - }); - } - }; - - $scope.$on('nextState', function () { - $localStorage.admin = $scope.admin; - }); - - // Listens on form validate event, dispatched by parent controller - $scope.$on('validate-' + $state.current.id, function() { - $scope.validate(); - }); - - // Dispatch 'validation-response' event to parent controller - $scope.validate = function() { - if ($scope.account.$valid) { - $scope.$emit('validation-response', true); - } else { - $scope.$emit('validation-response', false); - $scope.account.submitted = true; - } - }; - - // Update 'submitted' flag - $scope.$watch(function() { return $scope.account.$valid }, function(valid) { - if (valid) { - $scope.account.submitted = false; - } - }); - }]) - .directive('checkPassword', function() { - return{ - require: "ngModel", - link: function(scope, elm, attrs, ctrl){ - var validator = function(value){ - var minReg = /^(?=.*\d)(?=.*[a-zA-Z]).{6,}$/, - isValid = typeof value === 'string' && minReg.test(value); - - ctrl.$setValidity('checkPassword', isValid); - - return value; - }; - - ctrl.$parsers.unshift(validator); - ctrl.$formatters.unshift(validator); - } - }; - }) - .directive('checkUserNamePassword', function() { - return{ - require: "ngModel", - link: function(scope, elm, attrs, ctrl){ - var validator = function(value){ - var password = value, - userName = scope.account.adminUsername.$viewValue; - - if (password) { - password = password.toLowerCase(); - } - if (userName) { - userName = userName.toLowerCase(); - } - - ctrl.$setValidity('checkUserNamePasswordDifferent', password !== userName); - return value; - }; - - ctrl.$parsers.unshift(validator); - ctrl.$formatters.unshift(validator); - } - }; - }) - .directive('confirmPassword', function() { - return { - require: 'ngModel', - restrict: 'A', - link: function (scope, elem, attrs, ctrl) { - scope.$watch(function () { - return scope.$eval(attrs.confirmPassword) === ctrl.$modelValue; - }, function (value) { - ctrl.$setValidity('confirmPassword', value); - }); - - ctrl.$parsers.push(function (value) { - if (angular.isUndefined(value) || value === '') { - ctrl.$setValidity('confirmPassword', true); - return value; - } - var validated = value === scope.confirmPassword; - ctrl.$setValidity('confirmPassword', validated); - return value; - }); - } - }; - }); diff --git a/setup/pub/magento/setup/create-backup.js b/setup/pub/magento/setup/create-backup.js deleted file mode 100644 index 4ffb95660fba4..0000000000000 --- a/setup/pub/magento/setup/create-backup.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('create-backup', ['ngStorage']) - .controller('createBackupController', ['$scope', '$state', '$localStorage', function ($scope, $state, $localStorage) { - $scope.backupInfo = { - options: { - code: true, - media: true, - db: true - } - }; - - $scope.type = $state.current.type; - - if ($localStorage.backupInfo) { - $scope.backupInfo = $localStorage.backupInfo; - } - - $scope.nextButtonStatus = false; - - $scope.optionsSelected = function () { - if (!$scope.backupInfo.options.code && !$scope.backupInfo.options.media && !$scope.backupInfo.options.db) { - $scope.nextButtonStatus = true; - return true; - } else { - $scope.nextButtonStatus = false; - return false; - } - }; - - $scope.goToStartUpdater = function () { - if ($state.current.type === 'uninstall') { - $state.go('root.data-option'); - } else { - $state.go('root.start-updater-' + $state.current.type); - } - } - - $scope.$on('nextState', function () { - $localStorage.backupInfo = $scope.backupInfo; - }); - - $scope.$watch('backupInfo.options.code', function() { - $localStorage.backupInfo = $scope.backupInfo; - }); - - $scope.$watch('backupInfo.options.media', function() { - $localStorage.backupInfo = $scope.backupInfo; - }); - $scope.$watch('backupInfo.options.db', function() { - $localStorage.backupInfo = $scope.backupInfo; - }); - - // Listens on form validate event, dispatched by parent controller - $scope.$on('validate-' + $state.current.id, function() { - $scope.validate(); - }); - - // Dispatch 'validation-response' event to parent controller - $scope.validate = function() { - if ($scope.backup.$valid) { - $scope.$emit('validation-response', true); - } else { - $scope.$emit('validation-response', false); - $scope.backup.submitted = true; - } - } - - // Update 'submitted' flag - $scope.$watch(function() { return $scope.backup.$valid }, function(valid) { - if (valid) { - $scope.backup.submitted = false; - } - }); - }]); diff --git a/setup/pub/magento/setup/customize-your-store.js b/setup/pub/magento/setup/customize-your-store.js deleted file mode 100644 index d15c07c58ef16..0000000000000 --- a/setup/pub/magento/setup/customize-your-store.js +++ /dev/null @@ -1,198 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('customize-your-store', ['ngStorage', 'ngSanitize']) - .controller('customizeYourStoreController', ['$scope', '$localStorage' , '$state', '$http', '$sce', function ($scope, $localStorage, $state, $http, $sce) { - $scope.store = { - timezone: 'UTC', - currency: 'USD', - language: 'en_US', - useSampleData: false, - cleanUpDatabase: false, - loadedAllModules: false, - showModulesControl: false, - selectAll: true, - allModules: [], - errorFlag : false, - showError: false, - selectedModules : [], - disabledModules: [], - errorMessage: '', - force: false, - advanced: { - expanded: false - } - }; - - $scope.loading = false; - - if (!$localStorage.store) { - $http.get('index.php/customize-your-store/default-time-zone',{'responseType' : 'json'}) - .then(function successCallback(resp) { - $scope.store.timezone = resp.data.defaultTimeZone; - }, function errorCallback() { - $scope.store.timezone = 'UTC'; - }); - } - - if ($localStorage.store) { - $scope.store = $localStorage.store; - } - - $scope.checkModuleConstraints = function () { - $state.loadModules(); - $localStorage.store = $scope.store; - $scope.loading = true; - $http.post('index.php/modules/all-modules-valid', $scope.store) - .then(function successCallback(resp) { - $scope.checkModuleConstraints.result = resp.data; - - if ($scope.checkModuleConstraints.result !== undefined && - $scope.checkModuleConstraints.result.success - ) { - $scope.loading = false; - $scope.nextState(); - } else { - $scope.store.errorMessage = $sce.trustAsHtml($scope.checkModuleConstraints.result.error); - $scope.loading = false; - } - }); - }; - - if (!$scope.store.loadedAllModules) { - $http.get('index.php/modules').then(function successCallback(resp) { - $state.loadedModules = resp.data; - $scope.store.showModulesControl = true; - - if (resp.data.error) { - $scope.updateOnExpand($scope.store.advanced); - $scope.store.errorMessage = $sce.trustAsHtml(resp.data.error); - } - }); - } - - $state.loadModules = function () { - if(!$scope.store.loadedAllModules) { - var allModules = $scope.$state.loadedModules.modules; - for (var eachModule in allModules) { - $scope.store.allModules.push(allModules[eachModule].name); - if(allModules[eachModule].selected) { - $scope.store.selectedModules.push(allModules[eachModule].name); - } - if(allModules[eachModule].disabled) { - $scope.store.disabledModules.push(allModules[eachModule].name); - } - } - $scope.store.loadedAllModules = true; - $scope.checkIfAllAreSelected(); - } - } - - $scope.updateOnExpand = function(obj) { - $state.loadModules(); - obj.expanded = !obj.expanded; - }; - - $scope.expandError = function() { - $scope.store.errorFlag = !$scope.store.errorFlag; - }; - - $scope.toggleForce = function() { - $scope.force = !$scope.force; - }; - - $scope.toggleModule = function(module) { - var idx = $scope.store.selectedModules.indexOf(module); - if (idx > -1) { - $scope.store.selectedModules.splice(idx, 1); - } else { - $scope.store.selectedModules.push(module); - } - $scope.checkIfAllAreSelected(); - $scope.validateModules(module); - }; - - $scope.validateModules = function(module){ - if ($scope.force) return; - // validate enabling disabling here. - var idx = $scope.store.selectedModules.indexOf(module); - var moduleStatus = (idx > -1) ? true : false; - var allParameters = {'allModules' : $scope.store.allModules, 'selectedModules' : $scope.store.selectedModules, 'module' : module, 'status' : moduleStatus}; - - $http.post('index.php/modules/validate', allParameters) - .then(function successCallback(resp) { - $scope.checkModuleConstraints.result = resp.data; - - if ((($scope.checkModuleConstraints.result.error !== undefined) && (!$scope.checkModuleConstraints.result.success))) { - $scope.store.errorMessage = $sce.trustAsHtml($scope.checkModuleConstraints.result.error); - if (moduleStatus) { - $scope.store.selectedModules.splice(idx, 1); - } else { - $scope.store.selectedModules.push(module); - } - } else { - $state.loadedModules = resp.data; - $scope.store.errorMessage = false; - $scope.store.showError = false; - $scope.store.errorFlag = false; - $scope.store.loadedAllModules = false; - $scope.store.allModules =[]; - $scope.store.selectedModules =[]; - $scope.store.disabledModules =[]; - $state.loadModules(); - } - }); - - } - - $scope.toggleAllModules = function() { - $scope.store.selectAll = !$scope.store.selectAll; - if ($scope.store.selectAll) { - for(var i = 0; i < $scope.store.allModules.length; i++) { - $scope.store.selectedModules[i] = $scope.store.allModules[i]; - } - } else { - for(var i = 0; i < $scope.store.allModules.length; i++) { - var idx = $scope.store.selectedModules.indexOf($scope.store.allModules[i]); - if ($scope.store.disabledModules.indexOf($scope.store.allModules[i]) < 0) { - $scope.store.selectedModules.splice(idx, 1); - } - } - } - }; - - $scope.checkIfAllAreSelected = function() { - if ($scope.store.selectedModules.length === $scope.store.allModules.length && - $scope.store.selectedModules.length !== 0 ) { - $scope.store.selectAll = true; - } else { - $scope.store.selectAll = false; - } - } - - // Listens on form validate event, dispatched by parent controller - $scope.$on('validate-' + $state.current.id, function() { - $scope.validate(); - }); - - // Dispatch 'validation-response' event to parent controller - $scope.validate = function() { - if ($scope.customizeStore.$valid) { - $scope.$emit('validation-response', true); - } else { - $scope.$emit('validation-response', false); - $scope.customizeStore.submitted = true; - } - } - - // Update 'submitted' flag - $scope.$watch(function() { return $scope.customizeStore.$valid }, function(valid) { - if (valid) { - $scope.customizeStore.submitted = false; - } - }); - }]) - ; diff --git a/setup/pub/magento/setup/data-option.js b/setup/pub/magento/setup/data-option.js deleted file mode 100644 index 16bde5d32fdea..0000000000000 --- a/setup/pub/magento/setup/data-option.js +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('data-option', ['ngStorage']) - .controller('dataOptionController', ['$scope', '$localStorage', '$http', function ($scope, $localStorage, $http) { - $scope.component = { - dataOption : false, - hasUninstall : false - }; - - if ($localStorage.componentType === 'magento2-module') { - $http.post('index.php/data-option/hasUninstall', {'moduleName' : $localStorage.moduleName}) - .then(function successCallback(resp) { - $scope.component.hasUninstall = resp.data.hasUninstall; - }); - } - - if ($localStorage.dataOption) { - $scope.component.dataOption = $localStorage.dataOption; - } - - $scope.$watch('component.dataOption', function(value) { - $localStorage.dataOption = value; - }); - }]); diff --git a/setup/pub/magento/setup/extension-grid.js b/setup/pub/magento/setup/extension-grid.js deleted file mode 100644 index 416a767a483fa..0000000000000 --- a/setup/pub/magento/setup/extension-grid.js +++ /dev/null @@ -1,151 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; - -angular.module('extension-grid', ['ngStorage']) - .controller('extensionGridController', [ - '$rootScope', '$scope', '$http', '$localStorage', '$state','titleService', 'authService', 'paginationService', - function ($rootScope, $scope, $http, $localStorage, $state, titleService, authService, paginationService) { - authService.checkMarketplaceAuthorized(); - $rootScope.extensionsProcessed = false; - $scope.syncError = false; - $scope.currentPage = 1; - - $http.get('index.php/extensionGrid/extensions').then(function successCallback(resp) { - var data = resp.data; - - $scope.extensions = data.extensions; - $scope.total = data.total; - - if (data.error !== '') { - $scope.syncError = true; - $scope.ErrorMessage = data.error; - } - - if (typeof data.lastSyncData.lastSyncDate === 'undefined') { - $scope.isOutOfSync = true; - $scope.countOfUpdate = 0; - $scope.countOfInstall = 0; - } else { - $scope.lastSyncDate = data.lastSyncData.lastSyncDate.date; - $scope.lastSyncTime = data.lastSyncData.lastSyncDate.time; - $scope.countOfUpdate = data.lastSyncData.countOfUpdate; - $scope.countOfInstall = data.lastSyncData.countOfInstall; - $scope.enabledInstall = data.lastSyncData.countOfInstall ? true : false; - $scope.isOutOfSync = false; - } - $scope.availableUpdatePackages = data.lastSyncData.packages; - $scope.currentPage = 1; - $scope.rowLimit = '20'; - $scope.numberOfPages = Math.ceil($scope.total / $scope.rowLimit); - $rootScope.extensionsProcessed = true; - }); - - paginationService.initWatchers($scope); - - $scope.isOutOfSync = false; - $scope.isHiddenSpinner = true; - $scope.selectedExtension = null; - - $scope.reset = function () { - authService.reset({ - success: function() { - $scope.logout = true; - authService.checkMarketplaceAuthorized(); - } - }) - }; - - $scope.isActiveActionsCell = function(extension) { - return $scope.selectedExtension === extension; - }; - - $scope.toggleActiveActionsCell = function(extension) { - $scope.selectedExtension = $scope.selectedExtension == extension ? null : extension; - }; - - $scope.closeActiveActionsCell = function(extension) { - $scope.toggleActiveActionsCell(extension); - }; - - $scope.predicate = 'name'; - $scope.reverse = false; - $scope.order = function(predicate) { - $scope.reverse = $scope.predicate === predicate ? !$scope.reverse : false; - $scope.predicate = predicate; - }; - - $scope.sync = function() { - $scope.isHiddenSpinner = false; - $http.get('index.php/extensionGrid/sync').then(function successCallback(resp) { - var data = resp.data; - - if (typeof data.lastSyncData.lastSyncDate !== 'undefined') { - $scope.lastSyncDate = data.lastSyncData.lastSyncDate.date; - $scope.lastSyncTime = data.lastSyncData.lastSyncDate.time; - } - - if (data.error !== '') { - $scope.syncError = true; - $scope.ErrorMessage = data.error; - } - $scope.availableUpdatePackages = data.lastSyncData.packages; - $scope.countOfUpdate = data.lastSyncData.countOfUpdate; - $scope.countOfInstall = data.lastSyncData.countOfInstall; - $scope.enabledInstall = data.lastSyncData.countOfInstall ? true : false; - $scope.isHiddenSpinner = true; - $scope.isOutOfSync = false; - }); - }; - $scope.isAvailableUpdatePackage = function(packageName) { - $localStorage.isMarketplaceAuthorized = typeof $localStorage.isMarketplaceAuthorized !== 'undefined' ? $localStorage.isMarketplaceAuthorized : false; - var isAvailable = typeof $scope.availableUpdatePackages !== 'undefined' - && $localStorage.isMarketplaceAuthorized - && packageName in $scope.availableUpdatePackages; - return isAvailable; - }; - - $scope.getIndicatorInfo = function (extension, type) { - var indicators = { - 'info': { - 'icon': '_info', 'label': 'Update Available' - } - }; - - var types = ['label', 'icon']; - - if (types.indexOf(type) === -1) { - type = 'icon'; - } - - if ($scope.isAvailableUpdatePackage(extension.name)) { - return indicators.info[type]; - } - }; - - $scope.update = function(extension) { - $localStorage.packages = [ - { - name: extension.name, - version: $scope.availableUpdatePackages[extension.name]['latestVersion'] - } - ]; - titleService.setTitle('update', extension); - $state.go('root.readiness-check-update'); - }; - - $scope.uninstall = function(extension) { - $localStorage.packages = [ - { - name: extension.name - } - ]; - titleService.setTitle('uninstall', extension); - $localStorage.componentType = extension.type; - $state.go('root.readiness-check-uninstall'); - }; - } - ]); diff --git a/setup/pub/magento/setup/home.js b/setup/pub/magento/setup/home.js deleted file mode 100644 index 174cd500d83d4..0000000000000 --- a/setup/pub/magento/setup/home.js +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('home', ['ngStorage']) - .controller('homeController', ['$scope', '$http', '$localStorage', function ($scope, $http, $localStorage) { - $scope.page_title = "Magento setup tool"; - }]); diff --git a/setup/pub/magento/setup/install-extension-grid.js b/setup/pub/magento/setup/install-extension-grid.js deleted file mode 100644 index 6a94d99df372d..0000000000000 --- a/setup/pub/magento/setup/install-extension-grid.js +++ /dev/null @@ -1,99 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('install-extension-grid', ['ngStorage', 'clickOut']) - .controller('installExtensionGridController', ['$scope', '$http', '$localStorage', 'authService', 'paginationService', 'multipleChoiceService', - function ($scope, $http, $localStorage, authService, paginationService, multipleChoiceService) { - - $http.get('index.php/installExtensionGrid/extensions').then(function successCallback(resp) { - var data = resp.data; - - $scope.error = false; - $scope.errorMessage = ''; - $scope.multipleChoiceService = multipleChoiceService; - $scope.multipleChoiceService.reset(); - angular.forEach(data.extensions, function(value) { - $scope.multipleChoiceService.addExtension(value.name, value.version); - }); - $scope.extensions = data.extensions; - $scope.total = data.total; - $scope.currentPage = 1; - $scope.rowLimit = '20'; - $scope.numberOfPages = Math.ceil($scope.total / $scope.rowLimit); - }); - - paginationService.initWatchers($scope); - - $scope.predicate = 'name'; - $scope.reverse = false; - $scope.order = function(predicate) { - $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false; - $scope.predicate = predicate; - }; - - $scope.isHiddenSpinner = true; - $scope.installAll = function() { - $scope.isHiddenSpinner = false; - authService.checkAuth({ - success: function(response) { - $scope.isHiddenSpinner = true; - var result = $scope.multipleChoiceService.checkSelectedExtensions(); - $scope.error = result.error; - $scope.errorMessage = result.errorMessage; - - if (!$scope.error) { - $scope.nextState(); - } - }, - fail: function(response) { - $scope.isHiddenSpinner = true; - authService.openAuthDialog($scope); - }, - error: function() { - $scope.isHiddenSpinner = true; - $scope.error = true; - $scope.errorMessage = 'Internal server error'; - } - }); - }; - - $scope.install = function(extension) { - $scope.isHiddenSpinner = false; - authService.checkAuth({ - success: function(response) { - $scope.isHiddenSpinner = true; - if (extension === 'undefined') { - $scope.error = true; - $scope.errorMessage = 'No extensions for install'; - } else { - $localStorage.packages = [ - { - name: extension.name, - version: extension.version - } - ]; - $localStorage.moduleName = extension.name; - $localStorage.packageTitle = extension.package_title; - $scope.error = false; - $scope.errorMessage = ''; - } - - if (!$scope.error) { - $scope.nextState(); - } - }, - fail: function(response) { - authService.openAuthDialog($scope); - }, - error: function() { - $scope.isHiddenSpinner = true; - $scope.error = true; - $scope.errorMessage = 'Internal server error'; - } - }); - }; - } - ]); diff --git a/setup/pub/magento/setup/install.js b/setup/pub/magento/setup/install.js deleted file mode 100644 index 069700bdc333e..0000000000000 --- a/setup/pub/magento/setup/install.js +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('install', ['ngStorage']) - .controller('installController', ['$scope', '$sce', '$timeout', '$localStorage', '$rootScope', 'progress', function ($scope, $sce, $timeout, $localStorage, $rootScope, progress) { - $scope.isStarted = false; - $scope.isInProgress = false; - $scope.isConsole = false; - $scope.isDisabled = false; - $scope.isSampleDataError = false; - $scope.isShowCleanUpBox = false; - $scope.toggleConsole = function () { - $scope.isConsole = $scope.isConsole === false; - }; - - $scope.barStyle = function (value) { - return { width: value + '%' }; - }; - - $scope.checkProgress = function () { - if ($scope.isInProgress) { - $scope.displayProgress(); - } - progress.get(function (response) { - var log = ''; - response.data.console.forEach(function (message) { - log = log + message + '<br>'; - }); - $scope.log = $sce.trustAsHtml(log); - - if (response.data.success) { - $scope.progress = response.data.progress; - $scope.progressText = response.data.progress + '%'; - } else { - $scope.displayFailure(); - if (response.data.isSampleDataError) { - $scope.isSampleDataError = true; - } - } - if ($scope.isInProgress) { - $timeout(function() { - $scope.checkProgress(); - }, 1500); - } - }); - }; - - $scope.showCleanUpBox = function() { - $scope.isShowCleanUpBox = true; - }; - $scope.hideCleanUpBox = function() { - $scope.isShowCleanUpBox = false; - }; - $scope.startCleanup = function(performClenup) { - $scope.hideCleanUpBox(); - $scope.isSampleDataError = false; - $localStorage.store.cleanUpDatabase = performClenup; - $scope.start(); - }; - - $scope.start = function () { - if ($scope.isSampleDataError) { - $scope.showCleanUpBox(); - return; - } - var data = { - 'db': $localStorage.db, - 'admin': $localStorage.admin, - 'store': $localStorage.store, - 'config': $localStorage.config, - 'search': $localStorage.search - }; - $scope.isStarted = true; - $scope.isInProgress = true; - progress.post(data, function (response) { - response = response.data; - $scope.isInProgress = false; - - if (response.success) { - $localStorage.config.encrypt.key = response.key; - $localStorage.messages = response.messages; - $scope.nextState(); - } else { - $scope.displayFailure(); - - if (response.isSampleDataError) { - $scope.isSampleDataError = true; - } - } - }); - progress.get(function () { - $scope.checkProgress(); - }); - }; - $scope.displayProgress = function() { - $scope.isFailed = false; - $scope.isDisabled = true; - $rootScope.isMenuEnabled = false; - }; - $scope.displayFailure = function () { - $scope.isFailed = true; - $scope.isDisabled = false; - $rootScope.isMenuEnabled = true; - }; - }]) - .service('progress', ['$http', function ($http) { - return { - get: function (callback) { - $http.post('index.php/install/progress').then(callback, function errorCallback() {}); - }, - post: function (data, callback) { - $http.post('index.php/install/start', data).then(callback, function errorCallback() {}); - } - }; - }]); diff --git a/setup/pub/magento/setup/main.js b/setup/pub/magento/setup/main.js index fa9291e9a8507..48eed6d64be96 100644 --- a/setup/pub/magento/setup/main.js +++ b/setup/pub/magento/setup/main.js @@ -4,13 +4,14 @@ */ 'use strict'; + var main = angular.module('main', ['ngStorage', 'ngDialog']); main.controller('navigationController', ['$scope', '$state', '$rootScope', '$window', 'navigationService', '$localStorage', function ($scope, $state, $rootScope, $window, navigationService, $localStorage) { function loadMenu() { - angular.element(document).ready(function() { + angular.element(document).ready(function () { $scope.menu = $localStorage.menu; }); } @@ -22,89 +23,22 @@ main.controller('navigationController', return $state.$current.order <= order || !$rootScope.isMenuEnabled; }; }]) -.controller('headerController', ['$scope', '$localStorage', '$window', - function ($scope, $localStorage, $window) { - if ($localStorage.titles) { - $scope.titles = $localStorage.titles; - } - $scope.redirectTo = function (url) { - if (url) { - $window.location.href = url; - } - }; - } - ] -) .controller('mainController', [ - '$scope', '$state', 'navigationService', '$localStorage', '$interval', '$http', - function ($scope, $state, navigationService, $localStorage, $interval, $http) { - $interval( - function () { - $http.post('index.php/session/prolong').then( - function successCallback() {}, - function errorCallback() {} - ); - }, - 25000 - ); + '$scope', '$state', 'navigationService', '$localStorage', + function ($scope, $state, navigationService, $localStorage) { $scope.moduleName = $localStorage.moduleName; - $scope.$on('$stateChangeSuccess', function (event, state) { - $scope.valid = true; - }); $scope.nextState = function () { - if ($scope.validate()) { - $scope.$broadcast('nextState', $state.$current); - $state.go(navigationService.getNextState().id); - } - }; - - $scope.goToState = function (stateId) { - $state.go(stateId) + $scope.$broadcast('nextState', $state.$current); + $state.go(navigationService.getNextState().id); }; $scope.state = $state; $scope.previousState = function () { - $scope.valid = true; $state.go(navigationService.getPreviousState().id); - }; - - // Flag indicating the validity of the form - $scope.valid = true; - - // Check the validity of the form - $scope.validate = function() { - if ($state.current.validate) { - $scope.$broadcast('validate-' + $state.current.id); - } - return $scope.valid; - }; - - // Listens on 'validation-response' event, dispatched by descendant controller - $scope.$on('validation-response', function(event, data) { - $scope.valid = data; - event.stopPropagation(); - }); - - $scope.endsWith = function(str, suffix) { - return str.indexOf(suffix, str.length - suffix.length) !== -1; - }; - - $scope.goToBackup = function() { - $state.go('root.create-backup-uninstall'); - }; - - $scope.goToAction = function(action) { - if (['install', 'upgrade', 'update'].indexOf(action) !== -1) { - $state.go('root.' + action); - } else if (action === 'uninstall') { - $state.go('root.extension'); - } else { - $state.go('root.module'); - } - }; + }; } ]) .service('navigationService', ['$location', '$state', '$http', '$localStorage', @@ -128,9 +62,11 @@ main.controller('navigationController', data.titles[value] = data.titles[value] + $localStorage.moduleName; }); $localStorage.titles = data.titles; + if (self.isLoadedStates == false) { data.nav.forEach(function (item) { app.stateProvider.state(item.id, item); + if (item.default) { self.mainState = item; } @@ -140,6 +76,7 @@ main.controller('navigationController', isCurrentStateFound = true; } }); + if (!isCurrentStateFound) { $state.go(self.mainState.id); } @@ -154,6 +91,7 @@ main.controller('navigationController', nItem = item; } }); + return nItem; }, getPreviousState: function () { @@ -163,217 +101,19 @@ main.controller('navigationController', nItem = item; } }); + return nItem; } }; }]) -.service('authService', ['$localStorage', '$rootScope', '$state', '$http', 'ngDialog', - function ($localStorage, $rootScope, $state, $http, ngDialog) { - return { - checkMarketplaceAuthorized: function() { - $rootScope.isMarketplaceAuthorized = typeof $rootScope.isMarketplaceAuthorized !== 'undefined' - ? $rootScope.isMarketplaceAuthorized : false; - if ($rootScope.isMarketplaceAuthorized == false) { - this.goToAuthPage(); - } - }, - goToAuthPage: function() { - if ($state.current.type === 'upgrade') { - $state.go('root.upgrade'); - } else { - $state.go('root.extension-auth'); - } - }, - reset: function (context) { - return $http.post('index.php/marketplace/remove-credentials', []) - .then(function successCallback(response) { - if (response.data.success) { - $localStorage.isMarketplaceAuthorized = $rootScope.isMarketplaceAuthorized = false; - context.success(); - } - }); - }, - checkAuth: function(context) { - return $http.post('index.php/marketplace/check-auth', []) - .then(function successCallback(response) { - var data = response.data; - - if (data.success) { - $rootScope.isMarketplaceAuthorized = $localStorage.isMarketplaceAuthorized = true; - $localStorage.marketplaceUsername = data.username; - context.success(data); - } else { - $rootScope.isMarketplaceAuthorized = $localStorage.isMarketplaceAuthorized = false; - context.fail(data); - } - }, function errorCallback() { - $rootScope.isMarketplaceAuthorized = $localStorage.isMarketplaceAuthorized = false; - context.error(); - }); - }, - openAuthDialog: function(scope) { - return $http.get('index.php/marketplace/popup-auth').then(function successCallback(resp) { - var data = resp.data; - - scope.isHiddenSpinner = true; - ngDialog.open({ - scope: scope, - template: data, - plain: true, - showClose: false, - controller: 'authDialogController' - }); - }); - }, - closeAuthDialog: function() { - return ngDialog.close(); - }, - saveAuthJson: function (context) { - return $http.post('index.php/marketplace/save-auth-json', context.user) - .then(function successCallback(response) { - var data = response.data; - - $rootScope.isMarketplaceAuthorized = $localStorage.isMarketplaceAuthorized = data.success; - $localStorage.marketplaceUsername = context.user.username; - if (data.success) { - context.success(data); - } else { - context.fail(data); - } - }, function errorCallback(resp) { - $rootScope.isMarketplaceAuthorized = $localStorage.isMarketplaceAuthorized = false; - context.error(resp.data); - }); - } - }; - }] -) -.service('titleService', ['$localStorage', '$rootScope', - function ($localStorage, $rootScope) { - return { - setTitle: function(type, component) { - if (type === 'enable' || type === 'disable') { - $localStorage.packageTitle = $localStorage.moduleName = component.moduleName; - } else { - $localStorage.moduleName = component.moduleName ? component.moduleName : component.name; - $localStorage.packageTitle = component.package_title; - } - - if (typeof $localStorage.titles === 'undefined') { - $localStorage.titles = []; - } - $localStorage.titles[type] = type.charAt(0).toUpperCase() + type.slice(1) + ' ' - + ($localStorage.packageTitle ? $localStorage.packageTitle : $localStorage.moduleName); - $rootScope.titles = $localStorage.titles; - } - }; - }] -) -.service('paginationService', [ - function () { - return { - initWatchers: function ($scope) { - $scope.$watch('currentPage + rowLimit', function () { - $scope.numberOfPages = Math.ceil($scope.total / $scope.rowLimit); - if ($scope.currentPage > $scope.numberOfPages) { - $scope.currentPage = $scope.numberOfPages; - } - }); - } - }; - } -]) -.service('multipleChoiceService', ['$localStorage', - function ($localStorage) { - return { - selectedExtensions: {}, - allExtensions: {}, - someExtensionsSelected: false, - allExtensionsSelected: false, - isNewExtensionsMenuVisible: false, - - addExtension: function (name, version) { - this.allExtensions[name] = { - 'name': name, - 'version': version - }; - }, - reset: function () { - this.allExtensions = {}; - this.selectedExtensions = {}; - this.someExtensionsSelected = false; - this.allExtensionsSelected = false; - this.isNewExtensionsMenuVisible = false; - }, - updateSelectedExtensions: function ($event, name, version) { - var checkbox = $event.target; - if (checkbox.checked) { - this.selectedExtensions[name] = { - 'name': name, - 'version': version - }; - if (this._getObjectSize(this.selectedExtensions) == this._getObjectSize(this.allExtensions)) { - this.someExtensionsSelected = false; - this.allExtensionsSelected = true; - } else { - this.someExtensionsSelected = true; - this.allExtensionsSelected = false; - } - } else { - delete this.selectedExtensions[name]; - this.allExtensionsSelected = false; - this.someExtensionsSelected = (this._getObjectSize(this.selectedExtensions) > 0); - } - }, - toggleNewExtensionsMenu: function() { - this.isNewExtensionsMenuVisible = !this.isNewExtensionsMenuVisible; - }, - hideNewExtensionsMenu: function() { - this.isNewExtensionsMenuVisible = false; - }, - selectAllExtensions: function() { - this.isNewExtensionsMenuVisible = false; - this.someExtensionsSelected = false; - this.allExtensionsSelected = true; - this.selectedExtensions = angular.copy(this.allExtensions); - }, - deselectAllExtensions: function() { - this.isNewExtensionsMenuVisible = false; - this.someExtensionsSelected = false; - this.allExtensionsSelected = false; - this.selectedExtensions = {}; - }, - checkSelectedExtensions: function() { - var result = {error: false, errorMessage: ''}; - if (this._getObjectSize(this.selectedExtensions) > 0) { - result.error = false; - result.errorMessage = ''; - $localStorage.packages = this.selectedExtensions; - } else { - result.error = true; - result.errorMessage = 'Please select at least one extension'; - } - - return result; - }, - _getObjectSize: function (obj) { - var size = 0, key; - for (key in obj) { - if (obj.hasOwnProperty(key)) { - ++size; - } - } - return size; - } - }; - } -]) .filter('startFrom', function () { return function (input, start) { if (input !== undefined && start !== 'NaN') { start = parseInt(start, 10); + return input.slice(start); } + return 0; }; }); diff --git a/setup/pub/magento/setup/marketplace-credentials.js b/setup/pub/magento/setup/marketplace-credentials.js deleted file mode 100644 index a0d17c14d2a2a..0000000000000 --- a/setup/pub/magento/setup/marketplace-credentials.js +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('marketplace-credentials', ['ngStorage']) - .controller('MarketplaceCredentialsController', ['$scope', '$state', '$http', '$localStorage', '$rootScope', '$sce', 'authService', - function ($scope, $state, $http, $localStorage, $rootScope, $sce, authService) { - $scope.showCredsForm = false; - $scope.user = { - username : $localStorage.marketplaceUsername ? $localStorage.marketplaceUsername : '', - password : '', - submitted : false - }; - $scope.actionMessage = $state.current.type == 'upgrade' ? 'upgrade' : 'upgrade or install'; - $scope.errors = false; - - $scope.checkAuth = function() { - if (!$rootScope.isMarketplaceAuthorized) { - $scope.isHiddenSpinner = false; - authService.checkAuth({ - success: function(response) { - $scope.isHiddenSpinner = true; - $scope.user.username = response.data.username; - $scope.nextState(); - }, - fail: function(response) { - $scope.isHiddenSpinner = true; - $scope.showCredsForm = true; - }, - error: function() { - $scope.isHiddenSpinner = true; - $scope.errors = true; - } - }); - } else { - $scope.nextState(); - } - }; - - $scope.upgradeProcessError = false; - if ($state.current.type == 'upgrade') { - $scope.isHiddenSpinner = false; - $http.get('index.php/select-version/installedSystemPackage', {'responseType' : 'json'}) - .then(function successCallback(resp) { - var data = resp.data; - - $scope.isHiddenSpinner = true; - - if (data.responseType == 'error') { - $scope.upgradeProcessError = true; - $scope.upgradeProcessErrorMessage = $sce.trustAsHtml(data.error); - } else { - $scope.checkAuth(); - } - }, function errorCallback() { - $scope.isHiddenSpinner = true; - $scope.upgradeProcessError = true; - }); - } else { - $scope.checkAuth(); - } - - $scope.saveAuthJson = function () { - if ($scope.auth.$valid) { - $scope.isHiddenSpinner = false; - authService.saveAuthJson({ - user: $scope.user, - success: function(response) { - $scope.isHiddenSpinner = true; - $scope.saveAuthJson.result = response; - $scope.logout = false; - $scope.errors = false; - $scope.nextState(); - }, - fail: function(response) { - $scope.isHiddenSpinner = true; - $scope.saveAuthJson.result = response; - $scope.errors = true; - }, - error: function(data) { - $scope.isHiddenSpinner = true; - $scope.errors = true; - $scope.saveAuthJson.failed = data; - } - }); - } else { - $scope.validate(); - } - }; - - $scope.validate = function() { - $scope.user.submitted = !$scope.user.$valid; - } - }]); diff --git a/setup/pub/magento/setup/module-grid.js b/setup/pub/magento/setup/module-grid.js deleted file mode 100644 index 3866c41716aee..0000000000000 --- a/setup/pub/magento/setup/module-grid.js +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('module-grid', ['ngStorage']) - .controller('moduleGridController', ['$rootScope', '$scope', '$http', '$localStorage', '$state', 'titleService', 'paginationService', - function ($rootScope, $scope, $http, $localStorage, $state, titleService, paginationService) { - $rootScope.modulesProcessed = false; - $http.get('index.php/moduleGrid/modules').then(function successCallback(resp) { - var data = resp.data; - - $scope.modules = data.modules; - $scope.total = data.total; - $scope.currentPage = 1; - $scope.rowLimit = '20'; - $scope.numberOfPages = Math.ceil($scope.total/$scope.rowLimit); - $rootScope.modulesProcessed = true; - }); - - paginationService.initWatchers($scope); - - $scope.selectedComponent = null; - - $scope.isActiveActionsCell = function(component) { - return $scope.selectedComponent === component; - }; - - $scope.toggleActiveActionsCell = function(component) { - $scope.selectedComponent = $scope.selectedComponent == component ? null : component; - }; - - $scope.closeActiveActionsCell = function(component) { - $scope.toggleActiveActionsCell(component); - }; - - $scope.predicate = 'name'; - $scope.reverse = false; - $scope.order = function(predicate) { - $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false; - $scope.predicate = predicate; - }; - - $scope.getIndicatorInfo = function(component, type) { - var indicators = { - 'on' : {'icon' : '_on', 'label' : 'On'}, - 'off' : {'icon' : '_off', 'label' : 'Off'} - }; - - var types = ['label', 'icon']; - - if (types.indexOf(type) == -1) { - type = 'icon'; - } - - if (component.enable === true) { - return indicators.on[type]; - } - - return indicators.off[type]; - }; - - $scope.enableDisable = function(type, component) { - $localStorage.packages = [ - { - name: component.moduleName, - isComposerPackage: component.name !== 'unknown', - } - ]; - titleService.setTitle(type, component); - $localStorage.componentType = component.type; - $state.go('root.readiness-check-'+type); - }; - } - ]); diff --git a/setup/pub/magento/setup/readiness-check.js b/setup/pub/magento/setup/readiness-check.js deleted file mode 100644 index d32d640cab48b..0000000000000 --- a/setup/pub/magento/setup/readiness-check.js +++ /dev/null @@ -1,428 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('readiness-check', ['remove-dialog']) - .constant('COUNTER', 1) - .controller('readinessCheckController', ['$rootScope', '$scope', '$localStorage', '$http', '$timeout', '$sce', '$state', 'COUNTER', 'ngDialog', function ($rootScope, $scope, $localStorage, $http, $timeout, $sce, $state, COUNTER, ngDialog) { - $scope.Object = Object; - $scope.titles = $localStorage.titles; - $scope.moduleName = $localStorage.moduleName; - $scope.progressCounter = COUNTER; - $rootScope.needReCheck = false; - $scope.startProgress = function() { - ++$scope.progressCounter; - }; - $scope.componentDependency = { - enabled: true, - visible: false, - processed: false, - expanded: false, - isRequestError: false, - errorMessage: '', - packages: null - }; - switch ($state.current.type) { - case 'uninstall': - $scope.dependencyUrl = 'index.php/dependency-check/uninstall-dependency-check'; - if ($localStorage.packages) { - $scope.componentDependency.packages = $localStorage.packages; - } - break; - case 'enable': - case 'disable': - $scope.componentDependency.enabled = $localStorage.packages[0].isComposerPackage; - $scope.dependencyUrl = 'index.php/dependency-check/enable-disable-dependency-check'; - if ($localStorage.packages) { - $scope.componentDependency.packages = { - type: $state.current.type, - packages: $localStorage.packages - }; - } - break; - default: - $scope.dependencyUrl = 'index.php/dependency-check/component-dependency'; - if ($localStorage.packages) { - $scope.componentDependency.packages = $localStorage.packages; - } - } - $scope.stopProgress = function() { - --$scope.progressCounter; - if ($scope.progressCounter == COUNTER) { - $scope.resetProgress(); - } - }; - $scope.resetProgress = function() { - $scope.progressCounter = 0; - }; - $rootScope.checkingInProgress = function() { - return $scope.progressCounter > 0; - }; - $scope.requestFailedHandler = function(obj) { - obj.processed = true; - obj.isRequestError = true; - $scope.hasErrors = true; - $rootScope.hasErrors = true; - $scope.stopProgress(); - }; - $scope.completed = false; - $scope.hasErrors = false; - - $scope.version = { - visible: false, - processed: false, - expanded: false, - isRequestError: false - }; - $scope.settings = { - visible: false, - processed: false, - expanded: false, - isRequestError: false, - isRequestWarning: false - }; - $scope.extensions = { - visible: false, - processed: false, - expanded: false, - isRequestError: false - }; - $scope.permissions = { - visible: false, - processed: false, - expanded: false, - isRequestError: false - }; - $scope.updater = { - visible: false, - processed: false, - expanded: false, - isRequestError: false - }; - $scope.cronScript = { - visible: false, - processed: false, - expanded: false, - isRequestError: false, - notice: false, - setupErrorMessage: '', - updaterErrorMessage: '', - setupNoticeMessage: '', - updaterNoticeMessage: '' - }; - $scope.items = { - 'php-settings': { - url:'index.php/environment/php-settings', - params: $scope.actionFrom, - useGet: true, - show: function() { - $scope.startProgress(); - $scope.settings.visible = true; - }, - process: function(data) { - $scope.settings.processed = true; - angular.extend($scope.settings, data); - $scope.updateOnProcessed($scope.settings.responseType); - $scope.stopProgress(); - }, - fail: function() { - $scope.requestFailedHandler($scope.settings); - } - }, - 'php-extensions': { - url:'index.php/environment/php-extensions', - params: $scope.actionFrom, - useGet: true, - show: function() { - $scope.startProgress(); - $scope.extensions.visible = true; - }, - process: function(data) { - $scope.extensions.processed = true; - angular.extend($scope.extensions, data); - if(data.responseType !== 'error') { - $scope.extensions.length = Object.keys($scope.extensions.data.required).length; - } - $scope.updateOnProcessed($scope.extensions.responseType); - $scope.stopProgress(); - }, - fail: function() { - $scope.requestFailedHandler($scope.extensions); - } - } - }; - - if ($scope.actionFrom === 'installer') { - $scope.items['php-version'] = { - url:'index.php/environment/php-version', - params: $scope.actionFrom, - useGet: true, - show: function() { - $scope.startProgress(); - $scope.version.visible = true; - }, - process: function(data) { - $scope.version.processed = true; - angular.extend($scope.version, data); - $scope.updateOnProcessed($scope.version.responseType); - $scope.stopProgress(); - }, - fail: function() { - $scope.requestFailedHandler($scope.version); - } - }; - $scope.items['file-permissions'] = { - url:'index.php/environment/file-permissions', - show: function() { - $scope.startProgress(); - $scope.permissions.visible = true; - }, - process: function(data) { - $scope.permissions.processed = true; - angular.extend($scope.permissions, data); - $scope.updateOnProcessed($scope.permissions.responseType); - $scope.stopProgress(); - }, - fail: function() { - $scope.requestFailedHandler($scope.permissions); - } - }; - } - - if ($scope.actionFrom === 'updater') { - $scope.items['updater-application'] = { - url:'index.php/environment/updater-application', - show: function() { - $scope.startProgress(); - $scope.updater.visible = true; - }, - process: function(data) { - $scope.updater.processed = true; - angular.extend($scope.updater, data); - $scope.updateOnProcessed($scope.updater.responseType); - $scope.stopProgress(); - }, - fail: function() { - $scope.requestFailedHandler($scope.updater); - } - }; - $scope.items['cron-script'] = { - url:'index.php/environment/cron-script', - show: function() { - $scope.startProgress(); - $scope.cronScript.visible = true; - }, - process: function(data) { - $scope.cronScript.processed = true; - if (data.setupErrorMessage) { - data.setupErrorMessage = $sce.trustAsHtml(data.setupErrorMessage); - } - if (data.updaterErrorMessage) { - data.updaterErrorMessage = $sce.trustAsHtml(data.updaterErrorMessage); - } - if (data.setupNoticeMessage) { - $scope.cronScript.notice = true; - data.setupNoticeMessage = $sce.trustAsHtml(data.setupNoticeMessage); - } - if (data.updaterNoticeMessage) { - $scope.cronScript.notice = true; - data.updaterNoticeMessage = $sce.trustAsHtml(data.updaterNoticeMessage); - } - angular.extend($scope.cronScript, data); - $scope.updateOnProcessed($scope.cronScript.responseType); - $scope.stopProgress(); - }, - fail: function() { - $scope.requestFailedHandler($scope.cronScript); - } - }; - if ($scope.componentDependency.enabled) { - $scope.items['component-dependency'] = { - url: $scope.dependencyUrl, - params: $scope.componentDependency.packages, - show: function() { - $scope.startProgress(); - $scope.componentDependency.visible = true; - }, - process: function(data) { - $scope.componentDependency.processed = true; - if (data.errorMessage) { - data.errorMessage = $sce.trustAsHtml(data.errorMessage); - } - angular.extend($scope.componentDependency, data); - $scope.updateOnProcessed($scope.componentDependency.responseType); - $scope.stopProgress(); - }, - fail: function() { - $scope.requestFailedHandler($scope.componentDependency); - } - }; - } - } - - $scope.isCompleted = function() { - var cronProcessed = ( - $scope.cronScript.processed - && ($scope.componentDependency.processed || !$scope.componentDependency.enabled) - && $scope.updater.processed - ); - - return $scope.settings.processed - && $scope.extensions.processed - && ($scope.permissions.processed || ($scope.actionFrom === 'updater')) - && ($scope.version.processed || ($scope.actionFrom === 'updater')) - && (cronProcessed || ($scope.actionFrom !== 'updater')); - }; - - $scope.updateOnProcessed = function(value) { - if (!$rootScope.hasErrors) { - $rootScope.hasErrors = (value != 'success'); - $scope.hasErrors = $rootScope.hasErrors; - } - }; - - $scope.updateOnError = function(obj) { - obj.expanded = true; - }; - - $scope.updateOnSuccess = function(obj) { - obj.expanded = false; - }; - - $scope.updateOnExpand = function(obj) { - obj.expanded = !obj.expanded; - }; - - $scope.hasItem = function(haystack, needle) { - return haystack.indexOf(needle) > -1; - }; - - $scope.query = function(item) { - if (item.params) { - if (item.useGet === true) { - // The http request type has been changed from POST to GET for a reason. The POST request - // results in PHP throwing a warning regards to 'always_populate_raw_post_data' - // being incorrectly set to a value different than -1. This warning is throw during the initial - // boot up sequence when POST request is received before the control gets transferred over to - // the Magento customer error handler, hence not catchable. To avoid that warning, the HTTP - // request type is being changed from POST to GET for select queries. Those queries are: - // (1) PHP Version Check (2) PHP Settings Check and (3) PHP Extensions Check. - - item.url = item.url + '?type=' + item.params; - } else { - return $http.post(item.url, item.params) - .then(function successCallback(resp) { - item.process(resp.data); - }, function successCallback() { - item.fail(); - }); - } - } - // setting 1 minute timeout to prevent system from timing out - return $http.get(item.url, { timeout: 60000 }) - .then(function successCallback(resp) { - item.process(resp.data); - }, function errorCallback() { - item.fail(); - }); - }; - - $scope.progress = function() { - $rootScope.hasErrors = false; - $scope.hasErrors = false; - angular.forEach($scope.items, function(item) { - item.show(); - }); - var $delay = 0; - angular.forEach($scope.items, function(item) { - $timeout(function() { $scope.query(item); }, $delay * 1000); - $delay++; - }); - }; - - $scope.$on('$stateChangeSuccess', function (event, nextState) { - if (nextState.id == 'root.readiness-check-' + nextState.type +'.progress') { - $scope.progress(); - } - }); - - $scope.wordingOfReadinessCheckAction = function() { - var $actionString = 'We\'re making sure your server environment is ready for '; - if ($localStorage.moduleName) { - $actionString += $localStorage.packageTitle ? $localStorage.packageTitle : $localStorage.moduleName; - } else { - if($state.current.type === 'install' || $state.current.type === 'upgrade') { - $actionString += 'Magento'; - if ($state.current.type === 'upgrade' && $localStorage.packages.length > 1 ) { - $actionString += ' and selected components'; - } - } else { - $actionString += 'package'; - if ($scope.getObjectSize($localStorage.packages) > 1) { - $actionString += 's'; - } - } - } - $actionString += " to be " + $state.current.type; - if ($scope.endsWith($state.current.type, 'e')) { - $actionString += 'd'; - } else { - $actionString +='ed'; - } - - if ($localStorage.moduleName - && $localStorage.packageTitle - && $localStorage.moduleName != $localStorage.packageTitle - ) { - $actionString += ', which consists of the following packages:<br/>- ' + $localStorage.moduleName; - } - - return $actionString; - }; - - $scope.getExtensionsList = function () { - return $scope.componentDependency.packages ? $scope.componentDependency.packages : {}; - }; - - $scope.openDialog = function (name) { - $scope.extensionToRemove = name; - ngDialog.open({scope: $scope, template: 'removeDialog', controller: 'removeDialogController'}); - }; - - $scope.getCurrentVersion = function (name) { - if ($scope.getExtensionInfo(name).hasOwnProperty('currentVersion')) { - return $scope.getExtensionInfo(name)['currentVersion']; - } - - return ''; - }; - - $scope.getVersionsList = function (name) { - if ($scope.getExtensionInfo(name).hasOwnProperty('versions')) { - return $scope.getExtensionInfo(name)['versions']; - } - - return {}; - }; - - $scope.getExtensionInfo = function (name) { - var extensionsVersions = $localStorage.extensionsVersions; - return extensionsVersions.hasOwnProperty(name) ? extensionsVersions[name] : {}; - }; - - $scope.versionChanged = function () { - $rootScope.needReCheck = true; - }; - - $scope.getObjectSize = function (obj) { - var size = 0, key; - for (key in obj) { - if (obj.hasOwnProperty(key)) { - ++size; - } - } - return size; - }; - }]); diff --git a/setup/pub/magento/setup/remove-dialog.js b/setup/pub/magento/setup/remove-dialog.js deleted file mode 100644 index 7339cada398d8..0000000000000 --- a/setup/pub/magento/setup/remove-dialog.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('remove-dialog', []) - .controller('removeDialogController', ['$rootScope', '$scope', '$localStorage', - function ($rootScope, $scope, $localStorage) { - $scope.removeExtension = function (name) { - delete $scope.componentDependency.packages[name]; - $localStorage.packages = $scope.componentDependency.packages; - $rootScope.needReCheck = true; - $scope.closeThisDialog(); - }; - }]); diff --git a/setup/pub/magento/setup/select-version.js b/setup/pub/magento/setup/select-version.js deleted file mode 100644 index 52c1f4284a22d..0000000000000 --- a/setup/pub/magento/setup/select-version.js +++ /dev/null @@ -1,207 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('select-version', ['ngStorage']) - .controller('selectVersionController', ['$scope', '$http', '$localStorage', '$sce', function ($scope, $http, $localStorage, $sce) { - $scope.packages = [{ - name: '', - version: '' - }]; - $scope.upgradeReadyForNext = false; - $scope.upgradeProcessed = false; - $scope.upgradeProcessError = false; - $scope.upgradeAlreadyLatestVersion = false; - $scope.upgradeProcessErrorMessage = ''; - $scope.componentsReadyForNext = true; - $scope.componentsProcessed = false; - $scope.componentsProcessError = false; - $scope.showUnstable = false; - - $scope.tryAgainEnabled = function() { - return ($scope.upgradeProcessed || $scope.upgradeProcessError) - && ($scope.updateComponents.no || - ($scope.updateComponents.yes && ($scope.componentsProcessed || $scope.componentsProcessError)) - ); - }; - - $http.get('index.php/select-version/systemPackage', {'responseType' : 'json'}) - .then(function successCallback(resp) { - var data = resp.data; - - if (data.responseType != 'error') { - $scope.upgradeProcessError = true; - - angular.forEach(data.packages, function (value, key) { - if (!value.current) { - return $scope.upgradeProcessError = false; - } - }); - - if ($scope.upgradeProcessError) { - $scope.upgradeProcessErrorMessage = "You're already using the latest version, there's nothing for us to do."; - $scope.upgradeAlreadyLatestVersion = true; - } else { - $scope.selectedOption = []; - $scope.versions = []; - $scope.data = data; - angular.forEach(data.packages, function (value, key) { - if (value.stable && !value.current) { - $scope.versions.push({ - 'versionInfo': angular.toJson({ - 'package': value.package, - 'version': value.id - }), - 'version': value - }); - } else if (value.stable && value.current) { - $scope.currentVersion = value.name; - } - }); - - if ($scope.versions.length > 0) { - $scope.selectedOption = $scope.versions[0].versionInfo; - $scope.upgradeReadyForNext = true; - } - } - - } else { - $scope.upgradeProcessError = true; - $scope.upgradeProcessErrorMessage = $sce.trustAsHtml(data.error); - } - $scope.upgradeProcessed = true; - }, function errorCallback() { - $scope.upgradeProcessError = true; - }); - - $scope.updateComponents = { - yes: false, - no: true - }; - - $scope.$watch('currentPage + rowLimit', function() { - var begin = (($scope.currentPage - 1) * $scope.rowLimit); - var end = parseInt(begin) + parseInt(($scope.rowLimit)); - $scope.numberOfPages = Math.ceil($scope.total/$scope.rowLimit); - if ($scope.components !== undefined) { - $scope.displayComponents = $scope.components.slice(begin, end); - } - if ($scope.currentPage > $scope.numberOfPages) { - $scope.currentPage = $scope.numberOfPages; - } - }); - - $scope.$watch('updateComponents.no', function() { - if (angular.equals($scope.updateComponents.no, true)) { - $scope.updateComponents.yes = false; - } - }); - - $scope.$watch('updateComponents.yes', function() { - if (angular.equals($scope.updateComponents.yes, true)) { - $scope.updateComponents.no = false; - if (!$scope.componentsProcessed && !$scope.componentsProcessError) { - $scope.componentsReadyForNext = false; - $http.get('index.php/other-components-grid/components', {'responseType': 'json'}). - then(function successCallback(resp) { - var data = resp.data; - - if (data.responseType != 'error') { - $scope.components = data.components; - $scope.displayComponents = data.components; - $scope.totalForGrid = data.total; - $scope.total = data.total; - $scope.currentPage = 1; - $scope.rowLimit = '20'; - $scope.numberOfPages = Math.ceil(data.total/$scope.rowLimit); - for (var i = 0; i < $scope.totalForGrid; i++) { - $scope.packages.push({ - name: $scope.components[i].name, - version: $scope.components[i].updates[0].id - }); - } - $scope.componentsReadyForNext = true; - } else { - $scope.componentsProcessError = true; - } - $scope.componentsProcessed = true; - }, function errorCallback() { - $scope.componentsProcessError = true; - }); - } - } - }); - - $scope.setComponentVersion = function(name, $version) { - for (var i = 0; i < $scope.totalForGrid; i++) { - if ($scope.packages[i + 1].name === name) { - $scope.packages[i + 1].version = $version; - } - } - }; - - $scope.AddRemoveComponentOnSliderMove = function(component) { - var found = false; - for (var i = 0; i < $scope.packages.length; i++) { - if ($scope.packages[i].name === component.name) { - $scope.packages.splice(i, 1); - $scope.totalForGrid = $scope.totalForGrid - 1; - found = true; - } - } - if (!found) { - $scope.packages.push({ - name: component.name, - version: component.dropdownId - }); - $scope.totalForGrid = $scope.totalForGrid + 1; - } - }; - - $scope.isSelected = function(name) { - for (var i = 0; i < $scope.packages.length; i++) { - if ($scope.packages[i].name === name) { - return true; - } - } - return false; - }; - - $scope.showUnstableClick = function() { - $scope.upgradeReadyForNext = false; - $scope.selectedOption = []; - $scope.versions = []; - angular.forEach($scope.data.packages, function (value, key) { - if ((value.stable || $scope.showUnstable) && !value.current) { - $scope.versions.push({ - 'versionInfo': angular.toJson({ - 'package': value.package, - 'version': value.id - }), - 'version': value - }); - } - }); - - if ($scope.versions.length > 0) { - $scope.selectedOption = $scope.versions[0].versionInfo; - $scope.upgradeReadyForNext = true; - } - }; - - $scope.update = function() { - var selectedVersionInfo = angular.fromJson($scope.selectedOption); - $scope.packages[0]['name'] = selectedVersionInfo.package; - $scope.packages[0].version = selectedVersionInfo.version; - if (angular.equals($scope.updateComponents.no, true)) { - if ($scope.totalForGrid > 0) { - $scope.packages.splice(1, $scope.totalForGrid); - } - } - $localStorage.moduleName = ''; - $localStorage.packages = $scope.packages; - $scope.nextState(); - }; - }]); diff --git a/setup/pub/magento/setup/start-updater.js b/setup/pub/magento/setup/start-updater.js deleted file mode 100644 index 1b6e2e515bf72..0000000000000 --- a/setup/pub/magento/setup/start-updater.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('start-updater', ['ngStorage']) - .controller('startUpdaterController', ['$scope', '$state', '$localStorage', '$http', '$window', function ($scope, $state, $localStorage, $http, $window) { - - $scope.type = $state.current.type; - $scope.buttonText = $scope.type.charAt(0).toUpperCase() + $scope.type.slice(1); - $localStorage.successPageAction = $state.current.type; - - if ($localStorage.packages) { - $scope.packages = $localStorage.packages; - } - if ($localStorage.dataOption) { - $scope.dataOption = $localStorage.dataOption; - } - if ($localStorage.backupInfo) { - $scope.backupInfoPassed = $localStorage.backupInfo; - } - if ($localStorage.titles) { - $scope.title = $localStorage.titles[$state.current.type]; - } - - $scope.started = false; - $scope.errorMessage = ''; - $scope.update = function() { - $scope.started = true; - var payLoad = { - 'packages': $scope.packages, - 'type': $state.current.type, - 'headerTitle': $scope.packages.size == 1 ? $scope.title : 'Process extensions', - 'dataOption': $localStorage.dataOption - }; - $http.post('index.php/start-updater/update', payLoad) - .then(function successCallback(resp) { - var data = resp.data; - - if (data.success) { - $window.location.href = '../update/index.php'; - } else { - $scope.errorMessage = data.message; - } - }, function errorCallback() { - $scope.errorMessage = 'Something went wrong. Please try again.'; - }); - }; - $scope.goToPreviousState = function() { - if ($state.current.type === 'uninstall') { - $state.go('root.data-option'); - } else { - $state.go('root.create-backup-' + $state.current.type); - } - }; - }]); diff --git a/setup/pub/magento/setup/success.js b/setup/pub/magento/setup/success.js deleted file mode 100644 index 477e7250e3aff..0000000000000 --- a/setup/pub/magento/setup/success.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('success', ['ngStorage']) - .controller('successController', ['$scope', '$localStorage', function ($scope, $localStorage) { - $scope.url = { - front: '', - admin: '' - }; - $scope.db = $localStorage.db; - $scope.admin = $localStorage.admin; - $scope.config = $localStorage.config; - if ($scope.config.https.front) { - $scope.url.front = $scope.config.https.text; - } else { - $scope.url.front = $scope.config.address.actual_base_url; - } - if ($scope.config.https.admin) { - $scope.url.admin = $scope.config.https.text + $scope.config.address.admin + '/'; - } else { - $scope.url.admin = $scope.config.address.actual_base_url + $scope.config.address.admin + '/'; - } - $scope.messages = $localStorage.messages; - $localStorage.$reset(); - $scope.admin.password = ''; - $scope.db.password = ''; - $localStorage.$reset(); - }]); diff --git a/setup/pub/magento/setup/system-config.js b/setup/pub/magento/setup/system-config.js deleted file mode 100644 index 40b155076bc8f..0000000000000 --- a/setup/pub/magento/setup/system-config.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('system-config', ['ngStorage']) - .controller('systemConfigController', ['$scope', '$state', '$http', '$localStorage', '$rootScope', 'authService', - function ($scope, $state, $http, $localStorage, $rootScope, authService) { - $scope.isHiddenSpinner = false; - $scope.user = { - username : $localStorage.marketplaceUsername ? $localStorage.marketplaceUsername : '', - password : '', - submitted : false - }; - - if (!$rootScope.isMarketplaceAuthorized) { - $scope.isHiddenSpinner = false; - authService.checkAuth({ - success: function(response) { - $scope.isHiddenSpinner = true; - $scope.user.username = response.data.username; - }, - fail: function(response) { - $scope.isHiddenSpinner = true; - }, - error: function() { - $scope.isHiddenSpinner = true; - } - }); - } else { - $scope.isHiddenSpinner = true; - } - - $scope.saveAuthJson = function () { - if ($scope.auth.$valid) { - $scope.isHiddenSpinner = false; - authService.saveAuthJson({ - user: $scope.user, - success: function(response) { - $scope.isHiddenSpinner = true; - $scope.saveAuthJson.result = response; - $scope.logout = false; - }, - fail: function(response) { - $scope.isHiddenSpinner = true; - $scope.saveAuthJson.result = response; - }, - error: function(data) { - $scope.isHiddenSpinner = true; - $scope.saveAuthJson.failed = data; - } - }); - } else { - $scope.validate(); - } - }; - - $scope.reset = function () { - authService.reset({ - success: function() { - $scope.logout = true; - } - }) - }; - - $scope.validate = function() { - $scope.user.submitted = !$scope.user.$valid; - } - }]); diff --git a/setup/pub/magento/setup/update-extension-grid.js b/setup/pub/magento/setup/update-extension-grid.js deleted file mode 100644 index 78af0d7faf31d..0000000000000 --- a/setup/pub/magento/setup/update-extension-grid.js +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('update-extension-grid', ['ngStorage', 'clickOut']) - .controller('updateExtensionGridController', ['$scope', '$http', '$localStorage', 'titleService', 'authService', 'paginationService', 'multipleChoiceService', - function ($scope, $http, $localStorage, titleService, authService, paginationService, multipleChoiceService) { - $scope.isHiddenSpinner = false; - - $http.get('index.php/updateExtensionGrid/extensions').then(function successCallback(resp) { - var data = resp.data; - - $scope.error = false; - $scope.errorMessage = ''; - $scope.extensionsVersions = {}; - $scope.multipleChoiceService = multipleChoiceService; - $scope.multipleChoiceService.reset(); - angular.forEach(data.extensions, function(extension) { - extension.updateVersion = extension.latestVersion; - $scope.multipleChoiceService.addExtension(extension.name, extension.latestVersion); - $scope.extensionsVersions[extension.name] = { - 'currentVersion': extension.version, - 'versions': extension.versions - }; - }); - $scope.extensions = data.extensions; - $scope.total = data.total; - $scope.currentPage = 1; - $scope.rowLimit = '20'; - $scope.numberOfPages = Math.ceil($scope.total / $scope.rowLimit); - $scope.isHiddenSpinner = true; - $localStorage.extensionsVersions = $scope.extensionsVersions; - }); - - paginationService.initWatchers($scope); - - $scope.predicate = 'name'; - $scope.reverse = false; - $scope.order = function (predicate) { - $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false; - $scope.predicate = predicate; - }; - - $scope.update = function(extension) { - $localStorage.packages = [ - { - name: extension.name, - version: extension.updateVersion - } - ]; - titleService.setTitle('update', extension); - $scope.nextState(); - }; - $scope.isHiddenSpinner = true; - $scope.updateAll = function() { - $scope.isHiddenSpinner = false; - authService.checkAuth({ - success: function(response) { - $scope.isHiddenSpinner = true; - var result = $scope.multipleChoiceService.checkSelectedExtensions(); - $scope.error = result.error; - $scope.errorMessage = result.errorMessage; - - if (!$scope.error) { - $scope.nextState(); - } - }, - fail: function(response) { - $scope.isHiddenSpinner = true; - authService.openAuthDialog($scope); - }, - error: function() { - $scope.isHiddenSpinner = true; - $scope.error = true; - $scope.errorMessage = 'Internal server error'; - } - }); - }; - } - ]); diff --git a/setup/pub/magento/setup/updater-success.js b/setup/pub/magento/setup/updater-success.js deleted file mode 100644 index 96027959727d0..0000000000000 --- a/setup/pub/magento/setup/updater-success.js +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('updater-success', ['ngStorage']) - .controller('updaterSuccessController', ['$scope', '$state', '$localStorage', '$window', 'navigationService', function ($scope, $state, $localStorage, $window, navigationService) { - if ($localStorage.successPageAction) { - $scope.successPageAction = $localStorage.successPageAction; - switch (true) { - case $scope.endsWith($scope.successPageAction, 'd'): - $scope.successPageActionMessage = $scope.successPageAction; - break; - case $scope.endsWith($scope.successPageAction, 'e'): - $scope.successPageActionMessage = $scope.successPageAction + 'd'; - break; - default: - $scope.successPageActionMessage = $scope.successPageAction + 'ed'; - } - } - if ($localStorage.packages) { - $scope.packages = $localStorage.packages; - } - if (typeof $localStorage.rollbackStarted !== 'undefined') { - $scope.rollbackStarted = $localStorage.rollbackStarted; - } - $scope.back = function () { - if ($scope.successPageAction) { - $scope.goToAction($scope.successPageAction); - } else { - $window.location.href = ''; - } - }; - $localStorage.$reset(); - $scope.isHiddenSpinner = false; - navigationService.load().then(function () { - $scope.isHiddenSpinner = true; - }); - }]); diff --git a/setup/pub/magento/setup/web-configuration.js b/setup/pub/magento/setup/web-configuration.js deleted file mode 100644 index 8464a5d615f75..0000000000000 --- a/setup/pub/magento/setup/web-configuration.js +++ /dev/null @@ -1,148 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -'use strict'; -angular.module('web-configuration', ['ngStorage']) - .controller('webConfigurationController', ['$scope', '$state', '$localStorage', '$http', function ($scope, $state, $localStorage, $http) { - $scope.config = { - address: { - base_url: '', - auto_base_url: '', - actual_base_url: '', - admin: '' - }, - https: { - front: false, - admin: false, - text: '' - }, - rewrites: { - allowed: true - }, - encrypt: { - key: null, - type: 'magento' - }, - advanced: { - expanded: false - }, - sessionSave: { - type: 'files', - error: false - } - }; - - if ($localStorage.config) { - $scope.config = $localStorage.config; - } - - $scope.$on('nextState', function () { - $localStorage.config = $scope.config; - }); - - $scope.updateOnExpand = function(obj) { - obj.expanded = !obj.expanded; - }; - - $scope.fillBaseURL = function() { - if (angular.equals($scope.config.address.base_url, '')) { - $scope.config.address.base_url = $scope.config.address.auto_base_url; - } - }; - - $scope.$watch('config.address.base_url', function() { - if (angular.equals($scope.config.address.base_url, '')) { - $scope.config.address.actual_base_url = $scope.config.address.auto_base_url; - } else { - $scope.config.address.actual_base_url = $scope.config.address.base_url; - } - }); - - $scope.$watch('config.encrypt.type', function() { - if (angular.equals($scope.config.encrypt.type, 'magento')) { - $scope.config.encrypt.key = null; - } - }); - - $scope.$watch('config.address.base_url', function() { - if (angular.equals($scope.config.https.text, '') || angular.isUndefined($scope.config.https.text)) { - $scope.config.https.text = $scope.config.address.base_url.replace('http://', 'https://'); - } - }); - - $scope.populateHttps = function() { - $scope.config.https.text = $scope.config.address.base_url.replace('http://', 'https://'); - }; - - $scope.showEncryptKey = function() { - return angular.equals($scope.config.encrypt.type, 'user'); - }; - - $scope.showHttpsField = function() { - return ($scope.config.https.front || $scope.config.https.admin); - }; - - $scope.addSlash = function() { - if (angular.isUndefined($scope.config.address.base_url)) { - return; - } - - var p = $scope.config.address.base_url; - if (p.length > 1) { - var lastChar = p.substr(-1); - if (lastChar != '/') { - $scope.config.address.base_url = p + '/'; - } - } - }; - - // Listens on form validate event, dispatched by parent controller - $scope.$on('validate-' + $state.current.id, function() { - $scope.validate(); - }); - - // Dispatch 'validation-response' event to parent controller - $scope.validate = function() { - if ($scope.webconfig.$valid) { - $scope.$emit('validation-response', true); - } else { - $scope.$emit('validation-response', false); - $scope.webconfig.submitted = true; - } - }; - - // Update 'submitted' flag - $scope.$watch(function() { return $scope.webconfig.$valid }, function(valid) { - if (valid) { - $scope.webconfig.submitted = false; - } - }); - - // Validate URL - $scope.validateUrl = function () { - if (!$scope.webconfig.submitted) { - $http.post('index.php/url-check', $scope.config) - .then(function successCallback(resp) { - $scope.validateUrl.result = resp.data; - - if ($scope.validateUrl.result.successUrl && $scope.validateUrl.result.successSecureUrl) { - $scope.nextState(); - } - - if (!$scope.validateUrl.result.successUrl) { - $scope.webconfig.submitted = true; - $scope.webconfig.base_url.$setValidity('url', false); - } - - if (!$scope.validateUrl.result.successSecureUrl) { - $scope.webconfig.submitted = true; - $scope.webconfig.https.$setValidity('url', false); - } - }, function errorCallback(resp) { - $scope.validateUrl.failed = resp.data; - }); - } - }; - }]); diff --git a/setup/src/Magento/Setup/Console/Command/CronRunCommand.php b/setup/src/Magento/Setup/Console/Command/CronRunCommand.php deleted file mode 100644 index fde655843f5a6..0000000000000 --- a/setup/src/Magento/Setup/Console/Command/CronRunCommand.php +++ /dev/null @@ -1,158 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Console\Command; - -use Magento\Framework\App\DeploymentConfig; -use Magento\Setup\Model\Cron\Queue; -use Magento\Setup\Model\Cron\ReadinessCheck; -use Magento\Setup\Model\Cron\Status; -use Symfony\Component\Console\Input\InputInterface; -use Symfony\Component\Console\Output\OutputInterface; - -/** - * Command to run scheduled jobs, this command should be run as a cron job - */ -class CronRunCommand extends AbstractSetupCommand -{ - /** - * @var DeploymentConfig - */ - protected $deploymentConfig; - - /** - * @var Queue - */ - protected $queue; - - /** - * @var Status - */ - protected $status; - - /** - * @var ReadinessCheck - */ - protected $readinessCheck; - - /** - * @param DeploymentConfig $deploymentConfig - * @param Queue $queue - * @param ReadinessCheck $readinessCheck - * @param Status $status - */ - public function __construct( - DeploymentConfig $deploymentConfig, - Queue $queue, - ReadinessCheck $readinessCheck, - Status $status - ) { - $this->deploymentConfig = $deploymentConfig; - $this->queue = $queue; - $this->readinessCheck = $readinessCheck; - $this->status = $status; - parent::__construct(); - } - - /** - * Initialization of the command - * - * @return void - */ - protected function configure() - { - $this->setName('setup:cron:run') - ->setDescription('Runs cron job scheduled for setup application'); - - parent::configure(); - } - - /** - * {@inheritdoc} - */ - protected function execute(InputInterface $input, OutputInterface $output) - { - $notification = 'setup-cron: Please check var/log/update.log for execution summary.'; - - if (!$this->deploymentConfig->isAvailable()) { - $output->writeln($notification); - $this->status->add('Magento is not installed.', \Psr\Log\LogLevel::INFO); - return \Magento\Framework\Console\Cli::RETURN_SUCCESS; - } - - if (!$this->checkRun()) { - $output->writeln($notification); - // we must have an exit code higher than zero to indicate something was wrong - return \Magento\Framework\Console\Cli::RETURN_FAILURE; - } - try { - $this->status->toggleUpdateInProgress(); - } catch (\RuntimeException $e) { - $this->status->add($e->getMessage(), \Psr\Log\LogLevel::ERROR); - $output->writeln($notification); - // we must have an exit code higher than zero to indicate something was wrong - return \Magento\Framework\Console\Cli::RETURN_FAILURE; - } - - $returnCode = $this->executeJobsFromQueue(); - if ($returnCode != \Magento\Framework\Console\Cli::RETURN_SUCCESS) { - $output->writeln($notification); - } - - return $returnCode; - } - - /** - * Check if Cron job can be run - * - * @return bool - */ - private function checkRun() - { - return $this->readinessCheck->runReadinessCheck() - && !$this->status->isUpdateInProgress() - && !$this->status->isUpdateError(); - } - - /** - * Executes setup jobs from the queue - * - * @return int - */ - private function executeJobsFromQueue() - { - $returnCode = \Magento\Framework\Console\Cli::RETURN_SUCCESS; - try { - while (!empty($this->queue->peek()) && strpos($this->queue->peek()[Queue::KEY_JOB_NAME], 'setup:') === 0) { - $job = $this->queue->popQueuedJob(); - $this->status->add( - sprintf('Job "%s" has started' . PHP_EOL, $job), - \Psr\Log\LogLevel::INFO - ); - try { - $job->execute(); - $this->status->add( - sprintf('Job "%s" has been successfully completed', $job), - \Psr\Log\LogLevel::INFO - ); - } catch (\Exception $e) { - $this->status->toggleUpdateError(true); - $this->status->add( - sprintf('An error occurred while executing job "%s": %s', $job, $e->getMessage()), - \Psr\Log\LogLevel::ERROR - ); - $returnCode = \Magento\Framework\Console\Cli::RETURN_FAILURE; - } - } - } catch (\Exception $e) { - $this->status->add($e->getMessage(), \Psr\Log\LogLevel::ERROR); - $this->status->toggleUpdateError(true); - $returnCode = \Magento\Framework\Console\Cli::RETURN_FAILURE; - } finally { - $this->status->toggleUpdateInProgress(false); - } - return $returnCode; - } -} diff --git a/setup/src/Magento/Setup/Console/CommandList.php b/setup/src/Magento/Setup/Console/CommandList.php index 338330ef91599..ab31a3add07ed 100644 --- a/setup/src/Magento/Setup/Console/CommandList.php +++ b/setup/src/Magento/Setup/Console/CommandList.php @@ -44,7 +44,6 @@ protected function getCommandsClasses() \Magento\Setup\Console\Command\AdminUserCreateCommand::class, \Magento\Setup\Console\Command\BackupCommand::class, \Magento\Setup\Console\Command\ConfigSetCommand::class, - \Magento\Setup\Console\Command\CronRunCommand::class, \Magento\Setup\Console\Command\DbDataUpgradeCommand::class, \Magento\Setup\Console\Command\DbSchemaUpgradeCommand::class, \Magento\Setup\Console\Command\DbStatusCommand::class, diff --git a/setup/src/Magento/Setup/Controller/AddDatabase.php b/setup/src/Magento/Setup/Controller/AddDatabase.php deleted file mode 100644 index 4d12ea6a945d6..0000000000000 --- a/setup/src/Magento/Setup/Controller/AddDatabase.php +++ /dev/null @@ -1,27 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\ViewModel; - -/** - * AddDatabase controller - */ -class AddDatabase extends AbstractActionController -{ - /** - * Index action - * - * @return array|ViewModel - */ - public function indexAction() - { - $view = new ViewModel(); - $view->setTerminal(true); - return $view; - } -} diff --git a/setup/src/Magento/Setup/Controller/BackupActionItems.php b/setup/src/Magento/Setup/Controller/BackupActionItems.php deleted file mode 100644 index a9255d3324374..0000000000000 --- a/setup/src/Magento/Setup/Controller/BackupActionItems.php +++ /dev/null @@ -1,161 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -use Laminas\Http\Response; -use Laminas\Json\Json; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Framework\Backup\Factory; -use Magento\Framework\Backup\Filesystem; -use Magento\Framework\Exception\FileSystemException; -use Magento\Framework\Setup\BackupRollback; -use Magento\Setup\Model\ObjectManagerProvider; -use Magento\Setup\Model\WebLogger; - -/** - * BackupActionItems controller - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class BackupActionItems extends AbstractActionController -{ - /** - * Handler for BackupRollback - * - * @var BackupRollback - */ - private $backupHandler; - - /** - * Filesystem - * - * @var Filesystem - */ - private $fileSystem; - - /** - * Filesystem Directory List - * - * @var DirectoryList - */ - private $directoryList; - - /** - * @param ObjectManagerProvider $objectManagerProvider - * @param WebLogger $logger - * @param DirectoryList $directoryList - * @param Filesystem $fileSystem - * @throws \Magento\Setup\Exception - */ - public function __construct( - ObjectManagerProvider $objectManagerProvider, - WebLogger $logger, - DirectoryList $directoryList, - Filesystem $fileSystem - ) { - $objectManager = $objectManagerProvider->get(); - $this->backupHandler = $objectManager->create( - BackupRollback::class, - ['log' => $logger] - ); - $this->directoryList = $directoryList; - $this->fileSystem = $fileSystem; - } - - /** - * No index action, return 404 error page - * - * @return ViewModel - */ - public function indexAction() - { - $view = new ViewModel(); - $view->setTemplate('/error/404.phtml'); - $this->getResponse()->setStatusCode(Response::STATUS_CODE_404); - - return $view; - } - - /** - * Checks disk space availability - * - * @return JsonModel - * @throws FileSystemException - */ - public function checkAction() - { - $params = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); - $backupDir = $this->directoryList->getPath(DirectoryList::VAR_DIR) - . '/' . BackupRollback::DEFAULT_BACKUP_DIRECTORY; - try { - $totalSize = 0; - if (isset($params['options']['code']) && $params['options']['code']) { - $totalSize += $this->backupHandler->getFSDiskSpace(); - } - if (isset($params['options']['media']) && $params['options']['media']) { - $totalSize += $this->backupHandler->getFSDiskSpace(Factory::TYPE_MEDIA); - } - if (isset($params['options']['db']) && $params['options']['db']) { - $totalSize += $this->backupHandler->getDBDiskSpace(); - } - $this->fileSystem->validateAvailableDiscSpace($backupDir, $totalSize); - - return new JsonModel( - [ - 'responseType' => ResponseTypeInterface::RESPONSE_TYPE_SUCCESS, - 'size' => true - ] - ); - } catch (\Exception $e) { - return new JsonModel( - [ - 'responseType' => ResponseTypeInterface::RESPONSE_TYPE_ERROR, - 'error' => $e->getMessage() - ] - ); - } - } - - /** - * Takes backup for code, media or DB - * - * @return JsonModel - */ - public function createAction() - { - $params = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); - try { - $time = time(); - $backupFiles = []; - if (isset($params['options']['code']) && $params['options']['code']) { - $backupFiles[] = $this->backupHandler->codeBackup($time); - } - if (isset($params['options']['media']) && $params['options']['media']) { - $backupFiles[] = $this->backupHandler->codeBackup($time, Factory::TYPE_MEDIA); - } - if (isset($params['options']['db']) && $params['options']['db']) { - $backupFiles[] = $this->backupHandler->dbBackup($time); - } - - return new JsonModel( - [ - 'responseType' => ResponseTypeInterface::RESPONSE_TYPE_SUCCESS, - 'files' => $backupFiles - ] - ); - } catch (\Exception $e) { - return new JsonModel( - [ - 'responseType' => ResponseTypeInterface::RESPONSE_TYPE_ERROR, - 'error' => $e->getMessage() - ] - ); - } - } -} diff --git a/setup/src/Magento/Setup/Controller/CompleteBackup.php b/setup/src/Magento/Setup/Controller/CompleteBackup.php deleted file mode 100644 index 9f925d405cc41..0000000000000 --- a/setup/src/Magento/Setup/Controller/CompleteBackup.php +++ /dev/null @@ -1,41 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\ViewModel; - -/** - * CompleteBackup controller - */ -class CompleteBackup extends AbstractActionController -{ - /** - * Index action - * - * @return array|ViewModel - */ - public function indexAction() - { - $view = new ViewModel; - $view->setTemplate('/error/404.phtml'); - $this->getResponse()->setStatusCode(\Laminas\Http\Response::STATUS_CODE_404); - return $view; - } - - /** - * Progress action - * - * @return array|ViewModel - */ - public function progressAction() - { - $view = new ViewModel; - $view->setTemplate('/magento/setup/complete-backup/progress.phtml'); - $view->setTerminal(true); - return $view; - } -} diff --git a/setup/src/Magento/Setup/Controller/ConfigureCatalogSearch.php b/setup/src/Magento/Setup/Controller/ConfigureCatalogSearch.php deleted file mode 100644 index c91fc5d294477..0000000000000 --- a/setup/src/Magento/Setup/Controller/ConfigureCatalogSearch.php +++ /dev/null @@ -1,72 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Setup\Model\SearchConfigOptionsList; - -/** - * ConfigureCatalogSearch controller - */ -class ConfigureCatalogSearch extends AbstractActionController -{ - /** - * @var SearchConfigOptionsList - */ - private $searchConfigOptionsList; - - /** - * Default values to prefill form - * - * @var array - */ - private $prefillConfigValues = [ - 'engine' => 'elasticsearch7', - 'elasticsearch' => [ - 'hostname' => 'localhost', - 'port' => '9200', - 'timeout' => '15', - 'indexPrefix' => 'magento2', - 'enableAuth' => false - ] - ]; - - /** - * @param SearchConfigOptionsList $searchConfigOptionsList - */ - public function __construct(SearchConfigOptionsList $searchConfigOptionsList) - { - $this->searchConfigOptionsList = $searchConfigOptionsList; - } - - /** - * Index action - * - * @return ViewModel - */ - public function indexAction(): ViewModel - { - $view = new ViewModel([ - 'availableSearchEngines' => $this->searchConfigOptionsList->getAvailableSearchEngineList(), - ]); - $view->setTerminal(true); - return $view; - } - - /** - * Fetch default configuration parameters - * - * @return JsonModel - */ - public function defaultParametersAction(): JsonModel - { - return new JsonModel($this->prefillConfigValues); - } -} diff --git a/setup/src/Magento/Setup/Controller/CreateAdminAccount.php b/setup/src/Magento/Setup/Controller/CreateAdminAccount.php deleted file mode 100644 index 79c32c5b932e0..0000000000000 --- a/setup/src/Magento/Setup/Controller/CreateAdminAccount.php +++ /dev/null @@ -1,27 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\ViewModel; - -/** - * CreateAdminAccount controller - */ -class CreateAdminAccount extends AbstractActionController -{ - /** - * Index action - * - * @return ViewModel - */ - public function indexAction() - { - $view = new ViewModel; - $view->setTerminal(true); - return $view; - } -} diff --git a/setup/src/Magento/Setup/Controller/CreateBackup.php b/setup/src/Magento/Setup/Controller/CreateBackup.php deleted file mode 100644 index 42c86c42a5a15..0000000000000 --- a/setup/src/Magento/Setup/Controller/CreateBackup.php +++ /dev/null @@ -1,27 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\ViewModel; - -/** - * CreateBackup controller - */ -class CreateBackup extends AbstractActionController -{ - /** - * Index action - * - * @return array|ViewModel - */ - public function indexAction() - { - $view = new ViewModel(); - $view->setTerminal(true); - return $view; - } -} diff --git a/setup/src/Magento/Setup/Controller/CustomizeYourStore.php b/setup/src/Magento/Setup/Controller/CustomizeYourStore.php deleted file mode 100644 index 128e4b42e6d5e..0000000000000 --- a/setup/src/Magento/Setup/Controller/CustomizeYourStore.php +++ /dev/null @@ -1,92 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Magento\Framework\Module\FullModuleList; -use Magento\Framework\Setup\Lists; -use Magento\Setup\Model\ObjectManagerProvider; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\ViewModel; -use Laminas\View\Model\JsonModel; - -/** - * CustomizeYourStore controller - */ -class CustomizeYourStore extends AbstractActionController -{ - /** - * @var FullModuleList - */ - protected $moduleList; - - /** - * @var Lists - */ - protected $list; - - /** - * @var ObjectManagerProvider - */ - protected $objectManagerProvider; - - /** - * @param FullModuleList $moduleList - * @param Lists $list - * @param ObjectManagerProvider $objectManagerProvider - */ - public function __construct(FullModuleList $moduleList, Lists $list, ObjectManagerProvider $objectManagerProvider) - { - $this->moduleList = $moduleList; - $this->list = $list; - $this->objectManagerProvider = $objectManagerProvider; - } - - /** - * Index action - * - * @return ViewModel - * @throws \Magento\Setup\Exception - */ - public function indexAction() - { - $sampleDataDeployed = $this->moduleList->has('Magento_SampleData'); - if ($sampleDataDeployed) { - /** @var \Magento\Framework\Setup\SampleData\State $sampleData */ - $sampleData = $this->objectManagerProvider->get()->get(\Magento\Framework\Setup\SampleData\State::class); - $isSampleDataInstalled = $sampleData->isInstalled(); - $isSampleDataErrorInstallation = $sampleData->hasError(); - } else { - $isSampleDataInstalled = false; - $isSampleDataErrorInstallation = false; - } - - $view = new ViewModel([ - 'timezone' => $this->list->getTimezoneList(), - 'currency' => $this->list->getCurrencyList(), - 'language' => $this->list->getLocaleList(), - 'isSampleDataInstalled' => $isSampleDataInstalled, - 'isSampleDataErrorInstallation' => $isSampleDataErrorInstallation - ]); - $view->setTerminal(true); - return $view; - } - - /** - * Getting default time zone from server settings - * - * @return JsonModel - */ - public function defaultTimeZoneAction() - { - // phpcs:ignore Generic.PHP.NoSilencedErrors - $defaultTimeZone = trim(@date_default_timezone_get()); - if (empty($defaultTimeZone)) { - return new JsonModel(['defaultTimeZone' => 'UTC']); - } else { - return new JsonModel(['defaultTimeZone' => $defaultTimeZone]); - } - } -} diff --git a/setup/src/Magento/Setup/Controller/DataOption.php b/setup/src/Magento/Setup/Controller/DataOption.php deleted file mode 100644 index 549358f6e3cf2..0000000000000 --- a/setup/src/Magento/Setup/Controller/DataOption.php +++ /dev/null @@ -1,61 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -use Magento\Setup\Model\UninstallCollector; -use Laminas\Json\Json; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; - -/** - * Controller of data option selection - */ -class DataOption extends AbstractActionController -{ - /** - * @var UninstallCollector - */ - private $uninstallCollector; - - /** - * Constructor - * - * @param UninstallCollector $uninstallCollector - */ - public function __construct(UninstallCollector $uninstallCollector) - { - $this->uninstallCollector = $uninstallCollector; - } - - /** - * Shows data option page - * - * @return ViewModel|\Laminas\Http\Response - */ - public function indexAction() - { - $view = new ViewModel(); - $view->setTerminal(true); - $view->setTemplate('/magento/setup/data-option.phtml'); - return $view; - } - - /** - * Checks if module has uninstall class - * - * @return JsonModel - */ - public function hasUninstallAction() - { - $params = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); - if (isset($params['moduleName'])) { - $uninstallClasses = $this->uninstallCollector->collectUninstall([$params['moduleName']]); - } - return new JsonModel(['hasUninstall' => isset($uninstallClasses) && count($uninstallClasses) > 0]); - } -} diff --git a/setup/src/Magento/Setup/Controller/DatabaseCheck.php b/setup/src/Magento/Setup/Controller/DatabaseCheck.php deleted file mode 100644 index f84b6e680ab25..0000000000000 --- a/setup/src/Magento/Setup/Controller/DatabaseCheck.php +++ /dev/null @@ -1,85 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Magento\Framework\Config\ConfigOptionsListConstants; -use Magento\Setup\Validator\DbValidator; -use Laminas\Json\Json; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; - -/** - * DatabaseCheck controller - */ -class DatabaseCheck extends AbstractActionController -{ - /** - * @var DbValidator - */ - private $dbValidator; - - /** - * Constructor - * - * @param DbValidator $dbValidator - */ - public function __construct(DbValidator $dbValidator) - { - $this->dbValidator = $dbValidator; - } - - /** - * Result of checking DB credentials - * - * @return JsonModel - */ - public function indexAction() - { - try { - $params = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); - $password = isset($params['password']) ? $params['password'] : ''; - $driverOptions = []; - if ($this->isDriverOptionsGiven($params)) { - if (empty($params['driverOptionsSslVerify'])) { - $params['driverOptionsSslVerify'] = 0; - } - $driverOptions = [ - ConfigOptionsListConstants::KEY_MYSQL_SSL_KEY => $params['driverOptionsSslKey'], - ConfigOptionsListConstants::KEY_MYSQL_SSL_CERT => $params['driverOptionsSslCert'], - ConfigOptionsListConstants::KEY_MYSQL_SSL_CA => $params['driverOptionsSslCa'], - ConfigOptionsListConstants::KEY_MYSQL_SSL_VERIFY => (int) $params['driverOptionsSslVerify'], - ]; - } - $this->dbValidator->checkDatabaseConnectionWithDriverOptions( - $params['name'], - $params['host'], - $params['user'], - $password, - $driverOptions - ); - $tablePrefix = isset($params['tablePrefix']) ? $params['tablePrefix'] : ''; - $this->dbValidator->checkDatabaseTablePrefix($tablePrefix); - return new JsonModel(['success' => true]); - } catch (\Exception $e) { - return new JsonModel(['success' => false, 'error' => $e->getMessage()]); - } - } - - /** - * Is Driver Options Given - * - * @param array $params - * @return bool - */ - private function isDriverOptionsGiven($params) - { - return !( - empty($params['driverOptionsSslKey']) || - empty($params['driverOptionsSslCert']) || - empty($params['driverOptionsSslCa']) - ); - } -} diff --git a/setup/src/Magento/Setup/Controller/DependencyCheck.php b/setup/src/Magento/Setup/Controller/DependencyCheck.php deleted file mode 100644 index 49c2b661a8681..0000000000000 --- a/setup/src/Magento/Setup/Controller/DependencyCheck.php +++ /dev/null @@ -1,156 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -use Magento\Framework\Exception\LocalizedException; -use Magento\Framework\Module\Status; -use Magento\Framework\Phrase; -use Magento\Setup\Model\DependencyReadinessCheck; -use Magento\Setup\Model\ModuleStatusFactory; -use Magento\Setup\Model\UninstallDependencyCheck; -use Laminas\Json\Json; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; - -/** - * DependencyCheck controller - */ -class DependencyCheck extends AbstractActionController -{ - /** - * Dependency Readiness Check - * - * @var DependencyReadinessCheck - */ - protected $dependencyReadinessCheck; - - /** - * Uninstall Dependency Readiness Check - * - * @var UninstallDependencyCheck - */ - protected $uninstallDependencyCheck; - - /** - * Module/Status Object - * - * @var Status - */ - protected $moduleStatus; - - /** - * @param DependencyReadinessCheck $dependencyReadinessCheck - * @param UninstallDependencyCheck $uninstallDependencyCheck - * @param ModuleStatusFactory $moduleStatusFactory - */ - public function __construct( - DependencyReadinessCheck $dependencyReadinessCheck, - UninstallDependencyCheck $uninstallDependencyCheck, - ModuleStatusFactory $moduleStatusFactory - ) { - $this->dependencyReadinessCheck = $dependencyReadinessCheck; - $this->uninstallDependencyCheck = $uninstallDependencyCheck; - $this->moduleStatus = $moduleStatusFactory->create(); - } - - /** - * Verifies component dependency - * - * @return JsonModel - * @throws \Exception - */ - public function componentDependencyAction() - { - $responseType = ResponseTypeInterface::RESPONSE_TYPE_SUCCESS; - $packages = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); - $data = []; - foreach ($packages as $package) { - $data[] = implode(' ', $package); - } - $dependencyCheck = $this->dependencyReadinessCheck->runReadinessCheck($data); - $data = []; - if (!$dependencyCheck['success']) { - $responseType = ResponseTypeInterface::RESPONSE_TYPE_ERROR; - $data['errorMessage'] = $dependencyCheck['error']; - } - $data['responseType'] = $responseType; - return new JsonModel($data); - } - - /** - * Verifies component dependency for uninstall - * - * @return JsonModel - */ - public function uninstallDependencyCheckAction() - { - $responseType = ResponseTypeInterface::RESPONSE_TYPE_SUCCESS; - $packages = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); - - $packagesToDelete = []; - foreach ($packages as $package) { - $packagesToDelete[] = $package['name']; - } - - $dependencyCheck = $this->uninstallDependencyCheck->runUninstallReadinessCheck($packagesToDelete); - $data = []; - if (!$dependencyCheck['success']) { - $responseType = ResponseTypeInterface::RESPONSE_TYPE_ERROR; - $data['errorMessage'] = $dependencyCheck['error']; - } - $data['responseType'] = $responseType; - return new JsonModel($data); - } - - /** - * Verifies component dependency for enable/disable actions - * - * @return JsonModel - */ - public function enableDisableDependencyCheckAction() - { - $responseType = ResponseTypeInterface::RESPONSE_TYPE_SUCCESS; - $data = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); - - try { - if (empty($data['packages'])) { - throw new LocalizedException(new Phrase('No packages have been found.')); - } - - if (empty($data['type'])) { - throw new LocalizedException(new Phrase('Can not determine the flow.')); - } - - $modules = $data['packages']; - - $isEnable = ($data['type'] !== 'disable'); - - $modulesToChange = []; - foreach ($modules as $module) { - if (!isset($module['name'])) { - throw new LocalizedException(new Phrase('Can not find module name.')); - } - $modulesToChange[] = $module['name']; - } - - $constraints = $this->moduleStatus->checkConstraints($isEnable, $modulesToChange); - $data = []; - - if ($constraints) { - $data['errorMessage'] = "Unable to change status of modules because of the following constraints: " - . implode("<br>", $constraints); - $responseType = ResponseTypeInterface::RESPONSE_TYPE_ERROR; - } - } catch (\Exception $e) { - $responseType = ResponseTypeInterface::RESPONSE_TYPE_ERROR; - $data['errorMessage'] = $e->getMessage(); - } - - $data['responseType'] = $responseType; - return new JsonModel($data); - } -} diff --git a/setup/src/Magento/Setup/Controller/Environment.php b/setup/src/Magento/Setup/Controller/Environment.php deleted file mode 100644 index 063d23f5a48d6..0000000000000 --- a/setup/src/Magento/Setup/Controller/Environment.php +++ /dev/null @@ -1,242 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Framework\Filesystem; -use Magento\Setup\Model\Cron\ReadinessCheck; -use Laminas\Mvc\Controller\AbstractActionController; - -/** - * Class Environment - * - * Provides information and checks about the environment. - */ -class Environment extends AbstractActionController -{ - /** - * Path to updater application - */ - const UPDATER_DIR = 'update'; - - /** - * File system - * - * @var \Magento\Framework\Filesystem - */ - protected $filesystem; - - /** - * Cron Script Readiness Check - * - * @var \Magento\Setup\Model\CronScriptReadinessCheck - */ - protected $cronScriptReadinessCheck; - - /** - * PHP Readiness Check - * - * @var \Magento\Setup\Model\PhpReadinessCheck - */ - protected $phpReadinessCheck; - - /** - * @var \Magento\Framework\Setup\FilePermissions - */ - private $permissions; - - /** - * Constructor - * - * @param \Magento\Framework\Setup\FilePermissions $permissions - * @param \Magento\Framework\Filesystem $filesystem - * @param \Magento\Setup\Model\CronScriptReadinessCheck $cronScriptReadinessCheck - * @param \Magento\Setup\Model\PhpReadinessCheck $phpReadinessCheck - */ - public function __construct( - \Magento\Framework\Setup\FilePermissions $permissions, - \Magento\Framework\Filesystem $filesystem, - \Magento\Setup\Model\CronScriptReadinessCheck $cronScriptReadinessCheck, - \Magento\Setup\Model\PhpReadinessCheck $phpReadinessCheck - ) { - $this->permissions = $permissions; - $this->filesystem = $filesystem; - $this->cronScriptReadinessCheck = $cronScriptReadinessCheck; - $this->phpReadinessCheck = $phpReadinessCheck; - } - - /** - * No index action, return 404 error page - * - * @return \Laminas\View\Model\JsonModel - */ - public function indexAction() - { - $view = new \Laminas\View\Model\JsonModel([]); - $view->setTemplate('/error/404.phtml'); - $this->getResponse()->setStatusCode(\Laminas\Http\Response::STATUS_CODE_404); - return $view; - } - - /** - * Verifies php version - * - * @return \Laminas\View\Model\JsonModel - */ - public function phpVersionAction() - { - $type = $this->getRequest()->getQuery('type'); - - $data = []; - if ($type == ReadinessCheckInstaller::INSTALLER) { - $data = $this->phpReadinessCheck->checkPhpVersion(); - } elseif ($type == ReadinessCheckUpdater::UPDATER) { - $data = $this->getPhpChecksInfo(ReadinessCheck::KEY_PHP_VERSION_VERIFIED); - } - return new \Laminas\View\Model\JsonModel($data); - } - - /** - * Checks PHP settings - * - * @return \Laminas\View\Model\JsonModel - */ - public function phpSettingsAction() - { - $type = $this->getRequest()->getQuery('type'); - - $data = []; - if ($type == ReadinessCheckInstaller::INSTALLER) { - $data = $this->phpReadinessCheck->checkPhpSettings(); - } elseif ($type == ReadinessCheckUpdater::UPDATER) { - $data = $this->getPhpChecksInfo(ReadinessCheck::KEY_PHP_SETTINGS_VERIFIED); - } - return new \Laminas\View\Model\JsonModel($data); - } - - /** - * Verifies php verifications - * - * @return \Laminas\View\Model\JsonModel - */ - public function phpExtensionsAction() - { - $type = $this->getRequest()->getQuery('type'); - - $data = []; - if ($type == ReadinessCheckInstaller::INSTALLER) { - $data = $this->phpReadinessCheck->checkPhpExtensions(); - } elseif ($type == ReadinessCheckUpdater::UPDATER) { - $data = $this->getPhpChecksInfo(ReadinessCheck::KEY_PHP_EXTENSIONS_VERIFIED); - } - return new \Laminas\View\Model\JsonModel($data); - } - - /** - * Gets the PHP check info from Cron status file - * - * @param string $type - * @return array - */ - private function getPhpChecksInfo($type) - { - $read = $this->filesystem->getDirectoryRead(DirectoryList::VAR_DIR); - try { - $jsonData = json_decode($read->readFile(ReadinessCheck::SETUP_CRON_JOB_STATUS_FILE), true); - if (isset($jsonData[ReadinessCheck::KEY_PHP_CHECKS]) - && isset($jsonData[ReadinessCheck::KEY_PHP_CHECKS][$type]) - ) { - return $jsonData[ReadinessCheck::KEY_PHP_CHECKS][$type]; - } - return ['responseType' => ResponseTypeInterface::RESPONSE_TYPE_ERROR]; - } catch (\Exception $e) { - return ['responseType' => ResponseTypeInterface::RESPONSE_TYPE_ERROR]; - } - } - - /** - * Verifies file permissions - * - * @return \Laminas\View\Model\JsonModel - */ - public function filePermissionsAction() - { - $responseType = ResponseTypeInterface::RESPONSE_TYPE_SUCCESS; - $missingWritePermissionPaths = $this->permissions->getMissingWritablePathsForInstallation(true); - - $currentPaths = []; - $requiredPaths = []; - if ($missingWritePermissionPaths) { - foreach ($missingWritePermissionPaths as $key => $value) { - if (is_array($value)) { - $requiredPaths[] = ['path' => $key, 'missing' => $value]; - $responseType = ResponseTypeInterface::RESPONSE_TYPE_ERROR; - } else { - $requiredPaths[] = ['path' => $key]; - $currentPaths[] = $key; - } - } - } - $data = [ - 'responseType' => $responseType, - 'data' => [ - 'required' => $requiredPaths, - 'current' => $currentPaths, - ], - ]; - - return new \Laminas\View\Model\JsonModel($data); - } - - /** - * Verifies updater application exists - * - * @return \Laminas\View\Model\JsonModel - */ - public function updaterApplicationAction() - { - $responseType = ResponseTypeInterface::RESPONSE_TYPE_SUCCESS; - - if (!$this->filesystem->getDirectoryRead(DirectoryList::ROOT)->isExist(self::UPDATER_DIR)) { - $responseType = ResponseTypeInterface::RESPONSE_TYPE_ERROR; - } - $data = [ - 'responseType' => $responseType - ]; - return new \Laminas\View\Model\JsonModel($data); - } - - /** - * Verifies Setup and Updater Cron status - * - * @return \Laminas\View\Model\JsonModel - */ - public function cronScriptAction() - { - $responseType = ResponseTypeInterface::RESPONSE_TYPE_SUCCESS; - - $setupCheck = $this->cronScriptReadinessCheck->checkSetup(); - $updaterCheck = $this->cronScriptReadinessCheck->checkUpdater(); - $data = []; - if (!$setupCheck['success']) { - $responseType = ResponseTypeInterface::RESPONSE_TYPE_ERROR; - $data['setupErrorMessage'] = 'Error from Setup Application Cron Script:<br/>' . $setupCheck['error']; - } - if (!$updaterCheck['success']) { - $responseType = ResponseTypeInterface::RESPONSE_TYPE_ERROR; - $data['updaterErrorMessage'] = 'Error from Updater Application Cron Script:<br/>' . $updaterCheck['error']; - } - if (isset($setupCheck['notice'])) { - $data['setupNoticeMessage'] = 'Notice from Setup Application Cron Script:<br/>' . $setupCheck['notice']; - } - if (isset($updaterCheck['notice'])) { - $data['updaterNoticeMessage'] = 'Notice from Updater Application Cron Script:<br/>' . - $updaterCheck['notice']; - } - $data['responseType'] = $responseType; - return new \Laminas\View\Model\JsonModel($data); - } -} diff --git a/setup/src/Magento/Setup/Controller/ExtensionGrid.php b/setup/src/Magento/Setup/Controller/ExtensionGrid.php deleted file mode 100644 index cbe9340ffd8f8..0000000000000 --- a/setup/src/Magento/Setup/Controller/ExtensionGrid.php +++ /dev/null @@ -1,118 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Magento\Setup\Model\PackagesAuth; -use Magento\Setup\Model\PackagesData; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Setup\Model\Grid; - -/** - * Controller for extension grid tasks - */ -class ExtensionGrid extends AbstractActionController -{ - /** - * @var PackagesData - */ - private $packagesData; - - /** - * @var PackagesAuth - */ - private $packagesAuth; - - /** - * @var Grid\Extension - */ - private $gridExtension; - - /** - * @param PackagesData $packagesData - * @param PackagesAuth $packagesAuth - * @param Grid\Extension $gridExtension - */ - public function __construct( - PackagesData $packagesData, - PackagesAuth $packagesAuth, - Grid\Extension $gridExtension - ) { - $this->packagesData = $packagesData; - $this->packagesAuth = $packagesAuth; - $this->gridExtension = $gridExtension; - } - - /** - * Index page action - * - * @return \Laminas\View\Model\ViewModel - */ - public function indexAction() - { - $view = new ViewModel(); - $view->setTerminal(true); - return $view; - } - - /** - * Get extensions info action - * - * @return JsonModel - * @throws \RuntimeException - */ - public function extensionsAction() - { - $error = ''; - $lastSyncData = []; - $authDetails = $this->packagesAuth->getAuthJsonData(); - $extensions = []; - if ($authDetails) { - try { - $lastSyncData = $this->packagesData->syncPackagesData(); - $extensions = $this->gridExtension->getList(); - } catch (\Exception $e) { - $error = $e->getMessage(); - } - } - - return new JsonModel( - [ - 'success' => true, - 'extensions' => $extensions, - 'total' => count($extensions), - 'lastSyncData' => $lastSyncData, - 'error' => $error - ] - ); - } - - /** - * Sync action - * - * @return JsonModel - */ - public function syncAction() - { - $error = ''; - $lastSyncData = []; - try { - $authDataJson = $this->packagesAuth->getAuthJsonData(); - $this->packagesAuth->checkCredentials($authDataJson['username'], $authDataJson['password']); - $lastSyncData = $this->packagesData->syncPackagesData(); - } catch (\Exception $e) { - $error = $e->getMessage(); - } - return new JsonModel( - [ - 'success' => true, - 'lastSyncData' => $lastSyncData, - 'error' => $error - ] - ); - } -} diff --git a/setup/src/Magento/Setup/Controller/Home.php b/setup/src/Magento/Setup/Controller/Home.php deleted file mode 100644 index f06cfb89cb1d3..0000000000000 --- a/setup/src/Magento/Setup/Controller/Home.php +++ /dev/null @@ -1,30 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\ViewModel; - -/** - * Controller of homepage of setup - */ -class Home extends AbstractActionController -{ - /** - * Index action - * - * @return ViewModel|\Laminas\Http\Response - */ - public function indexAction() - { - $view = new ViewModel; - $view->setTerminal(true); - $view->setTemplate('/magento/setup/home.phtml'); - $view->setVariable('userName', 'UserName'); - return $view; - } -} diff --git a/setup/src/Magento/Setup/Controller/Install.php b/setup/src/Magento/Setup/Controller/Install.php deleted file mode 100644 index f110595a8b872..0000000000000 --- a/setup/src/Magento/Setup/Controller/Install.php +++ /dev/null @@ -1,175 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -use Laminas\Json\Json; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Framework\App\DeploymentConfig; -use Magento\Framework\Config\ConfigOptionsListConstants as SetupConfigOptionsList; -use Magento\Setup\Model\Installer; -use Magento\Setup\Model\Installer\ProgressFactory; -use Magento\Setup\Model\InstallerFactory; -use Magento\Setup\Model\RequestDataConverter; -use Magento\Setup\Model\WebLogger; - -/** - * Install controller - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class Install extends AbstractActionController -{ - /** - * @var WebLogger - */ - private $log; - - /** - * @var Installer - */ - private $installer; - - /** - * @var ProgressFactory - */ - private $progressFactory; - - /** - * @var \Magento\Framework\Setup\SampleData\State - */ - protected $sampleDataState; - - /** - * @var \Magento\Framework\App\DeploymentConfig - */ - private $deploymentConfig; - - /** - * @var RequestDataConverter - */ - private $requestDataConverter; - - /** - * @param WebLogger $logger - * @param InstallerFactory $installerFactory - * @param ProgressFactory $progressFactory - * @param \Magento\Framework\Setup\SampleData\State $sampleDataState - * @param \Magento\Framework\App\DeploymentConfig $deploymentConfig - * @param RequestDataConverter $requestDataConverter - */ - public function __construct( - WebLogger $logger, - InstallerFactory $installerFactory, - ProgressFactory $progressFactory, - \Magento\Framework\Setup\SampleData\State $sampleDataState, - DeploymentConfig $deploymentConfig, - RequestDataConverter $requestDataConverter - ) { - $this->log = $logger; - $this->installer = $installerFactory->create($logger); - $this->progressFactory = $progressFactory; - $this->sampleDataState = $sampleDataState; - $this->deploymentConfig = $deploymentConfig; - $this->requestDataConverter = $requestDataConverter; - } - - /** - * Index action - * - * @return ViewModel - */ - public function indexAction() - { - $view = new ViewModel(); - $view->setTerminal(true); - - return $view; - } - - /** - * Index Action - * - * @return JsonModel - */ - public function startAction() - { - $this->log->clear(); - $json = new JsonModel(); - try { - $this->checkForPriorInstall(); - $content = $this->getRequest()->getContent(); - $source = $content ? $source = Json::decode($content, Json::TYPE_ARRAY) : []; - $data = $this->requestDataConverter->convert($source); - $this->installer->install($data); - $json->setVariable( - 'key', - $this->installer->getInstallInfo()[SetupConfigOptionsList::KEY_ENCRYPTION_KEY] - ); - $json->setVariable('success', true); - if ($this->sampleDataState->hasError()) { - $json->setVariable('isSampleDataError', true); - } - $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; - } - - /** - * Checks progress of installation - * - * @return JsonModel - */ - public function progressAction() - { - $percent = 0; - $success = false; - $contents = []; - $json = new JsonModel(); - - // Depending upon the install environment and network latency, there is a possibility that - // "progress" check request may arrive before the Install POST request. In that case - // "install.log" file may not be created yet. Check the "install.log" is created before - // trying to read from it. - if (!$this->log->logfileExists()) { - return $json->setVariables(['progress' => $percent, 'success' => true, 'console' => $contents]); - } - - try { - $progress = $this->progressFactory->createFromLog($this->log); - $percent = sprintf('%d', $progress->getRatio() * 100); - $success = true; - $contents = $this->log->get(); - if ($this->sampleDataState->hasError()) { - $json->setVariable('isSampleDataError', true); - } - } catch (\Exception $e) { - $contents = [(string)$e]; - } - - return $json->setVariables(['progress' => $percent, 'success' => $success, 'console' => $contents]); - } - - /** - * Checks for prior install - * - * @return void - * @throws \Magento\Setup\Exception - */ - private function checkForPriorInstall() - { - if ($this->deploymentConfig->isAvailable()) { - throw new \Magento\Setup\Exception('Magento application is already installed.'); - } - } -} diff --git a/setup/src/Magento/Setup/Controller/InstallExtensionGrid.php b/setup/src/Magento/Setup/Controller/InstallExtensionGrid.php deleted file mode 100644 index b6bed4f3db1f1..0000000000000 --- a/setup/src/Magento/Setup/Controller/InstallExtensionGrid.php +++ /dev/null @@ -1,79 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Setup\Model\PackagesData; - -/** - * Controller for extensions grid tasks - */ -class InstallExtensionGrid extends AbstractActionController -{ - /** - * @var PackagesData - */ - private $packagesData; - - /** - * @param PackagesData $packagesData - */ - public function __construct( - PackagesData $packagesData - ) { - $this->packagesData = $packagesData; - } - - /** - * Index page action - * - * @return ViewModel - */ - public function indexAction() - { - $view = new ViewModel(); - $view->setTerminal(true); - return $view; - } - - /** - * Get Extensions info action - * - * @return JsonModel - */ - public function extensionsAction() - { - $extensions = $this->packagesData->getPackagesForInstall(); - $packages = isset($extensions['packages']) ? $extensions['packages'] : []; - $packages = $this->formatPackageList($packages); - - return new JsonModel( - [ - 'success' => true, - 'extensions' => array_values($packages), - 'total' => count($packages) - ] - ); - } - - /** - * Format package list - * - * @param array $packages - * @return array - */ - private function formatPackageList(array $packages) - { - array_walk($packages, function (&$package) { - $package['vendor'] = ucfirst($package['vendor']); - }); - - return $packages; - } -} diff --git a/setup/src/Magento/Setup/Controller/LandingInstaller.php b/setup/src/Magento/Setup/Controller/Landing.php similarity index 64% rename from setup/src/Magento/Setup/Controller/LandingInstaller.php rename to setup/src/Magento/Setup/Controller/Landing.php index 8aee28df15137..cea1e76082521 100644 --- a/setup/src/Magento/Setup/Controller/LandingInstaller.php +++ b/setup/src/Magento/Setup/Controller/Landing.php @@ -11,7 +11,7 @@ /** * Controller for Setup Landing page */ -class LandingInstaller extends AbstractActionController +class Landing extends AbstractActionController { /** * @var \Magento\Framework\App\ProductMetadata @@ -33,17 +33,10 @@ public function __construct(\Magento\Framework\App\ProductMetadata $productMetad */ public function indexAction() { - $welcomeMsg = "Welcome to Magento Admin, your online store headquarters.<br>" - . "Click 'Agree and Set Up Magento' or read "; - $docRef = "https://devdocs.magento.com/guides/v2.3/install-gde/install/web/install-web.html"; - $agreeButtonText = "Agree and Setup Magento"; $view = new ViewModel; $view->setTerminal(true); $view->setTemplate('/magento/setup/landing.phtml'); $view->setVariable('version', $this->productMetadata->getVersion()); - $view->setVariable('welcomeMsg', $welcomeMsg); - $view->setVariable('docRef', $docRef); - $view->setVariable('agreeButtonText', $agreeButtonText); return $view; } } diff --git a/setup/src/Magento/Setup/Controller/LandingUpdater.php b/setup/src/Magento/Setup/Controller/LandingUpdater.php deleted file mode 100644 index b3728e404f8c1..0000000000000 --- a/setup/src/Magento/Setup/Controller/LandingUpdater.php +++ /dev/null @@ -1,49 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\ViewModel; - -/** - * Controller for Updater Landing page - */ -class LandingUpdater extends AbstractActionController -{ - /** - * @var \Magento\Framework\App\ProductMetadata - */ - protected $productMetadata; - - /** - * @param \Magento\Framework\App\ProductMetadata $productMetadata - */ - public function __construct(\Magento\Framework\App\ProductMetadata $productMetadata) - { - $this->productMetadata = $productMetadata; - } - - /** - * Updater index action. - * - * @return array|ViewModel - */ - public function indexAction() - { - $welcomeMsg = "Welcome to Magento Module Manager.<br>" - . "Click 'Agree and Update Magento' or read "; - $docRef = "https://devdocs.magento.com/guides/v2.3/install-gde/install/web/install-web.html"; - $agreeButtonText = "Agree and Update Magento"; - $view = new ViewModel(); - $view->setTerminal(true); - $view->setTemplate('/magento/setup/landing.phtml'); - $view->setVariable('version', $this->productMetadata->getVersion()); - $view->setVariable('welcomeMsg', $welcomeMsg); - $view->setVariable('docRef', $docRef); - $view->setVariable('agreeButtonText', $agreeButtonText); - return $view; - } -} diff --git a/setup/src/Magento/Setup/Controller/Maintenance.php b/setup/src/Magento/Setup/Controller/Maintenance.php deleted file mode 100644 index 769f961f7fc0e..0000000000000 --- a/setup/src/Magento/Setup/Controller/Maintenance.php +++ /dev/null @@ -1,57 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -use Laminas\Json\Json; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; -use Magento\Framework\App\MaintenanceMode; - -/** - * Maintenance controller - */ -class Maintenance extends AbstractActionController -{ - /** - * Handler for maintenance mode - * - * @var MaintenanceMode - */ - private $maintenanceMode; - - /** - * Constructor - * - * @param MaintenanceMode $maintenanceMode - */ - public function __construct(MaintenanceMode $maintenanceMode) - { - $this->maintenanceMode = $maintenanceMode; - } - - /** - * Puts store in maintenance mode - * - * @return JsonModel - */ - public function indexAction() - { - try { - $params = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); - $action = isset($params['disable']) && $params['disable'] ? false : true; - $this->maintenanceMode->set($action); - return new JsonModel(['responseType' => ResponseTypeInterface::RESPONSE_TYPE_SUCCESS]); - } catch (\Exception $e) { - return new JsonModel( - [ - 'responseType' => ResponseTypeInterface::RESPONSE_TYPE_ERROR, - 'error' => $e->getMessage() - ] - ); - } - } -} diff --git a/setup/src/Magento/Setup/Controller/Marketplace.php b/setup/src/Magento/Setup/Controller/Marketplace.php deleted file mode 100644 index 7746fa08aac5c..0000000000000 --- a/setup/src/Magento/Setup/Controller/Marketplace.php +++ /dev/null @@ -1,135 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Laminas\Json\Json; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Setup\Model\PackagesAuth; -use Magento\Setup\Model\PackagesData; - -/** - * Marketplace controller - */ -class Marketplace extends AbstractActionController -{ - /** - * @var PackagesAuth - */ - private $packagesAuth; - - /** - * @var PackagesData - */ - private $packagesData; - - /** - * @param PackagesAuth $packagesAuth - * @param PackagesData $packagesData - */ - public function __construct(PackagesAuth $packagesAuth, PackagesData $packagesData) - { - $this->packagesAuth = $packagesAuth; - $this->packagesData = $packagesData; - } - - /** - * No index action, return 404 error page - * - * @return ViewModel - */ - public function indexAction() - { - $view = new ViewModel(); - $view->setTemplate('/error/404.phtml'); - $this->getResponse()->setStatusCode(\Laminas\Http\Response::STATUS_CODE_404); - return $view; - } - - /** - * Save auth.json - * - * @return array|ViewModel - */ - public function saveAuthJsonAction() - { - $params = []; - if ($this->getRequest()->getContent()) { - $params = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); - } - try { - $userName = isset($params['username']) ? $params['username'] : ''; - $password = isset($params['password']) ? $params['password'] : ''; - $isValid = $this->packagesAuth->checkCredentials($userName, $password); - $isValid = json_decode($isValid, true); - if ($isValid['success'] === true && $this->packagesAuth->saveAuthJson($userName, $password)) { - $this->packagesData->syncPackagesData(); - return new JsonModel(['success' => true]); - } else { - return new JsonModel(['success' => false, 'message' => $isValid['message']]); - } - } catch (\Exception $e) { - return new JsonModel(['success' => false, 'message' => $e->getMessage()]); - } - } - - /** - * Check if user authorize in connect - * - * @return JsonModel - */ - public function checkAuthAction() - { - try { - $authDataJson = $this->packagesAuth->getAuthJsonData(); - if ($authDataJson) { - $isValid = $this->packagesAuth->checkCredentials($authDataJson['username'], $authDataJson['password']); - $isValid = json_decode($isValid, true); - if ($isValid['success'] === true) { - return new JsonModel(['success' => true, 'data' => [ - PackagesAuth::KEY_USERNAME => $authDataJson[PackagesAuth::KEY_USERNAME] - ]]); - } else { - return new JsonModel(['success' => false, 'message' => $isValid['message']]); - } - } - return new JsonModel(['success' => false, 'data' => [ - PackagesAuth::KEY_USERNAME => $authDataJson[PackagesAuth::KEY_USERNAME] - ]]); - } catch (\Exception $e) { - return new JsonModel(['success' => false, 'message' => $e->getMessage()]); - } - } - - /** - * Remove credentials from auth.json - * - * @return JsonModel - */ - public function removeCredentialsAction() - { - try { - $result = $this->packagesAuth->removeCredentials(); - return new JsonModel(['success' => $result]); - } catch (\Exception $e) { - return new JsonModel(['success' => false, 'message' => $e->getMessage()]); - } - } - - /** - * Popup Auth action - * - * @return array|ViewModel - */ - public function popupAuthAction() - { - $view = new ViewModel(); - $view->setTemplate('/magento/setup/popupauth.phtml'); - $view->setTerminal(true); - return $view; - } -} diff --git a/setup/src/Magento/Setup/Controller/MarketplaceCredentials.php b/setup/src/Magento/Setup/Controller/MarketplaceCredentials.php deleted file mode 100644 index 9541b8ef7250f..0000000000000 --- a/setup/src/Magento/Setup/Controller/MarketplaceCredentials.php +++ /dev/null @@ -1,27 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\ViewModel; - -/** - * MarketplaceCredentials controller - */ -class MarketplaceCredentials extends AbstractActionController -{ - /** - * Index action - * - * @return ViewModel - */ - public function indexAction() - { - $view = new ViewModel(); - $view->setTerminal(true); - return $view; - } -} diff --git a/setup/src/Magento/Setup/Controller/ModuleGrid.php b/setup/src/Magento/Setup/Controller/ModuleGrid.php deleted file mode 100644 index f01e7bfbac11f..0000000000000 --- a/setup/src/Magento/Setup/Controller/ModuleGrid.php +++ /dev/null @@ -1,62 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -use Magento\Setup\Model\Grid; - -/** - * Controller for module grid tasks - */ -class ModuleGrid extends \Laminas\Mvc\Controller\AbstractActionController -{ - /** - * Module grid - * - * @var Grid\Module - */ - private $gridModule; - - /** - * @param Grid\Module $gridModule - */ - public function __construct( - Grid\Module $gridModule - ) { - $this->gridModule = $gridModule; - } - - /** - * Index page action - * - * @return \Laminas\View\Model\ViewModel - */ - public function indexAction() - { - $view = new \Laminas\View\Model\ViewModel(); - $view->setTerminal(true); - return $view; - } - - /** - * Get Components info action - * - * @return \Laminas\View\Model\JsonModel - * @throws \RuntimeException - */ - public function modulesAction() - { - $moduleList = $this->gridModule->getList(); - - return new \Laminas\View\Model\JsonModel( - [ - 'success' => true, - 'modules' => $moduleList, - 'total' => count($moduleList), - ] - ); - } -} diff --git a/setup/src/Magento/Setup/Controller/Modules.php b/setup/src/Magento/Setup/Controller/Modules.php deleted file mode 100644 index 35b225d1e6bba..0000000000000 --- a/setup/src/Magento/Setup/Controller/Modules.php +++ /dev/null @@ -1,147 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Magento\Setup\Model\ModuleStatus; -use Magento\Setup\Model\ObjectManagerProvider; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; -use Laminas\Json\Json; - -/** - * Modules controller - */ -class Modules extends AbstractActionController -{ - /** - * Object manager - * - * @var \Magento\Framework\ObjectManagerInterface - */ - private $objectManager; - - /** - * @var ModuleStatus - */ - protected $allModules; - - /** - * @param ModuleStatus $allModules - * @param ObjectManagerProvider $objectManagerProvider - */ - public function __construct(ModuleStatus $allModules, ObjectManagerProvider $objectManagerProvider) - { - $this->allModules = $allModules; - $this->objectManager = $objectManagerProvider->get(); - } - - /** - * Returns list of Modules - * - * @return JsonModel - */ - public function indexAction() - { - $allModules = $this->allModules->getAllModules(); - $enabledModules = []; - foreach ($allModules as $module) { - if ($module['selected']) { - $enabledModules[] = $module['name']; - } - } - $validity = $this->checkGraph($enabledModules); - ksort($allModules); - if ($validity->getVariable("success")) { - return new JsonModel(['success' => true, 'modules' => $allModules]); - } else { - $errorMessage = $validity->getVariable("error"); - return new JsonModel(['success' => false, 'modules' => $allModules, - 'error' => '<b> Corrupt config.php!</b> <br />' . $errorMessage]); - } - } - - /** - * Result of checking Modules Validity - * - * @return JsonModel - */ - public function allModulesValidAction() - { - try { - $params = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); - $enabledModules = isset($params['selectedModules']) ? $params['selectedModules'] : []; - return $this->checkGraph($enabledModules); - } catch (\Exception $e) { - return new JsonModel(['success' => false, 'error' => $e->getMessage()]); - } - } - - /** - * Checks validity of enabling/disabling modules. - * - * @param array $toBeEnabledModules - * @param bool $prettyFormat - * @return JsonModel - */ - private function checkGraph(array $toBeEnabledModules, $prettyFormat = false) - { - $status = $this->objectManager->create(\Magento\Framework\Module\Status::class); - - // checking enabling constraints - $constraints = $status->checkConstraints(true, $toBeEnabledModules, [], $prettyFormat); - if ($constraints) { - $message = $this->getConstraintsFailureMessage(true, $constraints); - return new JsonModel(['success' => false, 'error' => $message]); - } - - return new JsonModel(['success' => true]); - } - - /** - * Check Module Dependencies - * - * @return JsonModel - */ - public function validateAction() - { - $params = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); - $status = $this->objectManager->create(\Magento\Framework\Module\Status::class); - - $constraints = $status->checkConstraints( - $params['status'], - [$params['module']], - array_diff($params['selectedModules'], [$params['module']]) - ); - if ($constraints) { - $message = $this->getConstraintsFailureMessage($params['status'], $constraints); - return new JsonModel(['success' => false, 'error' => $message]); - } - - $this->allModules->setIsEnabled($params['status'], $params['module']); - $allModules = $this->allModules->getAllModules($params['selectedModules']); - ksort($allModules); - return new JsonModel(['modules' => $allModules]); - } - - /** - * Handles constraints - * - * @param bool $isEnable - * @param string[] $constraints - * @return string - */ - private function getConstraintsFailureMessage($isEnable, array $constraints) - { - if ($isEnable) { - $updateType = 'enable'; - } else { - $updateType = 'disable'; - } - $message = " Unable to $updateType modules because of the following constraints:<br>" . PHP_EOL - . implode("<br>" . PHP_EOL, $constraints); - return $message; - } -} diff --git a/setup/src/Magento/Setup/Controller/Navigation.php b/setup/src/Magento/Setup/Controller/Navigation.php index e3f2091accbbd..8f07bb814387f 100644 --- a/setup/src/Magento/Setup/Controller/Navigation.php +++ b/setup/src/Magento/Setup/Controller/Navigation.php @@ -8,9 +8,7 @@ use Laminas\Mvc\Controller\AbstractActionController; use Laminas\View\Model\JsonModel; use Laminas\View\Model\ViewModel; -use Magento\Backend\Model\UrlInterface; use Magento\Framework\ObjectManagerInterface; -use Magento\Setup\Model\Cron\Status; use Magento\Setup\Model\Navigation as NavModel; use Magento\Setup\Model\ObjectManagerProvider; @@ -24,11 +22,6 @@ class Navigation extends AbstractActionController */ protected $navigation; - /** - * @var Status - */ - protected $status; - /** * @var ViewModel */ @@ -41,13 +34,11 @@ class Navigation extends AbstractActionController /** * @param NavModel $navigation - * @param Status $status * @param ObjectManagerProvider $objectManagerProvider */ - public function __construct(NavModel $navigation, Status $status, ObjectManagerProvider $objectManagerProvider) + public function __construct(NavModel $navigation, ObjectManagerProvider $objectManagerProvider) { $this->navigation = $navigation; - $this->status = $status; $this->objectManagerProvider = $objectManagerProvider->get(); $this->view = new ViewModel(); $this->view->setVariable('menu', $this->navigation->getMenuItems()); @@ -82,37 +73,4 @@ public function menuAction() $this->view->setTerminal(true); return $this->view; } - - /** - * Side menu action - * - * @return array|ViewModel - */ - public function sideMenuAction() - { - /** @var UrlInterface $backendUrl */ - $backendUrl = $this->objectManagerProvider->get(UrlInterface::class); - $this->view->setTemplate('/magento/setup/navigation/side-menu.phtml'); - $this->view->setVariable('isInstaller', $this->navigation->getType() == NavModel::NAV_INSTALLER); - $this->view->setVariable('backendUrl', $backendUrl->getRouteUrl('adminhtml')); - $this->view->setTerminal(true); - return $this->view; - } - - /** - * Head bar action - * - * @return array|ViewModel - */ - public function headerBarAction() - { - if ($this->navigation->getType() === NavModel::NAV_UPDATER) { - if ($this->status->isUpdateError() || $this->status->isUpdateInProgress()) { - $this->view->setVariable('redirect', '../' . Environment::UPDATER_DIR . '/index.php'); - } - } - $this->view->setTemplate('/magento/setup/navigation/header-bar.phtml'); - $this->view->setTerminal(true); - return $this->view; - } } diff --git a/setup/src/Magento/Setup/Controller/OtherComponentsGrid.php b/setup/src/Magento/Setup/Controller/OtherComponentsGrid.php deleted file mode 100644 index edae5c5903090..0000000000000 --- a/setup/src/Magento/Setup/Controller/OtherComponentsGrid.php +++ /dev/null @@ -1,111 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -use Magento\Composer\InfoCommand; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; - -/** - * Controller for other components grid on select version page - */ -class OtherComponentsGrid extends AbstractActionController -{ - /** - * @var \Magento\Framework\Composer\ComposerInformation - */ - private $composerInformation; - - /** - * @var \Magento\Composer\InfoCommand - */ - private $infoCommand; - - /** - * @param \Magento\Framework\Composer\ComposerInformation $composerInformation - * @param \Magento\Framework\Composer\MagentoComposerApplicationFactory $magentoComposerApplicationFactory - */ - public function __construct( - \Magento\Framework\Composer\ComposerInformation $composerInformation, - \Magento\Framework\Composer\MagentoComposerApplicationFactory $magentoComposerApplicationFactory - ) { - $this->composerInformation = $composerInformation; - $this->infoCommand = $magentoComposerApplicationFactory->createInfoCommand(); - } - - /** - * No index action, return 404 error page - * - * @return \Laminas\View\Model\ViewModel - */ - public function indexAction() - { - $view = new \Laminas\View\Model\ViewModel; - $view->setTemplate('/error/404.phtml'); - $this->getResponse()->setStatusCode(\Laminas\Http\Response::STATUS_CODE_404); - return $view; - } - - /** - * Get Components from composer info command - * - * @return JsonModel - * @throws \RuntimeException - */ - public function componentsAction() - { - try { - $components = $this->composerInformation->getInstalledMagentoPackages(); - foreach ($components as $component) { - if (!$this->composerInformation->isPackageInComposerJson($component['name'])) { - unset($components[$component['name']]); - continue; - } - $componentNameParts = explode('/', $component['name']); - $packageInfo = $this->infoCommand->run($component['name']); - if (!$packageInfo) { - throw new \RuntimeException('Package info not found for ' . $component['name']); - } - if ($packageInfo[InfoCommand::NEW_VERSIONS]) { - $currentVersion = $packageInfo[InfoCommand::CURRENT_VERSION]; - $components[$component['name']]['version'] = $currentVersion; - $versions = []; - foreach ($packageInfo[InfoCommand::NEW_VERSIONS] as $version) { - $versions[] = ['id' => $version, 'name' => $version]; - } - $versions[] = [ - 'id' => $packageInfo[InfoCommand::CURRENT_VERSION], - 'name' => $packageInfo[InfoCommand::CURRENT_VERSION] - ]; - - $versions[0]['name'] .= ' (latest)'; - $versions[count($versions) - 1]['name'] .= ' (current)'; - - $components[$component['name']]['vendor'] = $componentNameParts[0]; - $components[$component['name']]['updates'] = $versions; - $components[$component['name']]['dropdownId'] = 'dd_' . $component['name']; - $components[$component['name']]['checkboxId'] = 'cb_' . $component['name']; - } else { - unset($components[$component['name']]); - } - } - return new JsonModel( - [ - 'components' => array_values($components), - 'total' => count($components), - 'responseType' => ResponseTypeInterface::RESPONSE_TYPE_SUCCESS - ] - ); - } catch (\Exception $e) { - return new JsonModel( - [ - 'responseType' => ResponseTypeInterface::RESPONSE_TYPE_ERROR - ] - ); - } - } -} diff --git a/setup/src/Magento/Setup/Controller/ReadinessCheckInstaller.php b/setup/src/Magento/Setup/Controller/ReadinessCheckInstaller.php deleted file mode 100644 index e507c645c2d02..0000000000000 --- a/setup/src/Magento/Setup/Controller/ReadinessCheckInstaller.php +++ /dev/null @@ -1,44 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\ViewModel; - -/** - * ReadinessCheckInstaller controller - */ -class ReadinessCheckInstaller extends AbstractActionController -{ - const INSTALLER = 'installer'; - - /** - * Index action - * - * @return array|ViewModel - */ - public function indexAction() - { - $view = new ViewModel(); - $view->setTerminal(true); - $view->setTemplate('/magento/setup/readiness-check.phtml'); - $view->setVariable('actionFrom', self::INSTALLER); - return $view; - } - - /** - * Progress action - * - * @return array|ViewModel - */ - public function progressAction() - { - $view = new ViewModel(); - $view->setTemplate('/magento/setup/readiness-check/progress.phtml'); - $view->setTerminal(true); - return $view; - } -} diff --git a/setup/src/Magento/Setup/Controller/ReadinessCheckUpdater.php b/setup/src/Magento/Setup/Controller/ReadinessCheckUpdater.php deleted file mode 100644 index 59220004d2ed8..0000000000000 --- a/setup/src/Magento/Setup/Controller/ReadinessCheckUpdater.php +++ /dev/null @@ -1,44 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\ViewModel; - -/** - * ReadinessCheckUpdater controller - */ -class ReadinessCheckUpdater extends AbstractActionController -{ - const UPDATER = 'updater'; - - /** - * Index action - * - * @return array|ViewModel - */ - public function indexAction() - { - $view = new ViewModel(); - $view->setTerminal(true); - $view->setTemplate('/magento/setup/readiness-check.phtml'); - $view->setVariable('actionFrom', self::UPDATER); - return $view; - } - - /** - * Progress action - * - * @return array|ViewModel - */ - public function progressAction() - { - $view = new ViewModel(); - $view->setTemplate('/magento/setup/readiness-check/progress.phtml'); - $view->setTerminal(true); - return $view; - } -} diff --git a/setup/src/Magento/Setup/Controller/SearchEngineCheck.php b/setup/src/Magento/Setup/Controller/SearchEngineCheck.php deleted file mode 100644 index 37059f0b03184..0000000000000 --- a/setup/src/Magento/Setup/Controller/SearchEngineCheck.php +++ /dev/null @@ -1,87 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Controller; - -use Laminas\Json\Json; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; -use Magento\Framework\Exception\InputException; -use Magento\Setup\Model\SearchConfigOptionsList; -use Magento\Setup\Validator\ElasticsearchConnectionValidator; - -/** - * SearchEngineCheck controller - */ -class SearchEngineCheck extends AbstractActionController -{ - /** - * @var ElasticsearchConnectionValidator - */ - private $connectionValidator; - - /** - * @var SearchConfigOptionsList - */ - private $searchConfigOptionsList; - - /** - * @param ElasticsearchConnectionValidator $connectionValidator - * @param SearchConfigOptionsList $searchConfigOptionsList - */ - public function __construct( - ElasticsearchConnectionValidator $connectionValidator, - SearchConfigOptionsList $searchConfigOptionsList - ) { - $this->connectionValidator = $connectionValidator; - $this->searchConfigOptionsList = $searchConfigOptionsList; - } - - /** - * Result of checking Elasticsearch connection - * - * @return JsonModel - */ - public function indexAction(): JsonModel - { - try { - $params = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); - $this->isValidSearchEngine($params); - $isValid = $this->connectionValidator->isValidConnection( - [ - 'hostname' => $params['elasticsearch']['hostname'] ?? null, - 'port' => $params['elasticsearch']['port'] ?? null, - 'enableAuth' => $params['elasticsearch']['enableAuth'] ?? false, - 'username' => $params['elasticsearch']['username'] ?? null, - 'password' => $params['elasticsearch']['password'] ?? null, - 'indexPrefix' => $params['elasticsearch']['indexPrefix'] ?? '' - ] - ); - return new JsonModel(['success' => $isValid]); - } catch (\Exception $e) { - return new JsonModel(['success' => false, 'error' => $e->getMessage()]); - } - } - - /** - * Check search engine parameter is valid - * - * @param array $requestParams - * @return bool - * @throws InputException - */ - private function isValidSearchEngine(array $requestParams): bool - { - $selectedEngine = $requestParams['engine'] ?? null; - $availableSearchEngines = $this->searchConfigOptionsList->getAvailableSearchEngineList(); - if (empty($selectedEngine) || !isset($availableSearchEngines[$selectedEngine])) { - throw new InputException(__('Please select a valid search engine.')); - } - - return true; - } -} diff --git a/setup/src/Magento/Setup/Controller/SelectVersion.php b/setup/src/Magento/Setup/Controller/SelectVersion.php deleted file mode 100644 index f22b41a8614b1..0000000000000 --- a/setup/src/Magento/Setup/Controller/SelectVersion.php +++ /dev/null @@ -1,83 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Setup\Model\SystemPackage; - -/** - * Controller for selecting version - */ -class SelectVersion extends AbstractActionController -{ - /** - * @var SystemPackage - */ - protected $systemPackage; - - /** - * @param SystemPackage $systemPackage - */ - public function __construct( - SystemPackage $systemPackage - ) { - $this->systemPackage = $systemPackage; - } - - /** - * Index action - * - * @return ViewModel|\Laminas\Http\Response - */ - public function indexAction() - { - $view = new ViewModel(); - $view->setTerminal(true); - $view->setTemplate('/magento/setup/select-version.phtml'); - return $view; - } - - /** - * Gets system package and versions - * - * @return JsonModel - */ - public function systemPackageAction() - { - $data = []; - try { - $data['packages'] = $this->systemPackage->getPackageVersions(); - $responseType = ResponseTypeInterface::RESPONSE_TYPE_SUCCESS; - } catch (\Exception $e) { - $responseType = ResponseTypeInterface::RESPONSE_TYPE_ERROR; - $data['error'] = $e->getMessage(); - } - $data['responseType'] = $responseType; - - return new JsonModel($data); - } - - /** - * Gets installed system package - * - * @return JsonModel - */ - public function installedSystemPackageAction() - { - $data = []; - try { - $data['packages'] = $this->systemPackage->getInstalledSystemPackages(); - $data['responseType'] = ResponseTypeInterface::RESPONSE_TYPE_SUCCESS; - } catch (\Exception $e) { - $data['error'] = $e->getMessage(); - $data['responseType'] = ResponseTypeInterface::RESPONSE_TYPE_ERROR; - } - return new JsonModel($data); - } -} diff --git a/setup/src/Magento/Setup/Controller/Session.php b/setup/src/Magento/Setup/Controller/Session.php deleted file mode 100644 index fa25924d01a15..0000000000000 --- a/setup/src/Magento/Setup/Controller/Session.php +++ /dev/null @@ -1,103 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -/** - * Sets up session for setup/index.php/session/prolong or redirects to error page - */ -class Session extends \Laminas\Mvc\Controller\AbstractActionController -{ - /** - * @var \Laminas\ServiceManager\ServiceManager - */ - private $serviceManager; - - /** - * @var \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider - */ - private $objectManagerProvider; - - /** - * @param \Laminas\ServiceManager\ServiceManager $serviceManager - * @param \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider - */ - public function __construct( - \Laminas\ServiceManager\ServiceManager $serviceManager, - \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider - ) { - $this->serviceManager = $serviceManager; - $this->objectManagerProvider = $objectManagerProvider; - } - - /** - * No index action, return 404 error page - * - * @return \Laminas\View\Model\ViewModel|\Laminas\Http\Response - */ - public function indexAction() - { - $view = new \Laminas\View\Model\ViewModel(); - $view->setTemplate('/error/404.phtml'); - $this->getResponse()->setStatusCode(\Laminas\Http\Response::STATUS_CODE_404); - return $view; - } - - /** - * Prolong session - * - * @return string - */ - public function prolongAction() - { - try { - if ($this->serviceManager->get(\Magento\Framework\App\DeploymentConfig::class)->isAvailable()) { - $objectManager = $this->objectManagerProvider->get(); - /* @var \Magento\Backend\Model\Auth\Session $session */ - $session = $objectManager->get(\Magento\Backend\Model\Auth\Session::class); - // check if session was already set in \Magento\Setup\Mvc\Bootstrap\InitParamListener::authPreDispatch - if (!$session->isSessionExists()) { - /** @var \Magento\Framework\App\State $adminAppState */ - $adminAppState = $objectManager->get(\Magento\Framework\App\State::class); - $adminAppState->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML); - $sessionConfig = $objectManager->get(\Magento\Backend\Model\Session\AdminConfig::class); - /** @var \Magento\Backend\Model\Url $backendUrl */ - $backendUrl = $objectManager->get(\Magento\Backend\Model\Url::class); - // phpcs:ignore Magento2.Functions.DiscouragedFunction - $urlPath = parse_url($backendUrl->getBaseUrl(), PHP_URL_PATH); - $cookiePath = $urlPath . 'setup'; - $sessionConfig->setCookiePath($cookiePath); - /* @var \Magento\Backend\Model\Auth\Session $session */ - $session = $objectManager->create( - \Magento\Backend\Model\Auth\Session::class, - [ - 'sessionConfig' => $sessionConfig, - 'appState' => $adminAppState - ] - ); - } - $session->prolong(); - return new \Laminas\View\Model\JsonModel(['success' => true]); - } - // phpcs:ignore Magento2.CodeAnalysis.EmptyBlock.DetectedCatch - } catch (\Exception $e) { - } - return new \Laminas\View\Model\JsonModel(['success' => false]); - } - - /** - * Unlogin action, return 401 error page - * - * @return \Laminas\View\Model\ViewModel|\Laminas\Http\Response - */ - public function unloginAction() - { - $view = new \Laminas\View\Model\ViewModel(); - $view->setTemplate('/error/401.phtml'); - $this->getResponse()->setStatusCode(\Laminas\Http\Response::STATUS_CODE_401); - return $view; - } -} diff --git a/setup/src/Magento/Setup/Controller/StartUpdater.php b/setup/src/Magento/Setup/Controller/StartUpdater.php deleted file mode 100644 index fb4d8ae03b9ef..0000000000000 --- a/setup/src/Magento/Setup/Controller/StartUpdater.php +++ /dev/null @@ -1,79 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -use Magento\Setup\Model\UpdaterTaskCreator; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Laminas\Json\Json; - -/** - * Controller for updater tasks - */ -class StartUpdater extends AbstractActionController -{ - /** - * @var \Magento\Setup\Model\UpdaterTaskCreator - */ - private $updaterTaskCreator; - - /** - * @var \Magento\Setup\Model\PayloadValidator - */ - private $payloadValidator; - - /** - * Constructor - * - * @param \Magento\Setup\Model\UpdaterTaskCreator $updaterTaskCreator - * @param \Magento\Setup\Model\PayloadValidator $payloadValidator - */ - public function __construct( - \Magento\Setup\Model\UpdaterTaskCreator $updaterTaskCreator, - \Magento\Setup\Model\PayloadValidator $payloadValidator - ) { - $this->updaterTaskCreator = $updaterTaskCreator; - $this->payloadValidator = $payloadValidator; - } - - /** - * Index page action - * - * @return ViewModel - */ - public function indexAction() - { - $view = new ViewModel(); - $view->setTerminal(true); - return $view; - } - - /** - * Update action - * - * @return JsonModel - */ - public function updateAction() - { - $postPayload = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); - $errorMessage = ''; - if (isset($postPayload[UpdaterTaskCreator::KEY_POST_PACKAGES]) - && is_array($postPayload[UpdaterTaskCreator::KEY_POST_PACKAGES]) - && isset($postPayload[UpdaterTaskCreator::KEY_POST_JOB_TYPE]) - ) { - $errorMessage .= $this->payloadValidator->validatePayload($postPayload); - if (empty($errorMessage)) { - $errorMessage = $this->updaterTaskCreator->createUpdaterTasks($postPayload); - } - } else { - $errorMessage .= 'Invalid request'; - } - $success = empty($errorMessage); - return new JsonModel(['success' => $success, 'message' => $errorMessage]); - } -} diff --git a/setup/src/Magento/Setup/Controller/Success.php b/setup/src/Magento/Setup/Controller/Success.php deleted file mode 100644 index c597dd8b1bc0a..0000000000000 --- a/setup/src/Magento/Setup/Controller/Success.php +++ /dev/null @@ -1,59 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Magento\Framework\Module\ModuleList; -use Magento\Setup\Model\ObjectManagerProvider; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\ViewModel; - -/** - * Success controller - */ -class Success extends AbstractActionController -{ - /** - * @var ModuleList - */ - protected $moduleList; - - /** - * @var ObjectManagerProvider - */ - protected $objectManagerProvider; - - /** - * @param ModuleList $moduleList - * @param ObjectManagerProvider $objectManagerProvider - */ - public function __construct(ModuleList $moduleList, ObjectManagerProvider $objectManagerProvider) - { - $this->moduleList = $moduleList; - $this->objectManagerProvider = $objectManagerProvider; - } - - /** - * Index action - * - * @return ViewModel - * @throws \Magento\Setup\Exception - */ - public function indexAction() - { - if ($this->moduleList->has('Magento_SampleData')) { - /** @var \Magento\Framework\Setup\SampleData\State $sampleData */ - $sampleData = $this->objectManagerProvider->get()->get(\Magento\Framework\Setup\SampleData\State::class); - $isSampleDataErrorInstallation = $sampleData->hasError(); - } else { - $isSampleDataErrorInstallation = false; - } - $view = new ViewModel([ - 'isSampleDataErrorInstallation' => $isSampleDataErrorInstallation - ]); - $view->setTerminal(true); - return $view; - } -} diff --git a/setup/src/Magento/Setup/Controller/SystemConfig.php b/setup/src/Magento/Setup/Controller/SystemConfig.php deleted file mode 100644 index 0067752997e17..0000000000000 --- a/setup/src/Magento/Setup/Controller/SystemConfig.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\ViewModel; - -/** - * SystemConfig controller - */ -class SystemConfig extends AbstractActionController -{ - /** - * Index action - * - * @return ViewModel - */ - public function indexAction() - { - $view = new ViewModel(); - $view->setTerminal(true); - return $view; - } -} diff --git a/setup/src/Magento/Setup/Controller/UpdateExtensionGrid.php b/setup/src/Magento/Setup/Controller/UpdateExtensionGrid.php deleted file mode 100644 index 55ff91a04cdf4..0000000000000 --- a/setup/src/Magento/Setup/Controller/UpdateExtensionGrid.php +++ /dev/null @@ -1,60 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Setup\Model\Grid; - -/** - * Controller for update extensions grid tasks - */ -class UpdateExtensionGrid extends AbstractActionController -{ - /** - * @var Grid\Extension - */ - private $gridExtension; - - /** - * @param Grid\Extension $gridExtension - */ - public function __construct(Grid\Extension $gridExtension) - { - $this->gridExtension = $gridExtension; - } - - /** - * Index page action - * - * @return ViewModel - */ - public function indexAction() - { - $view = new ViewModel(); - $view->setTerminal(true); - return $view; - } - - /** - * Get extensions action - * - * @return JsonModel - */ - public function extensionsAction() - { - $extensions = $this->gridExtension->getListForUpdate(); - - return new JsonModel( - [ - 'success' => true, - 'extensions' => array_values($extensions), - 'total' => count($extensions) - ] - ); - } -} diff --git a/setup/src/Magento/Setup/Controller/UpdaterSuccess.php b/setup/src/Magento/Setup/Controller/UpdaterSuccess.php deleted file mode 100644 index c12d9a164ac4c..0000000000000 --- a/setup/src/Magento/Setup/Controller/UpdaterSuccess.php +++ /dev/null @@ -1,45 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\ViewModel; -use Magento\Framework\App\MaintenanceMode; - -/** - * UpdaterSuccess controller - */ -class UpdaterSuccess extends AbstractActionController -{ - /** - * @var MaintenanceMode - */ - private $maintenanceMode; - - /** - * Constructor - * - * @param MaintenanceMode $maintenanceMode - */ - public function __construct(MaintenanceMode $maintenanceMode) - { - $this->maintenanceMode = $maintenanceMode; - } - - /** - * Index action - * - * @return ViewModel - */ - public function indexAction() - { - $this->maintenanceMode->set(false); - $view = new ViewModel(); - $view->setTerminal(true); - return $view; - } -} diff --git a/setup/src/Magento/Setup/Controller/UrlCheck.php b/setup/src/Magento/Setup/Controller/UrlCheck.php deleted file mode 100644 index 1dfe838e6ca2c..0000000000000 --- a/setup/src/Magento/Setup/Controller/UrlCheck.php +++ /dev/null @@ -1,62 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; -use Laminas\Json\Json; -use Magento\Framework\Validator\Url as UrlValidator; - -/** - * UrlCheck controller - */ -class UrlCheck extends AbstractActionController -{ - /** - * @var UrlValidator - */ - private $urlValidator; - - /** - * @param UrlValidator $urlValidator - */ - public function __construct(UrlValidator $urlValidator) - { - $this->urlValidator = $urlValidator; - } - - /** - * Validate URL - * - * @return JsonModel - */ - public function indexAction() - { - $params = Json::decode($this->getRequest()->getContent(), Json::TYPE_ARRAY); - $result = ['successUrl' => false, 'successSecureUrl' => true]; - - $hasBaseUrl = isset($params['address']['actual_base_url']); - $hasSecureBaseUrl = isset($params['https']['text']); - $hasSecureAdminUrl = !empty($params['https']['admin']); - $hasSecureFrontUrl = !empty($params['https']['front']); - $schemes = ['http', 'https']; - - // Validating of Base URL - if ($hasBaseUrl && $this->urlValidator->isValid($params['address']['actual_base_url'], $schemes)) { - $result['successUrl'] = true; - } - - // Validating of Secure Base URL - if ($hasSecureAdminUrl || $hasSecureFrontUrl) { - if (!($hasSecureBaseUrl && $this->urlValidator->isValid($params['https']['text'], $schemes))) { - $result['successSecureUrl'] = false; - } - } - - return new JsonModel($result); - } -} diff --git a/setup/src/Magento/Setup/Controller/ValidateAdminCredentials.php b/setup/src/Magento/Setup/Controller/ValidateAdminCredentials.php deleted file mode 100644 index 03faef928cdaf..0000000000000 --- a/setup/src/Magento/Setup/Controller/ValidateAdminCredentials.php +++ /dev/null @@ -1,61 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Controller; - -use Magento\Setup\Model\Installer; -use Magento\Setup\Model\RequestDataConverter; -use Magento\Setup\Validator\AdminCredentialsValidator; -use Laminas\Json\Json; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\JsonModel; - -/** - * Controller for admin credentials validation - */ -class ValidateAdminCredentials extends AbstractActionController -{ - /** - * @var AdminCredentialsValidator - */ - private $adminCredentialsValidator; - - /** - * @var RequestDataConverter - */ - private $requestDataConverter; - - /** - * Initialize dependencies. - * - * @param AdminCredentialsValidator $adminCredentialsValidator - * @param RequestDataConverter $requestDataConverter - */ - public function __construct( - AdminCredentialsValidator $adminCredentialsValidator, - RequestDataConverter $requestDataConverter - ) { - $this->adminCredentialsValidator = $adminCredentialsValidator; - $this->requestDataConverter = $requestDataConverter; - } - - /** - * Validate admin credentials. - * - * @return JsonModel - */ - public function indexAction() - { - try { - $content = $this->getRequest()->getContent(); - $source = $content ? $source = Json::decode($content, Json::TYPE_ARRAY) : []; - $data = $this->requestDataConverter->convert($source); - $this->adminCredentialsValidator->validate($data); - return new JsonModel(['success' => true]); - } catch (\Exception $e) { - return new JsonModel(['success' => false, 'error' => $e->getMessage()]); - } - } -} diff --git a/setup/src/Magento/Setup/Controller/WebConfiguration.php b/setup/src/Magento/Setup/Controller/WebConfiguration.php deleted file mode 100644 index eebe01a008afb..0000000000000 --- a/setup/src/Magento/Setup/Controller/WebConfiguration.php +++ /dev/null @@ -1,41 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Controller; - -use Magento\Framework\App\SetupInfo; -use Magento\Framework\Config\ConfigOptionsListConstants; -use Laminas\Mvc\Controller\AbstractActionController; -use Laminas\View\Model\ViewModel; - -/** - * WebConfiguration controller - */ -class WebConfiguration extends AbstractActionController -{ - /** - * Displays web configuration form - * - * @return array|ViewModel - */ - public function indexAction() - { - // phpcs:ignore Magento2.Security.Superglobal - $setupInfo = new SetupInfo($_SERVER); - $view = new ViewModel( - [ - 'autoBaseUrl' => $setupInfo->getProjectUrl(), - 'autoAdminPath' => $setupInfo->getProjectAdminPath(), - 'sessionSave' => [ - ConfigOptionsListConstants::SESSION_SAVE_FILES, - ConfigOptionsListConstants::SESSION_SAVE_DB, - ], - ] - ); - $view->setTerminal(true); - return $view; - } -} diff --git a/setup/src/Magento/Setup/Fixtures/WebsiteCategoryProvider.php b/setup/src/Magento/Setup/Fixtures/WebsiteCategoryProvider.php index 42370639839c6..673b8156b8453 100644 --- a/setup/src/Magento/Setup/Fixtures/WebsiteCategoryProvider.php +++ b/setup/src/Magento/Setup/Fixtures/WebsiteCategoryProvider.php @@ -3,10 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Setup\Fixtures; use Magento\Framework\App\ResourceConnection; +use Magento\Framework\DB\Adapter\AdapterInterface; /** * Website and category provider @@ -29,7 +31,7 @@ class WebsiteCategoryProvider private $resourceConnection; /** - * @var \Magento\Framework\DB\Adapter\AdapterInterface + * @var AdapterInterface */ private $connection; @@ -93,6 +95,8 @@ public function getCategoryId($productIndex) } /** + * Get categories and websites + * * @return array */ private function getCategoriesAndWebsites() @@ -106,7 +110,7 @@ private function getCategoriesAndWebsites() ['sg' => $this->resourceConnection->getTableName('store_group')], "c.path like concat('1/', sg.root_category_id, '/%')", ['website' => 'website_id'] - ); + )->order('category ASC'); $this->categoriesPerWebsite = $this->getConnection()->fetchAll($select); } @@ -114,6 +118,8 @@ private function getCategoriesAndWebsites() } /** + * Checks is assign_entities_to_all_websites flag set + * * @return bool */ private function isAssignToAllWebsites() @@ -122,6 +128,8 @@ private function isAssignToAllWebsites() } /** + * Provides all websites + * * @return array */ private function getAllWebsites() @@ -134,6 +142,8 @@ private function getAllWebsites() } /** + * Provides all categories + * * @return array */ private function getAllCategories() @@ -146,7 +156,9 @@ private function getAllCategories() } /** - * @return \Magento\Framework\DB\Adapter\AdapterInterface + * Provides connection + * + * @return AdapterInterface */ private function getConnection() { diff --git a/setup/src/Magento/Setup/Model/Cron/AbstractJob.php b/setup/src/Magento/Setup/Model/Cron/AbstractJob.php deleted file mode 100644 index ce481e2b7ab8b..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/AbstractJob.php +++ /dev/null @@ -1,124 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Cron; - -use Symfony\Component\Console\Output\OutputInterface; -use Magento\Framework\App\Cache; -use Magento\Framework\ObjectManagerInterface; - -/** - * Abstract class for jobs run by setup:cron:run command - */ -abstract class AbstractJob -{ - /** - * @var \Magento\Setup\Console\Command\AbstractSetupCommand - */ - protected $command; - - /** - * @var \Symfony\Component\Console\Output\OutputInterface - */ - protected $output; - - /** - * @var string - */ - protected $name; - - /** - * @var array - */ - protected $params; - - /** - * @var \Magento\Framework\App\Cache - */ - protected $cache; - - /** - * @var \Magento\Framework\App\State\CleanupFiles - */ - protected $cleanupFiles; - - /** - * @var Status - */ - protected $status; - - /** - * @var ObjectManagerInterface - */ - protected $objectManager; - - /** - * Constructor - * - * @param \Symfony\Component\Console\Output\OutputInterface $output - * @param \Magento\Setup\Model\Cron\Status $status - * @param \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider - * @param string $name - * @param array $params - */ - public function __construct( - \Symfony\Component\Console\Output\OutputInterface $output, - \Magento\Setup\Model\Cron\Status $status, - \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider, - $name, - array $params = [] - ) { - $this->output = $output; - $this->status = $status; - $this->name = $name; - $this->params = $params; - - $this->objectManager = $objectManagerProvider->get(); - $this->cleanupFiles = $this->objectManager->get(\Magento\Framework\App\State\CleanupFiles::class); - $this->cache = $this->objectManager->get(\Magento\Framework\App\Cache::class); - } - - /** - * Get job name. - * - * @return string - */ - public function getName() - { - return $this->name; - } - - /** - * Get string representation of a job. - * - * @return string - */ - public function __toString() - { - return $this->name . ' ' . json_encode($this->params, JSON_UNESCAPED_SLASHES); - } - - /** - * Do the cleanup - * - * @return void - */ - protected function performCleanup() - { - $this->status->add('Cleaning generated files...', \Psr\Log\LogLevel::INFO); - $this->cleanupFiles->clearCodeGeneratedFiles(); - $this->status->add('Complete!', \Psr\Log\LogLevel::INFO); - $this->status->add('Clearing cache...', \Psr\Log\LogLevel::INFO); - $this->cache->clean(); - $this->status->add('Complete!', \Psr\Log\LogLevel::INFO); - } - - /** - * Execute job - * - * @return void - */ - abstract public function execute(); -} diff --git a/setup/src/Magento/Setup/Model/Cron/Helper/ModuleUninstall.php b/setup/src/Magento/Setup/Model/Cron/Helper/ModuleUninstall.php deleted file mode 100644 index b88dd845dc331..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/Helper/ModuleUninstall.php +++ /dev/null @@ -1,69 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Cron\Helper; - -use Magento\Framework\Module\PackageInfoFactory; -use Magento\Setup\Model\ModuleRegistryUninstaller; -use Magento\Setup\Model\ModuleUninstaller; -use Symfony\Component\Console\Output\OutputInterface; - -/** - * Helper class for JobComponentUninstall to uninstall a module component - */ -class ModuleUninstall -{ - /** - * @var ModuleUninstaller - */ - private $moduleUninstaller; - - /** - * @var ModuleRegistryUninstaller - */ - private $moduleRegistryUninstaller; - - /** - * @var PackageInfoFactory - */ - private $packageInfoFactory; - - /** - * Constructor - * - * @param ModuleUninstaller $moduleUninstaller - * @param ModuleRegistryUninstaller $moduleRegistryUninstaller - * @param PackageInfoFactory $packageInfoFactory - */ - public function __construct( - ModuleUninstaller $moduleUninstaller, - ModuleRegistryUninstaller $moduleRegistryUninstaller, - PackageInfoFactory $packageInfoFactory - ) { - $this->moduleUninstaller = $moduleUninstaller; - $this->moduleRegistryUninstaller = $moduleRegistryUninstaller; - $this->packageInfoFactory = $packageInfoFactory; - } - - /** - * Perform setup side uninstall - * - * @param OutputInterface $output - * @param string $componentName - * @param bool $dataOption - * @return void - */ - public function uninstall(OutputInterface $output, $componentName, $dataOption) - { - $packageInfo = $this->packageInfoFactory->create(); - // convert to module name - $moduleName = $packageInfo->getModuleName($componentName); - if ($dataOption) { - $this->moduleUninstaller->uninstallData($output, [$moduleName]); - } - $this->moduleRegistryUninstaller->removeModulesFromDb($output, [$moduleName]); - $this->moduleRegistryUninstaller->removeModulesFromDeploymentConfig($output, [$moduleName]); - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/Helper/ThemeUninstall.php b/setup/src/Magento/Setup/Model/Cron/Helper/ThemeUninstall.php deleted file mode 100644 index 21a660f32d01e..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/Helper/ThemeUninstall.php +++ /dev/null @@ -1,51 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Cron\Helper; - -use Magento\Theme\Model\Theme\ThemePackageInfo; -use Magento\Theme\Model\Theme\ThemeUninstaller; -use Symfony\Component\Console\Output\OutputInterface; - -/** - * Helper class for JobComponentUninstall to uninstall a theme component - */ -class ThemeUninstall -{ - /** - * @var ThemeUninstaller - */ - private $themeUninstaller; - - /** - * @var ThemePackageInfo - */ - private $themePackageInfo; - - /** - * Constructor - * - * @param ThemeUninstaller $themeUninstaller - * @param ThemePackageInfo $themePackageInfo - */ - public function __construct(ThemeUninstaller $themeUninstaller, ThemePackageInfo $themePackageInfo) - { - $this->themeUninstaller = $themeUninstaller; - $this->themePackageInfo = $themePackageInfo; - } - - /** - * Perform setup side uninstall - * - * @param OutputInterface $output - * @param string $componentName - * @return void - */ - public function uninstall(OutputInterface $output, $componentName) - { - $themePath = $this->themePackageInfo->getFullThemePath($componentName); - $this->themeUninstaller->uninstallRegistry($output, [$themePath]); - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/JobComponentUninstall.php b/setup/src/Magento/Setup/Model/Cron/JobComponentUninstall.php deleted file mode 100644 index f1292394b57c1..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/JobComponentUninstall.php +++ /dev/null @@ -1,167 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Cron; - -use Magento\Setup\Model\Updater; -use Magento\Setup\Model\Cron\Queue; -use Magento\Framework\Composer\ComposerInformation; - -/** - * Job to remove a component. Run by Setup Cron Task - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - * @SuppressWarnings(PHPMD.ExcessiveParameterList) - */ -class JobComponentUninstall extends AbstractJob -{ - /** - * Component name - */ - const COMPONENT_NAME = 'name'; - - /** - * Data option - */ - const DATA_OPTION = 'dataOption'; - - /** - * @var \Magento\Framework\ObjectManagerInterface - */ - protected $objectManager; - - /** - * @var \Magento\Setup\Model\Updater - */ - private $updater; - - /** - * @var \Magento\Framework\Composer\ComposerInformation - */ - private $composerInformation; - - /** - * @var Helper\ModuleUninstall - */ - private $moduleUninstall; - - /** - * @var Helper\ThemeUninstall - */ - private $themeUninstall; - - /** - * @var \Magento\Setup\Model\Cron\Queue - */ - private $queue; - - /** - * Constructor - * - * @param \Magento\Framework\Composer\ComposerInformation $composerInformation - * @param Helper\ModuleUninstall $moduleUninstall - * @param Helper\ThemeUninstall $themeUninstall - * @param \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider - * @param \Symfony\Component\Console\Output\OutputInterface $output - * @param \Magento\Setup\Model\Cron\Queue $queue - * @param \Magento\Setup\Model\Cron\Status $status - * @param \Magento\Setup\Model\Updater $updater - * @param string $name - * @param array $params - */ - public function __construct( - \Magento\Framework\Composer\ComposerInformation $composerInformation, - Helper\ModuleUninstall $moduleUninstall, - Helper\ThemeUninstall $themeUninstall, - \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider, - \Symfony\Component\Console\Output\OutputInterface $output, - \Magento\Setup\Model\Cron\Queue $queue, - \Magento\Setup\Model\Cron\Status $status, - \Magento\Setup\Model\Updater $updater, - $name, - $params = [] - ) { - $this->composerInformation = $composerInformation; - $this->moduleUninstall = $moduleUninstall; - $this->themeUninstall = $themeUninstall; - $this->objectManager = $objectManagerProvider->get(); - $this->updater = $updater; - $this->queue = $queue; - parent::__construct($output, $status, $objectManagerProvider, $name, $params); - } - - /** - * Run remove component job - * - * @return void - * @throw \RuntimeException - */ - public function execute() - { - if (!isset($this->params['components']) || !is_array($this->params['components'])) { - $this->status->toggleUpdateError(true); - throw new \RuntimeException('Job parameter format is incorrect'); - } - $components = $this->params['components']; - foreach ($components as $component) { - $this->executeComponent($component); - } - $this->queue->addJobs( - [['name' => JobFactory::JOB_STATIC_REGENERATE, 'params' => []]] - ); - $errorMessage = $this->updater->createUpdaterTask($components, Updater::TASK_TYPE_UNINSTALL); - if ($errorMessage) { - $this->status->toggleUpdateError(true); - throw new \RuntimeException($errorMessage); - } - } - - /** - * Execute uninstall on a component - * - * @param array $component - * @return void - * @throw \RuntimeException - */ - private function executeComponent(array $component) - { - if (!isset($component[self::COMPONENT_NAME])) { - $this->status->toggleUpdateError(true); - throw new \RuntimeException('Job parameter format is incorrect'); - } - - $componentName = $component[self::COMPONENT_NAME]; - $installedPackages = $this->composerInformation->getInstalledMagentoPackages(); - if (isset($installedPackages[$componentName]['type'])) { - $type = $installedPackages[$componentName]['type']; - } else { - $this->status->toggleUpdateError(true); - throw new \RuntimeException('Component type not set'); - } - - if (!in_array($type, [ - ComposerInformation::MODULE_PACKAGE_TYPE, - ComposerInformation::THEME_PACKAGE_TYPE, - ComposerInformation::LANGUAGE_PACKAGE_TYPE, - ComposerInformation::COMPONENT_PACKAGE_TYPE - ])) { - $this->status->toggleUpdateError(true); - throw new \RuntimeException('Unknown component type'); - } - - switch ($type) { - case ComposerInformation::MODULE_PACKAGE_TYPE: - $dataOption = isset($this->params[self::DATA_OPTION]) && $this->params[self::DATA_OPTION] === 'true'; - $this->moduleUninstall->uninstall( - $this->output, - $componentName, - $dataOption - ); - break; - case ComposerInformation::THEME_PACKAGE_TYPE: - $this->themeUninstall->uninstall($this->output, $componentName); - break; - } - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/JobDbRollback.php b/setup/src/Magento/Setup/Model/Cron/JobDbRollback.php deleted file mode 100644 index 3be6137fad869..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/JobDbRollback.php +++ /dev/null @@ -1,91 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Cron; - -use Magento\Framework\Setup\BackupRollback; -use Magento\Framework\Setup\BackupRollbackFactory; -use Magento\Setup\Model\ObjectManagerProvider; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Output\OutputInterface; - -/** - * DB Rollback job - */ -class JobDbRollback extends AbstractJob -{ - /** - * @var BackupRollbackFactory - */ - private $backupRollbackFactory; - - /** - * Constructor - * @param BackupRollbackFactory $backupRollbackFactory - * @param OutputInterface $output - * @param Status $status - * @param ObjectManagerProvider $objectManagerProvider - * @param array $name - * @param array $params - */ - public function __construct( - BackupRollbackFactory $backupRollbackFactory, - OutputInterface $output, - Status $status, - ObjectManagerProvider $objectManagerProvider, - $name, - $params = [] - ) { - $this->backupRollbackFactory = $backupRollbackFactory; - parent::__construct($output, $status, $objectManagerProvider, $name, $params); - } - - /** - * Execute job - * - * @throws \RuntimeException - * @return void - */ - public function execute() - { - try { - $rollbackHandler = $this->backupRollbackFactory->create($this->output); - $dbBackupFile = $this->params['backup_file_name']; - if (!empty($dbBackupFile)) { - $this->setAreaCode(); - $rollbackHandler->dbRollback(basename($dbBackupFile)); - } else { - $this->status->add( - 'No available DB backup file found. Please refer to documentation specified ' - . 'in <a href=""> doc link </a> to rollback database to a previous version to ', - \Psr\Log\LogLevel::INFO - ); - } - } catch (\Exception $e) { - $this->status->toggleUpdateError(true); - throw new \RuntimeException( - sprintf('Could not complete %s successfully: %s', $this, $e->getMessage()), - $e->getCode(), - $e - ); - } - } - - /** - * Sets area code to start a session for database backup and rollback - * - * @return void - */ - private function setAreaCode() - { - $areaCode = 'adminhtml'; - /** @var \Magento\Framework\App\State $appState */ - $appState = $this->objectManager->get(\Magento\Framework\App\State::class); - $appState->setAreaCode($areaCode); - /** @var \Magento\Framework\ObjectManager\ConfigLoaderInterface $configLoader */ - $configLoader = $this->objectManager->get(\Magento\Framework\ObjectManager\ConfigLoaderInterface::class); - $this->objectManager->configure($configLoader->load($areaCode)); - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/JobFactory.php b/setup/src/Magento/Setup/Model/Cron/JobFactory.php deleted file mode 100644 index cae149ed38e8f..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/JobFactory.php +++ /dev/null @@ -1,183 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Model\Cron; - -use Magento\Backend\Console\Command\CacheDisableCommand; -use Magento\Backend\Console\Command\CacheEnableCommand; -use Magento\Framework\ObjectManagerInterface; -use Magento\Setup\Console\Command\ModuleDisableCommand; -use Magento\Setup\Console\Command\ModuleEnableCommand; -use Magento\Setup\Console\Command\UpgradeCommand; -use Laminas\ServiceManager\ServiceLocatorInterface; -use Magento\Setup\Console\Command\MaintenanceDisableCommand; -use Magento\Setup\Console\Command\MaintenanceEnableCommand; - -/** - * Factory class to create jobs - * - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class JobFactory -{ - /** - * Name of jobs - */ - const JOB_UPGRADE = 'setup:upgrade'; - const JOB_DB_ROLLBACK = 'setup:rollback'; - const JOB_COMPONENT_UNINSTALL = 'setup:component:uninstall'; - const JOB_MODULE_ENABLE = 'setup:module:enable'; - const JOB_MODULE_DISABLE = 'setup:module:disable'; - const JOB_STATIC_REGENERATE = 'setup:static:regenerate'; - const JOB_ENABLE_CACHE = 'setup:cache:enable'; - const JOB_DISABLE_CACHE = 'setup:cache:disable'; - const JOB_MAINTENANCE_MODE_ENABLE = 'setup:maintenance:enable'; - const JOB_MAINTENANCE_MODE_DISABLE = 'setup:maintenance:disable'; - - /** - * @var ServiceLocatorInterface - */ - private $serviceLocator; - - /** - * Constructor - * - * @param ServiceLocatorInterface $serviceLocator - */ - public function __construct(ServiceLocatorInterface $serviceLocator) - { - $this->serviceLocator = $serviceLocator; - } - - /** - * Create job instance. - * - * @param string $name - * @param array $params - * @return AbstractJob - * @throws \RuntimeException - * @SuppressWarnings(PHPMD.ExcessiveMethodLength) - * @SuppressWarnings(PHPMD.CyclomaticComplexity) - */ - public function create($name, array $params = []) - { - $cronStatus = $this->serviceLocator->get(\Magento\Setup\Model\Cron\Status::class); - // phpcs:ignore Magento2.Functions.DiscouragedFunction - $statusStream = fopen($cronStatus->getStatusFilePath(), 'a+'); - // phpcs:ignore Magento2.Functions.DiscouragedFunction - $logStream = fopen($cronStatus->getLogFilePath(), 'a+'); - $streamOutput = new MultipleStreamOutput([$statusStream, $logStream]); - $objectManagerProvider = $this->serviceLocator->get(\Magento\Setup\Model\ObjectManagerProvider::class); - /** @var ObjectManagerInterface $objectManager */ - $objectManager = $objectManagerProvider->get(); - switch ($name) { - case self::JOB_UPGRADE: - return new JobUpgrade( - $this->serviceLocator->get(UpgradeCommand::class), - $objectManagerProvider, - $streamOutput, - $this->serviceLocator->get(\Magento\Setup\Model\Cron\Queue::class), - $cronStatus, - $name, - $params - ); - case self::JOB_DB_ROLLBACK: - return new JobDbRollback( - $objectManager->get(\Magento\Framework\Setup\BackupRollbackFactory::class), - $streamOutput, - $cronStatus, - $objectManagerProvider, - $name, - $params - ); - case self::JOB_STATIC_REGENERATE: - return new JobStaticRegenerate( - $objectManagerProvider, - $streamOutput, - $cronStatus, - $name, - $params - ); - case self::JOB_COMPONENT_UNINSTALL: - $moduleUninstall = new Helper\ModuleUninstall( - $this->serviceLocator->get(\Magento\Setup\Model\ModuleUninstaller::class), - $this->serviceLocator->get(\Magento\Setup\Model\ModuleRegistryUninstaller::class), - $objectManager->get(\Magento\Framework\Module\PackageInfoFactory::class) - ); - $themeUninstall = new Helper\ThemeUninstall( - $objectManager->get(\Magento\Theme\Model\Theme\ThemeUninstaller::class), - $objectManager->get(\Magento\Theme\Model\Theme\ThemePackageInfo::class) - ); - return new JobComponentUninstall( - $objectManager->get(\Magento\Framework\Composer\ComposerInformation::class), - $moduleUninstall, - $themeUninstall, - $objectManagerProvider, - $streamOutput, - $this->serviceLocator->get(\Magento\Setup\Model\Cron\Queue::class), - $cronStatus, - $this->serviceLocator->get(\Magento\Setup\Model\Updater::class), - $name, - $params - ); - case self::JOB_MODULE_ENABLE: - return new JobModule( - $this->serviceLocator->get(ModuleEnableCommand::class), - $objectManagerProvider, - $streamOutput, - $cronStatus, - $name, - $params - ); - case self::JOB_MODULE_DISABLE: - return new JobModule( - $this->serviceLocator->get(ModuleDisableCommand::class), - $objectManagerProvider, - $streamOutput, - $cronStatus, - $name, - $params - ); - case self::JOB_ENABLE_CACHE: - return new JobSetCache( - $objectManager->get(CacheEnableCommand::class), - $objectManagerProvider, - $streamOutput, - $cronStatus, - $name, - $params - ); - case self::JOB_DISABLE_CACHE: - return new JobSetCache( - $objectManager->get(CacheDisableCommand::class), - $objectManagerProvider, - $streamOutput, - $cronStatus, - $name - ); - case self::JOB_MAINTENANCE_MODE_ENABLE: - return new JobSetMaintenanceMode( - $this->serviceLocator->get(MaintenanceEnableCommand::class), - $objectManagerProvider, - $streamOutput, - $cronStatus, - $name, - $params - ); - case self::JOB_MAINTENANCE_MODE_DISABLE: - return new JobSetMaintenanceMode( - $this->serviceLocator->get(MaintenanceDisableCommand::class), - $objectManagerProvider, - $streamOutput, - $cronStatus, - $name, - $params - ); - default: - throw new \RuntimeException(sprintf('"%s" job is not supported.', $name)); - } - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/JobModule.php b/setup/src/Magento/Setup/Model/Cron/JobModule.php deleted file mode 100644 index c5c222db3d68a..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/JobModule.php +++ /dev/null @@ -1,100 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Cron; - -use Magento\Setup\Console\Command\AbstractSetupCommand; -use Magento\Setup\Model\ObjectManagerProvider; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Output\OutputInterface; - -/** - * Job that handles module commands. E.g. "module:enable", "module:disable" - */ -class JobModule extends AbstractJob -{ - /** - * @var string $cmdString - */ - protected $cmdString; - - /** - * Constructor - * - * @param AbstractSetupCommand $command - * @param ObjectManagerProvider $objectManagerProvider - * @param OutputInterface $output - * @param Status $status - * @param string $name - * @param array $params - */ - public function __construct( - AbstractSetupCommand $command, - ObjectManagerProvider $objectManagerProvider, - OutputInterface $output, - Status $status, - $name, - $params = [] - ) { - $this->command = $command; - parent::__construct($output, $status, $objectManagerProvider, $name, $params); - - // map name to command string - $this->setCommandString($name); - } - - /** - * Sets up the command to be run through bin/magento - * - * @param string $name - * @return void - */ - private function setCommandString($name) - { - if ($name == 'setup:module:enable') { - $this->cmdString = 'module:enable'; - } else { - $this->cmdString = 'module:disable'; - } - } - - /** - * Execute job - * - * @throws \RuntimeException - * @return void - */ - public function execute() - { - try { - foreach ($this->params['components'] as $compObj) { - if (isset($compObj['name']) && (!empty($compObj['name']))) { - $moduleNames[] = $compObj['name']; - } else { - throw new \RuntimeException('component name is not set.'); - } - } - - // prepare the arguments to invoke Symfony run() - $arguments['command'] = $this->cmdString; - $arguments['module'] = $moduleNames; - - $statusCode = $this->command->run(new ArrayInput($arguments), $this->output); - - // check for return statusCode to catch any Symfony errors - if ($statusCode != 0) { - throw new \RuntimeException('Symfony run() returned StatusCode: ' . $statusCode); - } - - //perform the generated file cleanup - $this->performCleanup(); - } catch (\Exception $e) { - $this->status->toggleUpdateError(true); - throw new \RuntimeException( - sprintf('Could not complete %s successfully: %s', $this->cmdString, $e->getMessage()) - ); - } - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/JobSetCache.php b/setup/src/Magento/Setup/Model/Cron/JobSetCache.php deleted file mode 100644 index 7974d124bee85..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/JobSetCache.php +++ /dev/null @@ -1,87 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Cron; - -use Magento\Backend\Console\Command\AbstractCacheManageCommand; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Input\InputDefinition; -use Symfony\Component\Console\Input\InputArgument; - -class JobSetCache extends AbstractJob -{ - /** - * @var \Magento\Backend\Console\Command\AbstractCacheSetCommand - */ - protected $command; - - /** - * @var \Symfony\Component\Console\Output\OutputInterface - */ - protected $output; - - /** - * @var Status - */ - protected $status; - - /** - * @param \Magento\Backend\Console\Command\AbstractCacheSetCommand $command - * @param \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider - * @param \Symfony\Component\Console\Output\OutputInterface $output - * @param Status $status - * @param string $name - * @param array $params - */ - public function __construct( - \Magento\Backend\Console\Command\AbstractCacheSetCommand $command, - \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider, - \Symfony\Component\Console\Output\OutputInterface $output, - \Magento\Setup\Model\Cron\Status $status, - $name, - $params = [] - ) { - $this->command = $command; - parent::__construct($output, $status, $objectManagerProvider, $name, $params); - } - - /** - * Execute set cache command - * - * @return void - */ - public function execute() - { - try { - $arguments = []; - if ($this->getName() === 'setup:cache:enable') { - if (!empty($this->params)) { - $arguments[AbstractCacheManageCommand::INPUT_KEY_TYPES] = explode(' ', $this->params[0]); - } - $arguments['command'] = 'cache:enable'; - $inputDefinition = []; - if ($this->command->getDefinition()->hasArgument('command')) { - $inputDefinition[] = new InputArgument('command', InputArgument::REQUIRED); - } - if ($this->command->getDefinition()->hasArgument(AbstractCacheManageCommand::INPUT_KEY_TYPES)) { - $inputDefinition[] = new InputArgument( - AbstractCacheManageCommand::INPUT_KEY_TYPES, - InputArgument::REQUIRED - ); - } - if (!empty($inputDefinition)) { - $definition = new InputDefinition($inputDefinition); - $this->command->setDefinition($definition); - } - } else { - $arguments['command'] = 'cache:disable'; - } - $this->command->run(new ArrayInput($arguments), $this->output); - } catch (\Exception $e) { - $this->status->toggleUpdateError(true); - throw new \RuntimeException(sprintf('Could not complete %s successfully: %s', $this, $e->getMessage())); - } - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/JobSetMaintenanceMode.php b/setup/src/Magento/Setup/Model/Cron/JobSetMaintenanceMode.php deleted file mode 100644 index 57d7b094c21e0..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/JobSetMaintenanceMode.php +++ /dev/null @@ -1,90 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Cron; - -use Magento\Setup\Console\Command\AbstractSetupCommand; -use Magento\Setup\Console\Command\MaintenanceDisableCommand; -use Magento\Setup\Model\ObjectManagerProvider; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Output\OutputInterface; - -/** - * Job that handles maintenance mode. E.g. "maintenance:enable", "maintenance:disable" - */ -class JobSetMaintenanceMode extends AbstractJob -{ - /** - * Constructor - * - * @param AbstractSetupCommand $command - * @param ObjectManagerProvider $objectManagerProvider - * @param OutputInterface $output - * @param Status $status - * @param string $name - * @param array $params - */ - public function __construct( - AbstractSetupCommand $command, - ObjectManagerProvider $objectManagerProvider, - OutputInterface $output, - Status $status, - $name, - $params = [] - ) { - $this->command = $command; - parent::__construct($output, $status, $objectManagerProvider, $name, $params); - } - - /** - * Execute job - * - * @throws \RuntimeException - * @return void - */ - public function execute() - { - if ($this->command instanceof MaintenanceDisableCommand && $this->command->isSetAddressInfo()) { - // Maintenance mode should not be unset from updater application if it was set manually by the admin - throw new \RuntimeException( - $this->getExceptionMessage( - 'Magento maintenance mode was not disabled. It can be disabled from the Magento Backend.' - ) - ); - } - - try { - // Prepare the arguments to invoke Symfony run() - $arguments['command'] = $this->getCommand(); - $this->command->run(new ArrayInput($arguments), $this->output); - } catch (\Exception $e) { - $this->status->toggleUpdateError(true); - throw new \RuntimeException( - $this->getExceptionMessage($e->getMessage()) - ); - } - } - - /** - * Get exception message - * - * @param string $msg - * @return string - */ - private function getExceptionMessage($msg) - { - return sprintf('Could not complete %s successfully: %s', $this, $msg); - } - - /** - * Get the command to be run through bin/magento - * - * @return string - */ - private function getCommand() - { - return $this->getName() === 'setup:maintenance:enable' ? 'maintenance:enable' : 'maintenance:disable'; - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/JobStaticRegenerate.php b/setup/src/Magento/Setup/Model/Cron/JobStaticRegenerate.php deleted file mode 100644 index 9edbf3e981e8a..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/JobStaticRegenerate.php +++ /dev/null @@ -1,148 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Cron; - -/** - * Static regenerate job - */ -class JobStaticRegenerate extends AbstractJob -{ - /** - * @var \Magento\Framework\App\Cache - */ - protected $cache; - - /** - * @var \Magento\Framework\App\State\CleanupFiles - */ - protected $cleanupFiles; - - /** - * @var \Magento\Setup\Model\Cron\Status - */ - protected $status; - - /** - * Constructor - * - * @param \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider - * @param \Symfony\Component\Console\Output\OutputInterface $output - * @param \Magento\Setup\Model\Cron\Status $status - * @param array $name - * @param array $params - */ - public function __construct( - \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider, - \Symfony\Component\Console\Output\OutputInterface $output, - \Magento\Setup\Model\Cron\Status $status, - $name, - $params = [] - ) { - $this->cleanupFiles = $objectManagerProvider->get()->get(\Magento\Framework\App\State\CleanupFiles::class); - $this->cache = $objectManagerProvider->get()->get(\Magento\Framework\App\Cache::class); - - parent::__construct($output, $status, $objectManagerProvider, $name, $params); - } - - /** - * Execute job - * - * @throws \RuntimeException - * @return void - */ - public function execute() - { - try { - $mode = $this->getModeObject(); - if ($mode->getMode() == \Magento\Framework\App\State::MODE_PRODUCTION) { - $filesystem = $this->getFilesystem(); - $filesystem->regenerateStatic($this->getOutputObject()); - } else { - $this->getStatusObject()->add( - 'Cleaning generated files...', - \Psr\Log\LogLevel::INFO - ); - $this->getCleanFilesObject()->clearCodeGeneratedFiles(); - $this->getStatusObject()->add('Clearing cache...', \Psr\Log\LogLevel::INFO); - $this->getCacheObject()->clean(); - $this->getStatusObject()->add( - 'Cleaning static view files', - \Psr\Log\LogLevel::INFO - ); - $this->getCleanFilesObject()->clearMaterializedViewFiles(); - } - } catch (\Exception $e) { - $this->getStatusObject()->toggleUpdateError(true); - throw new \RuntimeException(sprintf('Could not complete %s successfully: %s', $this, $e->getMessage())); - } - } - - /** - * Returns cache object - * - * @return \Magento\Framework\App\Cache - */ - public function getCacheObject() - { - return $this->cache; - } - - /** - * Returns CleanFiles object - * - * @return \Magento\Framework\App\State\CleanupFiles - */ - public function getCleanFilesObject() - { - return $this->cleanupFiles; - } - - /** - * Returns Status object - * - * @return \Magento\Setup\Model\Cron\Status - */ - public function getStatusObject() - { - return $this->status; - } - - /** - * Returns output object - * - * @return \Symfony\Component\Console\Output\OutputInterface - */ - public function getOutputObject() - { - return $this->output; - } - - /** - * Returns filesystem object - * - * @return \Magento\Deploy\Model\Filesystem - */ - public function getFilesystem() - { - return $this->objectManager->create(\Magento\Deploy\Model\Filesystem::class); - } - - /** - * Returns mode object - * - * @return \Magento\Deploy\Model\Mode - */ - public function getModeObject() - { - return $this->objectManager->create( - \Magento\Deploy\Model\Mode::class, - [ - 'input' => new \Symfony\Component\Console\Input\ArrayInput([]), - 'output' => $this->output, - ] - ); - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/JobUpgrade.php b/setup/src/Magento/Setup/Model/Cron/JobUpgrade.php deleted file mode 100644 index ab88f123ec2e8..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/JobUpgrade.php +++ /dev/null @@ -1,77 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Cron; - -use Magento\Setup\Console\Command\AbstractSetupCommand; -use Magento\Setup\Model\ObjectManagerProvider; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Output\OutputInterface; -use Magento\Setup\Model\Cron\Queue; - -/** - * Upgrade job - */ -class JobUpgrade extends AbstractJob -{ - /** - * @var \Magento\Setup\Model\Cron\Status - */ - protected $status; - - /** - * @var \Magento\Setup\Model\Cron\Queue - */ - private $queue; - - /** - * Constructor - * - * @param \Magento\Setup\Console\Command\AbstractSetupCommand $command - * @param \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider - * @param \Symfony\Component\Console\Output\OutputInterface $output - * @param \Magento\Setup\Model\Cron\Queue $queue - * @param \Magento\Setup\Model\Cron\Status $status - * @param string $name - * @param array $params - */ - public function __construct( - \Magento\Setup\Console\Command\AbstractSetupCommand $command, - \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider, - \Symfony\Component\Console\Output\OutputInterface $output, - \Magento\Setup\Model\Cron\Queue $queue, - \Magento\Setup\Model\Cron\Status $status, - $name, - $params = [] - ) { - $this->command = $command; - $this->queue = $queue; - parent::__construct($output, $status, $objectManagerProvider, $name, $params); - } - - /** - * Execute job - * - * @throws \RuntimeException - * @return void - */ - public function execute() - { - try { - $this->queue->addJobs( - [['name' => JobFactory::JOB_STATIC_REGENERATE, 'params' => []]] - ); - - $this->queue->addJobs( - [['name' => \Magento\Setup\Model\Cron\JobFactory::JOB_MAINTENANCE_MODE_DISABLE, 'params' => []]] - ); - $this->params['command'] = 'setup:upgrade'; - $this->command->run(new ArrayInput($this->params), $this->output); - } catch (\Exception $e) { - $this->status->toggleUpdateError(true); - throw new \RuntimeException(sprintf('Could not complete %s successfully: %s', $this, $e->getMessage())); - } - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/MultipleStreamOutput.php b/setup/src/Magento/Setup/Model/Cron/MultipleStreamOutput.php deleted file mode 100644 index 1823d3aea720b..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/MultipleStreamOutput.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Cron; - -use Symfony\Component\Console\Formatter\OutputFormatterInterface; -use Symfony\Component\Console\Output\Output; - -/** - * Class to allow output to multiple file streams - */ -class MultipleStreamOutput extends Output -{ - /** - * @var array - */ - private $streams; - - /** - * Constructor - * - * @param array $streams - * @param bool|int $verbosity - * @param bool $decorated - * @param OutputFormatterInterface $formatter - */ - public function __construct( - array $streams, - $verbosity = self::VERBOSITY_NORMAL, - $decorated = false, - OutputFormatterInterface $formatter = null - ) { - foreach ($streams as $stream) { - if (!is_resource($stream) || 'stream' !== get_resource_type($stream)) { - throw new \InvalidArgumentException('The StreamOutput class needs a stream as its first argument.'); - } - } - $this->streams = $streams; - parent::__construct($verbosity, $decorated, $formatter); - } - - /** - * {@inheritdoc} - */ - protected function doWrite($message, $newline) - { - foreach ($this->streams as $stream) { - if (false === @fwrite($stream, $message . ($newline ? PHP_EOL : ''))) { - // should never happen - throw new \RuntimeException('Unable to write output.'); - } - - fflush($stream); - } - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/Queue.php b/setup/src/Magento/Setup/Model/Cron/Queue.php deleted file mode 100644 index e168b50730871..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/Queue.php +++ /dev/null @@ -1,139 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Cron; - -/** - * Job Queue - */ -class Queue -{ - /**#@+ - * Key used in queue file. - */ - const KEY_JOBS = 'jobs'; - const KEY_JOB_NAME = 'name'; - const KEY_JOB_PARAMS = 'params'; - /**#@-*/ - - /**#@-*/ - protected $reader; - - /** - * @var Queue\Writer - */ - protected $writer; - - /** - * @var JobFactory - */ - protected $jobFactory; - - /** - * Initialize dependencies. - * - * @param Queue\Reader $reader - * @param Queue\Writer $writer - * @param JobFactory $jobFactory - */ - public function __construct(Queue\Reader $reader, Queue\Writer $writer, JobFactory $jobFactory) - { - $this->reader = $reader; - $this->jobFactory = $jobFactory; - $this->writer = $writer; - } - - /** - * Peek at job queue - * - * @return array - */ - public function peek() - { - $queue = json_decode($this->reader->read(), true); - if (!is_array($queue)) { - return []; - } - if (isset($queue[self::KEY_JOBS]) && is_array($queue[self::KEY_JOBS])) { - $this->validateJobDeclaration($queue[self::KEY_JOBS][0]); - return $queue[self::KEY_JOBS][0]; - } else { - throw new \RuntimeException(sprintf('"%s" field is missing or is not an array.', self::KEY_JOBS)); - } - } - - /** - * Pop job queue. - * - * @return AbstractJob|null - * @throws \RuntimeException - */ - public function popQueuedJob() - { - $job = null; - $queue = json_decode($this->reader->read(), true); - if (!is_array($queue)) { - return $job; - } - if (isset($queue[self::KEY_JOBS]) && is_array($queue[self::KEY_JOBS])) { - $this->validateJobDeclaration($queue[self::KEY_JOBS][0]); - $job = $this->jobFactory->create( - $queue[self::KEY_JOBS][0][self::KEY_JOB_NAME], - $queue[self::KEY_JOBS][0][self::KEY_JOB_PARAMS] - ); - array_shift($queue[self::KEY_JOBS]); - if (empty($queue[self::KEY_JOBS])) { - $this->writer->write(''); - } else { - $this->writer->write(json_encode($queue, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); - } - } else { - throw new \RuntimeException(sprintf('"%s" field is missing or is not an array.', self::KEY_JOBS)); - } - return $job; - } - - /** - * Returns if job queue is empty - * - * @return bool - */ - public function isEmpty() - { - $queue = json_decode($this->reader->read(), true); - return empty($queue); - } - - /** - * @param array $jobs - * @return void - */ - public function addJobs(array $jobs) - { - foreach ($jobs as $job) { - $this->validateJobDeclaration($job); - $queue = json_decode($this->reader->read(), true); - $queue[self::KEY_JOBS][] = $job; - $this->writer->write(json_encode($queue, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); - } - } - - /** - * Make sure job declaration is correct. - * - * @param object $job - * @return void - * @throws \RuntimeException - */ - protected function validateJobDeclaration($job) - { - $requiredFields = [self::KEY_JOB_NAME, self::KEY_JOB_PARAMS]; - foreach ($requiredFields as $field) { - if (!isset($job[$field])) { - throw new \RuntimeException(sprintf('"%s" field is missing for one or more jobs.', $field)); - } - } - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/Queue/Reader.php b/setup/src/Magento/Setup/Model/Cron/Queue/Reader.php deleted file mode 100644 index 3e771e3b0c568..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/Queue/Reader.php +++ /dev/null @@ -1,61 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Model\Cron\Queue; - -use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Framework\Filesystem; - -/** - * Queue content file reader. - */ -class Reader -{ - /** - * @var \Magento\Framework\Filesystem\Directory\ReadInterface - */ - protected $reader; - - /** - * @var string - */ - protected $queueFileBasename; - - /** - * Initialize reader. - * - * @param Filesystem $filesystem - * @param string|null $queueFileBasename - */ - public function __construct(Filesystem $filesystem, $queueFileBasename = null) - { - $this->reader = $filesystem->getDirectoryRead(DirectoryList::VAR_DIR); - $this->queueFileBasename = $queueFileBasename ? $queueFileBasename : '.update_queue.json'; - } - - /** - * Read Magento updater application jobs queue as a JSON string. - * - * @return string Queue file content (valid JSON string) - * @throws \RuntimeException - */ - public function read() - { - $queue = ''; - if (!$this->reader->isExist($this->queueFileBasename)) { - return $queue; - } - $queueFileContent = $this->reader->readFile($this->queueFileBasename); - if ($queueFileContent) { - json_decode($queueFileContent); - if (json_last_error() !== JSON_ERROR_NONE) { - throw new \RuntimeException(sprintf('Content of "%s" must be a valid JSON.', $this->queueFileBasename)); - } - $queue = $queueFileContent; - } - return $queue; - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/Queue/Writer.php b/setup/src/Magento/Setup/Model/Cron/Queue/Writer.php deleted file mode 100644 index 21285f0c78092..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/Queue/Writer.php +++ /dev/null @@ -1,43 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Cron\Queue; - -use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Framework\Filesystem; - -/** - * Queue content writer - */ -class Writer extends Reader -{ - /** - * @var \Magento\Framework\Filesystem\Directory\WriteInterface - */ - private $writer; - - /** - * Initialize reader. - * - * @param Filesystem $filesystem - * @param string|null $queueFileBasename - */ - public function __construct(Filesystem $filesystem, $queueFileBasename = null) - { - $this->writer = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR); - parent::__construct($filesystem, $queueFileBasename); - } - - /** - * Write JSON string into queue - * - * @param string $data - * @return void - */ - public function write($data) - { - $this->writer->writeFile($this->queueFileBasename, $data); - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/ReadinessCheck.php b/setup/src/Magento/Setup/Model/Cron/ReadinessCheck.php deleted file mode 100644 index 8a2b32aaf6e01..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/ReadinessCheck.php +++ /dev/null @@ -1,261 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Cron; - -use Magento\Setup\Controller\ResponseTypeInterface; -use Magento\Setup\Model\BasePackageInfo; - -/** - * This class is used by setup:cron:run command to check if this command can be run properly. It also checks if PHP - * version, settings and extensions are correct. - */ -class ReadinessCheck -{ - /** - * Basename to readiness check result file - */ - const SETUP_CRON_JOB_STATUS_FILE = '.setup_cronjob_status'; - - /**#@+ - * Keys used in status file - */ - const KEY_READINESS_CHECKS = 'readiness_checks'; - const KEY_PHP_CHECKS = 'php_checks'; - const KEY_DB_WRITE_PERMISSION_VERIFIED = 'db_write_permission_verified'; - const KEY_PHP_VERSION_VERIFIED = 'php_version_verified'; - const KEY_PHP_SETTINGS_VERIFIED = 'php_settings_verified'; - const KEY_PHP_EXTENSIONS_VERIFIED = 'php_extensions_verified'; - const KEY_FILE_PATHS = 'file_paths'; - const KEY_ERROR = 'error'; - const KEY_LIST = 'list'; - const KEY_CURRENT_TIMESTAMP = 'current_timestamp'; - const KEY_LAST_TIMESTAMP = 'last_timestamp'; - /**#@-*/ - - /**#@-*/ - private $dbValidator; - - /** - * @var \Magento\Framework\App\DeploymentConfig - */ - private $deploymentConfig; - - /** - * @var \Magento\Framework\Filesystem - */ - private $filesystem; - - /** - * @var \Magento\Setup\Model\PhpReadinessCheck - */ - private $phpReadinessCheck; - - /** - * @var BasePackageInfo - */ - private $basePackageInfo; - - /** - * @var Status - */ - private $status; - - /** - * Constructor - * - * @param \Magento\Setup\Validator\DbValidator $dbValidator - * @param \Magento\Framework\App\DeploymentConfig $deploymentConfig - * @param \Magento\Framework\Filesystem $filesystem - * @param \Magento\Setup\Model\PhpReadinessCheck $phpReadinessCheck - * @param BasePackageInfo $basePackageInfo - * @param Status $status - */ - public function __construct( - \Magento\Setup\Validator\DbValidator $dbValidator, - \Magento\Framework\App\DeploymentConfig $deploymentConfig, - \Magento\Framework\Filesystem $filesystem, - \Magento\Setup\Model\PhpReadinessCheck $phpReadinessCheck, - BasePackageInfo $basePackageInfo, - Status $status - ) { - $this->dbValidator = $dbValidator; - $this->deploymentConfig = $deploymentConfig; - $this->filesystem = $filesystem; - $this->phpReadinessCheck = $phpReadinessCheck; - $this->basePackageInfo = $basePackageInfo; - $this->status = $status; - } - - /** - * Run the readiness check - * - * @return bool - */ - public function runReadinessCheck() - { - $resultJsonRawData = [self::KEY_READINESS_CHECKS => []]; - $errorLogMessages = []; - - // check PHP version - $phpVersionCheckResult = $this->phpReadinessCheck->checkPhpVersion(); - $errorMessage = $this->getPhpVersionCheckErrorLogMessage($phpVersionCheckResult); - if (!empty($errorMessage)) { - $errorLogMessages[] = $errorMessage; - } - - // check PHP extensions - $phpExtensionsCheckResult = $this->phpReadinessCheck->checkPhpExtensions(); - $errorMessage = $this->getPhpExtensionsCheckErrorLogMessage($phpExtensionsCheckResult); - if (!empty($errorMessage)) { - $errorLogMessages[] = $errorMessage; - } - - // check PHP settings - $phpSettingsCheckResult = $this->phpReadinessCheck->checkPhpCronSettings(); - $errorMessage = $this->getPhpSettingsCheckErrorLogMessage($phpSettingsCheckResult); - if (!empty($errorMessage)) { - $errorLogMessages[] = $errorMessage; - } - - $resultJsonRawData[self::KEY_PHP_CHECKS][self::KEY_PHP_VERSION_VERIFIED] = $phpVersionCheckResult; - $resultJsonRawData[self::KEY_PHP_CHECKS][self::KEY_PHP_EXTENSIONS_VERIFIED] = $phpExtensionsCheckResult; - $resultJsonRawData[self::KEY_PHP_CHECKS][self::KEY_PHP_SETTINGS_VERIFIED] = $phpSettingsCheckResult; - - // check DB connection - $errorMessage = $this->performDBCheck(); - if (empty($errorMessage)) { - $resultJsonRawData[self::KEY_READINESS_CHECKS][self::KEY_DB_WRITE_PERMISSION_VERIFIED] = true; - } else { - $resultJsonRawData[self::KEY_READINESS_CHECKS][self::KEY_DB_WRITE_PERMISSION_VERIFIED] = false; - $resultJsonRawData[self::KEY_READINESS_CHECKS][self::KEY_ERROR] = $errorMessage; - $errorLogMessages[] = $errorMessage; - } - - // Prepare list of magento specific files and directory paths for updater application to check write - // permissions - $errorMessage = ''; - try { - $filePaths = $this->basePackageInfo->getPaths(); - $resultJsonRawData[self::KEY_FILE_PATHS][self::KEY_LIST] = $filePaths; - } catch (\Exception $e) { - $errorMessage = $e->getMessage(); - $resultJsonRawData[self::KEY_FILE_PATHS][self::KEY_LIST] = []; - $errorLogMessages[] = $errorMessage; - } - $resultJsonRawData[self::KEY_FILE_PATHS][self::KEY_ERROR] = $errorMessage; - - // updates timestamp - $write = $this->filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR); - if ($write->isExist(self::SETUP_CRON_JOB_STATUS_FILE)) { - $jsonData = json_decode($write->readFile(self::SETUP_CRON_JOB_STATUS_FILE), true); - if (isset($jsonData[self::KEY_CURRENT_TIMESTAMP])) { - $resultJsonRawData[self::KEY_LAST_TIMESTAMP] = $jsonData[self::KEY_CURRENT_TIMESTAMP]; - } - } - $resultJsonRawData[self::KEY_CURRENT_TIMESTAMP] = time(); - - // write to transient log file to display on GUI - $resultJson = json_encode($resultJsonRawData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); - $write->writeFile(self::SETUP_CRON_JOB_STATUS_FILE, $resultJson); - - // write to permanent log file, var/log/update.log - foreach ($errorLogMessages as $errorLog) { - $this->status->add($errorLog, \Psr\Log\LogLevel::ERROR, false); - } - return (empty($errorLogMessages)); - } - - /** - * Private function to help build log message for php version check action - * - * @param array $phpVersionCheckResult - * @return string - */ - private function getPhpVersionCheckErrorLogMessage($phpVersionCheckResult) - { - $message = ''; - if (isset($phpVersionCheckResult['responseType']) && - $phpVersionCheckResult['responseType'] == ResponseTypeInterface::RESPONSE_TYPE_ERROR) { - if (isset($phpVersionCheckResult['data']['message'])) { - $message = $phpVersionCheckResult['data']['message']; - } else { - $message = 'Minimum required version is' . - $phpVersionCheckResult['data']['required'] . - '. While your installed version is ' . - $phpVersionCheckResult['data']['current'] . - '.'; - } - } - return $message; - } - - /** - * Private function to help build log message for php extensions check action - * - * @param array $phpExtensionsCheckResult - * @return string - */ - private function getPhpExtensionsCheckErrorLogMessage($phpExtensionsCheckResult) - { - $message = ''; - if (isset($phpExtensionsCheckResult['responseType']) && - $phpExtensionsCheckResult['responseType'] == ResponseTypeInterface::RESPONSE_TYPE_ERROR) { - if (isset($phpExtensionsCheckResult['data']['message'])) { - $message = $phpExtensionsCheckResult['data']['message']; - } else { - $message = 'Following required PHP extensions are missing:' . - PHP_EOL . - "\t" . - implode(PHP_EOL . "\t", $phpExtensionsCheckResult['data']['missing']); - } - } - return $message; - } - - /** - * Private function to help build log message for php settings check action - * - * @param array $phpSettingsCheckResult - * @return string - */ - private function getPhpSettingsCheckErrorLogMessage($phpSettingsCheckResult) - { - $messages = []; - if (isset($phpSettingsCheckResult['responseType']) && - $phpSettingsCheckResult['responseType'] == ResponseTypeInterface::RESPONSE_TYPE_ERROR) { - foreach ($phpSettingsCheckResult['data'] as $valueArray) { - if ($valueArray['error'] == true) { - $messages[] = preg_replace('/\s+/S', " ", $valueArray['message']); - } - } - } - return implode(PHP_EOL . "\t", $messages); - } - - /** - * A private function to check database access and return appropriate error message in case of error - * - * @return string - */ - private function performDBCheck() - { - $errorLogMessage = ''; - $dbInfo = $this->deploymentConfig->get( - \Magento\Framework\Config\ConfigOptionsListConstants::CONFIG_PATH_DB_CONNECTION_DEFAULT - ); - try { - $this->dbValidator->checkDatabaseConnection( - $dbInfo[\Magento\Framework\Config\ConfigOptionsListConstants::KEY_NAME], - $dbInfo[\Magento\Framework\Config\ConfigOptionsListConstants::KEY_HOST], - $dbInfo[\Magento\Framework\Config\ConfigOptionsListConstants::KEY_USER], - $dbInfo[\Magento\Framework\Config\ConfigOptionsListConstants::KEY_PASSWORD] - ); - } catch (\Exception $e) { - $errorLogMessage = $e->getMessage(); - } - return $errorLogMessage; - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/SetupLoggerFactory.php b/setup/src/Magento/Setup/Model/Cron/SetupLoggerFactory.php deleted file mode 100644 index 071d29c02e1fb..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/SetupLoggerFactory.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Model\Cron; - -/** - * Class to get PSR-3 compliant logger instance - */ -class SetupLoggerFactory -{ - /** - * Create logger instance. - * - * @param string $channelName - * - * @return \Psr\Log\LoggerInterface - */ - public function create($channelName = 'setup-cron') - { - $logger = new \Monolog\Logger($channelName); - $path = BP . '/var/log/update.log'; - $logger->pushHandler(new \Monolog\Handler\StreamHandler($path)); - return $logger; - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/SetupStreamHandler.php b/setup/src/Magento/Setup/Model/Cron/SetupStreamHandler.php deleted file mode 100644 index 432dce491c900..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/SetupStreamHandler.php +++ /dev/null @@ -1,36 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Model\Cron; - -use Magento\Framework\Filesystem\DriverInterface; - -/** - * Setup specific stream handler - */ -class SetupStreamHandler extends \Magento\Framework\Logger\Handler\Base -{ - /** - * @var string - */ - protected $fileName = '/var/log/update.log'; - - /** - * @var int - */ - protected $loggerType = \Magento\Framework\Logger\Monolog::ERROR; - - /** - * @param DriverInterface $filesystem - * @param string $filePath - */ - public function __construct( - DriverInterface $filesystem, - $filePath = null - ) { - parent::__construct($filesystem, $filePath); - } -} diff --git a/setup/src/Magento/Setup/Model/Cron/Status.php b/setup/src/Magento/Setup/Model/Cron/Status.php deleted file mode 100644 index 96172d4668f37..0000000000000 --- a/setup/src/Magento/Setup/Model/Cron/Status.php +++ /dev/null @@ -1,223 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Model\Cron; - -use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Framework\Exception\FileSystemException; -use Magento\Framework\Filesystem; - -/** - * Class which provides access to the current status of the Magento setup application. - * - * Each job is using this class to share information about its current status. - * Current status can be seen on the update app web page. - * - * @SuppressWarnings(PHPMD.NPathComplexity) - */ -class Status -{ - /** - * Path to a file, which content is displayed on the update web page. - * - * @var string - */ - protected $statusFilePath; - - /** - * Path to a log file, which contains all the information displayed on the web page. - * - * Note that it can be cleared only manually, it is not cleared by clear() method. - * - * @var string - */ - protected $logFilePath; - - /** - * Path to a flag, which exists when update app is running. - * - * @var string - */ - protected $updateInProgressFlagFilePath; - - /** - * Path to a flag, which exists when error occurred during update app execution. - * - * @var string - */ - protected $updateErrorFlagFilePath; - - /** - * @var Filesystem\Directory\WriteInterface - */ - protected $varReaderWriter; - - /** - * @var \Psr\Log\LoggerInterface - */ - private $logger; - - /** - * Constructor - * - * @param Filesystem $filesystem - * @param SetupLoggerFactory $setupLoggerFactory - * @param string $statusFilePath - * @param string $logFilePath - * @param string $updateInProgressFlagFilePath - * @param string $updateErrorFlagFilePath - */ - public function __construct( - Filesystem $filesystem, - SetupLoggerFactory $setupLoggerFactory, - $statusFilePath = null, - $logFilePath = null, - $updateInProgressFlagFilePath = null, - $updateErrorFlagFilePath = null - ) { - $this->varReaderWriter = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR); - $this->statusFilePath = $statusFilePath ? $statusFilePath : '.update_status.txt'; - $this->logFilePath = $logFilePath ? $logFilePath : DirectoryList::LOG . '/update.log'; - $this->updateInProgressFlagFilePath = $updateInProgressFlagFilePath - ? $updateInProgressFlagFilePath - : '.update_in_progress.flag'; - $this->updateErrorFlagFilePath = $updateErrorFlagFilePath - ? $updateErrorFlagFilePath - : '.update_error.flag'; - $this->logger = $setupLoggerFactory->create('setup-cron'); - } - - /** - * Get status file path - * - * @return string - */ - public function getStatusFilePath() - { - return $this->varReaderWriter->getAbsolutePath($this->statusFilePath); - } - - /** - * Get log file path - * - * @return string - */ - public function getLogFilePath() - { - return $this->varReaderWriter->getAbsolutePath($this->logFilePath); - } - - /** - * Add status update. - * - * Add information to a temporary file which is used for status display on a web page and to a permanent status log. - * - * @param string $text - * @param int $severity - * @param bool $writeToStatusFile - * - * @return $this - * @throws \RuntimeException - */ - public function add($text, $severity = \Psr\Log\LogLevel::INFO, $writeToStatusFile = true) - { - $this->logger->log($severity, $text); - $currentUtcTime = '[' . date('Y-m-d H:i:s T', time()) . '] '; - $text = $currentUtcTime . $text; - if ($writeToStatusFile) { - $this->writeMessageToFile($text, $this->statusFilePath); - } - return $this; - } - - /** - * Write status information to the file. - * - * @param string $text - * @param string $filePath - * @return $this - * @throws \RuntimeException - */ - protected function writeMessageToFile($text, $filePath) - { - $isNewFile = !$this->varReaderWriter->isExist($filePath); - if (!$isNewFile && $this->varReaderWriter->readFile($filePath)) { - $text = "\n{$text}"; - } - try { - $this->varReaderWriter->writeFile($filePath, $text, 'a+'); - } catch (FileSystemException $e) { - throw new \RuntimeException(sprintf('Cannot add status information to "%s"', $filePath)); - } - if ($isNewFile) { - chmod($filePath, 0777); - } - return $this; - } - - /** - * Check if update application is running. - * - * @return bool - */ - public function isUpdateInProgress() - { - return $this->varReaderWriter->isExist($this->updateInProgressFlagFilePath); - } - - /** - * Set current update app status: true if update is in progress, false otherwise. - * - * @param bool $isInProgress - * @return $this - */ - public function toggleUpdateInProgress($isInProgress = true) - { - return $this->setFlagValue($this->updateInProgressFlagFilePath, $isInProgress); - } - - /** - * Check if error has occurred during update application execution. - * - * @return bool - */ - public function isUpdateError() - { - return $this->varReaderWriter->isExist($this->updateErrorFlagFilePath); - } - - /** - * Set current update app status: true if error occurred during update app execution, false otherwise. - * - * @param bool $isErrorOccurred - * @return $this - */ - public function toggleUpdateError($isErrorOccurred = true) - { - return $this->setFlagValue($this->updateErrorFlagFilePath, $isErrorOccurred); - } - - /** - * Create flag in case when value is set to 'true', remove it if value is set to 'false'. - * - * @param string $pathToFlagFile - * @param bool $value - * @return $this - */ - protected function setFlagValue($pathToFlagFile, $value) - { - if ($value) { - try { - $this->varReaderWriter->touch($pathToFlagFile); - } catch (FileSystemException $e) { - throw new \RuntimeException(sprintf('"%s" cannot be created.', $pathToFlagFile)); - } - } elseif ($this->varReaderWriter->isExist($pathToFlagFile)) { - $this->varReaderWriter->delete($pathToFlagFile); - } - return $this; - } -} diff --git a/setup/src/Magento/Setup/Model/CronScriptReadinessCheck.php b/setup/src/Magento/Setup/Model/CronScriptReadinessCheck.php deleted file mode 100644 index a2b292a7127fe..0000000000000 --- a/setup/src/Magento/Setup/Model/CronScriptReadinessCheck.php +++ /dev/null @@ -1,160 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model; - -use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Framework\Filesystem; -use Magento\Setup\Model\Cron\ReadinessCheck; - -/** - * This class is used by Readiness check page to verify if Setup cron command - * and Updater cron script are running properly. - * This includes verifying file permission in Updater Cron and db privileges in Setup Cron. - * It also verifies Cron time interval configuration. - * This class only verifies the status files created by both Cron jobs. No actual checking logic is done in this class. - */ -class CronScriptReadinessCheck -{ - /** - * Setup type - */ - const SETUP = 'setup'; - - /** - * Updater type - */ - const UPDATER = 'updater'; - - /** - * Basename to Updater status file - */ - const UPDATER_CRON_JOB_STATS_FILE = '.update_cronjob_status'; - - /** - * Key in Updater status file - */ - const UPDATER_KEY_FILE_PERMISSIONS_VERIFIED = 'file_permissions_verified'; - - /** - * Error message for dependant checks - */ - const OTHER_CHECKS_WILL_FAIL_MSG = - '<br/>Other checks will fail as a result (PHP version, PHP settings, and PHP extensions)'; - - /** - * @var Filesystem - */ - private $filesystem; - - /** - * Constructor - * - * @param Filesystem $filesystem - */ - public function __construct(Filesystem $filesystem) - { - $this->filesystem = $filesystem; - } - - /** - * Check Setup Cron job status file - * - * @return array - */ - public function checkSetup() - { - return $this->checkJson(self::SETUP); - } - - /** - * Check Updater Cron job status file - * - * @return array - */ - public function checkUpdater() - { - return $this->checkJson(self::UPDATER); - } - - /** - * Check JSON file created by Setup cron command and Updater cron script - * - * @param string $type - * @return array - */ - private function checkJson($type) - { - $read = $this->filesystem->getDirectoryRead(DirectoryList::VAR_DIR); - try { - switch ($type) { - case self::SETUP: - $key = ReadinessCheck::KEY_DB_WRITE_PERMISSION_VERIFIED; - $jsonData = json_decode($read->readFile(ReadinessCheck::SETUP_CRON_JOB_STATUS_FILE), true); - break; - case self::UPDATER: - $key = self::UPDATER_KEY_FILE_PERMISSIONS_VERIFIED; - $jsonData = json_decode($read->readFile(self::UPDATER_CRON_JOB_STATS_FILE), true); - break; - default: - return ['success' => false, 'error' => 'Internal Error']; - } - } catch (\Magento\Framework\Exception\FileSystemException $e) { - $error = 'Cron job has not been configured yet'; - if ($type == self::SETUP) { - $error .= self::OTHER_CHECKS_WILL_FAIL_MSG; - } - return [ - 'success' => false, - 'error' => $error - ]; - } - - if (isset($jsonData[ReadinessCheck::KEY_READINESS_CHECKS]) - && isset($jsonData[ReadinessCheck::KEY_READINESS_CHECKS][$key]) - ) { - if ($jsonData[ReadinessCheck::KEY_READINESS_CHECKS][$key]) { - return $this->checkCronTime($jsonData); - } - return ['success' => false, 'error' => $jsonData[ReadinessCheck::KEY_READINESS_CHECKS]['error']]; - } - $error = 'Cron job has not been configured yet'; - if ($type == self::SETUP) { - $error .= self::OTHER_CHECKS_WILL_FAIL_MSG; - } - return [ - 'success' => false, - 'error' => $error - ]; - } - - /** - * Check if Cron Job time interval is within acceptable range - * - * @param array $jsonData - * @return array - */ - private function checkCronTime(array $jsonData) - { - if (isset($jsonData[ReadinessCheck::KEY_CURRENT_TIMESTAMP]) - && isset($jsonData[ReadinessCheck::KEY_LAST_TIMESTAMP]) - ) { - $timeDifference = $jsonData[ReadinessCheck::KEY_CURRENT_TIMESTAMP] - - $jsonData[ReadinessCheck::KEY_LAST_TIMESTAMP]; - if ($timeDifference < 90) { - return ['success' => true]; - } - return [ - 'success' => true, - 'notice' => 'We recommend you schedule cron to run every 1 minute' - ]; - } - return [ - 'success' => true, - 'notice' => 'Unable to determine cron time interval. ' . - 'We recommend you schedule cron to run every 1 minute' - ]; - } -} diff --git a/setup/src/Magento/Setup/Model/DependencyReadinessCheck.php b/setup/src/Magento/Setup/Model/DependencyReadinessCheck.php deleted file mode 100644 index d9f8d154abdf2..0000000000000 --- a/setup/src/Magento/Setup/Model/DependencyReadinessCheck.php +++ /dev/null @@ -1,110 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model; - -use Magento\Composer\MagentoComposerApplication; -use Magento\Composer\RequireUpdateDryRunCommand; -use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Framework\Composer\ComposerJsonFinder; -use Magento\Framework\Composer\MagentoComposerApplicationFactory; -use Magento\Framework\Escaper; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\Filesystem\Driver\File; - -/** - * This class checks for dependencies between components after an upgrade. It is used in readiness check. - */ -class DependencyReadinessCheck -{ - /** - * @var Escaper - */ - private $escaper; - - /** - * @var ComposerJsonFinder - */ - private $composerJsonFinder; - - /** - * @var DirectoryList - */ - private $directoryList; - - /** - * @var RequireUpdateDryRunCommand - */ - private $requireUpdateDryRunCommand; - - /** - * @var File - */ - private $file; - - /** - * @var MagentoComposerApplication - */ - private $magentoComposerApplication; - - /** - * Constructor - * - * @param ComposerJsonFinder $composerJsonFinder - * @param DirectoryList $directoryList - * @param File $file - * @param MagentoComposerApplicationFactory $composerAppFactory - * @param Escaper|null $escaper - */ - public function __construct( - ComposerJsonFinder $composerJsonFinder, - DirectoryList $directoryList, - File $file, - MagentoComposerApplicationFactory $composerAppFactory, - Escaper $escaper = null - ) { - $this->composerJsonFinder = $composerJsonFinder; - $this->directoryList = $directoryList; - $this->file = $file; - $this->requireUpdateDryRunCommand = $composerAppFactory->createRequireUpdateDryRunCommand(); - $this->magentoComposerApplication = $composerAppFactory->create(); - $this->escaper = $escaper ?? ObjectManager::getInstance()->get( - Escaper::class - ); - } - - /** - * Run Composer dependency check - * - * @param array $packages - * @return array - * @throws \Exception - */ - public function runReadinessCheck(array $packages) - { - $composerJson = $this->composerJsonFinder->findComposerJson(); - $this->file->copy($composerJson, $this->directoryList->getPath(DirectoryList::VAR_DIR) . '/composer.json'); - $workingDir = $this->directoryList->getPath(DirectoryList::VAR_DIR); - try { - foreach ($packages as $package) { - if (strpos($package, 'magento/product-enterprise-edition') !== false) { - $this->magentoComposerApplication->runComposerCommand( - [ - 'command' => 'remove', - 'packages' => ['magento/product-community-edition'], - '--no-update' => true - ], - $workingDir - ); - } - } - $this->requireUpdateDryRunCommand->run($packages, $workingDir); - return ['success' => true]; - } catch (\RuntimeException $e) { - $message = str_replace(PHP_EOL, '<br/>', $this->escaper->escapeHtml($e->getMessage())); - return ['success' => false, 'error' => $message]; - } - } -} diff --git a/setup/src/Magento/Setup/Model/Grid/Extension.php b/setup/src/Magento/Setup/Model/Grid/Extension.php deleted file mode 100644 index a9aabf7c28b6d..0000000000000 --- a/setup/src/Magento/Setup/Model/Grid/Extension.php +++ /dev/null @@ -1,86 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Grid; - -use Magento\Framework\Composer\ComposerInformation; -use Magento\Setup\Model\PackagesData; - -/** - * Extension Grid - */ -class Extension -{ - /** - * @var ComposerInformation - */ - private $composerInformation; - - /** - * @var PackagesData - */ - private $packagesData; - - /** - * @param ComposerInformation $composerInformation - * @param PackagesData $packagesData - */ - public function __construct( - ComposerInformation $composerInformation, - PackagesData $packagesData - ) { - $this->composerInformation = $composerInformation; - $this->packagesData = $packagesData; - } - - /** - * Get formatted list of installed extensions - * - * @return array - */ - public function getList() - { - $extensions = $this->packagesData->getInstalledPackages(); - $packagesForUpdate = $this->packagesData->getPackagesForUpdate(); - - foreach ($extensions as &$extension) { - $extension['update'] = array_key_exists($extension['name'], $packagesForUpdate); - $extension['uninstall'] = true; - if ($extension['type'] === ComposerInformation::METAPACKAGE_PACKAGE_TYPE - || !$this->composerInformation->isPackageInComposerJson($extension['name']) - ) { - $extension['uninstall'] = false; - } - } - - return $this->formatExtensions($extensions); - } - - /** - * Get formatted list of extensions that have new version - * - * @return array - */ - public function getListForUpdate() - { - $extensions = $this->packagesData->getPackagesForUpdate(); - - return $this->formatExtensions($extensions); - } - - /** - * Format given array of extensions, add vendor and format extension type - * - * @param array $extensions - * @return array - */ - private function formatExtensions(array $extensions) - { - foreach ($extensions as &$extension) { - $extension['vendor'] = ucfirst(current(explode('/', $extension['name']))); - } - return array_values($extensions); - } -} diff --git a/setup/src/Magento/Setup/Model/Grid/Module.php b/setup/src/Magento/Setup/Model/Grid/Module.php deleted file mode 100644 index fd9dc3285de3e..0000000000000 --- a/setup/src/Magento/Setup/Model/Grid/Module.php +++ /dev/null @@ -1,190 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Grid; - -use Magento\Framework\Composer\ComposerInformation; -use Magento\Framework\Module\ModuleList; -use Magento\Framework\Module\PackageInfoFactory; -use Magento\Setup\Model\PackagesData; - -/** - * Module grid - */ -class Module -{ - /** - * Const for unknown package name and version - */ - const UNKNOWN_PACKAGE_NAME = 'unknown'; - const UNKNOWN_VERSION = '—'; - - /** - * @var ComposerInformation - */ - private $composerInformation; - - /** - * Module package info - * - * @var \Magento\Framework\Module\PackageInfo - */ - private $packageInfo; - - /** - * @var \Magento\Setup\Model\ObjectManagerProvider - */ - private $objectManagerProvider; - - /** - * Full Module info - * - * @var \Magento\Framework\Module\FullModuleList - */ - private $fullModuleList; - - /** - * Module info - * - * @var ModuleList - */ - private $moduleList; - - /** - * @var PackagesData - */ - private $packagesData; - - /** - * @param ComposerInformation $composerInformation - * @param \Magento\Framework\Module\FullModuleList $fullModuleList - * @param ModuleList $moduleList - * @param \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider - * @param PackagesData $packagesData - */ - public function __construct( - ComposerInformation $composerInformation, - \Magento\Framework\Module\FullModuleList $fullModuleList, - ModuleList $moduleList, - \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider, - PackagesData $packagesData - ) { - $this->composerInformation = $composerInformation; - $this->fullModuleList = $fullModuleList; - $this->moduleList = $moduleList; - $this->objectManagerProvider = $objectManagerProvider; - $this->packagesData = $packagesData; - } - - /** - * Get list of installed modules (composer + direct installation) - * - * @return array - */ - public function getList() - { - $this->packageInfo = $this->objectManagerProvider->get() - ->get(PackageInfoFactory::class) - ->create(); - - $items = array_replace_recursive( - $this->getModuleListFromComposer(), - $this->getFullModuleList() - ); - - $items = $this->addRequiredBy($this->addGeneralInfo($items)); - - return $items; - } - - /** - * Get module list from composer - * - * @return array - */ - private function getModuleListFromComposer() - { - return array_filter( - $this->composerInformation->getInstalledMagentoPackages(), - function ($item) { - return $item['type'] === ComposerInformation::MODULE_PACKAGE_TYPE; - } - ); - } - - /** - * Get full module list - * - * @return array - */ - private function getFullModuleList() - { - return $this->getModulesInfo( - $this->fullModuleList->getNames() - ); - } - - /** - * Add all modules, extensions, metapackages a module required by - * - * @param array $items - * @return array - */ - private function addRequiredBy(array $items) - { - foreach ($items as $key => $item) { - $items[$key]['requiredBy'] = $item['name'] != self::UNKNOWN_PACKAGE_NAME ? - $this->addGeneralInfo( - $this->getModulesInfo( - $this->packageInfo->getRequiredBy($item['name']) - ) - ) : []; - } - - return $items; - } - - /** - * Get modules info - * - * @param array $moduleList - * @return array - */ - private function getModulesInfo(array $moduleList) - { - $result = []; - foreach ($moduleList as $moduleName) { - $packageName = $this->packageInfo->getPackageName($moduleName); - $key = $packageName ?: $moduleName; - $result[$key] = [ - 'name' => $packageName ?: self::UNKNOWN_PACKAGE_NAME, - 'moduleName' => $moduleName, - 'type' => ComposerInformation::MODULE_PACKAGE_TYPE, - 'version' => $this->packageInfo->getVersion($moduleName) ?: self::UNKNOWN_VERSION, - ]; - } - - return $result; - } - - /** - * Add general info to result array - * - * @param array $items - * @return array - */ - private function addGeneralInfo(array $items) - { - foreach ($items as &$item) { - $item['moduleName'] = $item['moduleName'] ?? $this->packageInfo->getModuleName($item['name']); - $item['enable'] = $this->moduleList->has($item['moduleName']); - $vendorSource = $item['name'] == self::UNKNOWN_PACKAGE_NAME ? $item['moduleName'] : $item['name']; - $item['vendor'] = ucfirst(current(preg_split('%[/_]%', $vendorSource))); - $item = $this->packagesData->addPackageExtraInfo($item); - } - - return array_values($items); - } -} diff --git a/setup/src/Magento/Setup/Model/Grid/TypeMapper.php b/setup/src/Magento/Setup/Model/Grid/TypeMapper.php deleted file mode 100644 index 1619742e55205..0000000000000 --- a/setup/src/Magento/Setup/Model/Grid/TypeMapper.php +++ /dev/null @@ -1,52 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model\Grid; - -use Magento\Framework\Composer\ComposerInformation; - -/** - * Class TypeMapper - */ -class TypeMapper -{ - /**#@+ - * Constants for package types in setup grid - */ - const UNDEFINED_PACKAGE_TYPE = 'Undefined'; - const EXTENSION_PACKAGE_TYPE = 'Extension'; - const THEME_PACKAGE_TYPE = 'Theme'; - const MODULE_PACKAGE_TYPE = 'Module'; - const LANGUAGE_PACKAGE_TYPE = 'Language'; - const METAPACKAGE_PACKAGE_TYPE = 'Metapackage'; - const COMPONENT_PACKAGE_TYPE = 'Component'; - const LIBRARY_PACKAGE_TYPE = 'Library'; - /**#@-*/ - - /** - * @var array - */ - private $packageTypesMap = [ - ComposerInformation::THEME_PACKAGE_TYPE => self::THEME_PACKAGE_TYPE, - ComposerInformation::LANGUAGE_PACKAGE_TYPE => self::LANGUAGE_PACKAGE_TYPE, - ComposerInformation::MODULE_PACKAGE_TYPE => self::MODULE_PACKAGE_TYPE, - ComposerInformation::METAPACKAGE_PACKAGE_TYPE => self::METAPACKAGE_PACKAGE_TYPE, - ComposerInformation::COMPONENT_PACKAGE_TYPE => self::COMPONENT_PACKAGE_TYPE, - ComposerInformation::LIBRARY_PACKAGE_TYPE => self::LIBRARY_PACKAGE_TYPE - ]; - - /** - * Retrieve package type for a grid. - * - * @param string $packageType - * @return string - * @internal param string $packageName - */ - public function map($packageType) - { - return isset($this->packageTypesMap[$packageType]) ? - $this->packageTypesMap[$packageType] : self::UNDEFINED_PACKAGE_TYPE; - } -} diff --git a/setup/src/Magento/Setup/Model/Installer/ProgressFactory.php b/setup/src/Magento/Setup/Model/Installer/ProgressFactory.php deleted file mode 100644 index f7cfad8b4bd53..0000000000000 --- a/setup/src/Magento/Setup/Model/Installer/ProgressFactory.php +++ /dev/null @@ -1,35 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Model\Installer; - -use Magento\Setup\Model\Installer; -use Magento\Setup\Model\WebLogger; - -/** - * Factory for progress indicator model - */ -class ProgressFactory -{ - /** - * Creates a progress indicator from log contents - * - * @param WebLogger $logger - * @return Progress - */ - public function createFromLog(WebLogger $logger) - { - $total = 1; - $current = 0; - $contents = implode('', $logger->get()); - if (preg_match_all(Installer::PROGRESS_LOG_REGEX, $contents, $matches, PREG_SET_ORDER)) { - $last = array_pop($matches); - list(, $current, $total) = $last; - } - $progress = new Progress($total, $current); - return $progress; - } -} diff --git a/setup/src/Magento/Setup/Model/ModuleStatus.php b/setup/src/Magento/Setup/Model/ModuleStatus.php deleted file mode 100644 index a70125e8df3eb..0000000000000 --- a/setup/src/Magento/Setup/Model/ModuleStatus.php +++ /dev/null @@ -1,162 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Model; - -use Magento\Framework\App\DeploymentConfig; -use Magento\Framework\Config\ConfigOptionsListConstants; -use Magento\Framework\Module\DependencyChecker; -use Magento\Framework\Module\ModuleList\Loader as ModuleLoader; - -/** - * Setup module status - */ -class ModuleStatus -{ - /** - * List of Modules - * - * @var array - */ - protected $allModules; - - /** - * Deployment Config - * - * @var DeploymentConfig - */ - protected $deploymentConfig; - - /** - * Dependency Checker - * - * @var DependencyChecker - */ - private $dependencyChecker; - - /** - * Constructor - * - * @param ModuleLoader $moduleLoader - * @param DeploymentConfig $deploymentConfig - * @param ObjectManagerProvider $objectManagerProvider - */ - public function __construct( - ModuleLoader $moduleLoader, - DeploymentConfig $deploymentConfig, - ObjectManagerProvider $objectManagerProvider - ) { - $this->allModules = $moduleLoader->load(); - foreach (array_keys($this->allModules) as $module) { - $this->allModules[$module]['selected'] = true; - $this->allModules[$module]['disabled'] = true; - } - $this->deploymentConfig = $deploymentConfig; - $this->dependencyChecker = $objectManagerProvider->get() - ->get(\Magento\Framework\Module\DependencyChecker::class); - } - - /** - * Returns list of Modules to be displayed - * - * @param array $selectedModules - * @return array - */ - public function getAllModules(array $selectedModules = null) - { - if (isset($this->allModules)) { - if (isset($selectedModules)) { - $diff = array_diff(array_keys($this->allModules), $selectedModules); - foreach ($diff as $module) { - $this->allModules[$module]['selected'] = false; - } - } else { - $this->deselectDisabledModules(); - } - $disableModules = $this->getListOfDisableModules(); - if (isset($disableModules)) { - foreach ($disableModules as $module) { - $this->allModules[$module]['disabled'] = false; - } - } - //check if module is not checked and disabled - possible when config is incorrectly modified. - foreach ($this->allModules as $module) { - if (!$module['selected'] && $module['disabled']) { - $this->allModules[$module['name']]['disabled'] = false; - } - } - return $this->allModules; - } - return []; - } - - /** - * Returns list of modules that can be disabled - * - * @return array - */ - private function getListOfDisableModules() - { - $canBeDisabled = []; - $enabledModules = $this->getListOfEnabledModules(); - foreach ($this->allModules as $module) { - $errorMessages = $this->dependencyChecker->checkDependenciesWhenDisableModules( - [$module['name']], - $enabledModules - ); - if (count($errorMessages[$module['name']]) === 0) { - $canBeDisabled[] = $module['name']; - } - } - return $canBeDisabled; - } - - /** - * Returns list of enabled modules - * - * @return array - */ - private function getListOfEnabledModules() - { - $enabledModules = []; - foreach ($this->allModules as $module) { - if ($module['selected']) { - $enabledModules[] = $module['name']; - } - } - return $enabledModules; - } - - /** - * Set module status is enabled - * - * @param bool $status - * @param String $moduleName - * - * @return void - */ - public function setIsEnabled($status, $moduleName) - { - $this->allModules[$moduleName]['selected'] = $status; - } - - /** - * Marks modules that are disabled in deploymentConfig as unselected. - * - * @return void - */ - private function deselectDisabledModules() - { - $existingModules = $this->deploymentConfig->get(ConfigOptionsListConstants::KEY_MODULES); - if (isset($existingModules)) { - foreach ($existingModules as $module => $value) { - if (!$value) { - $this->allModules[$module]['selected'] = false; - } - } - } - } -} diff --git a/setup/src/Magento/Setup/Model/ModuleStatusFactory.php b/setup/src/Magento/Setup/Model/ModuleStatusFactory.php deleted file mode 100644 index b55f1b6340bcd..0000000000000 --- a/setup/src/Magento/Setup/Model/ModuleStatusFactory.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Model; - -use Magento\Framework\Module\Status; - -/** - * Class ModuleStatusFactory creates instance of Status - */ -class ModuleStatusFactory -{ - /** - * @var ObjectManagerProvider - */ - private $objectManagerProvider; - - /** - * Constructor - * - * @param ObjectManagerProvider $objectManagerProvider - */ - public function __construct(ObjectManagerProvider $objectManagerProvider) - { - $this->objectManagerProvider = $objectManagerProvider; - } - - /** - * Creates Status object - * - * @return Status - */ - public function create() - { - return $this->objectManagerProvider->get()->get(\Magento\Framework\Module\Status::class); - } -} diff --git a/setup/src/Magento/Setup/Model/Navigation.php b/setup/src/Magento/Setup/Model/Navigation.php index 3eaa1fad4016e..ecc4609ff30a7 100644 --- a/setup/src/Magento/Setup/Model/Navigation.php +++ b/setup/src/Magento/Setup/Model/Navigation.php @@ -14,14 +14,14 @@ */ class Navigation { - /**#@+ - * Types of wizards + /** + * Type of navigation */ - const NAV_INSTALLER = 'navInstaller'; - const NAV_UPDATER = 'navUpdater'; - /**#@- */ + const NAV_LANDING = 'navLanding'; - /**#@- */ + /** + * @var string + */ private $navStates; /** @@ -35,22 +35,13 @@ class Navigation private $titles; /** - * @param ServiceLocatorInterface $serviceLocator - * @param DeploymentConfig $deploymentConfig - * @throws \Magento\Framework\Exception\FileSystemException - * @throws \Magento\Framework\Exception\RuntimeException + * @param \Laminas\ServiceManager\ServiceLocatorInterface $serviceLocator */ - public function __construct(ServiceLocatorInterface $serviceLocator, DeploymentConfig $deploymentConfig) + public function __construct(ServiceLocatorInterface $serviceLocator) { - if ($deploymentConfig->isAvailable()) { - $this->navStates = $serviceLocator->get('config')[self::NAV_UPDATER]; - $this->navType = self::NAV_UPDATER; - $this->titles = $serviceLocator->get('config')[self::NAV_UPDATER . 'Titles']; - } else { - $this->navStates = $serviceLocator->get('config')[self::NAV_INSTALLER]; - $this->navType = self::NAV_INSTALLER; - $this->titles = $serviceLocator->get('config')[self::NAV_INSTALLER . 'Titles']; - } + $this->navStates = $serviceLocator->get('config')[self::NAV_LANDING]; + $this->navType = self::NAV_LANDING; + $this->titles = $serviceLocator->get('config')[self::NAV_LANDING . 'Titles']; } /** diff --git a/setup/src/Magento/Setup/Model/PackagesAuth.php b/setup/src/Magento/Setup/Model/PackagesAuth.php index b0363a5363d41..619521d348bba 100644 --- a/setup/src/Magento/Setup/Model/PackagesAuth.php +++ b/setup/src/Magento/Setup/Model/PackagesAuth.php @@ -11,7 +11,7 @@ use Magento\Framework\Phrase; /** - * Class PackagesAuth, checks, saves and removes auth details related to packages. + * Class PackagesAuth contains auth details. */ class PackagesAuth { @@ -29,186 +29,4 @@ class PackagesAuth const PATH_TO_AUTH_FILE = 'auth.json'; const PATH_TO_PACKAGES_FILE = 'packages.json'; /**#@-*/ - - /** - * @var \Laminas\ServiceManager\ServiceLocatorInterface - */ - protected $serviceLocator; - - /** - * @var \Magento\Framework\HTTP\Client\Curl - */ - protected $curlClient; - - /** - * @var string - */ - protected $urlPrefix = 'https://'; - - /** - * @var \Magento\Framework\Filesystem - */ - private $filesystem; - - /** - * @var \Magento\Framework\Serialize\Serializer\Json - */ - private $serializer; - - /** - * @param \Laminas\ServiceManager\ServiceLocatorInterface $serviceLocator - * @param \Magento\Framework\HTTP\Client\Curl $curl - * @param \Magento\Framework\Filesystem $filesystem - * @param \Magento\Framework\Serialize\Serializer\Json|null $serializer - * @throws \RuntimeException - */ - public function __construct( - \Laminas\ServiceManager\ServiceLocatorInterface $serviceLocator, - \Magento\Framework\HTTP\Client\Curl $curl, - \Magento\Framework\Filesystem $filesystem, - \Magento\Framework\Serialize\Serializer\Json $serializer = null - ) { - $this->serviceLocator = $serviceLocator; - $this->curlClient = $curl; - $this->filesystem = $filesystem; - $this->serializer = $serializer ?: \Magento\Framework\App\ObjectManager::getInstance() - ->get(\Magento\Framework\Serialize\Serializer\Json::class); - } - - /** - * Get packages json URL - * - * @return string - */ - private function getPackagesJsonUrl() - { - return $this->urlPrefix . $this->getCredentialBaseUrl() . '/packages.json'; - } - - /** - * Get credentials base URL - * - * @return string - */ - public function getCredentialBaseUrl() - { - $config = $this->serviceLocator->get('config'); - return $config['marketplace']['check_credentials_url']; - } - - /** - * Check credentials - * - * @param string $token - * @param string $secretKey - * @return string - * @throws \InvalidArgumentException - */ - public function checkCredentials($token, $secretKey) - { - $response = ['success' => true]; - $serviceUrl = $this->getPackagesJsonUrl(); - $this->curlClient->setCredentials($token, $secretKey); - try { - $this->curlClient->post($serviceUrl, []); - if ($this->curlClient->getStatus() == 200) { - $packagesInfo = $this->curlClient->getBody(); - $directory = $this->filesystem->getDirectoryWrite(DirectoryList::COMPOSER_HOME); - $directory->writeFile(self::PATH_TO_PACKAGES_FILE, $packagesInfo); - } else { - $response = ['success' => false, 'message' => 'Bad credentials']; - } - } catch (\Exception $e) { - $response = ['success' => false, 'message' => $e->getMessage()]; - } - return $this->serializer->serialize($response); - } - - /** - * Gets auth.json file - * - * @return array|false - */ - public function getAuthJsonData() - { - try { - $authJson = $this->getAuthJson(); - $serviceUrl = $this->getCredentialBaseUrl(); - $authJsonData = isset($authJson['http-basic'][$serviceUrl]) ? $authJson['http-basic'][$serviceUrl] : false; - } catch (\Exception $e) { - $authJsonData = false; - } - return $authJsonData; - } - - /** - * Gets auth.json - * - * @return bool|mixed - * @throws \Exception - */ - private function getAuthJson() - { - $directory = $this->filesystem->getDirectoryRead(DirectoryList::COMPOSER_HOME); - if ($directory->isExist(self::PATH_TO_AUTH_FILE) && $directory->isReadable(self::PATH_TO_AUTH_FILE)) { - try { - $data = $directory->readFile(self::PATH_TO_AUTH_FILE); - return json_decode($data, true); - } catch (\Exception $e) { - throw new LocalizedException(new Phrase('Error in reading Auth file')); - } - } - return false; - } - - /** - * Removes credentials from auth.json - * - * @return bool - * @throws \Exception - */ - public function removeCredentials() - { - $serviceUrl = $this->getCredentialBaseUrl(); - $directory = $this->filesystem->getDirectoryWrite(DirectoryList::COMPOSER_HOME); - if ($directory->isExist(self::PATH_TO_AUTH_FILE) && $directory->isReadable(self::PATH_TO_AUTH_FILE)) { - $authJsonData = $this->getAuthJson(); - if (isset($authJsonData['http-basic']) && isset($authJsonData['http-basic'][$serviceUrl])) { - unset($authJsonData['http-basic'][$serviceUrl]); - if ($authJsonData === ['http-basic' => []]) { - return $directory->delete(self::PATH_TO_AUTH_FILE); - } else { - $data = json_encode($authJsonData, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT); - return $data !== false && $directory->writeFile(self::PATH_TO_AUTH_FILE, $data); - } - } - } - return false; - } - - /** - * Saves auth.json file - * - * @param string $username - * @param string $password - * @return bool - * @throws \Exception - */ - public function saveAuthJson($username, $password) - { - $directory = $this->filesystem->getDirectoryWrite(DirectoryList::COMPOSER_HOME); - $authContent = [ - PackagesAuth::KEY_HTTPBASIC => [ - $this->getCredentialBaseUrl() => [ - PackagesAuth::KEY_USERNAME => "$username", - PackagesAuth::KEY_PASSWORD => "$password" - ] - ] - ]; - $json = new \Laminas\View\Model\JsonModel($authContent); - $json->setOption('prettyPrint', true); - $jsonContent = $json->serialize(); - - return $directory->writeFile(self::PATH_TO_AUTH_FILE, $jsonContent); - } } diff --git a/setup/src/Magento/Setup/Model/PackagesData.php b/setup/src/Magento/Setup/Model/PackagesData.php deleted file mode 100644 index 67ab85ab64205..0000000000000 --- a/setup/src/Magento/Setup/Model/PackagesData.php +++ /dev/null @@ -1,532 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model; - -/** - * Class PackagesData returns system packages and available for update versions - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class PackagesData -{ - /**#@+ - * Composer command params and options - */ - const COMPOSER_SHOW = 'show'; - const PARAM_COMMAND = 'command'; - const PARAM_PACKAGE = 'package'; - const PARAM_AVAILABLE = '--available'; - /**#@-*/ - - /** - * @var \Magento\Framework\Composer\ComposerInformation - */ - private $composerInformation; - - /** - * @var string - */ - protected $urlPrefix = 'https://'; - - /** - * @var array - */ - private $packagesJson; - - /** - * @var \Magento\Framework\Filesystem - */ - private $filesystem; - - /** - * @var \Magento\Setup\Model\PackagesAuth - */ - private $packagesAuth; - - /** - * @var \Magento\Setup\Model\DateTime\TimeZoneProvider - */ - private $timeZoneProvider; - - /** - * @var \Magento\Setup\Model\ObjectManagerProvider - */ - private $objectManagerProvider; - - /** - * @var array - */ - private $metapackagesMap; - - /** - * PackagesData constructor. - * - * @param \Magento\Framework\Composer\ComposerInformation $composerInformation , - * @param \Magento\Setup\Model\DateTime\TimeZoneProvider $timeZoneProvider , - * @param \Magento\Setup\Model\PackagesAuth $packagesAuth , - * @param \Magento\Framework\Filesystem $filesystem , - * @param \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider - * @param TypeMapper $typeMapper - */ - public function __construct( - \Magento\Framework\Composer\ComposerInformation $composerInformation, - \Magento\Setup\Model\DateTime\TimeZoneProvider $timeZoneProvider, - \Magento\Setup\Model\PackagesAuth $packagesAuth, - \Magento\Framework\Filesystem $filesystem, - \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider, - \Magento\Setup\Model\Grid\TypeMapper $typeMapper - ) { - $this->objectManagerProvider = $objectManagerProvider; - $this->composerInformation = $composerInformation; - $this->timeZoneProvider = $timeZoneProvider; - $this->packagesAuth = $packagesAuth; - $this->filesystem = $filesystem; - $this->typeMapper = $typeMapper; - } - - /** - * @return array|bool|mixed - * @throws \RuntimeException - */ - public function syncPackagesData() - { - try { - $lastSyncData = []; - $lastSyncData['lastSyncDate'] = $this->getLastSyncDate(); - $lastSyncData['packages'] = $this->getPackagesForUpdate(); - $packagesForInstall = $this->syncPackagesForInstall(); - $lastSyncData = $this->formatLastSyncData($packagesForInstall, $lastSyncData); - return $lastSyncData; - } catch (\Exception $e) { - throw new \RuntimeException($e->getMessage()); - } - } - - /** - * Gets last sync date - * - * @return string - */ - private function getLastSyncDate() - { - $directory = $this->filesystem->getDirectoryRead( - \Magento\Framework\App\Filesystem\DirectoryList::COMPOSER_HOME - ); - if ($directory->isExist(PackagesAuth::PATH_TO_PACKAGES_FILE)) { - $fileData = $directory->stat(PackagesAuth::PATH_TO_PACKAGES_FILE); - return $fileData['mtime']; - } - return ''; - } - - /** - * Format the lastSyncData for use on frontend - * - * @param array $packagesForInstall - * @param array $lastSyncData - * @return mixed - */ - private function formatLastSyncData($packagesForInstall, $lastSyncData) - { - $lastSyncData['countOfInstall'] - = isset($packagesForInstall['packages']) ? count($packagesForInstall['packages']) : 0; - $lastSyncData['countOfUpdate'] = isset($lastSyncData['packages']) ? count($lastSyncData['packages']) : 0; - $lastSyncData['installPackages'] = $packagesForInstall['packages']; - if (isset($lastSyncData['lastSyncDate'])) { - $lastSyncData['lastSyncDate'] = $this->formatSyncDate($lastSyncData['lastSyncDate']); - } - return $lastSyncData; - } - - /** - * Format a UTC timestamp (seconds since epoch) to structure expected by frontend - * - * @param string $syncDate seconds since epoch - * @return array - */ - private function formatSyncDate($syncDate) - { - $timezone = $this->timeZoneProvider->get(); - return [ - 'date' => $timezone->formatDateTime( - new \DateTime('@' . $syncDate), - \IntlDateFormatter::MEDIUM, - \IntlDateFormatter::NONE, - null, - null, - 'd MMM Y' - ), - 'time' => $timezone->formatDateTime( - new \DateTime('@' . $syncDate), - \IntlDateFormatter::NONE, - \IntlDateFormatter::MEDIUM, - null, - null, - 'hh:mma' - ), - ]; - } - - /** - * Get list of manually installed package - * - * @return array - */ - public function getInstalledPackages() - { - $installedPackages = array_intersect_key( - $this->composerInformation->getInstalledMagentoPackages(), - $this->composerInformation->getRootPackage()->getRequires() - ); - - foreach ($installedPackages as &$package) { - $package = $this->addPackageExtraInfo($package); - } - - return $this->filterPackagesList($installedPackages); - } - - /** - * Get packages that need updates - * - * @return array - */ - public function getPackagesForUpdate() - { - $packagesForUpdate = []; - $packages = $this->getInstalledPackages(); - - foreach ($packages as $package) { - $latestProductVersion = $this->getLatestNonDevVersion($package['name']); - if ($latestProductVersion && version_compare($latestProductVersion, $package['version'], '>')) { - $availableVersions = $this->getPackageAvailableVersions($package['name']); - $package['latestVersion'] = $latestProductVersion; - $package['versions'] = array_filter($availableVersions, function ($version) use ($package) { - return version_compare($version, $package['version'], '>'); - }); - $packagesForUpdate[$package['name']] = $package; - } - } - - return $packagesForUpdate; - } - - /** - * Retrieve the latest available stable version for a package - * - * @param string $package - * @return string - */ - private function getLatestNonDevVersion($package) - { - $versionParser = new \Composer\Package\Version\VersionParser(); - foreach ($this->getPackageAvailableVersions($package) as $version) { - if ($versionParser->parseStability($version) != 'dev') { - return $version; - } - } - return ''; - } - - /** - * Gets array of packages from packages.json - * - * @return array - * @throws \RuntimeException - */ - private function getPackagesJson() - { - if ($this->packagesJson !== null) { - return $this->packagesJson; - } - - try { - $jsonData = ''; - $directory = $this->filesystem->getDirectoryRead( - \Magento\Framework\App\Filesystem\DirectoryList::COMPOSER_HOME - ); - if ($directory->isExist(PackagesAuth::PATH_TO_PACKAGES_FILE)) { - $jsonData = $directory->readFile(PackagesAuth::PATH_TO_PACKAGES_FILE); - } - $packagesData = json_decode($jsonData, true); - - $this->packagesJson = isset($packagesData['packages']) ? - $packagesData['packages'] : - []; - - return $this->packagesJson; - } catch (\Exception $e) { - throw new \RuntimeException('Error in reading packages.json'); - } - } - - /** - * Sync packages for install - * - * @return array - * @throws \RuntimeException - */ - private function syncPackagesForInstall() - { - try { - $packagesJson = $this->getPackagesJson(); - $packages = $this->composerInformation->getInstalledMagentoPackages(); - $packageNames = array_column($packages, 'name'); - $installPackages = []; - foreach ($packagesJson as $packageName => $package) { - if (!empty($package) && isset($package) && is_array($package)) { - $package = $this->unsetDevVersions($package); - ksort($package); - $packageValues = array_values($package); - if ($this->isNewUserPackage($packageValues[0], $packageNames)) { - uksort($package, 'version_compare'); - $installPackage = $packageValues[0]; - $installPackage['versions'] = array_reverse(array_keys($package)); - $installPackage['name'] = $packageName; - $installPackage['vendor'] = explode('/', $packageName)[0]; - $installPackages[$packageName] = $this->addPackageExtraInfo($installPackage); - } - } - } - $packagesForInstall['packages'] = $this->filterPackagesList($installPackages); - return $packagesForInstall; - } catch (\Exception $e) { - throw new \RuntimeException('Error in syncing packages for Install'); - } - } - - /** - * Get package extra info - * - * @param string $packageName - * @param string $packageVersion - * @return array - */ - private function getPackageExtraInfo($packageName, $packageVersion) - { - $packagesJson = $this->getPackagesJson(); - - return isset($packagesJson[$packageName][$packageVersion]['extra']) ? - $packagesJson[$packageName][$packageVersion]['extra'] : []; - } - - /** - * Add package extra info - * - * @param array $package - * @return array - */ - public function addPackageExtraInfo(array $package) - { - $extraInfo = $this->getPackageExtraInfo($package['name'], $package['version']); - - $package['package_title'] = isset($extraInfo['x-magento-ext-title']) ? - $extraInfo['x-magento-ext-title'] : $package['name']; - $package['package_type'] = isset($extraInfo['x-magento-ext-type']) ? $extraInfo['x-magento-ext-type'] : - $this->typeMapper->map($package['type']); - $package['package_link'] = isset($extraInfo['x-magento-ext-package-link']) ? - $extraInfo['x-magento-ext-package-link'] : ''; - - return $package; - } - - /** - * Check if this new user package - * - * @param array $package - * @param array $packageNames - * @return bool - */ - protected function isNewUserPackage($package, $packageNames) - { - if (!in_array($package['name'], $packageNames) && - in_array($package['type'], $this->composerInformation->getPackagesTypes()) && - strpos($package['name'], 'magento/product-') === false && - strpos($package['name'], 'magento/project-') === false - ) { - return true; - } - return false; - } - - /** - * Unset dev versions - * - * @param array $package - * @return array - */ - protected function unsetDevVersions($package) - { - foreach ($package as $key => $version) { - if (strpos($key, 'dev') !== false) { - unset($package[$key]); - } - } - unset($version); - - return $package; - } - - /** - * Sync list of available for install versions for packages - * - * @return array - * @throws \RuntimeException - */ - public function getPackagesForInstall() - { - $actualInstallPackages = []; - - try { - $installPackages = $this->syncPackagesForInstall()['packages']; - $metaPackageByPackage = $this->getMetaPackageForPackage($installPackages); - foreach ($installPackages as $package) { - $package['metapackage'] = - isset($metaPackageByPackage[$package['name']]) ? $metaPackageByPackage[$package['name']] : ''; - $actualInstallPackages[$package['name']] = $package; - $actualInstallPackages[$package['name']]['version'] = $package['versions'][0]; - } - $installPackagesInfo['packages'] = $actualInstallPackages; - return $installPackagesInfo; - } catch (\Exception $e) { - throw new \RuntimeException('Error in getting new packages to install'); - } - } - - /** - * Filter packages by allowed types - * - * @param array $packages - * @return array - */ - private function filterPackagesList(array $packages) - { - return array_filter( - $packages, - function ($item) { - return in_array( - $item['package_type'], - [ - \Magento\Setup\Model\Grid\TypeMapper::LANGUAGE_PACKAGE_TYPE, - \Magento\Setup\Model\Grid\TypeMapper::MODULE_PACKAGE_TYPE, - \Magento\Setup\Model\Grid\TypeMapper::EXTENSION_PACKAGE_TYPE, - \Magento\Setup\Model\Grid\TypeMapper::THEME_PACKAGE_TYPE, - \Magento\Setup\Model\Grid\TypeMapper::METAPACKAGE_PACKAGE_TYPE - ] - ); - } - ); - } - - /** - * Get MetaPackage for package - * - * @param array $packages - * @return array - */ - private function getMetaPackageForPackage($packages) - { - $result = []; - foreach ($packages as $package) { - if ($package['type'] == \Magento\Framework\Composer\ComposerInformation::METAPACKAGE_PACKAGE_TYPE) { - if (isset($package['require'])) { - foreach ($package['require'] as $key => $requirePackage) { - $result[$key] = $package['name']; - } - } - } - } - unset($requirePackage); - - return $result; - } - - /** - * Get all metapackages - * - * @return array - */ - public function getMetaPackagesMap() - { - if ($this->metapackagesMap === null) { - $packages = $this->getPackagesJson(); - array_walk($packages, function ($packageVersions) { - $package = array_shift($packageVersions); - if ($package['type'] == \Magento\Framework\Composer\ComposerInformation::METAPACKAGE_PACKAGE_TYPE - && isset($package['require']) - ) { - foreach (array_keys($package['require']) as $key) { - $this->metapackagesMap[$key] = $package['name']; - } - } - }); - } - - return $this->metapackagesMap; - } - - /** - * Retrieve all available versions for a package - * - * @param string $package - * @return array - * @throws \RuntimeException - */ - private function getPackageAvailableVersions($package) - { - $magentoRepositories = $this->composerInformation->getRootRepositories(); - - // Check we have only one repo.magento.com repository - if (count($magentoRepositories) === 1 - && strpos($magentoRepositories[0], $this->packagesAuth->getCredentialBaseUrl()) !== false - ) { - $packagesJson = $this->getPackagesJson(); - - if (isset($packagesJson[$package])) { - $packageVersions = $packagesJson[$package]; - uksort($packageVersions, 'version_compare'); - $packageVersions = array_reverse($packageVersions); - - return array_keys($packageVersions); - } - } - - return $this->getAvailableVersionsFromAllRepositories($package); - } - - /** - * Get available versions of package by "composer show" command - * - * @param string $package - * @return array - * @exception \RuntimeException - */ - private function getAvailableVersionsFromAllRepositories($package) - { - $versionsPattern = '/^versions\s*\:\s(.+)$/m'; - - $commandParams = [ - self::PARAM_COMMAND => self::COMPOSER_SHOW, - self::PARAM_PACKAGE => $package, - self::PARAM_AVAILABLE => true - ]; - - $applicationFactory = $this->objectManagerProvider->get() - ->get(\Magento\Framework\Composer\MagentoComposerApplicationFactory::class); - /** @var \Magento\Composer\MagentoComposerApplication $application */ - $application = $applicationFactory->create(); - - $result = $application->runComposerCommand($commandParams); - $matches = []; - preg_match($versionsPattern, $result, $matches); - if (isset($matches[1])) { - return explode(', ', $matches[1]); - } - - throw new \RuntimeException( - sprintf('Couldn\'t get available versions for package %s', $package) - ); - } -} diff --git a/setup/src/Magento/Setup/Model/PayloadValidator.php b/setup/src/Magento/Setup/Model/PayloadValidator.php deleted file mode 100644 index 9d6ef012eab87..0000000000000 --- a/setup/src/Magento/Setup/Model/PayloadValidator.php +++ /dev/null @@ -1,117 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Model; - -/** - * Validates payloads for updater tasks - */ -class PayloadValidator -{ - /** - * @var \Magento\Framework\Module\FullModuleList - */ - private $moduleList; - - /** - * @param \Magento\Framework\Module\FullModuleList $moduleList - */ - public function __construct(\Magento\Framework\Module\FullModuleList $moduleList) - { - $this->moduleList = $moduleList; - } - - /** - * Validate POST request payload - * - * @param array $postPayload - * @return string - */ - public function validatePayload(array $postPayload) - { - $jobType = $postPayload[UpdaterTaskCreator::KEY_POST_JOB_TYPE]; - $errorMessage = ''; - switch ($jobType) { - case 'uninstall': - $errorMessage = $this->validateUninstallPayload($postPayload); - break; - - case 'update': - $errorMessage = $this->validateUpdatePayload($postPayload); - break; - - case 'enable': - case 'disable': - $errorMessage = $this->validateEnableDisablePayload($postPayload); - break; - } - return $errorMessage; - } - - /** - * Validate 'uninstall' job type payload - * - * @param array $postPayload - * @return string - */ - private function validateUninstallPayload(array $postPayload) - { - $errorMessage = ''; - if (!isset($postPayload[UpdaterTaskCreator::KEY_POST_DATA_OPTION])) { - $errorMessage = 'Missing dataOption' . PHP_EOL; - } - return $errorMessage; - } - - /** - * Validate 'update' job type payload - * - * @param array $postPayload - * @return string - */ - private function validateUpdatePayload(array $postPayload) - { - $errorMessage = ''; - if (!isset($postPayload[UpdaterTaskCreator::KEY_POST_PACKAGES])) { - $errorMessage = 'Missing packages' . PHP_EOL; - } else { - $packages = $postPayload[UpdaterTaskCreator::KEY_POST_PACKAGES]; - foreach ($packages as $package) { - if ((!isset($package[UpdaterTaskCreator::KEY_POST_PACKAGE_NAME])) - || (!isset($package[UpdaterTaskCreator::KEY_POST_PACKAGE_VERSION])) - ) { - $errorMessage .= 'Missing package information' . PHP_EOL; - break; - } - } - } - return $errorMessage; - } - - /** - * Validate 'enable/disable' job type payload - * - * @param array $postPayload - * @return string - */ - private function validateEnableDisablePayload(array $postPayload) - { - $errorMessage = ''; - if (!isset($postPayload[UpdaterTaskCreator::KEY_POST_PACKAGES])) { - $errorMessage = 'Missing packages' . PHP_EOL; - } else { - $packages = $postPayload[UpdaterTaskCreator::KEY_POST_PACKAGES]; - foreach ($packages as $package) { - if (!$this->moduleList->has($package[UpdaterTaskCreator::KEY_POST_PACKAGE_NAME])) { - $errorMessage .= 'Invalid Magento module name: ' - . $package[UpdaterTaskCreator::KEY_POST_PACKAGE_NAME] . PHP_EOL; - break; - } - } - } - return $errorMessage; - } -} diff --git a/setup/src/Magento/Setup/Model/RequestDataConverter.php b/setup/src/Magento/Setup/Model/RequestDataConverter.php deleted file mode 100644 index edcc19565ec82..0000000000000 --- a/setup/src/Magento/Setup/Model/RequestDataConverter.php +++ /dev/null @@ -1,178 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Model; - -use Magento\Framework\Config\ConfigOptionsListConstants as SetupConfigOptionsList; -use Magento\Backend\Setup\ConfigOptionsList as BackendConfigOptionsList; -use Magento\Setup\Model\StoreConfigurationDataMapper as UserConfig; -use Magento\Setup\Console\Command\InstallCommand; - -/** - * Converter of request data into format compatible with models. - */ -class RequestDataConverter -{ - /** - * Convert request data into format compatible with models. - * - * @param array $source - * @return array - */ - public function convert(array $source) - { - $result = array_merge( - $this->convertDeploymentConfigForm($source), - $this->convertUserConfigForm($source), - $this->convertAdminUserForm($source), - $this->convertSearchConfigForm($source) - ); - return $result; - } - - /** - * Convert data from request to format of deployment config model - * - * @param array $source - * @return array - * @SuppressWarnings(PHPMD.CyclomaticComplexity) - * @SuppressWarnings(PHPMD.NPathComplexity) - */ - private function convertDeploymentConfigForm(array $source) - { - $result = []; - $result[SetupConfigOptionsList::INPUT_KEY_DB_HOST] = isset($source['db']['host']) ? $source['db']['host'] : ''; - $result[SetupConfigOptionsList::INPUT_KEY_DB_NAME] = isset($source['db']['name']) ? $source['db']['name'] : ''; - $result[SetupConfigOptionsList::INPUT_KEY_DB_USER] = isset($source['db']['user']) ? $source['db']['user'] : ''; - $result[SetupConfigOptionsList::INPUT_KEY_DB_PASSWORD] = - isset($source['db']['password']) ? $source['db']['password'] : ''; - $result[SetupConfigOptionsList::INPUT_KEY_DB_PREFIX] = - isset($source['db']['tablePrefix']) ? $source['db']['tablePrefix'] : ''; - $result[BackendConfigOptionsList::INPUT_KEY_BACKEND_FRONTNAME] = isset($source['config']['address']['admin']) - ? $source['config']['address']['admin'] : ''; - $result[SetupConfigOptionsList::INPUT_KEY_DB_SSL_KEY] = isset($source['db']['driverOptionsSslKey']) - ? $source['db']['driverOptionsSslKey'] : ''; - $result[SetupConfigOptionsList::INPUT_KEY_DB_SSL_CERT] = isset($source['db']['driverOptionsSslCert']) - ? $source['db']['driverOptionsSslCert'] : ''; - $result[SetupConfigOptionsList::INPUT_KEY_DB_SSL_CA] = isset($source['db']['driverOptionsSslCa']) - ? $source['db']['driverOptionsSslCa'] : ''; - $result[SetupConfigOptionsList::INPUT_KEY_DB_SSL_VERIFY] = isset($source['db']['driverOptionsSslVerify']) - ? $source['db']['driverOptionsSslVerify'] : ''; - $result[SetupConfigOptionsList::INPUT_KEY_ENCRYPTION_KEY] = isset($source['config']['encrypt']['key']) - ? $source['config']['encrypt']['key'] : null; - $result[SetupConfigOptionsList::INPUT_KEY_SESSION_SAVE] = isset($source['config']['sessionSave']['type']) - ? $source['config']['sessionSave']['type'] : SetupConfigOptionsList::SESSION_SAVE_FILES; - $result[Installer::ENABLE_MODULES] = isset($source['store']['selectedModules']) - ? implode(',', $source['store']['selectedModules']) : ''; - $result[Installer::DISABLE_MODULES] = isset($source['store']['allModules']) - ? implode(',', array_diff($source['store']['allModules'], $source['store']['selectedModules'])) : ''; - return $result; - } - - /** - * Convert data from request to format of user config model - * - * @param array $source - * @return array - * @SuppressWarnings(PHPMD.CyclomaticComplexity) - * @SuppressWarnings(PHPMD.NPathComplexity) - */ - private function convertUserConfigForm(array $source) - { - $result = []; - if (isset($source['config']['address']['base_url']) && !empty($source['config']['address']['base_url'])) { - $result[UserConfig::KEY_BASE_URL] = $source['config']['address']['base_url']; - } - $result[UserConfig::KEY_USE_SEF_URL] = isset($source['config']['rewrites']['allowed']) - ? $source['config']['rewrites']['allowed'] : ''; - $result[UserConfig::KEY_IS_SECURE] = isset($source['config']['https']['front']) - ? $source['config']['https']['front'] : ''; - $result[UserConfig::KEY_IS_SECURE_ADMIN] = isset($source['config']['https']['admin']) - ? $source['config']['https']['admin'] : ''; - $result[UserConfig::KEY_BASE_URL_SECURE] = (isset($source['config']['https']['front']) - || isset($source['config']['https']['admin'])) - ? $source['config']['https']['text'] : ''; - $result[UserConfig::KEY_LANGUAGE] = isset($source['store']['language']) - ? $source['store']['language'] : ''; - $result[UserConfig::KEY_TIMEZONE] = isset($source['store']['timezone']) - ? $source['store']['timezone'] : ''; - $result[UserConfig::KEY_CURRENCY] = isset($source['store']['currency']) - ? $source['store']['currency'] : ''; - $result[InstallCommand::INPUT_KEY_USE_SAMPLE_DATA] = isset($source['store']['useSampleData']) - ? $source['store']['useSampleData'] : ''; - $result[InstallCommand::INPUT_KEY_CLEANUP_DB] = isset($source['store']['cleanUpDatabase']) - ? $source['store']['cleanUpDatabase'] : ''; - return $result; - } - - /** - * Convert data from request to format of admin account model - * - * @param array $source - * @return array - */ - private function convertAdminUserForm(array $source) - { - $result = []; - $result[AdminAccount::KEY_USER] = isset($source['admin']['username']) ? $source['admin']['username'] : ''; - $result[AdminAccount::KEY_PASSWORD] = isset($source['admin']['password']) ? $source['admin']['password'] : ''; - $result[AdminAccount::KEY_EMAIL] = isset($source['admin']['email']) ? $source['admin']['email'] : ''; - $result[AdminAccount::KEY_FIRST_NAME] = $result[AdminAccount::KEY_USER]; - $result[AdminAccount::KEY_LAST_NAME] = $result[AdminAccount::KEY_USER]; - return $result; - } - - /** - * Convert data from request to format of search config model - * - * @param array $source - * @return array - */ - private function convertSearchConfigForm(array $source): array - { - $result = []; - if (!isset($source['search'])) { - return $result; - } - $result[SearchConfigOptionsList::INPUT_KEY_SEARCH_ENGINE] = - $this->getValueFromArray($source['search'], 'engine', ''); - - $esConfig = $source['search']['elasticsearch']; - $result[SearchConfigOptionsList::INPUT_KEY_ELASTICSEARCH_HOST] = - $this->getValueFromArray($esConfig, 'hostname', ''); - $result[SearchConfigOptionsList::INPUT_KEY_ELASTICSEARCH_PORT] = - $this->getValueFromArray($esConfig, 'port', ''); - $result[SearchConfigOptionsList::INPUT_KEY_ELASTICSEARCH_INDEX_PREFIX] = - $this->getValueFromArray($esConfig, 'indexPrefix', ''); - $result[SearchConfigOptionsList::INPUT_KEY_ELASTICSEARCH_TIMEOUT] = - $this->getValueFromArray($esConfig, 'timeout', ''); - - if (isset($esConfig['enableAuth']) && true === $esConfig['enableAuth']) { - $result[SearchConfigOptionsList::INPUT_KEY_ELASTICSEARCH_ENABLE_AUTH] = $esConfig['enableAuth']; - $result[SearchConfigOptionsList::INPUT_KEY_ELASTICSEARCH_USERNAME] = - $this->getValueFromArray($esConfig, 'username', ''); - $result[SearchConfigOptionsList::INPUT_KEY_ELASTICSEARCH_PASSWORD] = - $this->getValueFromArray($esConfig, 'password', ''); - } else { - $result[SearchConfigOptionsList::INPUT_KEY_ELASTICSEARCH_ENABLE_AUTH] = - $this->getValueFromArray($esConfig, 'enableAuth', false); - } - - return $result; - } - - /** - * Get value from array by key, or return default - * - * @param array $array - * @param string $key - * @param mixed $defaultValue - * @return mixed - */ - private function getValueFromArray(array $array, string $key, $defaultValue = null) - { - return isset($array[$key]) ? $array[$key] : $defaultValue; - } -} diff --git a/setup/src/Magento/Setup/Model/SystemPackage.php b/setup/src/Magento/Setup/Model/SystemPackage.php deleted file mode 100644 index d8041990b4f81..0000000000000 --- a/setup/src/Magento/Setup/Model/SystemPackage.php +++ /dev/null @@ -1,284 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Model; - -use Magento\Composer\InfoCommand; -use Magento\Composer\MagentoComposerApplication; -use Magento\Framework\Composer\ComposerInformation; -use Magento\Framework\Composer\MagentoComposerApplicationFactory; - -/** - * Class SystemPackage returns system package and available for update versions - */ -class SystemPackage -{ - /** - * @var InfoCommand - */ - private $infoCommand; - - /** - * @var MagentoComposerApplication - */ - private $magentoComposerApplication; - - /** - * @var ComposerInformation - */ - private $composerInfo; - - const EDITION_COMMUNITY = 'magento/product-community-edition'; - - const EDITION_ENTERPRISE = 'magento/product-enterprise-edition'; - - /** - * Constructor - * - * @param MagentoComposerApplicationFactory $composerAppFactory - * @param ComposerInformation $composerInfo - */ - public function __construct( - MagentoComposerApplicationFactory $composerAppFactory, - ComposerInformation $composerInfo - ) { - $this->infoCommand = $composerAppFactory->createInfoCommand(); - $this->magentoComposerApplication = $composerAppFactory->create(); - $this->composerInfo = $composerInfo; - } - - /** - * Returns system package and available versions - * - * @return array - * @throws \RuntimeException - */ - public function getPackageVersions() - { - $currentCE = '0'; - - $result = []; - $systemPackages = $this->getInstalledSystemPackages(); - foreach ($systemPackages as $systemPackage) { - $systemPackageInfo = $this->infoCommand->run($systemPackage); - if (!$systemPackageInfo) { - throw new \RuntimeException("We cannot retrieve information on $systemPackage."); - } - - $versions = $this->getSystemPackageVersions($systemPackageInfo); - - if ($systemPackageInfo['name'] == static::EDITION_COMMUNITY) { - $currentCE = $systemPackageInfo[InfoCommand::CURRENT_VERSION]; - } - - if (count($versions) > 1) { - $versions[0]['name'] .= ' (latest)'; - } - - $result[] = [ - 'package' => $systemPackageInfo['name'], - 'versions' => $versions, - ]; - } - - if (!in_array(static::EDITION_ENTERPRISE, $systemPackages)) { - $result = array_merge($this->getAllowedEnterpriseVersions($currentCE), $result); - } - - $result = $this->formatPackages($result); - - return $result; - } - - /** - * Retrieve allowed EE versions - * - * @param string $currentCE - * @return array - */ - public function getAllowedEnterpriseVersions($currentCE) - { - $result = []; - $enterpriseVersions = $this->infoCommand->run(static::EDITION_ENTERPRISE); - $eeVersions = []; - $maxVersion = ''; - if (is_array($enterpriseVersions) && array_key_exists(InfoCommand::AVAILABLE_VERSIONS, $enterpriseVersions)) { - $enterpriseVersions = $this->sortVersions($enterpriseVersions); - if (isset($enterpriseVersions[InfoCommand::AVAILABLE_VERSIONS][0])) { - $maxVersion = $enterpriseVersions[InfoCommand::AVAILABLE_VERSIONS][0]; - } - $eeVersions = $this->filterEeVersions($currentCE, $enterpriseVersions, $maxVersion); - } - - if (!empty($eeVersions)) { - $result[] = [ - 'package' => static::EDITION_ENTERPRISE, - 'versions' => $eeVersions, - ]; - } - return $result; - } - - /** - * Retrieve package versions - * - * @param array $systemPackageInfo - * @return array - */ - public function getSystemPackageVersions($systemPackageInfo) - { - $editionType = ''; - $versions = []; - - if ($systemPackageInfo['name'] == static::EDITION_COMMUNITY) { - $editionType .= 'CE'; - } elseif ($systemPackageInfo['name'] == static::EDITION_ENTERPRISE) { - $editionType .= 'EE'; - } - - foreach ($systemPackageInfo[InfoCommand::NEW_VERSIONS] as $version) { - $versions[] = ['id' => $version, 'name' => 'Version ' . $version . ' ' . $editionType, 'current' => false]; - } - - if ($systemPackageInfo[InfoCommand::CURRENT_VERSION]) { - $versions[] = [ - 'id' => $systemPackageInfo[InfoCommand::CURRENT_VERSION], - 'name' => 'Version ' . $systemPackageInfo[InfoCommand::CURRENT_VERSION] . ' ' . $editionType, - 'current' => true, - ]; - } - return $versions; - } - - /** - * Get installed system packages. - * - * @return array - * @throws \Exception - * @throws \RuntimeException - */ - public function getInstalledSystemPackages() - { - $locker = $this->magentoComposerApplication->createComposer()->getLocker(); - - /** @var \Composer\Package\CompletePackage $package */ - foreach ($locker->getLockedRepository()->getPackages() as $package) { - $packageName = $package->getName(); - if ($this->composerInfo->isSystemPackage($packageName)) { - if ($packageName == static::EDITION_COMMUNITY) { - if ($this->composerInfo->isPackageInComposerJson($packageName)) { - $systemPackages[] = $packageName; - } - } else { - $systemPackages[] = $packageName; - } - } - } - if (empty($systemPackages)) { - throw new \RuntimeException( - 'We\'re sorry, no components are available because you cloned the Magento 2 GitHub repository. ' . - 'You must manually update components as discussed in the ' . - '<a href="https://devdocs.magento.com/guides/v2.3/install-gde/install/cli/dev_options.html">' . - 'Installation Guide</a>.' - ); - } - return $systemPackages; - } - - /** - * Sort versions. - * - * @param array $enterpriseVersions - * @return array - */ - public function sortVersions($enterpriseVersions) - { - usort( - $enterpriseVersions[InfoCommand::AVAILABLE_VERSIONS], - function ($versionOne, $versionTwo) { - if (version_compare($versionOne, $versionTwo, '==')) { - return 0; - } - return (version_compare($versionOne, $versionTwo, '<')) ? 1 : -1; - } - ); - - return $enterpriseVersions; - } - - /** - * Re-formats packages array to merge packages, sort versions and add technical data - * - * @param array $packages - * @return array - */ - private function formatPackages($packages) - { - $versions = []; - - foreach ($packages as $package) { - foreach ($package['versions'] as $version) { - $version['package'] = $package['package']; - - if (preg_match('/^[0-9].[0-9].[0-9]$/', $version['id']) || $version['current']) { - $version['stable'] = true; - } else { - $version['name'] = $version['name'] . ' (unstable version)'; - $version['stable'] = false; - } - - $versions[] = $version; - } - } - - usort( - $versions, - function ($versionOne, $versionTwo) { - if (version_compare($versionOne['id'], $versionTwo['id'], '==')) { - if ($versionOne['package'] === static::EDITION_COMMUNITY) { - return 1; - } - return 0; - } - return (version_compare($versionOne['id'], $versionTwo['id'], '<')) ? 1 : -1; - } - ); - - return $versions; - } - - /** - * Filter enterprise versions. - * - * @param string $currentCE - * @param array $enterpriseVersions - * @param string $maxVersion - * @return array - */ - public function filterEeVersions($currentCE, $enterpriseVersions, $maxVersion) - { - $eeVersions = []; - foreach ($enterpriseVersions[InfoCommand::AVAILABLE_VERSIONS] as $version) { - $requires = $this->composerInfo->getPackageRequirements(static::EDITION_ENTERPRISE, $version); - if (array_key_exists(static::EDITION_COMMUNITY, $requires)) { - /** @var \Composer\Package\Link $ceRequire */ - $ceRequire = $requires[static::EDITION_COMMUNITY]; - if (version_compare( - $ceRequire->getConstraint()->getPrettyString(), - $currentCE, - '>=' - )) { - $name = 'Version ' . $version . ' EE'; - if ($maxVersion == $version) { - $name .= ' (latest)'; - } - $eeVersions[] = ['id' => $version, 'name' => $name, 'current' => false]; - } - } - } - return $eeVersions; - } -} diff --git a/setup/src/Magento/Setup/Model/UninstallDependencyCheck.php b/setup/src/Magento/Setup/Model/UninstallDependencyCheck.php deleted file mode 100644 index 3a2b6fda44025..0000000000000 --- a/setup/src/Magento/Setup/Model/UninstallDependencyCheck.php +++ /dev/null @@ -1,128 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Model; - -use Magento\Framework\Composer\ComposerInformation; -use Magento\Framework\Composer\DependencyChecker; -use Magento\Framework\Exception\RuntimeException; -use Magento\Theme\Model\Theme\ThemeDependencyChecker; -use Magento\Framework\Escaper; -use Magento\Framework\App\ObjectManager; - -/** - * Class checks components dependencies for uninstall flow - */ -class UninstallDependencyCheck -{ - /** - * @var Escaper - */ - private $escaper; - - /** - * @var ComposerInformation - */ - private $composerInfo; - - /** - * @var DependencyChecker - */ - private $packageDependencyChecker; - - /** - * Theme Dependency Checker - * - * @var ThemeDependencyChecker - */ - private $themeDependencyChecker; - - /** - * Constructor - * - * @param ComposerInformation $composerInfo - * @param DependencyChecker $dependencyChecker - * @param ThemeDependencyCheckerFactory $themeDependencyCheckerFactory - * @param Escaper|null $escaper - */ - public function __construct( - ComposerInformation $composerInfo, - DependencyChecker $dependencyChecker, - ThemeDependencyCheckerFactory $themeDependencyCheckerFactory, - Escaper $escaper = null - ) { - $this->composerInfo = $composerInfo; - $this->packageDependencyChecker = $dependencyChecker; - $this->themeDependencyChecker = $themeDependencyCheckerFactory->create(); - $this->escaper = $escaper ?? ObjectManager::getInstance()->get( - Escaper::class - ); - } - - /** - * Run Composer dependency check for uninstall - * - * @param array $packages - * @return array - */ - public function runUninstallReadinessCheck(array $packages) - { - try { - return $this->checkForMissingDependencies($packages); - } catch (\RuntimeException $e) { - $message = str_replace(PHP_EOL, '<br/>', $this->escaper->escapeHtml($e->getMessage())); - return ['success' => false, 'error' => $message]; - } - } - - /** - * Check for missing dependencies - * - * @param array $packages - * @return array - * @throws \RuntimeException - */ - private function checkForMissingDependencies(array $packages) - { - $packagesAndTypes = $this->composerInfo->getRootRequiredPackageTypesByName(); - $dependencies = $this->packageDependencyChecker->checkDependencies($packages, true); - $messages = []; - $themes = []; - - foreach ($packages as $package) { - if (!isset($packagesAndTypes[$package])) { - throw new \RuntimeException('Package ' . $package . ' not found in the system.'); - } - - switch ($packagesAndTypes[$package]) { - case ComposerInformation::METAPACKAGE_PACKAGE_TYPE: - unset($dependencies[$package]); - break; - case ComposerInformation::THEME_PACKAGE_TYPE: - $themes[] = $package; - break; - } - - if (!empty($dependencies[$package])) { - $messages[] = $package . " has the following dependent package(s): " - . implode(', ', $dependencies[$package]); - } - } - - if (!empty($themes)) { - $messages = array_merge( - $messages, - $this->themeDependencyChecker->checkChildThemeByPackagesName($themes) - ); - } - - if (!empty($messages)) { - throw new \RuntimeException(implode(PHP_EOL, $messages)); - } - - return ['success' => true]; - } -} diff --git a/setup/src/Magento/Setup/Model/Updater.php b/setup/src/Magento/Setup/Model/Updater.php deleted file mode 100644 index d55d1eb77f457..0000000000000 --- a/setup/src/Magento/Setup/Model/Updater.php +++ /dev/null @@ -1,64 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Model; - -use Magento\Framework\Filesystem; -use Magento\Setup\Model\Cron\Queue; - -/** - * Class Updater passes information to the updater application - */ -class Updater -{ - /**#@+ - * Task types - */ - const TASK_TYPE_UPDATE = 'update'; - const TASK_TYPE_UNINSTALL = 'uninstall'; - const TASK_TYPE_MAINTENANCE_MODE = 'maintenance_mode'; - /**#@-*/ - - /**#@-*/ - private $queue; - - /** - * Constructor - * - * @param Queue $queue - */ - public function __construct(Queue $queue) - { - $this->queue = $queue; - } - - /** - * Create an update task for Updater app - * - * @param array $packages - * @param string $type - * @param array $additionalOptions - * @return string - */ - public function createUpdaterTask(array $packages, $type, array $additionalOptions = []) - { - try { - // write to .update_queue.json file - $params = []; - if (!empty($packages)) { - $params['components'] = $packages; - } - foreach ($additionalOptions as $key => $value) { - $params[$key] = $value; - } - - $this->queue->addJobs([['name' => $type, 'params' => $params]]); - return ''; - } catch (\Exception $e) { - return $e->getMessage(); - } - } -} diff --git a/setup/src/Magento/Setup/Model/UpdaterTaskCreator.php b/setup/src/Magento/Setup/Model/UpdaterTaskCreator.php deleted file mode 100644 index c80717fe7c857..0000000000000 --- a/setup/src/Magento/Setup/Model/UpdaterTaskCreator.php +++ /dev/null @@ -1,202 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Model; - -use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Setup\Model\Cron\JobComponentUninstall; -use Laminas\Json\Json; - -/** - * Validates payloads for updater tasks - */ -class UpdaterTaskCreator -{ - /**#@+ - * Keys in Post payload - */ - const KEY_POST_PACKAGE_NAME = 'name'; - const KEY_POST_PACKAGE_VERSION = 'version'; - const KEY_POST_JOB_TYPE = 'type'; - const KEY_POST_PACKAGES = 'packages'; - const KEY_POST_HEADER_TITLE = 'headerTitle'; - const KEY_POST_DATA_OPTION = 'dataOption'; - /**#@- */ - - /** - * @var \Magento\Framework\Filesystem - */ - private $filesystem; - - /** - * @var \Magento\Setup\Model\Navigation - */ - private $navigation; - - /** - * @var \Magento\Setup\Model\Updater - */ - private $updater; - - /** - * @var \Magento\Setup\Model\ObjectManagerProvider - */ - private $objectManagerProvider; - - /** - * @param \Magento\Framework\Filesystem $filesystem - * @param \Magento\Setup\Model\Navigation $navigation - * @param \Magento\Setup\Model\Updater $updater - * @param \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider - */ - public function __construct( - \Magento\Framework\Filesystem $filesystem, - \Magento\Setup\Model\Navigation $navigation, - \Magento\Setup\Model\Updater $updater, - \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider - ) { - $this->filesystem = $filesystem; - $this->navigation = $navigation; - $this->updater = $updater; - $this->objectManagerProvider = $objectManagerProvider; - } - - /** - * Create flag to be used in Updater - * - * @param string $type - * @param string $title - * @return void - */ - private function createTypeFlag($type, $title) - { - $data = []; - $data[self::KEY_POST_JOB_TYPE] = $type; - $data[self::KEY_POST_HEADER_TITLE] = $title; - - $menuItems = $this->navigation->getMenuItems(); - $titles = []; - foreach ($menuItems as $menuItem) { - if (isset($menuItem['type']) && $menuItem['type'] === $type) { - $titles[] = str_replace("\n", '<br />', $menuItem['title']); - } - } - $data['titles'] = $titles; - $directoryWrite = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_DIR); - $directoryWrite->writeFile('.type.json', Json::encode($data)); - } - - /** - * Create Update tasks - * - * @param array $postPayload - * @return string - */ - public function createUpdaterTasks(array $postPayload) - { - $errorMessage = ''; - $packages = $postPayload[self::KEY_POST_PACKAGES]; - $jobType = $postPayload[self::KEY_POST_JOB_TYPE]; - $this->createTypeFlag($jobType, $postPayload[self::KEY_POST_HEADER_TITLE]); - - $additionalOptions = []; - $cronTaskType = ''; - $this->getCronTaskConfigInfo($jobType, $postPayload, $additionalOptions, $cronTaskType); - - $errorMessage .= $this->updater->createUpdaterTask( - [], - \Magento\Setup\Model\Cron\JobFactory::JOB_MAINTENANCE_MODE_ENABLE - ); - - /** - * @var \Magento\Framework\App\Cache\Manager $cacheManager - */ - $cacheManager = $this->objectManagerProvider->get()->get(\Magento\Framework\App\Cache\Manager::class); - $cacheStatus = $cacheManager->getStatus(); - - $errorMessage .= $this->updater->createUpdaterTask( - [], - \Magento\Setup\Model\Cron\JobFactory::JOB_DISABLE_CACHE, - [] - ); - - $errorMessage .= $this->updater->createUpdaterTask( - $packages, - $cronTaskType, - $additionalOptions - ); - - // for module enable job types, we need to follow up with 'setup:upgrade' task to - // make sure enabled modules are properly registered - if ($jobType == 'enable') { - $errorMessage .= $this->updater->createUpdaterTask( - [], - \Magento\Setup\Model\Cron\JobFactory::JOB_UPGRADE, - [] - ); - } - - $enabledCaches = []; - foreach ($cacheStatus as $cacheName => $value) { - if ($value === 1) { - $enabledCaches[] = $cacheName; - } - } - - if (!empty($enabledCaches)) { - $errorMessage .= $this->updater->createUpdaterTask( - [], - \Magento\Setup\Model\Cron\JobFactory::JOB_ENABLE_CACHE, - [implode(' ', $enabledCaches)] - ); - } - - if ($jobType == 'disable') { - $errorMessage .= $this->updater->createUpdaterTask( - [], - \Magento\Setup\Model\Cron\JobFactory::JOB_MAINTENANCE_MODE_DISABLE - ); - } - - return $errorMessage; - } - - /** - * Returns cron config info based on passed in job type - * - * @param string $jobType - * @param array $postPayload - * @param array $additionalOptions - * @param string $cronTaskType - * @return void - */ - private function getCronTaskConfigInfo($jobType, $postPayload, &$additionalOptions, &$cronTaskType) - { - $additionalOptions = []; - switch ($jobType) { - case 'uninstall': - $additionalOptions = [ - JobComponentUninstall::DATA_OPTION => $postPayload[self::KEY_POST_DATA_OPTION] - ]; - $cronTaskType = \Magento\Setup\Model\Cron\JobFactory::JOB_COMPONENT_UNINSTALL; - break; - - case 'upgrade': - case 'update': - case 'install': - $cronTaskType = \Magento\Setup\Model\Updater::TASK_TYPE_UPDATE; - break; - - case 'enable': - $cronTaskType = \Magento\Setup\Model\Cron\JobFactory::JOB_MODULE_ENABLE; - break; - - case 'disable': - $cronTaskType = \Magento\Setup\Model\Cron\JobFactory::JOB_MODULE_DISABLE; - break; - } - } -} diff --git a/setup/src/Magento/Setup/Model/WebLogger.php b/setup/src/Magento/Setup/Model/WebLogger.php deleted file mode 100644 index 93ac7fa1d5f66..0000000000000 --- a/setup/src/Magento/Setup/Model/WebLogger.php +++ /dev/null @@ -1,162 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -namespace Magento\Setup\Model; - -use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Framework\Filesystem; -use Magento\Framework\Setup\LoggerInterface; - -/** - * Web UI Logger - * - * @package Magento\Setup\Model - */ -class WebLogger implements LoggerInterface -{ - /** - * Log File - * - * @var string - */ - protected $logFile = 'install.log'; - - /** - * Currently open file resource - * - * @var Filesystem - */ - protected $filesystem; - - /** - * Currently open file resource - * - * @var \Magento\Framework\Filesystem\Directory\WriteInterface - */ - protected $directory; - - /** - * Indicator of whether inline output is started - * - * @var bool - */ - private $isInline = false; - - /** - * Constructor - * @param Filesystem $filesystem - * @param string $logFile - */ - public function __construct(Filesystem $filesystem, $logFile = null) - { - $this->directory = $filesystem->getDirectoryWrite(DirectoryList::LOG); - if ($logFile) { - $this->logFile = $logFile; - } - } - - /** - * {@inheritdoc} - */ - public function logSuccess($message) - { - $this->terminateLine(); - $this->writeToFile('<span class="text-success">[SUCCESS] ' . $message . '</span><br>'); - } - - /** - * {@inheritdoc} - */ - public function logError(\Exception $e) - { - $this->terminateLine(); - $this->writeToFile('<span class="text-danger">[ERROR] ' . $e . '<span><br>'); - } - - /** - * {@inheritdoc} - */ - public function log($message) - { - $this->terminateLine(); - $this->writeToFile('<span class="text-info">' . $message . '</span><br>'); - } - - /** - * {@inheritdoc} - */ - public function logInline($message) - { - $this->isInline = true; - $this->writeToFile('<span class="text-info">' . $message . '</span>'); - } - - /** - * {@inheritdoc} - */ - public function logMeta($message) - { - $this->terminateLine(); - $this->writeToFile('<span class="hidden">' . $message . '</span><br>'); - } - - /** - * Write the message to file - * - * @param string $message - * @return void - */ - private function writeToFile($message) - { - $this->directory->writeFile($this->logFile, $message, 'a+'); - } - - /** - * Gets contents of the log - * - * @return array - */ - public function get() - { - $fileContents = explode(PHP_EOL, $this->directory->readFile($this->logFile)); - return $fileContents; - } - - /** - * Clears contents of the log - * - * @return void - */ - public function clear() - { - if ($this->directory->isExist($this->logFile)) { - $this->directory->delete($this->logFile); - } - } - - /** - * Checks existence of install.log file - * - * @return bool - */ - public function logfileExists() - { - return ($this->directory->isExist($this->logFile)); - } - - /** - * Terminates line if the inline logging is started - * - * @return void - */ - private function terminateLine() - { - if ($this->isInline) { - $this->isInline = false; - $this->writeToFile('<br>'); - } - } -} diff --git a/setup/src/Magento/Setup/Module.php b/setup/src/Magento/Setup/Module.php index 7808ead3808e3..f1fde437f0094 100644 --- a/setup/src/Magento/Setup/Module.php +++ b/setup/src/Magento/Setup/Module.php @@ -78,15 +78,7 @@ public function getConfig() include __DIR__ . '/../../../config/router.config.php', include __DIR__ . '/../../../config/di.config.php', include __DIR__ . '/../../../config/states.install.config.php', - include __DIR__ . '/../../../config/states.update.config.php', - include __DIR__ . '/../../../config/states.home.config.php', - include __DIR__ . '/../../../config/states.extensionManager.config.php', - include __DIR__ . '/../../../config/states.upgrade.config.php', - include __DIR__ . '/../../../config/states.uninstall.config.php', - include __DIR__ . '/../../../config/states.enable.config.php', - include __DIR__ . '/../../../config/states.disable.config.php', include __DIR__ . '/../../../config/languages.config.php', - include __DIR__ . '/../../../config/marketplace.config.php' ); // phpcs:enable return $result; diff --git a/setup/src/Magento/Setup/Mvc/Bootstrap/InitParamListener.php b/setup/src/Magento/Setup/Mvc/Bootstrap/InitParamListener.php index dc564c3a8f7c5..4c25753aa87ac 100644 --- a/setup/src/Magento/Setup/Mvc/Bootstrap/InitParamListener.php +++ b/setup/src/Magento/Setup/Mvc/Bootstrap/InitParamListener.php @@ -41,16 +41,6 @@ class InitParamListener implements ListenerAggregateInterface, FactoryInterface */ private $listeners = []; - /** - * List of controllers and their actions which should be skipped from auth check - * - * @var array - */ - private $controllersToSkip = [ - \Magento\Setup\Controller\Session::class => ['index', 'unlogin'], - \Magento\Setup\Controller\Success::class => ['index'] - ]; - /** * @inheritdoc * @@ -104,96 +94,6 @@ public function onBootstrap(MvcEvent $e) $serviceManager = $application->getServiceManager(); $serviceManager->setService(\Magento\Framework\App\Filesystem\DirectoryList::class, $directoryList); $serviceManager->setService(\Magento\Framework\Filesystem::class, $this->createFilesystem($directoryList)); - - if (!($application->getRequest() instanceof Request)) { - $eventManager = $application->getEventManager(); - $eventManager->attach(MvcEvent::EVENT_DISPATCH, [$this, 'authPreDispatch'], 100); - } - } - - /** - * Check if user logged-in and has permissions - * - * @param \Laminas\Mvc\MvcEvent $event - * @return false|\Laminas\Http\Response - * - * @throws \Magento\Framework\Exception\LocalizedException - * @throws \Magento\Setup\Exception - */ - public function authPreDispatch($event) - { - /** @var RouteMatch $routeMatch */ - $routeMatch = $event->getRouteMatch(); - $controller = $routeMatch->getParam('controller'); - $action = $routeMatch->getParam('action'); - - $skipCheck = array_key_exists($controller, $this->controllersToSkip) - && in_array($action, $this->controllersToSkip[$controller]); - - if (!$skipCheck) { - /** @var Application $application */ - $application = $event->getApplication(); - $serviceManager = $application->getServiceManager(); - - if ($serviceManager->get(\Magento\Framework\App\DeploymentConfig::class)->isAvailable()) { - /** @var \Magento\Setup\Model\ObjectManagerProvider $objectManagerProvider */ - $objectManagerProvider = $serviceManager->get(\Magento\Setup\Model\ObjectManagerProvider::class); - /** @var \Magento\Framework\ObjectManagerInterface $objectManager */ - $objectManager = $objectManagerProvider->get(); - /** @var \Magento\Framework\App\State $adminAppState */ - $adminAppState = $objectManager->get(\Magento\Framework\App\State::class); - $adminAppState->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML); - /** @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' => $sessionConfig, - 'appState' => $adminAppState - ] - ); - /** @var \Magento\Backend\Model\Auth $auth */ - $authentication = $objectManager->get(\Magento\Backend\Model\Auth::class); - - if (!$authentication->isLoggedIn() || - !$adminSession->isAllowed('Magento_Backend::setup_wizard') - ) { - $adminSession->destroy(); - /** @var \Laminas\Http\Response $response */ - $response = $event->getResponse(); - $baseUrl = Http::getDistroBaseUrlPath($_SERVER); - $response->getHeaders()->addHeaderLine('Location', $baseUrl . 'index.php/session/unlogin'); - $response->setStatusCode(302); - $event->stopPropagation(); - - return $response; - } - } - } - - 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\Url $url */ - $url = $objectManager->create(\Magento\Backend\Model\Url::class); - $baseUrl = parse_url($url->getBaseUrl(), PHP_URL_PATH); - $baseUrl = \Magento\Framework\App\Request\Http::getUrlNoScript($baseUrl); - $cookiePath = $baseUrl . $backendApp->getCookiePath(); - return $cookiePath; } /** diff --git a/setup/src/Magento/Setup/Test/Unit/Console/Command/CronRunCommandTest.php b/setup/src/Magento/Setup/Test/Unit/Console/Command/CronRunCommandTest.php deleted file mode 100644 index f771c4d4343e4..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Console/Command/CronRunCommandTest.php +++ /dev/null @@ -1,179 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Console\Command; - -use Magento\Framework\App\DeploymentConfig; -use Magento\Setup\Console\Command\CronRunCommand; -use Magento\Setup\Model\Cron\AbstractJob; -use Magento\Setup\Model\Cron\Queue; -use Magento\Setup\Model\Cron\ReadinessCheck; -use Magento\Setup\Model\Cron\Status; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Tester\CommandTester; - -class CronRunCommandTest extends TestCase -{ - /** - * @var MockObject|DeploymentConfig - */ - private $deploymentConfig; - - /** - * @var CronRunCommand - */ - private $command; - - /** - * @var CommandTester - */ - private $commandTester; - - /** - * @var MockObject|Queue - */ - private $queue; - - /** - * @var MockObject|ReadinessCheck - */ - private $readinessCheck; - - /** - * @var MockObject|Status - */ - private $status; - - protected function setUp(): void - { - $this->deploymentConfig = $this->createMock(DeploymentConfig::class); - $this->queue = $this->createMock(Queue::class); - $this->readinessCheck = $this->createMock(ReadinessCheck::class); - $this->status = $this->createMock(Status::class); - $this->command = new CronRunCommand( - $this->deploymentConfig, - $this->queue, - $this->readinessCheck, - $this->status - ); - $this->commandTester = new CommandTester($this->command); - } - - public function testExecuteNotInstalled() - { - $this->deploymentConfig->expects($this->once())->method('isAvailable')->willReturn(false); - $this->status->expects($this->once())->method($this->anything()); - $this->queue->expects($this->never())->method($this->anything()); - $this->readinessCheck->expects($this->never())->method($this->anything()); - $this->commandTester->execute([]); - } - - public function testExecuteFailedReadinessCheck() - { - $this->deploymentConfig->expects($this->once())->method('isAvailable')->willReturn(true); - $this->status->expects($this->never())->method($this->anything()); - $this->queue->expects($this->never())->method($this->anything()); - $this->readinessCheck->expects($this->once())->method('runReadinessCheck')->willReturn(false); - $this->commandTester->execute([]); - } - - public function testExecuteUpdateInProgress() - { - $this->deploymentConfig->expects($this->once())->method('isAvailable')->willReturn(true); - $this->queue->expects($this->never())->method($this->anything()); - $this->readinessCheck->expects($this->once())->method('runReadinessCheck')->willReturn(true); - $this->status->expects($this->once())->method('isUpdateInProgress')->willReturn(true); - $this->status->expects($this->never())->method('add'); - $this->status->expects($this->never())->method('isUpdateError'); - $this->commandTester->execute([]); - } - - public function testExecuteUpdateError() - { - $this->deploymentConfig->expects($this->once())->method('isAvailable')->willReturn(true); - $this->queue->expects($this->never())->method($this->anything()); - $this->readinessCheck->expects($this->once())->method('runReadinessCheck')->willReturn(true); - $this->status->expects($this->once())->method('isUpdateInProgress')->willReturn(false); - $this->status->expects($this->never())->method('add'); - $this->status->expects($this->once())->method('isUpdateError')->willReturn(true); - $this->commandTester->execute([]); - } - - public function testExecuteErrorOnToggleInProgress() - { - $this->deploymentConfig->expects($this->once())->method('isAvailable')->willReturn(true); - $this->queue->expects($this->never())->method($this->anything()); - $this->readinessCheck->expects($this->once())->method('runReadinessCheck')->willReturn(true); - $this->status->expects($this->once())->method('isUpdateInProgress')->willReturn(false); - $this->status->expects($this->once())->method('add')->with('runtime exception'); - $this->status->expects($this->once())->method('isUpdateError')->willReturn(false); - $this->status->expects($this->once()) - ->method('toggleUpdateInProgress') - ->willThrowException(new \RuntimeException('runtime exception')); - $this->commandTester->execute([]); - } - - public function setUpPreliminarySuccess() - { - $this->deploymentConfig->expects($this->once())->method('isAvailable')->willReturn(true); - $this->readinessCheck->expects($this->once())->method('runReadinessCheck')->willReturn(true); - $this->status->expects($this->once())->method('isUpdateInProgress')->willReturn(false); - $this->status->expects($this->once())->method('isUpdateError')->willReturn(false); - $this->status->expects($this->exactly(2))->method('toggleUpdateInProgress'); - } - - public function testExecuteNoJobInQueue() - { - $this->setUpPreliminarySuccess(); - $this->queue->expects($this->once())->method('peek')->willReturn([]); - $this->queue->expects($this->never())->method('popQueuedJob'); - $this->commandTester->execute([]); - } - - public function testExecuteFirstJobNotSupported() - { - $this->setUpPreliminarySuccess(); - $this->queue->expects($this->exactly(2))->method('peek')->willReturn(['name' => 'update']); - $this->queue->expects($this->never())->method('popQueuedJob'); - $this->commandTester->execute([]); - } - - public function testExecutePopQueueFails() - { - $this->setUpPreliminarySuccess(); - $this->queue->expects($this->exactly(2))->method('peek')->willReturn(['name' => 'setup:']); - $this->queue->expects($this->once())->method('popQueuedJob')->willThrowException(new \Exception('pop failed')); - $this->status->expects($this->once())->method('add')->with('pop failed'); - $this->status->expects($this->once())->method('toggleUpdateError')->with(true); - $this->commandTester->execute([]); - } - - public function testExecuteJobFailed() - { - $this->setUpPreliminarySuccess(); - $this->queue->expects($this->at(0))->method('peek')->willReturn(['name' => 'setup:']); - $this->queue->expects($this->at(1))->method('peek')->willReturn(['name' => 'setup:']); - $job = $this->getMockForAbstractClass(AbstractJob::class, [], '', false); - $job->expects($this->once())->method('execute')->willThrowException(new \Exception('job failed')); - $this->queue->expects($this->at(2))->method('popQueuedJob')->willReturn($job); - $this->status->expects($this->atLeastOnce())->method('toggleUpdateError')->with(true); - $this->commandTester->execute([]); - } - - public function testExecute() - { - $this->setUpPreliminarySuccess(); - $this->queue->expects($this->at(0))->method('peek')->willReturn(['name' => 'setup:']); - $this->queue->expects($this->at(1))->method('peek')->willReturn(['name' => 'setup:']); - $job = $this->getMockForAbstractClass(AbstractJob::class, [], '', false); - $job->expects($this->once())->method('execute'); - $this->queue->expects($this->at(2))->method('popQueuedJob')->willReturn($job); - $this->status->expects($this->never())->method('toggleUpdateError')->with(true); - $this->commandTester->execute([]); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/AddDatabaseTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/AddDatabaseTest.php deleted file mode 100644 index 87be70ebddca8..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/AddDatabaseTest.php +++ /dev/null @@ -1,24 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\ViewModel; -use Magento\Setup\Controller\AddDatabase; -use PHPUnit\Framework\TestCase; - -class AddDatabaseTest extends TestCase -{ - public function testIndexAction() - { - /** @var AddDatabase $controller */ - $controller = new AddDatabase(); - $viewModel = $controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/BackupActionItemsTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/BackupActionItemsTest.php deleted file mode 100644 index 8304ed5db9377..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/BackupActionItemsTest.php +++ /dev/null @@ -1,149 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\Http\PhpEnvironment\Request; -use Laminas\Http\PhpEnvironment\Response; -use Laminas\Mvc\MvcEvent; -use Laminas\Mvc\Router\RouteMatch; -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Framework\Backup\Filesystem; -use Magento\Framework\ObjectManagerInterface; -use Magento\Framework\Setup\BackupRollback; -use Magento\Setup\Controller\BackupActionItems; -use Magento\Setup\Controller\ResponseTypeInterface; -use Magento\Setup\Model\ObjectManagerProvider; -use Magento\Setup\Model\WebLogger; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class BackupActionItemsTest extends TestCase -{ - /** - * @var ObjectManagerProvider|MockObject - */ - private $objectManagerProvider; - - /** - * @var WebLogger|MockObject - */ - private $log; - - /** - * @var BackupRollback|MockObject - */ - private $backupRollback; - - /** - * @var DirectoryList|MockObject - */ - private $directoryList; - - /** - * @var Filesystem|MockObject - */ - private $filesystem; - - /** - * Controller - * - * @var BackupActionItems - */ - private $controller; - - protected function setUp(): void - { - $this->directoryList = - $this->createMock(DirectoryList::class); - $this->objectManagerProvider = - $this->createMock(ObjectManagerProvider::class); - $this->backupRollback = - $this->createPartialMock(BackupRollback::class, ['getDBDiskSpace', 'dbBackup']); - $objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $objectManager->expects($this->once())->method('create')->willReturn($this->backupRollback); - $this->objectManagerProvider->expects($this->once())->method('get')->willReturn($objectManager); - $this->log = $this->createMock(WebLogger::class); - $this->filesystem = $this->createMock(Filesystem::class); - - $this->controller = new BackupActionItems( - $this->objectManagerProvider, - $this->log, - $this->directoryList, - $this->filesystem - ); - - $request = $this->createMock(Request::class); - $response = $this->createMock(Response::class); - $routeMatch = $this->createMock(RouteMatch::class); - - $mvcEvent = $this->createMock(MvcEvent::class); - $mvcEvent->expects($this->any())->method('setRequest')->with($request)->willReturn($mvcEvent); - $mvcEvent->expects($this->any())->method('setResponse')->with($response)->willReturn($mvcEvent); - $mvcEvent->expects($this->any())->method('setTarget')->with($this->controller)->willReturn($mvcEvent); - $mvcEvent->expects($this->any())->method('getRouteMatch')->willReturn($routeMatch); - $mvcEvent->expects($this->any())->method('getName')->willReturn('dispatch'); - - $contentArray = '{"options":{"code":false,"media":false,"db":true}}'; - $request->expects($this->any())->method('getContent')->willReturn($contentArray); - - $this->controller->setEvent($mvcEvent); - $this->controller->dispatch($request, $response); - } - - public function testCheckAction() - { - $this->backupRollback->expects($this->once())->method('getDBDiskSpace')->willReturn(500); - $this->directoryList->expects($this->once())->method('getPath')->willReturn(__DIR__); - $this->filesystem->expects($this->once())->method('validateAvailableDiscSpace'); - $jsonModel = $this->controller->checkAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('responseType', $variables); - $this->assertEquals(ResponseTypeInterface::RESPONSE_TYPE_SUCCESS, $variables['responseType']); - $this->assertArrayHasKey('size', $variables); - $this->assertTrue($variables['size']); - } - - public function testCheckActionWithError() - { - $this->directoryList->expects($this->once())->method('getPath')->willReturn(__DIR__); - $this->filesystem->expects($this->once())->method('validateAvailableDiscSpace')->willThrowException( - new \Exception("Test error message") - ); - $jsonModel = $this->controller->checkAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('responseType', $variables); - $this->assertEquals(ResponseTypeInterface::RESPONSE_TYPE_ERROR, $variables['responseType']); - $this->assertArrayHasKey('error', $variables); - $this->assertEquals("Test error message", $variables['error']); - } - - public function testCreateAction() - { - $this->backupRollback->expects($this->once())->method('dbBackup')->willReturn('backup/path/'); - $jsonModel = $this->controller->createAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('responseType', $variables); - $this->assertEquals(ResponseTypeInterface::RESPONSE_TYPE_SUCCESS, $variables['responseType']); - $this->assertArrayHasKey('files', $variables); - $this->assertEquals(['backup/path/'], $variables['files']); - } - - public function testIndexAction() - { - $model = $this->controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $model); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/CompleteBackupTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/CompleteBackupTest.php deleted file mode 100644 index d296fef5f73b5..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/CompleteBackupTest.php +++ /dev/null @@ -1,47 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\Http\Response; -use Laminas\View\Model\ViewModel; -use Magento\Setup\Controller\CompleteBackup; -use PHPUnit\Framework\TestCase; - -class CompleteBackupTest extends TestCase -{ - /** - * Controller - * - * @var CompleteBackup - */ - private $controller; - - protected function setUp(): void - { - $this->controller = new CompleteBackup(); - } - - public function testIndexAction() - { - $viewModel = $this->controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertSame('/error/404.phtml', $viewModel->getTemplate()); - $this->assertSame( - Response::STATUS_CODE_404, - $this->controller->getResponse()->getStatusCode() - ); - } - - public function testProgressAction() - { - $viewModel = $this->controller->progressAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - $this->assertSame('/magento/setup/complete-backup/progress.phtml', $viewModel->getTemplate()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/ConfigureCatalogSearchTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/ConfigureCatalogSearchTest.php deleted file mode 100644 index 82eef828c4d87..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/ConfigureCatalogSearchTest.php +++ /dev/null @@ -1,64 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Setup\Controller\ConfigureCatalogSearch; -use Magento\Setup\Model\SearchConfigOptionsList; -use PHPUnit\Framework\TestCase; - -class ConfigureCatalogSearchTest extends TestCase -{ - /** - * @var ConfigureCatalogSearch - */ - private $controller; - - /** - * @var SearchConfigOptionsList - */ - private $searchConfigOptionsList; - - protected function setup(): void - { - $this->searchConfigOptionsList = new SearchConfigOptionsList(); - $this->controller = new ConfigureCatalogSearch($this->searchConfigOptionsList); - } - - public function testIndexAction() - { - $viewModel = $this->controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertNotEmpty($viewModel->getVariables()); - $expectedAvailableSearchEngines = [ - 'elasticsearch5' => 'Elasticsearch 5.x (deprecated)', - 'elasticsearch6' => 'Elasticsearch 6.x', - 'elasticsearch7' => 'Elasticsearch 7.x', - ]; - $this->assertEquals($expectedAvailableSearchEngines, $viewModel->getVariable('availableSearchEngines')); - } - - public function testDefaultParametersAction() - { - $jsonModel = $this->controller->defaultParametersAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - - $expectedDefaultParameters = [ - 'engine' => 'elasticsearch7', - 'elasticsearch' => [ - 'hostname' => 'localhost', - 'port' => '9200', - 'timeout' => '15', - 'indexPrefix' => 'magento2', - 'enableAuth' => false - ] - ]; - $this->assertEquals($expectedDefaultParameters, $jsonModel->getVariables()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/CreateAdminAccountTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/CreateAdminAccountTest.php deleted file mode 100644 index 57b2a2f3203ac..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/CreateAdminAccountTest.php +++ /dev/null @@ -1,23 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\ViewModel; -use Magento\Setup\Controller\CreateAdminAccount; -use PHPUnit\Framework\TestCase; - -class CreateAdminAccountTest extends TestCase -{ - public function testIndexAction() - { - $controller = new CreateAdminAccount(); - $viewModel = $controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/CreateBackupTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/CreateBackupTest.php deleted file mode 100644 index 0dd0c314efc59..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/CreateBackupTest.php +++ /dev/null @@ -1,24 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\ViewModel; -use Magento\Setup\Controller\CreateBackup; -use PHPUnit\Framework\TestCase; - -class CreateBackupTest extends TestCase -{ - public function testIndexAction() - { - /** @var CreateBackup $controller */ - $controller = new CreateBackup(); - $viewModel = $controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/CustomizeYourStoreTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/CustomizeYourStoreTest.php deleted file mode 100644 index fcef7bde2b727..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/CustomizeYourStoreTest.php +++ /dev/null @@ -1,125 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\Module\FullModuleList; -use Magento\Framework\Setup\Lists; -use Magento\Framework\Setup\SampleData\State; -use Magento\Setup\Controller\CustomizeYourStore; -use Magento\Setup\Model\ObjectManagerProvider; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class CustomizeYourStoreTest extends TestCase -{ - /** - * @var CustomizeYourStore - */ - private $controller; - - /** - * @var MockObject|State - */ - private $sampleDataState; - - /** - * @var MockObject|Lists - */ - private $lists; - - /** - * @var MockObject|ObjectManager - */ - private $objectManager; - - /** - * @var MockObject|FullModuleList - */ - private $moduleList; - - protected function setup(): void - { - $objectManagerProvider = $this->createMock(ObjectManagerProvider::class); - $this->objectManager = $this->createMock(ObjectManager::class); - $objectManagerProvider->expects($this->any())->method('get')->willReturn($this->objectManager); - $this->sampleDataState = $this->createMock(State::class); - $this->lists = $this->createMock(Lists::class); - $this->moduleList = $this->createMock(FullModuleList::class); - $this->controller = new CustomizeYourStore($this->moduleList, $this->lists, $objectManagerProvider); - } - - /** - * @param array $expected - * @param $withSampleData - * - * @dataProvider indexActionDataProvider - */ - public function testIndexAction($expected, $withSampleData) - { - if ($withSampleData) { - $this->moduleList->expects($this->once())->method('has')->willReturn(true); - $this->objectManager->expects($this->once())->method('get')->willReturn($this->sampleDataState); - $this->sampleDataState->expects($this->once())->method('isInstalled') - ->willReturn($expected['isSampleDataInstalled']); - $this->sampleDataState->expects($this->once())->method('hasError') - ->willReturn($expected['isSampleDataErrorInstallation']); - } else { - $this->moduleList->expects($this->once())->method('has')->willReturn(false); - $this->objectManager->expects($this->never())->method('get'); - } - $this->lists->expects($this->once())->method('getTimezoneList')->willReturn($expected['timezone']); - $this->lists->expects($this->once())->method('getCurrencyList')->willReturn($expected['currency']); - $this->lists->expects($this->once())->method('getLocaleList')->willReturn($expected['language']); - - $viewModel = $this->controller->indexAction(); - - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - - $variables = $viewModel->getVariables(); - $this->assertArrayHasKey('timezone', $variables); - $this->assertArrayHasKey('currency', $variables); - $this->assertArrayHasKey('language', $variables); - $this->assertSame($expected, $variables); - } - - /** - * @return array - */ - public function indexActionDataProvider() - { - $timezones = ['timezone' => ['America/New_York'=>'EST', 'America/Chicago' => 'CST']]; - $currency = ['currency' => ['USD'=>'US Dollar', 'EUR' => 'Euro']]; - $language = ['language' => ['en_US'=>'English (USA)', 'en_UK' => 'English (UK)']]; - $sampleData = [ - 'isSampleDataInstalled' => false, - 'isSampleDataErrorInstallation' => false - ]; - - return [ - 'with_all_data' => [array_merge($timezones, $currency, $language, $sampleData), true], - 'no_currency_data' => [array_merge($timezones, ['currency' => null], $language, $sampleData), true], - 'no_timezone_data' => [array_merge(['timezone' => null], $currency, $language, $sampleData), true], - 'no_language_data' => [array_merge($timezones, $currency, ['language' => null], $sampleData), true], - 'empty_currency_data' => [array_merge($timezones, ['currency' => []], $language, $sampleData), true], - 'empty_timezone_data' => [array_merge(['timezone' => []], $currency, $language, $sampleData), true], - 'empty_language_data' => [array_merge($timezones, $currency, ['language' => []], $sampleData), true], - 'no_sample_data' => [array_merge($timezones, $currency, $language, $sampleData), false], - ]; - } - - public function testDefaultTimeZoneAction() - { - $jsonModel = $this->controller->defaultTimeZoneAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $this->assertArrayHasKey('defaultTimeZone', $jsonModel->getVariables()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/DataOptionTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/DataOptionTest.php deleted file mode 100644 index 3eb1b36ff01ef..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/DataOptionTest.php +++ /dev/null @@ -1,121 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\Http\PhpEnvironment\Request; -use Laminas\Http\PhpEnvironment\Response; -use Laminas\Mvc\MvcEvent; -use Laminas\Mvc\Router\RouteMatch; -use Laminas\View\Model\ViewModel; -use Magento\Setup\Controller\DataOption; -use Magento\Setup\Model\UninstallCollector; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class DataOptionTest extends TestCase -{ - /** - * @var MockObject|UninstallCollector - */ - private $uninstallCollector; - - /** - * @var MockObject|Request - */ - private $request; - - /** - * @var MockObject|Response - */ - private $response; - - /** - * @var MvcEvent|MockObject - */ - private $mvcEvent; - - /** - * @var DataOption - */ - private $controller; - - protected function setUp(): void - { - $this->request = $this->createMock(Request::class); - $this->response = $this->createMock(Response::class); - $routeMatch = $this->createMock(RouteMatch::class); - - $this->uninstallCollector = $this->createMock(UninstallCollector::class); - $this->controller = new DataOption($this->uninstallCollector); - - $this->mvcEvent = $this->createMock(MvcEvent::class); - $this->mvcEvent->expects($this->any()) - ->method('setRequest') - ->with($this->request) - ->willReturn($this->mvcEvent); - $this->mvcEvent->expects($this->any()) - ->method('setResponse') - ->with($this->response) - ->willReturn($this->mvcEvent); - $this->mvcEvent->expects($this->any()) - ->method('setTarget') - ->with($this->controller) - ->willReturn($this->mvcEvent); - $this->mvcEvent->expects($this->any())->method('getRouteMatch')->willReturn($routeMatch); - $this->mvcEvent->expects($this->any())->method('getName')->willReturn('dispatch'); - } - - public function testIndexAction() - { - $viewModel = $this->controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - } - - public function testNoHasUninstallAction() - { - $this->request->expects($this->any())->method('getContent')->willReturn('{}'); - $this->controller->setEvent($this->mvcEvent); - $this->controller->dispatch($this->request, $this->response); - $this->uninstallCollector->expects($this->never())->method('collectUninstall')->with(["some_module"]); - $this->assertFalse($this->controller->hasUninstallAction()->getVariable("hasUninstall")); - } - - /** - * @param string $content - * @param array $expected - * @param bool $result - * @dataProvider hasUninstallActionDataProvider - */ - public function testHasUninstallAction($content, $expected, $result) - { - $this->request->expects($this->any())->method('getContent')->willReturn($content); - $this->controller->setEvent($this->mvcEvent); - $this->controller->dispatch($this->request, $this->response); - - $this->uninstallCollector - ->expects($this->once()) - ->method('collectUninstall') - ->with(["some_module"]) - ->willReturn($expected); - - $this->assertSame($result, $this->controller->hasUninstallAction()->getVariable("hasUninstall")); - } - - /** - * @return array - */ - public function hasUninstallActionDataProvider() - { - $content = '{"moduleName": "some_module"}'; - return [ - 'module has uninstall class' => [$content, ['module'], true], - 'module does not have uninstall class' => [$content, [], false], - ]; - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/EnvironmentTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/EnvironmentTest.php deleted file mode 100644 index 57cd1941f1476..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/EnvironmentTest.php +++ /dev/null @@ -1,330 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\Http\PhpEnvironment\Request; -use Laminas\Http\PhpEnvironment\Response; -use Laminas\Mvc\MvcEvent; -use Laminas\Mvc\Router\RouteMatch; -use Laminas\View\Model\JsonModel; -use Magento\Framework\Filesystem; -use Magento\Framework\Filesystem\Directory\ReadInterface; -use Magento\Framework\Setup\FilePermissions; -use Magento\Setup\Controller\Environment; -use Magento\Setup\Controller\ReadinessCheckInstaller; -use Magento\Setup\Controller\ReadinessCheckUpdater; -use Magento\Setup\Controller\ResponseTypeInterface; -use Magento\Setup\Model\CronScriptReadinessCheck; -use Magento\Setup\Model\PhpReadinessCheck; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class EnvironmentTest extends TestCase -{ - /** - * @var FilePermissions|MockObject - */ - private $permissions; - - /** - * @var Filesystem|MockObject - */ - private $filesystem; - - /** - * @var CronScriptReadinessCheck|MockObject - */ - private $cronScriptReadinessCheck; - - /** - * @var PhpReadinessCheck|MockObject - */ - private $phpReadinessCheck; - - /** - * @var Environment - */ - private $environment; - - protected function setUp(): void - { - $this->filesystem = $this->createMock(Filesystem::class); - $this->permissions = $this->createMock(FilePermissions::class); - $this->cronScriptReadinessCheck = $this->createMock(CronScriptReadinessCheck::class); - $this->phpReadinessCheck = $this->createMock(PhpReadinessCheck::class); - $this->environment = new Environment( - $this->permissions, - $this->filesystem, - $this->cronScriptReadinessCheck, - $this->phpReadinessCheck - ); - } - - public function testFilePermissionsInstaller() - { - $request = $this->createMock(Request::class); - $response = $this->createMock(Response::class); - $routeMatch = $this->createMock(RouteMatch::class); - - $mvcEvent = $this->getMvcEventMock($request, $response, $routeMatch); - - $this->permissions->expects($this->once())->method('getMissingWritablePathsForInstallation'); - $this->environment->setEvent($mvcEvent); - $this->environment->dispatch($request, $response); - $this->environment->filePermissionsAction(); - } - - public function testPhpVersionActionInstaller() - { - $request = $this->createMock(Request::class); - $response = $this->createMock(Response::class); - $routeMatch = $this->createMock(RouteMatch::class); - - $mvcEvent = $this->getMvcEventMock($request, $response, $routeMatch); - - $request->expects($this->once())->method('getQuery')->willReturn(ReadinessCheckInstaller::INSTALLER); - $this->phpReadinessCheck->expects($this->once())->method('checkPhpVersion'); - $this->environment->setEvent($mvcEvent); - $this->environment->dispatch($request, $response); - $this->environment->phpVersionAction(); - } - - public function testPhpVersionActionUpdater() - { - $request = $this->createMock(Request::class); - $response = $this->createMock(Response::class); - $routeMatch = $this->createMock(RouteMatch::class); - - $mvcEvent = $this->getMvcEventMock($request, $response, $routeMatch); - - $request->expects($this->once())->method('getQuery')->willReturn(ReadinessCheckUpdater::UPDATER); - $this->phpReadinessCheck->expects($this->never())->method('checkPhpVersion'); - $read = - $this->getMockForAbstractClass(ReadInterface::class, [], '', false); - $this->filesystem->expects($this->once())->method('getDirectoryRead')->willReturn($read); - $read->expects($this->once()) - ->method('readFile') - ->willReturn(''); - $this->environment->setEvent($mvcEvent); - $this->environment->dispatch($request, $response); - $this->environment->phpVersionAction(); - } - - public function testPhpSettingsActionInstaller() - { - $request = $this->createMock(Request::class); - $response = $this->createMock(Response::class); - $routeMatch = $this->createMock(RouteMatch::class); - - $mvcEvent = $this->getMvcEventMock($request, $response, $routeMatch); - - $request->expects($this->once())->method('getQuery')->willReturn(ReadinessCheckInstaller::INSTALLER); - $this->phpReadinessCheck->expects($this->once())->method('checkPhpSettings'); - $this->environment->setEvent($mvcEvent); - $this->environment->dispatch($request, $response); - $this->environment->phpSettingsAction(); - } - - public function testPhpSettingsActionUpdater() - { - $request = $this->createMock(Request::class); - $response = $this->createMock(Response::class); - $routeMatch = $this->createMock(RouteMatch::class); - - $mvcEvent = $this->getMvcEventMock($request, $response, $routeMatch); - - $request->expects($this->once())->method('getQuery')->willReturn(ReadinessCheckUpdater::UPDATER); - $this->phpReadinessCheck->expects($this->never())->method('checkPhpSettings'); - $read = - $this->getMockForAbstractClass(ReadInterface::class, [], '', false); - $this->filesystem->expects($this->once())->method('getDirectoryRead')->willReturn($read); - $read->expects($this->once()) - ->method('readFile') - ->willReturn(''); - $this->environment->setEvent($mvcEvent); - $this->environment->dispatch($request, $response); - $this->environment->phpSettingsAction(); - } - - public function testPhpExtensionsActionInstaller() - { - $request = $this->createMock(Request::class); - $response = $this->createMock(Response::class); - $routeMatch = $this->createMock(RouteMatch::class); - - $mvcEvent = $this->getMvcEventMock($request, $response, $routeMatch); - - $request->expects($this->once())->method('getQuery')->willReturn(ReadinessCheckInstaller::INSTALLER); - $this->phpReadinessCheck->expects($this->once())->method('checkPhpExtensions'); - $this->environment->setEvent($mvcEvent); - $this->environment->dispatch($request, $response); - $this->environment->phpExtensionsAction(); - } - - public function testPhpExtensionsActionUpdater() - { - $request = $this->createMock(Request::class); - $response = $this->createMock(Response::class); - $routeMatch = $this->createMock(RouteMatch::class); - - $mvcEvent = $this->getMvcEventMock($request, $response, $routeMatch); - - $request->expects($this->once())->method('getQuery')->willReturn(ReadinessCheckUpdater::UPDATER); - $this->phpReadinessCheck->expects($this->never())->method('checkPhpExtensions'); - $read = - $this->getMockForAbstractClass(ReadInterface::class, [], '', false); - $this->filesystem->expects($this->once())->method('getDirectoryRead')->willReturn($read); - $read->expects($this->once()) - ->method('readFile') - ->willReturn(''); - $this->environment->setEvent($mvcEvent); - $this->environment->dispatch($request, $response); - $this->environment->phpExtensionsAction(); - } - - public function testCronScriptAction() - { - $this->cronScriptReadinessCheck->expects($this->once())->method('checkSetup')->willReturn(['success' => true]); - $this->cronScriptReadinessCheck->expects($this->once()) - ->method('checkUpdater') - ->willReturn(['success' => true]); - $expected = new JsonModel(['responseType' => ResponseTypeInterface::RESPONSE_TYPE_SUCCESS]); - $this->assertEquals($expected, $this->environment->cronScriptAction()); - } - - public function testCronScriptActionSetupFailed() - { - $this->cronScriptReadinessCheck->expects($this->once()) - ->method('checkSetup') - ->willReturn(['success' => false, 'error' => 'error message setup']); - $this->cronScriptReadinessCheck->expects($this->once()) - ->method('checkUpdater') - ->willReturn(['success' => true]); - $expected = new JsonModel( - [ - 'responseType' => ResponseTypeInterface::RESPONSE_TYPE_ERROR, - 'setupErrorMessage' => 'Error from Setup Application Cron Script:<br/>error message setup' - ] - ); - $this->assertEquals($expected, $this->environment->cronScriptAction()); - } - - public function testCronScriptActionUpdaterFailed() - { - $this->cronScriptReadinessCheck->expects($this->once())->method('checkSetup')->willReturn(['success' => true]); - $this->cronScriptReadinessCheck->expects($this->once()) - ->method('checkUpdater') - ->willReturn(['success' => false, 'error' => 'error message updater']); - $expected = new JsonModel( - [ - 'responseType' => ResponseTypeInterface::RESPONSE_TYPE_ERROR, - 'updaterErrorMessage' => 'Error from Updater Application Cron Script:<br/>error message updater' - ] - ); - $this->assertEquals($expected, $this->environment->cronScriptAction()); - } - - public function testCronScriptActionBothFailed() - { - $this->cronScriptReadinessCheck->expects($this->once()) - ->method('checkSetup') - ->willReturn(['success' => false, 'error' => 'error message setup']); - $this->cronScriptReadinessCheck->expects($this->once()) - ->method('checkUpdater') - ->willReturn(['success' => false, 'error' => 'error message updater']); - $expected = new JsonModel( - [ - 'responseType' => ResponseTypeInterface::RESPONSE_TYPE_ERROR, - 'setupErrorMessage' => 'Error from Setup Application Cron Script:<br/>error message setup', - 'updaterErrorMessage' => 'Error from Updater Application Cron Script:<br/>error message updater', - ] - ); - $this->assertEquals($expected, $this->environment->cronScriptAction()); - } - - public function testCronScriptActionSetupNotice() - { - $this->cronScriptReadinessCheck->expects($this->once()) - ->method('checkSetup') - ->willReturn(['success' => true, 'notice' => 'notice setup']); - $this->cronScriptReadinessCheck->expects($this->once()) - ->method('checkUpdater') - ->willReturn(['success' => true]); - $expected = new JsonModel( - [ - 'responseType' => ResponseTypeInterface::RESPONSE_TYPE_SUCCESS, - 'setupNoticeMessage' => 'Notice from Setup Application Cron Script:<br/>notice setup' - ] - ); - $this->assertEquals($expected, $this->environment->cronScriptAction()); - } - - public function testCronScriptActionUpdaterNotice() - { - $this->cronScriptReadinessCheck->expects($this->once())->method('checkSetup')->willReturn(['success' => true]); - $this->cronScriptReadinessCheck->expects($this->once()) - ->method('checkUpdater') - ->willReturn(['success' => true, 'notice' => 'notice updater']); - $expected = new JsonModel( - [ - 'responseType' => ResponseTypeInterface::RESPONSE_TYPE_SUCCESS, - 'updaterNoticeMessage' => 'Notice from Updater Application Cron Script:<br/>notice updater' - ] - ); - $this->assertEquals($expected, $this->environment->cronScriptAction()); - } - - public function testCronScriptActionBothNotice() - { - $this->cronScriptReadinessCheck->expects($this->once()) - ->method('checkSetup') - ->willReturn(['success' => true, 'notice' => 'notice setup']); - $this->cronScriptReadinessCheck->expects($this->once()) - ->method('checkUpdater') - ->willReturn(['success' => true, 'notice' => 'notice updater']); - $expected = new JsonModel( - [ - 'responseType' => ResponseTypeInterface::RESPONSE_TYPE_SUCCESS, - 'setupNoticeMessage' => 'Notice from Setup Application Cron Script:<br/>notice setup', - 'updaterNoticeMessage' => 'Notice from Updater Application Cron Script:<br/>notice updater' - ] - ); - $this->assertEquals($expected, $this->environment->cronScriptAction()); - } - - public function testIndexAction() - { - $model = $this->environment->indexAction(); - $this->assertInstanceOf(JsonModel::class, $model); - } - - /** - * @param MockObject $request - * @param MockObject $response - * @param MockObject $routeMatch - * - * @return MockObject - */ - protected function getMvcEventMock( - MockObject $request, - MockObject $response, - MockObject $routeMatch - ) { - $mvcEvent = $this->createMock(MvcEvent::class); - $mvcEvent->expects($this->once())->method('setRequest')->with($request)->willReturn($mvcEvent); - $mvcEvent->expects($this->once())->method('setResponse')->with($response)->willReturn($mvcEvent); - $mvcEvent->expects($this->once())->method('setTarget')->with($this->environment)->willReturn($mvcEvent); - $mvcEvent->expects($this->any())->method('getRouteMatch')->willReturn($routeMatch); - $mvcEvent->expects($this->any())->method('getName')->willReturn('dispatch'); - - return $mvcEvent; - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/ExtensionGridTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/ExtensionGridTest.php deleted file mode 100644 index 6859c29e1451e..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/ExtensionGridTest.php +++ /dev/null @@ -1,158 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Magento\Setup\Controller\ExtensionGrid; -use Magento\Setup\Model\Grid\Extension; -use Magento\Setup\Model\PackagesAuth; -use Magento\Setup\Model\PackagesData; -use PHPUnit\Framework\MockObject\MockObject; - -/** - * Test for \Magento\Setup\Controller\ExtensionGrid - */ -class ExtensionGridTest extends \PHPUnit\Framework\TestCase -{ - /** - * @var Extension|MockObject - */ - private $gridExtensionMock; - - /** - * Controller - * - * @var ExtensionGrid - */ - private $controller; - - /** - * @var PackagesData|MockObject - */ - private $packagesDataMock; - - /** - * @var PackagesAuth|MockObject - */ - private $packagesAuthMock; - - /** - * @var array - */ - private $extensionData = []; - - /** - * @var array - */ - private $lastSyncData = []; - - /**#@+ - * Formatted date and time to return from mock - */ - const FORMATTED_DATE = 'Jan 15 1980'; - const FORMATTED_TIME = '01:55PM'; - /**#@-*/ - - protected function setUp(): void - { - $this->lastSyncData = [ - "lastSyncDate" => [ - 'date' => self::FORMATTED_DATE, - 'time' => self::FORMATTED_TIME, - ], - "packages" => [ - 'magento/sample-module-one' => [ - 'name' => 'magento/sample-module-one', - 'type' => 'magento2-module', - 'version' => '1.0.0' - ] - ], - 'countOfInstall' => 0, - 'countOfUpdate' => 1 - ]; - $this->extensionData = [ - [ - 'name' => 'magento/sample-module-one', - 'type' => 'magento2-module', - 'version' => '1.0.0', - 'update' => false, - 'uninstall' => true, - 'vendor' => 'magento', - ] - ]; - - $this->packagesDataMock = $this->createMock(PackagesData::class); - $this->packagesAuthMock = $this->createMock(PackagesAuth::class); - $this->gridExtensionMock = $this->createMock(Extension::class); - - $this->controller = new ExtensionGrid( - $this->packagesDataMock, - $this->packagesAuthMock, - $this->gridExtensionMock - ); - } - - public function testIndexAction() - { - $viewModel = $this->controller->indexAction(); - $this->assertInstanceOf(\Laminas\View\Model\ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - } - - public function testExtensionsAction() - { - $this->gridExtensionMock->expects($this->once()) - ->method('getList') - ->willReturn($this->extensionData); - $this->packagesDataMock->expects($this->once()) - ->method('syncPackagesData') - ->willReturn($this->lastSyncData); - $this->packagesAuthMock->expects($this->once()) - ->method('getAuthJsonData') - ->willReturn( - [ - 'username' => 'someusername', - 'password' => 'somepassword' - ] - ); - - $jsonModel = $this->controller->extensionsAction(); - $this->assertInstanceOf(\Laminas\View\Model\JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertTrue($variables['success']); - $this->assertEquals($this->extensionData, $variables['extensions']); - $this->assertArrayHasKey('total', $variables); - $this->assertEquals(1, $variables['total']); - $this->assertEquals($this->lastSyncData, $variables['lastSyncData']); - } - - public function testSyncAction() - { - $authDataJson = ['username' => 'admin', 'password' => '12345']; - - $this->packagesDataMock->expects($this->once()) - ->method('syncPackagesData') - ->willReturn($this->lastSyncData); - $this->packagesAuthMock->expects($this->once()) - ->method('getAuthJsonData') - ->willReturn($authDataJson); - $this->packagesAuthMock->expects($this->once()) - ->method('checkCredentials') - ->with( - $authDataJson['username'], - $authDataJson['password'] - ); - - $jsonModel = $this->controller->syncAction(); - $this->assertInstanceOf(\Laminas\View\Model\JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertTrue($variables['success']); - $this->assertEquals($this->lastSyncData, $variables['lastSyncData']); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/InstallExtensionGridTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/InstallExtensionGridTest.php deleted file mode 100644 index 373546420920c..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/InstallExtensionGridTest.php +++ /dev/null @@ -1,105 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Framework\Composer\ComposerInformation; -use Magento\Setup\Controller\InstallExtensionGrid; -use Magento\Setup\Model\PackagesData; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class InstallExtensionGridTest extends TestCase -{ - /** - * Controller - * - * @var InstallExtensionGrid - */ - private $controller; - - /** - * @var PackagesData|MockObject - */ - private $packagesData; - - protected function setUp(): void - { - $this->packagesData = $this->getMockBuilder(PackagesData::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->controller = new InstallExtensionGrid( - $this->packagesData - ); - } - - /** - * @covers \Magento\Setup\Controller\InstallExtensionGrid::indexAction - */ - public function testIndexAction() - { - $viewModel = $this->controller->indexAction(); - static::assertInstanceOf(ViewModel::class, $viewModel); - } - - /** - * @param array $extensions - * @dataProvider dataProviderForTestExtensionsAction - * @covers \Magento\Setup\Controller\InstallExtensionGrid::extensionsAction - */ - public function testExtensionsAction($extensions) - { - $this->packagesData->expects(static::once()) - ->method('getPackagesForInstall') - ->willReturn($extensions); - - $jsonModel = $this->controller->extensionsAction(); - static::assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - static::assertArrayHasKey('success', $variables); - static::assertArrayHasKey('extensions', $variables); - static::assertArrayHasKey('total', $variables); - static::assertTrue($variables['success']); - } - - /** - * @return array - */ - public function dataProviderForTestExtensionsAction() - { - $extensions['packages'] = [ - 'magento/testing-extension' => [ - 'name' => 'magento/testing-extension', - 'type' => ComposerInformation::MODULE_PACKAGE_TYPE, - 'vendor' => 'magento', - 'version' => '2.2.2', - 'author' => 'magento'], - 'magento/my-first-module' => [ - 'name' => 'magento/my-first-module', - 'type' => ComposerInformation::MODULE_PACKAGE_TYPE, - 'vendor' => 'magento', - 'version' => '2.0.0', - 'author' => 'magento'], - 'magento/last-extension' => [ - 'name' => 'magento/theme', - 'type' => ComposerInformation::THEME_PACKAGE_TYPE, - 'vendor' => 'magento', - 'version' => '2.1.1', - 'author' => 'magento'], - 'magento/magento-second-module' => [ - 'name' => 'magento/magento-second-module', - 'type' => ComposerInformation::COMPONENT_PACKAGE_TYPE, - 'vendor' => 'magento', - 'version' => '2.0.0', - 'author' => 'magento'] - ]; - return [[$extensions]]; - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/InstallTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/InstallTest.php deleted file mode 100644 index 457a9ba4366a9..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/InstallTest.php +++ /dev/null @@ -1,255 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\Http\PhpEnvironment\Request; -use Laminas\Http\PhpEnvironment\Response; -use Laminas\Mvc\MvcEvent; -use Laminas\Mvc\Router\RouteMatch; -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Framework\App\DeploymentConfig; -use Magento\Framework\Setup\SampleData\State; -use Magento\Setup\Controller\Install; -use Magento\Setup\Model\Installer; -use Magento\Setup\Model\Installer\Progress; -use Magento\Setup\Model\Installer\ProgressFactory; -use Magento\Setup\Model\InstallerFactory; -use Magento\Setup\Model\RequestDataConverter; -use Magento\Setup\Model\WebLogger; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class InstallTest extends TestCase -{ - /** - * @var MockObject|WebLogger - */ - private $webLogger; - - /** - * @var MockObject|Installer - */ - private $installer; - - /** - * @var MockObject|ProgressFactory - */ - private $progressFactory; - - /** - * @var MockObject|RequestDataConverter - */ - private $requestDataConverter; - - /** - * @var Install - */ - private $controller; - - /** - * @var State|MockObject - */ - private $sampleDataState; - - /** - * @var DeploymentConfig|MockObject - */ - private $deploymentConfig; - - protected function setUp(): void - { - $this->webLogger = $this->createMock(WebLogger::class); - $installerFactory = $this->createMock(InstallerFactory::class); - $this->installer = $this->createMock(Installer::class); - $this->progressFactory = - $this->createMock(ProgressFactory::class); - $this->sampleDataState = $this->createMock(State::class); - $this->deploymentConfig = $this->createMock(DeploymentConfig::class); - $this->requestDataConverter = $this->createMock(RequestDataConverter::class); - - $installerFactory->expects($this->once())->method('create')->with($this->webLogger) - ->willReturn($this->installer); - $this->controller = new Install( - $this->webLogger, - $installerFactory, - $this->progressFactory, - $this->sampleDataState, - $this->deploymentConfig, - $this->requestDataConverter - ); - } - - public function testIndexAction() - { - $viewModel = $this->controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - } - - 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') - ->willReturn( - [ - 'key' => null, - 'message' => null, - ] - ); - $this->deploymentConfig->expects($this->once())->method('isAvailable')->willReturn(false); - $jsonModel = $this->controller->startAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('key', $variables); - $this->assertArrayHasKey('success', $variables); - $this->assertArrayHasKey('messages', $variables); - $this->assertTrue($variables['success']); - } - - 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(JsonModel::class, $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->createMock('\Exception')); - $jsonModel = $this->controller->startAction(); - $this->assertNull($jsonModel->getVariable('isSampleDataError')); - } - - 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->installer->expects($this->exactly(2)) - ->method('getInstallInfo') - ->willReturn( - [ - 'key' => null, - 'message' => null, - ] - ); - $this->sampleDataState->expects($this->once())->method('hasError')->willReturn(true); - $jsonModel = $this->controller->startAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertTrue($variables['success']); - $this->assertTrue($jsonModel->getVariable('isSampleDataError')); - } - - public function testProgressAction() - { - $numValue = 42; - $consoleMessages = ['key1' => 'log message 1', 'key2' => 'log message 2']; - - $this->webLogger->expects($this->once())->method('logfileExists')->willReturn(true); - $progress = $this->createMock(Progress::class); - $this->progressFactory->expects($this->once())->method('createFromLog')->with($this->webLogger) - ->willReturn($progress); - $progress->expects($this->once())->method('getRatio')->willReturn($numValue); - $this->webLogger->expects($this->once())->method('get')->willReturn($consoleMessages); - $jsonModel = $this->controller->progressAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('progress', $variables); - $this->assertArrayHasKey('success', $variables); - $this->assertArrayHasKey('console', $variables); - $this->assertSame($consoleMessages, $variables['console']); - $this->assertTrue($variables['success']); - $this->assertSame(sprintf('%d', $numValue * 100), $variables['progress']); - } - - public function testProgressActionWithError() - { - $e = 'Some exception message'; - $this->webLogger->expects($this->once())->method('logfileExists')->willReturn(true); - $this->progressFactory->expects($this->once())->method('createFromLog') - ->willThrowException(new \LogicException($e)); - $jsonModel = $this->controller->progressAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertArrayHasKey('console', $variables); - $this->assertFalse($variables['success']); - $this->assertStringContainsString('LogicException', $variables['console'][0]); - $this->assertStringContainsString($e, $variables['console'][0]); - } - - public function testProgressActionWithSampleDataError() - { - $numValue = 42; - $this->webLogger->expects($this->once())->method('logfileExists')->willReturn(true); - $progress = $this->createMock(Progress::class); - $progress->expects($this->once())->method('getRatio')->willReturn($numValue); - $this->progressFactory->expects($this->once())->method('createFromLog')->willReturn($progress); - $this->sampleDataState->expects($this->once())->method('hasError')->willReturn(true); - $jsonModel = $this->controller->progressAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertArrayHasKey('console', $variables); - $this->assertTrue($variables['success']); - $this->assertTrue($jsonModel->getVariable('isSampleDataError')); - $this->assertSame(sprintf('%d', $numValue * 100), $variables['progress']); - } - - public function testProgressActionNoInstallLogFile() - { - $this->webLogger->expects($this->once())->method('logfileExists')->willReturn(false); - $jsonModel = $this->controller->progressAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertArrayHasKey('console', $variables); - $this->assertTrue($variables['success']); - $this->assertEmpty($variables['console']); - $this->assertSame(0, $variables['progress']); - } - - public function testDispatch() - { - $request = $this->createMock(Request::class); - $response = $this->createMock(Response::class); - $routeMatch = $this->createMock(RouteMatch::class); - - $mvcEvent = $this->createMock(MvcEvent::class); - $mvcEvent->expects($this->once())->method('setRequest')->with($request)->willReturn($mvcEvent); - $mvcEvent->expects($this->once())->method('setResponse')->with($response)->willReturn($mvcEvent); - $mvcEvent->expects($this->once())->method('setTarget')->with($this->controller)->willReturn($mvcEvent); - $mvcEvent->expects($this->any())->method('getRouteMatch')->willReturn($routeMatch); - $mvcEvent->expects($this->any())->method('getName')->willReturn('dispatch'); - - $contentArray = '{"config": { "address": { "base_url": "http://123.45.678.12"}}}'; - $request->expects($this->any())->method('getContent')->willReturn($contentArray); - $this->controller->setEvent($mvcEvent); - $this->controller->dispatch($request, $response); - $this->controller->startAction(); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/LandingInstallerTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/LandingInstallerTest.php deleted file mode 100644 index afa7304aa9457..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/LandingInstallerTest.php +++ /dev/null @@ -1,48 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\ViewModel; -use Magento\Framework\App\ProductMetadata; -use Magento\Setup\Controller\LandingInstaller; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class LandingInstallerTest extends TestCase -{ - /** - * Test Product Version Value - */ - const TEST_PRODUCT_VERSION = '222.333.444'; - - public function testIndexAction() - { - /** @var ProductMetadata|MockObject $productMetadataMock */ - $productMetadataMock = $this->getMockBuilder(ProductMetadata::class) - ->setMethods(['getVersion']) - ->disableOriginalConstructor() - ->getMock(); - $productMetadataMock->expects($this->once()) - ->method('getVersion') - ->willReturn($this::TEST_PRODUCT_VERSION); - /** @var LandingInstaller $controller */ - $controller = new LandingInstaller($productMetadataMock); - $_SERVER['DOCUMENT_ROOT'] = 'some/doc/root/value'; - $viewModel = $controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - $this->assertEquals('/magento/setup/landing.phtml', $viewModel->getTemplate()); - $variables = $viewModel->getVariables(); - $this->assertArrayHasKey('version', $variables); - $this->assertEquals($this::TEST_PRODUCT_VERSION, $variables['version']); - $this->assertArrayHasKey('welcomeMsg', $variables); - $this->assertArrayHasKey('docRef', $variables); - $this->assertArrayHasKey('agreeButtonText', $variables); - $this->assertEquals('Agree and Setup Magento', $variables['agreeButtonText']); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/LandingUpdaterTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/LandingTest.php similarity index 74% rename from setup/src/Magento/Setup/Test/Unit/Controller/LandingUpdaterTest.php rename to setup/src/Magento/Setup/Test/Unit/Controller/LandingTest.php index 6034ea6bed50c..41066894e7002 100644 --- a/setup/src/Magento/Setup/Test/Unit/Controller/LandingUpdaterTest.php +++ b/setup/src/Magento/Setup/Test/Unit/Controller/LandingTest.php @@ -9,11 +9,11 @@ use Laminas\View\Model\ViewModel; use Magento\Framework\App\ProductMetadata; -use Magento\Setup\Controller\LandingUpdater; +use Magento\Setup\Controller\Landing; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -class LandingUpdaterTest extends TestCase +class LandingTest extends TestCase { /** * Test Product Version Value @@ -30,8 +30,8 @@ public function testIndexAction() $productMetadataMock->expects($this->once()) ->method('getVersion') ->willReturn($this::TEST_PRODUCT_VERSION); - /** @var LandingUpdater $controller */ - $controller = new LandingUpdater($productMetadataMock); + /** @var Landing $controller */ + $controller = new Landing($productMetadataMock); $_SERVER['DOCUMENT_ROOT'] = 'some/doc/root/value'; $viewModel = $controller->indexAction(); $this->assertInstanceOf(ViewModel::class, $viewModel); @@ -40,9 +40,5 @@ public function testIndexAction() $variables = $viewModel->getVariables(); $this->assertArrayHasKey('version', $variables); $this->assertEquals($this::TEST_PRODUCT_VERSION, $variables['version']); - $this->assertArrayHasKey('welcomeMsg', $variables); - $this->assertArrayHasKey('docRef', $variables); - $this->assertArrayHasKey('agreeButtonText', $variables); - $this->assertEquals('Agree and Update Magento', $variables['agreeButtonText']); } } diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/MaintenanceTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/MaintenanceTest.php deleted file mode 100644 index 6521150f9ae33..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/MaintenanceTest.php +++ /dev/null @@ -1,82 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\Http\PhpEnvironment\Request; -use Laminas\Http\PhpEnvironment\Response; -use Laminas\Mvc\MvcEvent; -use Laminas\Mvc\Router\RouteMatch; -use Laminas\View\Model\JsonModel; -use Magento\Framework\App\MaintenanceMode; -use Magento\Setup\Controller\Maintenance; -use Magento\Setup\Controller\ResponseTypeInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class MaintenanceTest extends TestCase -{ - - /** - * @var MaintenanceMode|MockObject - */ - private $maintenanceMode; - - /** - * Controller - * - * @var Maintenance - */ - private $controller; - - protected function setUp(): void - { - $this->maintenanceMode = $this->createMock(MaintenanceMode::class); - $this->controller = new Maintenance($this->maintenanceMode); - - $request = $this->createMock(Request::class); - $response = $this->createMock(Response::class); - $routeMatch = $this->createMock(RouteMatch::class); - - $mvcEvent = $this->createMock(MvcEvent::class); - $mvcEvent->expects($this->any())->method('setRequest')->with($request)->willReturn($mvcEvent); - $mvcEvent->expects($this->any())->method('setResponse')->with($response)->willReturn($mvcEvent); - $mvcEvent->expects($this->any())->method('setTarget')->with($this->controller)->willReturn($mvcEvent); - $mvcEvent->expects($this->any())->method('getRouteMatch')->willReturn($routeMatch); - $mvcEvent->expects($this->any())->method('getName')->willReturn('dispatch'); - - $contentArray = '{"disable":false}'; - $request->expects($this->any())->method('getContent')->willReturn($contentArray); - - $this->controller->setEvent($mvcEvent); - $this->controller->dispatch($request, $response); - } - - public function testIndexAction() - { - $this->maintenanceMode->expects($this->once())->method('set'); - $jsonModel = $this->controller->indexAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('responseType', $variables); - $this->assertEquals(ResponseTypeInterface::RESPONSE_TYPE_SUCCESS, $variables['responseType']); - } - - public function testIndexActionWithExceptions() - { - $this->maintenanceMode->expects($this->once())->method('set')->willThrowException( - new \Exception("Test error message") - ); - $jsonModel = $this->controller->indexAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('responseType', $variables); - $this->assertEquals(ResponseTypeInterface::RESPONSE_TYPE_ERROR, $variables['responseType']); - $this->assertArrayHasKey('error', $variables); - $this->assertEquals("Test error message", $variables['error']); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/MarketplaceTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/MarketplaceTest.php deleted file mode 100644 index 5a988cf59a25e..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/MarketplaceTest.php +++ /dev/null @@ -1,147 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Setup\Controller\Marketplace; -use Magento\Setup\Model\PackagesAuth; -use Magento\Setup\Model\PackagesData; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class MarketplaceTest extends TestCase -{ - /** - * @var MockObject|PackagesAuth - */ - private $packagesAuth; - - /** - * @var MockObject|PackagesData - */ - private $packagesData; - - /** - * Controller - * - * @var Marketplace - */ - private $controller; - - protected function setUp(): void - { - $this->packagesAuth = $this->createMock(PackagesAuth::class); - $this->packagesData = $this->createMock(PackagesData::class); - $this->controller = new Marketplace($this->packagesAuth, $this->packagesData); - } - - public function testSaveAuthJsonAction() - { - $this->packagesAuth - ->expects($this->once()) - ->method('checkCredentials') - ->willReturn(json_encode(['success' => true])); - $this->packagesAuth - ->expects($this->once()) - ->method('saveAuthJson') - ->willReturn(true); - $jsonModel = $this->controller->saveAuthJsonAction(); - $this->assertInstanceOf(ViewModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertTrue($variables['success']); - } - - public function testSaveAuthJsonActionWithError() - { - $this->packagesAuth - ->expects($this->once()) - ->method('checkCredentials') - ->willThrowException(new \Exception()); - $this->packagesAuth->expects($this->never())->method('saveAuthJson'); - $jsonModel = $this->controller->saveAuthJsonAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertArrayHasKey('message', $variables); - $this->assertFalse($variables['success']); - } - - public function testCheckAuthAction() - { - $this->packagesAuth - ->expects($this->once()) - ->method('getAuthJsonData') - ->willReturn(['username' => 'test', 'password' => 'test']); - $this->packagesAuth - ->expects($this->once()) - ->method('checkCredentials') - ->willReturn(json_encode(['success' => true])); - $jsonModel = $this->controller->checkAuthAction(); - $this->assertInstanceOf(ViewModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertTrue($variables['success']); - } - - public function testCheckAuthActionWithError() - { - $this->packagesAuth - ->expects($this->once()) - ->method('getAuthJsonData') - ->willThrowException(new \Exception()); - $jsonModel = $this->controller->checkAuthAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertArrayHasKey('message', $variables); - $this->assertFalse($variables['success']); - } - - public function testRemoveCredentialsAction() - { - $this->packagesAuth - ->expects($this->once()) - ->method('removeCredentials') - ->willReturn(true); - - $jsonModel = $this->controller->removeCredentialsAction(); - $this->assertInstanceOf(ViewModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertTrue($variables['success']); - } - - public function testRemoveCredentialsWithError() - { - $this->packagesAuth - ->expects($this->once()) - ->method('removeCredentials') - ->willThrowException(new \Exception()); - $jsonModel = $this->controller->removeCredentialsAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertArrayHasKey('message', $variables); - $this->assertFalse($variables['success']); - } - - public function testPopupAuthAction() - { - $viewModel = $this->controller->popupAuthAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - } - - public function testIndexAction() - { - $model = $this->controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $model); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/ModuleGridTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/ModuleGridTest.php deleted file mode 100644 index cacc3575d15cb..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/ModuleGridTest.php +++ /dev/null @@ -1,88 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Setup\Controller\ModuleGrid; -use Magento\Setup\Model\Grid\Module; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Test for \Magento\Setup\Controller\ModuleGrid - */ -class ModuleGridTest extends TestCase -{ - /** - * @var Module|MockObject - */ - private $gridModuleMock; - - /** - * Controller - * - * @var ModuleGrid - */ - private $controller; - - protected function setUp(): void - { - $this->gridModuleMock = $this->getMockBuilder(Module::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->controller = new ModuleGrid( - $this->gridModuleMock - ); - } - - public function testIndexAction() - { - $viewModel = $this->controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - } - - public function testModulesAction() - { - $moduleList = [ - [ - 'name' => 'magento/sample-module-one', - 'type' => 'Module', - 'version' => '1.0.0', - 'vendor' => 'magento', - 'moduleName' => 'Sample_Module_One', - 'enable' => true, - 'requiredBy' => [] - ], - [ - 'name' => 'magento/sample-module-two', - 'type' => 'Module', - 'version' => '1.0.0', - 'vendor' => 'magento', - 'moduleName' => 'Sample_Module_Two', - 'enable' => true, - 'requiredBy' => [] - ] - ]; - - $this->gridModuleMock->expects(static::once()) - ->method('getList') - ->willReturn($moduleList); - - $jsonModel = $this->controller->modulesAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertTrue($variables['success']); - $this->assertEquals($moduleList, $variables['modules']); - $this->assertArrayHasKey('total', $variables); - $this->assertEquals(2, $variables['total']); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/ModulesTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/ModulesTest.php deleted file mode 100644 index ee47fc12b4bf9..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/ModulesTest.php +++ /dev/null @@ -1,116 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\JsonModel; -use Magento\Framework\Module\Status; -use Magento\Framework\ObjectManagerInterface; -use Magento\Setup\Controller\Modules; -use Magento\Setup\Model\ModuleStatus; -use Magento\Setup\Model\ObjectManagerProvider; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class ModulesTest extends TestCase -{ - /** - * @var MockObject|ObjectManagerInterface - */ - private $objectManager; - - /** - * @var MockObject|Status - */ - private $status; - - /** - * @var MockObject|ModuleStatus - */ - private $modules; - - /** - * Controller - * - * @var Modules - */ - private $controller; - - protected function setUp(): void - { - $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); - /** @var - * $objectManagerProvider \PHPUnit\Framework\MockObject\MockObject|\Magento\Setup\Model\ObjectManagerProvider - */ - $objectManagerProvider = $this->createMock(ObjectManagerProvider::class); - $objectManagerProvider->expects($this->once())->method('get')->willReturn($this->objectManager); - $this->modules = $this->createMock(ModuleStatus::class); - $this->status = $this->createMock(Status::class); - $this->objectManager->expects($this->once())->method('create')->willReturn($this->status); - $this->controller = new Modules($this->modules, $objectManagerProvider); - } - - /** - * @param array $expected - * - * @dataProvider indexActionDataProvider - */ - public function testIndexAction(array $expected) - { - $this->modules->expects($this->once())->method('getAllModules')->willReturn($expected['modules']); - $this->status->expects($this->once())->method('checkConstraints')->willReturn([]); - $jsonModel = $this->controller->indexAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertTrue($variables['success']); - } - - /** - * @param array $expected - * - * @dataProvider indexActionDataProvider - */ - public function testIndexActionWithError(array $expected) - { - $this->modules->expects($this->once())->method('getAllModules')->willReturn($expected['modules']); - $this->status->expects($this->once()) - ->method('checkConstraints') - ->willReturn(['ModuleA', 'ModuleB']); - $jsonModel = $this->controller->indexAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('success', $variables); - $this->assertArrayHasKey('error', $variables); - $this->assertFalse($variables['success']); - } - - /** - * @return array - */ - public function indexActionDataProvider() - { - return [ - 'with_modules' => [['modules' => [ - 'module1' => ['name' => 'module1', 'selected' => true, 'disabled' => true], - 'module2' => ['name' => 'module2', 'selected' => true, 'disabled' => true], - 'module3' => ['name' => 'module3', 'selected' => true, 'disabled' => true] - ]]], - 'some_not_selected' => [['modules' => [ - 'module1' => ['name' => 'module1', 'selected' => false, 'disabled' => true], - 'module2' => ['name' => 'module2', 'selected' => true, 'disabled' => true], - 'module3' => ['name' => 'module3', 'selected' => false, 'disabled' => true] - ]]], - 'some_disabled' => [['modules' => [ - 'module1' => ['name' => 'module1', 'selected' => true, 'disabled' => false], - 'module2' => ['name' => 'module2', 'selected' => true, 'disabled' => true], - 'module3' => ['name' => 'module3', 'selected' => true, 'disabled' => false] - ]]], - 'no_modules' => [['modules' => []]], - ]; - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/NavigationTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/NavigationTest.php index 2334e1e3cee20..46f09a7e93eb3 100644 --- a/setup/src/Magento/Setup/Test/Unit/Controller/NavigationTest.php +++ b/setup/src/Magento/Setup/Test/Unit/Controller/NavigationTest.php @@ -10,8 +10,6 @@ use Laminas\View\Model\JsonModel; use Laminas\View\Model\ViewModel; use Magento\Setup\Controller\Navigation; -use Magento\Setup\Model\Cron\Status; -use Magento\Setup\Model\Navigation as NavModel; use Magento\Setup\Model\ObjectManagerProvider; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -28,11 +26,6 @@ class NavigationTest extends TestCase */ private $controller; - /** - * @var Status|MockObject - */ - private $status; - /** * @var ObjectManagerProvider|MockObject */ @@ -41,10 +34,9 @@ class NavigationTest extends TestCase protected function setUp(): void { $this->navigationModel = $this->createMock(\Magento\Setup\Model\Navigation::class); - $this->status = $this->createMock(Status::class); $this->objectManagerProvider = $this->createMock(ObjectManagerProvider::class); - $this->controller = new Navigation($this->navigationModel, $this->status, $this->objectManagerProvider); + $this->controller = new Navigation($this->navigationModel, $this->objectManagerProvider); } public function testIndexAction() @@ -77,28 +69,4 @@ public function testMenuActionInstaller() $this->assertTrue($viewModel->terminate()); $this->assertSame('/magento/setup/navigation/menu.phtml', $viewModel->getTemplate()); } - - public function testHeaderBarInstaller() - { - $this->navigationModel->expects($this->once())->method('getType')->willReturn(NavModel::NAV_INSTALLER); - $viewModel = $this->controller->headerBarAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $variables = $viewModel->getVariables(); - $this->assertArrayHasKey('menu', $variables); - $this->assertArrayHasKey('main', $variables); - $this->assertTrue($viewModel->terminate()); - $this->assertSame('/magento/setup/navigation/header-bar.phtml', $viewModel->getTemplate()); - } - - public function testHeaderBarUpdater() - { - $this->navigationModel->expects($this->once())->method('getType')->willReturn(NavModel::NAV_UPDATER); - $viewModel = $this->controller->headerBarAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $variables = $viewModel->getVariables(); - $this->assertArrayHasKey('menu', $variables); - $this->assertArrayHasKey('main', $variables); - $this->assertTrue($viewModel->terminate()); - $this->assertSame('/magento/setup/navigation/header-bar.phtml', $viewModel->getTemplate()); - } } diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/OtherComponentsGridTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/OtherComponentsGridTest.php deleted file mode 100644 index 4d76cf9de82ca..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/OtherComponentsGridTest.php +++ /dev/null @@ -1,130 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Composer\InfoCommand; -use Magento\Framework\Composer\ComposerInformation; -use Magento\Framework\Composer\MagentoComposerApplicationFactory; -use Magento\Setup\Controller\OtherComponentsGrid; -use Magento\Setup\Controller\ResponseTypeInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class OtherComponentsGridTest extends TestCase -{ - /** - * @var ComposerInformation|MockObject - */ - private $composerInformation; - - /** - * @var InfoCommand|MockObject - */ - private $infoCommand; - - /** - * Controller - * - * @var OtherComponentsGrid - */ - private $controller; - - protected function setUp(): void - { - $this->composerInformation = $this->createMock(ComposerInformation::class); - $this->infoCommand = $this->createMock(InfoCommand::class); - $magentoComposerApplicationFactory = - $this->createMock(MagentoComposerApplicationFactory::class); - $magentoComposerApplicationFactory->expects($this->once()) - ->method('createInfoCommand') - ->willReturn($this->infoCommand); - $this->controller = new OtherComponentsGrid( - $this->composerInformation, - $magentoComposerApplicationFactory - ); - } - - public function testComponentsAction() - { - $this->composerInformation->expects($this->once()) - ->method('getInstalledMagentoPackages') - ->willReturn([ - 'magento/sample-module1' => [ - 'name' => 'magento/sample-module1', - 'type' => 'magento2-module', - 'version' => '1.0.0' - ] - ]); - $this->composerInformation->expects($this->once()) - ->method('isPackageInComposerJson') - ->willReturn(true); - $this->infoCommand->expects($this->once()) - ->method('run') - ->willReturn([ - 'versions' => '3.0.0, 2.0.0', - 'current_version' => '1.0.0', - 'new_versions' => [ - '3.0.0', - '2.0.0' - ] - ]); - $jsonModel = $this->controller->componentsAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('responseType', $variables); - $this->assertEquals(ResponseTypeInterface::RESPONSE_TYPE_SUCCESS, $variables['responseType']); - $this->assertArrayHasKey('components', $variables); - $expected = [ - '0' => [ - 'name' => 'magento/sample-module1', - 'type' => 'magento2-module', - 'version' => '1.0.0', - 'vendor' => 'magento', - 'updates' => [ - [ - 'id' => '3.0.0', - 'name' => '3.0.0 (latest)' - ], - [ - 'id' => '2.0.0', - 'name' => '2.0.0' - ], - [ - 'id' => '1.0.0', - 'name' => '1.0.0 (current)' - ] - ], - 'dropdownId' => 'dd_magento/sample-module1', - 'checkboxId' => 'cb_magento/sample-module1' - ] - ]; - $this->assertEquals($expected, $variables['components']); - $this->assertArrayHasKey('total', $variables); - $this->assertEquals(1, $variables['total']); - } - - public function testComponentsActionWithError() - { - $this->composerInformation->expects($this->once()) - ->method('getInstalledMagentoPackages') - ->willThrowException(new \Exception("Test error message")); - $jsonModel = $this->controller->componentsAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('responseType', $variables); - $this->assertEquals(ResponseTypeInterface::RESPONSE_TYPE_ERROR, $variables['responseType']); - } - - public function testIndexAction() - { - $model = $this->controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $model); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/ReadinessCheckInstallerTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/ReadinessCheckInstallerTest.php deleted file mode 100644 index cfcb3e903c43f..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/ReadinessCheckInstallerTest.php +++ /dev/null @@ -1,43 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\ViewModel; -use Magento\Setup\Controller\ReadinessCheckInstaller; -use PHPUnit\Framework\TestCase; - -class ReadinessCheckInstallerTest extends TestCase -{ - /** - * @var ReadinessCheckInstaller - */ - private $controller; - - protected function setUp(): void - { - $this->controller = new ReadinessCheckInstaller(); - } - - public function testIndexAction() - { - $viewModel = $this->controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - $variables = $viewModel->getVariables(); - $this->assertArrayHasKey('actionFrom', $variables); - $this->assertEquals('installer', $variables['actionFrom']); - } - - public function testProgressAction() - { - $viewModel = $this->controller->progressAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - $this->assertSame('/magento/setup/readiness-check/progress.phtml', $viewModel->getTemplate()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/ReadinessCheckUpdaterTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/ReadinessCheckUpdaterTest.php deleted file mode 100644 index ddebb39d94cd2..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/ReadinessCheckUpdaterTest.php +++ /dev/null @@ -1,43 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\ViewModel; -use Magento\Setup\Controller\ReadinessCheckUpdater; -use PHPUnit\Framework\TestCase; - -class ReadinessCheckUpdaterTest extends TestCase -{ - /** - * @var ReadinessCheckUpdater - */ - private $controller; - - protected function setUp(): void - { - $this->controller = new ReadinessCheckUpdater(); - } - - public function testIndexAction() - { - $viewModel = $this->controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - $variables = $viewModel->getVariables(); - $this->assertArrayHasKey('actionFrom', $variables); - $this->assertEquals('updater', $variables['actionFrom']); - } - - public function testProgressAction() - { - $viewModel = $this->controller->progressAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - $this->assertSame('/magento/setup/readiness-check/progress.phtml', $viewModel->getTemplate()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/SearchEngineCheckTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/SearchEngineCheckTest.php deleted file mode 100644 index 862f908adb54e..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/SearchEngineCheckTest.php +++ /dev/null @@ -1,140 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\Stdlib\RequestInterface; -use Laminas\View\Model\JsonModel; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\Setup\Controller\SearchEngineCheck; -use Magento\Setup\Model\SearchConfigOptionsList; -use Magento\Setup\Validator\ElasticsearchConnectionValidator; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class SearchEngineCheckTest extends TestCase -{ - /** - * @var SearchEngineCheck - */ - private $controller; - - /** - * @var ElasticsearchConnectionValidator|MockObject - */ - private $connectionValidatorMock; - - /** - * @var ObjectManager - */ - private $objectManagerHelper; - - protected function setUp(): void - { - $searchConfigOptionsList = new SearchConfigOptionsList(); - $this->objectManagerHelper = new ObjectManager($this); - $this->connectionValidatorMock = $this->getMockBuilder(ElasticsearchConnectionValidator::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->controller = new SearchEngineCheck( - $this->connectionValidatorMock, - $searchConfigOptionsList - ); - } - - public function testIndexAction() - { - $requestData = [ - 'engine' => 'elasticsearch7', - 'elasticsearch' => [ - 'hostname' => 'localhost', - 'port' => '9200', - 'timeout' => '15', - 'indexPrefix' => 'prefix', - 'enableAuth' => false, - 'username' => '', - 'password' => '' - ] - ]; - /** @var RequestInterface|MockObject $requestMock */ - $requestMock = $this->getMockBuilder(RequestInterface::class) - ->getMockForAbstractClass(); - $requestMock->expects($this->once()) - ->method('getContent') - ->willReturn(json_encode($requestData)); - $this->objectManagerHelper->setBackwardCompatibleProperty($this->controller, 'request', $requestMock); - - $this->connectionValidatorMock->expects($this->once())->method('isValidConnection')->willReturn(true); - - $jsonModel = $this->controller->indexAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $this->assertEquals(['success' => true], $jsonModel->getVariables()); - } - - public function testIndexActionFailure() - { - $requestData = [ - 'engine' => 'elasticsearch7', - 'elasticsearch' => [ - 'hostname' => 'other.host', - 'port' => '9200', - 'timeout' => '15', - 'indexPrefix' => 'prefix', - 'enableAuth' => false, - 'username' => '', - 'password' => '' - ] - ]; - /** @var RequestInterface|MockObject $requestMock */ - $requestMock = $this->getMockBuilder(RequestInterface::class) - ->getMockForAbstractClass(); - $requestMock->expects($this->once()) - ->method('getContent') - ->willReturn(json_encode($requestData)); - $this->objectManagerHelper->setBackwardCompatibleProperty($this->controller, 'request', $requestMock); - - $exceptionMessage = 'Could not connect to Elasticsearch server.'; - $this->connectionValidatorMock - ->expects($this->once()) - ->method('isValidConnection') - ->willThrowException(new \Exception($exceptionMessage)); - - $jsonModel = $this->controller->indexAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $this->assertEquals(['success' => false, 'error' => $exceptionMessage], $jsonModel->getVariables()); - } - - public function testIndexActionInvalidEngine() - { - $requestData = [ - 'engine' => 'other-engine', - 'elasticsearch' => [ - 'hostname' => 'other.host', - 'port' => '9200', - 'timeout' => '15', - 'indexPrefix' => 'prefix', - 'enableAuth' => false, - 'username' => '', - 'password' => '' - ] - ]; - /** @var RequestInterface|MockObject $requestMock */ - $requestMock = $this->getMockBuilder(RequestInterface::class) - ->getMockForAbstractClass(); - $requestMock->expects($this->once()) - ->method('getContent') - ->willReturn(json_encode($requestData)); - $this->objectManagerHelper->setBackwardCompatibleProperty($this->controller, 'request', $requestMock); - $this->connectionValidatorMock->expects($this->never())->method('isValidConnection'); - - $expectedErrorMessage = 'Please select a valid search engine.'; - $jsonModel = $this->controller->indexAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $this->assertEquals(['success' => false, 'error' => $expectedErrorMessage], $jsonModel->getVariables()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/SelectVersionTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/SelectVersionTest.php deleted file mode 100644 index f051005e54931..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/SelectVersionTest.php +++ /dev/null @@ -1,105 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Setup\Controller\ResponseTypeInterface; -use Magento\Setup\Controller\SelectVersion; -use Magento\Setup\Model\SystemPackage; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class SelectVersionTest extends TestCase -{ - /** - * @var SystemPackage|MockObject - */ - private $systemPackage; - - /** - * Controller - * - * @var SelectVersion - */ - private $controller; - - protected function setUp(): void - { - $this->systemPackage = $this->createMock(SystemPackage::class); - $this->controller = new SelectVersion( - $this->systemPackage - ); - } - - public function testIndexAction() - { - $viewModel = $this->controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - } - - public function testSystemPackageAction() - { - $this->systemPackage->expects($this->once()) - ->method('getPackageVersions') - ->willReturn([ - 'package' => 'magento/product-community-edition', - 'versions' => [ - 'id' => 'magento/product-community-edition', - 'name' => 'Version 1.0.0' - ] - ]); - $jsonModel = $this->controller->systemPackageAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('responseType', $variables); - $this->assertEquals(ResponseTypeInterface::RESPONSE_TYPE_SUCCESS, $variables['responseType']); - } - - public function testSystemPackageActionActionWithError() - { - $this->systemPackage->expects($this->once()) - ->method('getPackageVersions') - ->willThrowException(new \Exception("Test error message")); - $jsonModel = $this->controller->systemPackageAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('responseType', $variables); - $this->assertEquals(ResponseTypeInterface::RESPONSE_TYPE_ERROR, $variables['responseType']); - } - - public function testInstalledSystemPackageAction() - { - $this->systemPackage->expects($this->once()) - ->method('getInstalledSystemPackages') - ->willReturn([ - 'package' => 'magento/product-community-edition', - 'versions' => [ - 'id' => 'magento/product-community-edition', - 'name' => 'Version 1.0.0' - ] - ]); - $jsonModel = $this->controller->installedSystemPackageAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('responseType', $variables); - $this->assertEquals(ResponseTypeInterface::RESPONSE_TYPE_SUCCESS, $variables['responseType']); - } - - public function testInstalledSystemPackageActionWithError() - { - $this->systemPackage->expects($this->once()) - ->method('getInstalledSystemPackages') - ->willThrowException(new \Exception("Test error message")); - $jsonModel = $this->controller->installedSystemPackageAction(); - $variables = $jsonModel->getVariables(); - $this->assertArrayHasKey('responseType', $variables); - $this->assertEquals(ResponseTypeInterface::RESPONSE_TYPE_ERROR, $variables['responseType']); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/SessionTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/SessionTest.php deleted file mode 100644 index c492fee67c313..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/SessionTest.php +++ /dev/null @@ -1,136 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\ServiceManager\ServiceManager; -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Backend\Model\Session\AdminConfig; -use Magento\Backend\Model\Url; -use Magento\Framework\App\DeploymentConfig; -use Magento\Framework\App\State; -use Magento\Framework\ObjectManagerInterface; -use Magento\Setup\Controller\Session; -use Magento\Setup\Model\ObjectManagerProvider; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class SessionTest extends TestCase -{ - /** - * @var MockObject|ObjectManagerInterface - */ - private $objectManager; - - /** - * @var MockObject|ObjectManagerProvider - */ - private $objectManagerProvider; - - /** - * @var ServiceManager - */ - private $serviceManager; - - protected function setUp(): void - { - $objectManager = - $this->getMockForAbstractClass(ObjectManagerInterface::class, [], '', false); - $objectManagerProvider = - $this->createPartialMock(ObjectManagerProvider::class, ['get']); - $this->objectManager = $objectManager; - $this->objectManagerProvider = $objectManagerProvider; - $this->serviceManager = $this->createPartialMock(ServiceManager::class, ['get']); - } - - /** - * @covers \Magento\Setup\Controller\Session::unloginAction - */ - public function testUnloginAction() - { - $this->objectManagerProvider->expects($this->once())->method('get')->willReturn( - $this->objectManager - ); - $deployConfigMock = - $this->createPartialMock(DeploymentConfig::class, ['isAvailable']); - $deployConfigMock->expects($this->once())->method('isAvailable')->willReturn(true); - - $sessionMock = $this->createPartialMock( - \Magento\Backend\Model\Auth\Session::class, - ['prolong', 'isSessionExists'] - ); - $sessionMock->expects($this->once())->method('isSessionExists')->willReturn(false); - - $stateMock = $this->createPartialMock(State::class, ['setAreaCode']); - $stateMock->expects($this->once())->method('setAreaCode'); - - $sessionConfigMock = - $this->createPartialMock(AdminConfig::class, ['setCookiePath']); - $sessionConfigMock->expects($this->once())->method('setCookiePath'); - $urlMock = $this->createMock(Url::class); - - $returnValueMap = [ - [\Magento\Backend\Model\Auth\Session::class, $sessionMock], - [State::class, $stateMock], - [AdminConfig::class, $sessionConfigMock], - [Url::class, $urlMock] - ]; - - $this->serviceManager->expects($this->once())->method('get')->willReturn($deployConfigMock); - - $this->objectManager->expects($this->atLeastOnce()) - ->method('get') - ->willReturnMap($returnValueMap); - - $this->objectManager->expects($this->once()) - ->method('create') - ->willReturn($sessionMock); - $controller = new Session($this->serviceManager, $this->objectManagerProvider); - $urlMock->expects($this->once())->method('getBaseUrl'); - $controller->prolongAction(); - } - - /** - * @covers \Magento\Setup\Controller\SystemConfig::indexAction - */ - public function testIndexAction() - { - /** @var Session $controller */ - $controller = new Session($this->serviceManager, $this->objectManagerProvider); - $viewModel = $controller->unloginAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - } - - /** - * @covers \Magento\Setup\Controller\SystemConfig::prolongAction - */ - public function testProlongActionWithExistingSession() - { - $this->objectManagerProvider->expects($this->once())->method('get')->willReturn( - $this->objectManager - ); - $deployConfigMock = - $this->createPartialMock(DeploymentConfig::class, ['isAvailable']); - $deployConfigMock->expects($this->once())->method('isAvailable')->willReturn(true); - $sessionMock = $this->createPartialMock( - \Magento\Backend\Model\Auth\Session::class, - ['prolong', 'isSessionExists'] - ); - $sessionMock->expects($this->once())->method('isSessionExists')->willReturn(true); - - $this->serviceManager->expects($this->once())->method('get')->willReturn($deployConfigMock); - $this->objectManager->expects($this->once()) - ->method('get') - ->willReturn($sessionMock); - $controller = new Session($this->serviceManager, $this->objectManagerProvider); - $this->assertEquals(new JsonModel(['success' => true]), $controller->prolongAction()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/StartUpdaterTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/StartUpdaterTest.php deleted file mode 100644 index d0c231eb474f3..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/StartUpdaterTest.php +++ /dev/null @@ -1,132 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\Http\PhpEnvironment\Request; -use Laminas\Http\PhpEnvironment\Response; -use Laminas\Mvc\MvcEvent; -use Laminas\Mvc\Router\RouteMatch; -use Laminas\View\Model\ViewModel; -use Magento\Setup\Controller\StartUpdater; -use Magento\Setup\Model\PayloadValidator; -use Magento\Setup\Model\UpdaterTaskCreator; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Test for \Magento\Setup\Controller\StartUpdater - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class StartUpdaterTest extends TestCase -{ - /** - * @var StartUpdater|MockObject - */ - private $controller; - - /** - * @var Request|MockObject - */ - private $request; - - /** - * @var Response|MockObject - */ - private $response; - - /** - * @var MvcEvent|MockObject - */ - private $mvcEvent; - - /** - * @var PayloadValidator|MockObject - */ - private $payloadValidator; - - /** - * @var UpdaterTaskCreator|MockObject - */ - private $updaterTaskCreator; - - protected function setUp(): void - { - $this->payloadValidator = $this->createMock(PayloadValidator::class); - $this->updaterTaskCreator = $this->createMock(UpdaterTaskCreator::class); - - $this->controller = new StartUpdater( - $this->updaterTaskCreator, - $this->payloadValidator - ); - $this->request = $this->createMock(Request::class); - $this->response = $this->createMock(Response::class); - $routeMatch = $this->createMock(RouteMatch::class); - $this->mvcEvent = $this->createMock(MvcEvent::class); - $this->mvcEvent->expects($this->any()) - ->method('setRequest') - ->with($this->request) - ->willReturn($this->mvcEvent); - $this->mvcEvent->expects($this->any()) - ->method('setResponse') - ->with($this->response) - ->willReturn($this->mvcEvent); - $this->mvcEvent->expects($this->any()) - ->method('setTarget') - ->with($this->controller) - ->willReturn($this->mvcEvent); - $this->mvcEvent->expects($this->any())->method('getRouteMatch')->willReturn($routeMatch); - $this->mvcEvent->expects($this->any())->method('getName')->willReturn('dispatch'); - } - - public function testIndexAction() - { - $viewModel = $this->controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - } - - /** - * @param string $content - * @param int $payload - * @dataProvider updateInvalidRequestDataProvider - */ - public function testUpdateInvalidRequest($content, $payload) - { - $this->request->expects($this->any())->method('getContent')->willReturn($content); - $this->payloadValidator->expects($this->exactly($payload))->method('validatePayload'); - $this->controller->setEvent($this->mvcEvent); - $this->controller->dispatch($this->request, $this->response); - $this->controller->updateAction(); - } - - /** - * @return array - */ - public function updateInvalidRequestDataProvider() - { - return [ - 'NoParmas' => ['{}', 0], - 'NoArray' => ['{"packages":"test","type":"update"}', 0], - 'NoVersion' => ['{"packages":[{"name":"vendor\/package"}],"type":"update"}', 1], - 'NoDataOption' => ['{"packages":[{"name":"vendor\/package", "version": "1.0.0"}],"type":"uninstall"}', 1], - 'NoPackageInfo' => ['{"packages":"test","type":"update"}', 0] - ]; - } - - public function testUpdateActionSuccess() - { - $content = '{"packages":[{"name":"vendor\/package","version":"1.0"}],"type":"update",' - . '"headerTitle": "Update package 1" }'; - $this->request->expects($this->any())->method('getContent')->willReturn($content); - $this->payloadValidator->expects($this->once())->method('validatePayload')->willReturn(''); - $this->updaterTaskCreator->expects($this->once())->method('createUpdaterTasks')->willReturn(''); - $this->controller->setEvent($this->mvcEvent); - $this->controller->dispatch($this->request, $this->response); - $this->controller->updateAction(); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/SuccessTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/SuccessTest.php deleted file mode 100644 index c2f03f5c46777..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/SuccessTest.php +++ /dev/null @@ -1,37 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\ViewModel; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\Module\ModuleList; -use Magento\Framework\Setup\SampleData\State; -use Magento\Setup\Controller\Success; -use Magento\Setup\Model\ObjectManagerProvider; -use PHPUnit\Framework\TestCase; - -class SuccessTest extends TestCase -{ - public function testIndexAction() - { - $moduleList = $this->createMock(ModuleList::class); - $moduleList->expects($this->once())->method('has')->willReturn(true); - $objectManagerProvider = $this->createMock(ObjectManagerProvider::class); - $objectManager = $this->createMock(ObjectManager::class); - $objectManagerProvider->expects($this->once())->method('get')->willReturn($objectManager); - $sampleDataState = - $this->createPartialMock(State::class, ['hasError']); - $objectManager->expects($this->once())->method('get')->willReturn($sampleDataState); - /** @var Success $controller */ - $controller = new Success($moduleList, $objectManagerProvider); - $sampleDataState->expects($this->once())->method('hasError'); - $viewModel = $controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/SystemConfigTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/SystemConfigTest.php deleted file mode 100644 index e1108e8bb5fae..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/SystemConfigTest.php +++ /dev/null @@ -1,27 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\ViewModel; -use Magento\Setup\Controller\SystemConfig; -use PHPUnit\Framework\TestCase; - -class SystemConfigTest extends TestCase -{ - /** - * @covers \Magento\Setup\Controller\SystemConfig::indexAction - */ - public function testIndexAction() - { - /** @var SystemConfig $controller */ - $controller = new SystemConfig(); - $viewModel = $controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/UpdateExtensionGridTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/UpdateExtensionGridTest.php deleted file mode 100644 index c3d4496d93c18..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/UpdateExtensionGridTest.php +++ /dev/null @@ -1,79 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\JsonModel; -use Laminas\View\Model\ViewModel; -use Magento\Setup\Controller\UpdateExtensionGrid; -use Magento\Setup\Model\Grid\Extension; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * CTest for \Magento\Setup\Controller\UpdateExtensionGrid - */ -class UpdateExtensionGridTest extends TestCase -{ - /** - * @var Extension|MockObject - */ - private $gridExtensionMock; - - /** - * Controller - * - * @var UpdateExtensionGrid - */ - private $controller; - - protected function setUp(): void - { - $this->gridExtensionMock = $this->createMock(Extension::class); - - $this->controller = new UpdateExtensionGrid( - $this->gridExtensionMock - ); - } - - public function testIndexAction() - { - $viewModel = $this->controller->indexAction(); - - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - } - - public function testExtensionsAction() - { - $extensionData = [ - [ - 'name' => 'magento-package-1', - 'product_name' => 'magento/package-1', - 'type' => 'magento2-module', - 'version' => '1.0.0', - 'latestVersion' => '2.0.5', - 'versions' => ['2.0.5', '2.0.4', '2.0.3'], - 'update' => true, - 'uninstall' => true - ] - ]; - $this->gridExtensionMock->expects($this->once()) - ->method('getListForUpdate') - ->willReturn($extensionData); - - $jsonModel = $this->controller->extensionsAction(); - $this->assertInstanceOf(JsonModel::class, $jsonModel); - $variables = $jsonModel->getVariables(); - - $this->assertArrayHasKey('success', $variables); - $this->assertTrue($variables['success']); - $this->assertEquals($extensionData, $variables['extensions']); - $this->assertArrayHasKey('total', $variables); - $this->assertEquals(1, $variables['total']); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/UpdaterSuccessTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/UpdaterSuccessTest.php deleted file mode 100644 index 281938aa0d839..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/UpdaterSuccessTest.php +++ /dev/null @@ -1,28 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\ViewModel; -use Magento\Framework\App\MaintenanceMode; -use Magento\Setup\Controller\UpdaterSuccess; -use PHPUnit\Framework\TestCase; - -class UpdaterSuccessTest extends TestCase -{ - public function testIndexAction() - { - /** @var MaintenanceMode $maintenanceMode */ - $maintenanceMode = $this->createMock(MaintenanceMode::class); - $maintenanceMode->expects($this->once())->method('set')->with(false); - /** @var UpdaterSuccess $controller */ - $controller = new UpdaterSuccess($maintenanceMode); - $viewModel = $controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/UrlCheckTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/UrlCheckTest.php deleted file mode 100644 index f8bb41d46a952..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/UrlCheckTest.php +++ /dev/null @@ -1,147 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\Stdlib\RequestInterface; -use Laminas\View\Model\JsonModel; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; -use Magento\Framework\Validator\Url as UrlValidator; -use Magento\Setup\Controller\UrlCheck; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class UrlCheckTest extends TestCase -{ - /** - * @param array $requestJson - * @param array $expectedResult - * @dataProvider indexActionDataProvider - */ - public function testIndexAction($requestJson, $expectedResult) - { - /** @var ObjectManagerHelper $objectManagerHelper */ - $objectManagerHelper = new ObjectManagerHelper($this); - - $allowedSchemes = ['http', 'https']; - $returnMap = []; - if (isset($requestJson['address']['actual_base_url'])) { - $returnMap[] = [ - $requestJson['address']['actual_base_url'], - $allowedSchemes, - $expectedResult['successUrl'], - ]; - } - if (isset($requestJson['https']['text'])) { - $returnMap[] = [ - $requestJson['https']['text'], - $allowedSchemes, - $expectedResult['successSecureUrl'], - ]; - } - - /** @var UrlValidator|MockObject $validator */ - $validator = $this->getMockBuilder(UrlValidator::class) - ->disableOriginalConstructor() - ->getMock(); - $validator->expects($this->any()) - ->method('isValid') - ->willReturnMap($returnMap); - - /** @var RequestInterface|MockObject $requestMock */ - $requestMock = $this->getMockBuilder(RequestInterface::class) - ->getMockForAbstractClass(); - $requestMock->expects($this->once()) - ->method('getContent') - ->willReturn(json_encode($requestJson)); - - $controller = $objectManagerHelper->getObject( - UrlCheck::class, - ['urlValidator' => $validator] - ); - $objectManagerHelper->setBackwardCompatibleProperty($controller, 'request', $requestMock); - - $this->assertEquals(new JsonModel($expectedResult), $controller->indexAction()); - } - - /** - * @return array - */ - public function indexActionDataProvider() - { - return [ - [ - 'requestJson' => [ - 'address' => [ - 'actual_base_url' => 'http://localhost' - ] - ], - 'expectedResult' => ['successUrl' => true, 'successSecureUrl' => true] - ], - [ - 'requestJson' => [ - 'address' => [ - 'actual_base_url' => 'http://localhost.com_test' - ] - ], - 'expectedResult' => ['successUrl' => false, 'successSecureUrl' => true] - ], - [ - 'requestJson' => [ - 'address' => [ - 'actual_base_url' => 'http://localhost.com_test' - ], - 'https' => [ - 'admin' => false, - 'front' => false, - 'text' => '' - ] - ], - 'expectedResult' => ['successUrl' => false, 'successSecureUrl' => true] - ], - [ - 'requestJson' => [ - 'address' => [ - 'actual_base_url' => 'http://localhost.com:8080' - ], - 'https' => [ - 'admin' => true, - 'front' => false, - 'text' => 'https://example.com.ua/' - ] - ], - 'expectedResult' => ['successUrl' => true, 'successSecureUrl' => true] - ], - [ - 'requestJson' => [ - 'address' => [ - 'actual_base_url' => 'http://localhost.com:8080/folder_name/' - ], - 'https' => [ - 'admin' => false, - 'front' => true, - 'text' => 'https://example.com.ua/' - ] - ], - 'expectedResult' => ['successUrl' => true, 'successSecureUrl' => true] - ], - [ - 'requestJson' => [ - 'address' => [ - 'actual_base_url' => 'http://localhost.com:8080/folder_name/' - ], - 'https' => [ - 'admin' => true, - 'front' => true, - 'text' => 'https://example.com.ua:8090/folder_name/' - ] - ], - 'expectedResult' => ['successUrl' => true, 'successSecureUrl' => true] - ], - ]; - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Controller/WebConfigurationTest.php b/setup/src/Magento/Setup/Test/Unit/Controller/WebConfigurationTest.php deleted file mode 100644 index c9359b2e6f3c3..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Controller/WebConfigurationTest.php +++ /dev/null @@ -1,26 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Controller; - -use Laminas\View\Model\ViewModel; -use Magento\Setup\Controller\WebConfiguration; -use PHPUnit\Framework\TestCase; - -class WebConfigurationTest extends TestCase -{ - public function testIndexAction() - { - /** @var WebConfiguration $controller */ - $controller = new WebConfiguration(); - $_SERVER['DOCUMENT_ROOT'] = 'some/doc/root/value'; - $viewModel = $controller->indexAction(); - $this->assertInstanceOf(ViewModel::class, $viewModel); - $this->assertTrue($viewModel->terminate()); - $this->assertArrayHasKey('autoBaseUrl', $viewModel->getVariables()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Cron/Helper/ModuleUninstallTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Cron/Helper/ModuleUninstallTest.php deleted file mode 100644 index a824bee996385..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Cron/Helper/ModuleUninstallTest.php +++ /dev/null @@ -1,61 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Cron\Helper; - -use Magento\Framework\Module\PackageInfo; -use Magento\Framework\Module\PackageInfoFactory; -use Magento\Setup\Model\Cron\Helper\ModuleUninstall; -use Magento\Setup\Model\ModuleRegistryUninstaller; -use Magento\Setup\Model\ModuleUninstaller; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Output\OutputInterface; - -class ModuleUninstallTest extends TestCase -{ - public function testUninstallRemoveData() - { - $output = - $this->getMockForAbstractClass(OutputInterface::class, [], '', false); - $packageInfoFactory = $this->createMock(PackageInfoFactory::class); - $packageInfo = $this->createMock(PackageInfo::class); - $packageInfo->expects($this->once())->method('getModuleName')->willReturn('Module_A'); - $packageInfoFactory->expects($this->any())->method('create')->willReturn($packageInfo); - $moduleUninstaller = $this->createMock(ModuleUninstaller::class); - $moduleUninstaller->expects($this->once())->method('uninstallData')->with($output, ['Module_A']); - $moduleRegistryUninstaller = - $this->createMock(ModuleRegistryUninstaller::class); - $moduleRegistryUninstaller->expects($this->once())->method('removeModulesFromDb')->with($output, ['Module_A']); - $moduleRegistryUninstaller->expects($this->once()) - ->method('removeModulesFromDeploymentConfig') - ->with($output, ['Module_A']); - - $moduleUninstall = new ModuleUninstall($moduleUninstaller, $moduleRegistryUninstaller, $packageInfoFactory); - $moduleUninstall->uninstall($output, 'vendor/module-package', true); - } - - public function testUninstallNotRemoveData() - { - $output = - $this->getMockForAbstractClass(OutputInterface::class, [], '', false); - $packageInfoFactory = $this->createMock(PackageInfoFactory::class); - $packageInfo = $this->createMock(PackageInfo::class); - $packageInfo->expects($this->once())->method('getModuleName')->willReturn('Module_A'); - $packageInfoFactory->expects($this->any())->method('create')->willReturn($packageInfo); - $moduleUninstaller = $this->createMock(ModuleUninstaller::class); - $moduleUninstaller->expects($this->never())->method('uninstallData'); - $moduleRegistryUninstaller = - $this->createMock(ModuleRegistryUninstaller::class); - $moduleRegistryUninstaller->expects($this->once())->method('removeModulesFromDb')->with($output, ['Module_A']); - $moduleRegistryUninstaller->expects($this->once()) - ->method('removeModulesFromDeploymentConfig') - ->with($output, ['Module_A']); - - $moduleUninstall = new ModuleUninstall($moduleUninstaller, $moduleRegistryUninstaller, $packageInfoFactory); - $moduleUninstall->uninstall($output, 'vendor/module-package', false); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Cron/Helper/ThemeUninstallTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Cron/Helper/ThemeUninstallTest.php deleted file mode 100644 index e8cde6a8bfaa4..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Cron/Helper/ThemeUninstallTest.php +++ /dev/null @@ -1,29 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Cron\Helper; - -use Magento\Setup\Model\Cron\Helper\ThemeUninstall; -use Magento\Theme\Model\Theme\ThemePackageInfo; -use Magento\Theme\Model\Theme\ThemeUninstaller; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Output\OutputInterface; - -class ThemeUninstallTest extends TestCase -{ - public function testUninstall() - { - $themeUninstaller = $this->createMock(ThemeUninstaller::class); - $themePackageInfo = $this->createMock(ThemePackageInfo::class); - $output = - $this->getMockForAbstractClass(OutputInterface::class, [], '', false); - $themePackageInfo->expects($this->once())->method('getFullThemePath')->willReturn('theme/path'); - $themeUninstaller->expects($this->once())->method('uninstallRegistry')->with($output, ['theme/path']); - $themeUninstall = new ThemeUninstall($themeUninstaller, $themePackageInfo); - $themeUninstall->uninstall($output, 'vendor/package-theme'); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobComponentUninstallTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobComponentUninstallTest.php deleted file mode 100644 index e4a8ef110031a..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobComponentUninstallTest.php +++ /dev/null @@ -1,318 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Cron; - -use Magento\Framework\Composer\ComposerInformation; -use Magento\Framework\Module\PackageInfo; -use Magento\Framework\Module\PackageInfoFactory; -use Magento\Framework\ObjectManagerInterface; -use Magento\Setup\Model\Cron\Helper\ModuleUninstall; -use Magento\Setup\Model\Cron\Helper\ThemeUninstall; -use Magento\Setup\Model\Cron\JobComponentUninstall; -use Magento\Setup\Model\Cron\Queue; -use Magento\Setup\Model\Cron\Status; -use Magento\Setup\Model\ObjectManagerProvider; -use Magento\Setup\Model\Updater; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Output\OutputInterface; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class JobComponentUninstallTest extends TestCase -{ - /** - * @var JobComponentUninstall - */ - private $job; - - /** - * @var MockObject|OutputInterface - */ - private $output; - - /** - * @var MockObject|Status - */ - private $status; - - /** - * @var MockObject|Updater - */ - private $updater; - - /** - * @var MockObject|ObjectManagerInterface - */ - private $objectManager; - - /** - * @var MockObject|ObjectManagerProvider - */ - private $objectManagerProvider; - - /** - * @var MockObject|ModuleUninstall - */ - private $moduleUninstallHelper; - - /** - * @var MockObject|ThemeUninstall - */ - private $themeUninstallHelper; - - /** - * @var MockObject|ComposerInformation - */ - private $composerInformation; - - /** - * @var MockObject|Queue - */ - private $quence; - - protected function setUp(): void - { - $this->output = $this->getMockForAbstractClass( - OutputInterface::class, - [], - '', - false - ); - $this->status = $this->createMock(Status::class); - $this->moduleUninstallHelper = $this->createMock(ModuleUninstall::class); - $this->themeUninstallHelper = $this->createMock(ThemeUninstall::class); - $this->composerInformation = $this->createMock(ComposerInformation::class); - $this->objectManagerProvider = - $this->createMock(ObjectManagerProvider::class); - $this->objectManager = $this->getMockForAbstractClass( - ObjectManagerInterface::class, - [], - '', - false - ); - - $packageInfoFactory = $this->createMock(PackageInfoFactory::class); - $packageInfo = $this->createMock(PackageInfo::class); - $packageInfoFactory->expects($this->any())->method('create')->willReturn($packageInfo); - $this->objectManagerProvider->expects($this->any())->method('get')->willReturn($this->objectManager); - $this->updater = $this->createMock(Updater::class); - $this->quence = $this->createPartialMock(Queue::class, ['addJobs']); - } - - private function setUpUpdater() - { - $this->updater->expects($this->any())->method('createUpdaterTask')->willReturn(''); - } - - private function setUpQuence() - { - $this->quence->expects($this->once())->method('addJobs'); - } - - public function testExecuteModule() - { - $this->setUpUpdater(); - $this->setUpQuence(); - $this->moduleUninstallHelper->expects($this->once()) - ->method('uninstall') - ->with($this->output, 'vendor/module-package', true); - - $this->job = new JobComponentUninstall( - $this->composerInformation, - $this->moduleUninstallHelper, - $this->themeUninstallHelper, - $this->objectManagerProvider, - $this->output, - $this->quence, - $this->status, - $this->updater, - 'setup:component:uninstall', - [ - 'components' => [ - [ - JobComponentUninstall::COMPONENT_NAME => 'vendor/module-package', - ] - ], - 'dataOption' => 'true' - ] - ); - - $this->composerInformation->expects($this->once()) - ->method('getInstalledMagentoPackages') - ->willReturn(['vendor/module-package' => ['type' => ComposerInformation::MODULE_PACKAGE_TYPE]]); - $this->job->execute(); - } - - public function testExecuteLanguage() - { - $this->setUpUpdater(); - $this->setUpQuence(); - $this->composerInformation->expects($this->once()) - ->method('getInstalledMagentoPackages') - ->willReturn(['vendor/language-a' => ['type' => ComposerInformation::LANGUAGE_PACKAGE_TYPE]]); - - $this->moduleUninstallHelper->expects($this->never())->method($this->anything()); - $this->themeUninstallHelper->expects($this->never())->method($this->anything()); - - $this->job = new JobComponentUninstall( - $this->composerInformation, - $this->moduleUninstallHelper, - $this->themeUninstallHelper, - $this->objectManagerProvider, - $this->output, - $this->quence, - $this->status, - $this->updater, - 'setup:component:uninstall', - [ - 'components' => [ - [ - JobComponentUninstall::COMPONENT_NAME => 'vendor/language-a', - ] - ] - ] - ); - $this->job->execute(); - } - - public function testExecuteTheme() - { - $this->setUpUpdater(); - $this->setUpQuence(); - $this->composerInformation->expects($this->once()) - ->method('getInstalledMagentoPackages') - ->willReturn(['vendor/theme-a' => ['type' => ComposerInformation::THEME_PACKAGE_TYPE]]); - $this->themeUninstallHelper->expects($this->once()) - ->method('uninstall') - ->with($this->output, 'vendor/theme-a'); - $this->moduleUninstallHelper->expects($this->never())->method($this->anything()); - - $this->job = new JobComponentUninstall( - $this->composerInformation, - $this->moduleUninstallHelper, - $this->themeUninstallHelper, - $this->objectManagerProvider, - $this->output, - $this->quence, - $this->status, - $this->updater, - 'setup:component:uninstall', - [ - 'components' => [ - [ - JobComponentUninstall::COMPONENT_NAME => 'vendor/theme-a', - ] - ] - ] - ); - $this->job->execute(); - } - - public function testExecuteUnknownType() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('Unknown component type'); - $this->setUpUpdater(); - $this->composerInformation->expects($this->once()) - ->method('getInstalledMagentoPackages') - ->willReturn(['vendor/unknown-a' => ['type' => 'unknown']]); - - $this->moduleUninstallHelper->expects($this->never())->method($this->anything()); - $this->themeUninstallHelper->expects($this->never())->method($this->anything()); - - $this->job = new JobComponentUninstall( - $this->composerInformation, - $this->moduleUninstallHelper, - $this->themeUninstallHelper, - $this->objectManagerProvider, - $this->output, - $this->quence, - $this->status, - $this->updater, - 'setup:component:uninstall', - [ - 'components' => [ - [ - JobComponentUninstall::COMPONENT_NAME => 'vendor/unknown-a', - ] - ] - ] - ); - $this->job->execute(); - } - - /** - * @param array $params - * @dataProvider executeWrongFormatDataProvider - */ - public function testExecuteWrongFormat(array $params) - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('Job parameter format is incorrect'); - $this->moduleUninstallHelper->expects($this->never())->method($this->anything()); - $this->themeUninstallHelper->expects($this->never())->method($this->anything()); - - $this->job = new JobComponentUninstall( - $this->composerInformation, - $this->moduleUninstallHelper, - $this->themeUninstallHelper, - $this->objectManagerProvider, - $this->output, - $this->quence, - $this->status, - $this->updater, - 'setup:component:uninstall', - $params - ); - $this->job->execute(); - } - - /** - * @return array - */ - public function executeWrongFormatDataProvider() - { - return [ - 'empty' => [[]], - 'no name' => [['components' => [['key' => 'value']]]], - 'components not array' => [['components' => '']], - ]; - } - - public function testExecuteUpdateFails() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('error'); - $this->updater->expects($this->once())->method('createUpdaterTask')->willReturn('error'); - $this->composerInformation->expects($this->once()) - ->method('getInstalledMagentoPackages') - ->willReturn(['vendor/language-a' => ['type' => ComposerInformation::LANGUAGE_PACKAGE_TYPE]]); - - $this->job = new JobComponentUninstall( - $this->composerInformation, - $this->moduleUninstallHelper, - $this->themeUninstallHelper, - $this->objectManagerProvider, - $this->output, - $this->quence, - $this->status, - $this->updater, - 'setup:component:uninstall', - [ - 'components' => [ - [ - JobComponentUninstall::COMPONENT_NAME => 'vendor/language-a', - ] - ] - ] - ); - $this->job->execute(); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobDbRollbackTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobDbRollbackTest.php deleted file mode 100644 index a81577152a15b..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobDbRollbackTest.php +++ /dev/null @@ -1,102 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Cron; - -use Magento\Framework\App\State; -use Magento\Framework\ObjectManager\ConfigLoaderInterface; -use Magento\Framework\ObjectManagerInterface; -use Magento\Framework\Setup\BackupRollback; -use Magento\Framework\Setup\BackupRollbackFactory; -use Magento\Setup\Model\Cron\JobDbRollback; -use Magento\Setup\Model\Cron\Status; -use Magento\Setup\Model\ObjectManagerProvider; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Output\OutputInterface; - -class JobDbRollbackTest extends TestCase -{ - /** - * @var JobDbRollback - */ - private $jobDbRollback; - - /** - * @var MockObject|BackupRollbackFactory - */ - private $backupRollbackFactory; - - /** - * @var MockObject|BackupRollback - */ - private $backupRollback; - - /** - * @var MockObject|Status - */ - private $status; - - /** - * @var MockObject|ObjectManagerProvider - */ - private $objectManagerProvider; - - protected function setup(): void - { - $this->backupRollbackFactory = $this->createMock(BackupRollbackFactory::class); - $this->backupRollback = $this->createMock(BackupRollback::class); - $this->status = $this->createMock(Status::class); - $output = - $this->getMockForAbstractClass(OutputInterface::class, [], '', false); - $this->objectManagerProvider = - $this->createMock(ObjectManagerProvider::class); - - $appState = $this->createMock(State::class); - $configLoader = $this->getMockForAbstractClass( - ConfigLoaderInterface::class, - [], - '', - false - ); - $configLoader->expects($this->any())->method('load')->willReturn([]); - $objectManager = - $this->getMockForAbstractClass(ObjectManagerInterface::class, [], '', false); - $objectManager->expects($this->any()) - ->method('get') - ->willReturnMap([ - [State::class, $appState], - [ConfigLoaderInterface::class, $configLoader], - ]); - - $this->objectManagerProvider->expects($this->once())->method('get')->willReturn($objectManager); - - $this->jobDbRollback = new JobDbRollback( - $this->backupRollbackFactory, - $output, - $this->status, - $this->objectManagerProvider, - 'setup:rollback', - ['backup_file_name' => 'someFileName'] - ); - } - - public function testExecute() - { - $this->backupRollbackFactory->expects($this->once())->method('create')->willReturn($this->backupRollback); - $this->backupRollback->expects($this->once())->method('dbRollback'); - $this->jobDbRollback->execute(); - } - - public function testExceptionOnExecute() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('Could not complete'); - $this->backupRollbackFactory->expects($this->once())->method('create')->willThrowException(new \Exception()); - $this->jobDbRollback->execute(); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobFactoryTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobFactoryTest.php deleted file mode 100644 index 8ca45e1ad54fd..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobFactoryTest.php +++ /dev/null @@ -1,255 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Cron; - -use Laminas\ServiceManager\ServiceLocatorInterface; -use Magento\Backend\Console\Command\CacheDisableCommand; -use Magento\Backend\Console\Command\CacheEnableCommand; -use Magento\Framework\App\Cache; -use Magento\Framework\App\State\CleanupFiles; -use Magento\Framework\Composer\ComposerInformation; -use Magento\Framework\Module\PackageInfoFactory; -use Magento\Framework\ObjectManagerInterface; -use Magento\Framework\Setup\BackupRollbackFactory; -use Magento\Setup\Console\Command\MaintenanceDisableCommand; -use Magento\Setup\Console\Command\MaintenanceEnableCommand; -use Magento\Setup\Console\Command\ModuleDisableCommand; -use Magento\Setup\Console\Command\ModuleEnableCommand; -use Magento\Setup\Console\Command\UpgradeCommand; -use Magento\Setup\Model\Cron\AbstractJob; -use Magento\Setup\Model\Cron\JobComponentUninstall; -use Magento\Setup\Model\Cron\JobFactory; -use Magento\Setup\Model\Cron\JobSetCache; -use Magento\Setup\Model\Cron\JobSetMaintenanceMode; -use Magento\Setup\Model\Cron\Queue; -use Magento\Setup\Model\Cron\Status; -use Magento\Setup\Model\ModuleRegistryUninstaller; -use Magento\Setup\Model\ModuleUninstaller; -use Magento\Setup\Model\ObjectManagerProvider; -use Magento\Setup\Model\Updater; -use Magento\Theme\Model\Theme\ThemePackageInfo; -use Magento\Theme\Model\Theme\ThemeUninstaller; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class JobFactoryTest extends TestCase -{ - /** - * @var MockObject|ObjectManagerInterface - */ - private $objectManager; - - /** - * @var JobFactory - */ - private $jobFactory; - - protected function setUp(): void - { - $serviceManager = - $this->getMockForAbstractClass(ServiceLocatorInterface::class, [], '', false); - $status = $this->createMock(Status::class); - $status->expects($this->once())->method('getStatusFilePath')->willReturn('path_a'); - $status->expects($this->once())->method('getLogFilePath')->willReturn('path_b'); - $objectManagerProvider = $this->createMock(ObjectManagerProvider::class); - $this->objectManager = $this->getMockForAbstractClass( - ObjectManagerInterface::class, - [], - '', - false - ); - $objectManagerProvider->expects($this->atLeastOnce())->method('get')->willReturn($this->objectManager); - - $upgradeCommand = $this->createMock(UpgradeCommand::class); - $moduleUninstaller = $this->createMock(ModuleUninstaller::class); - $moduleRegistryUninstaller = - $this->createMock(ModuleRegistryUninstaller::class); - $moduleEnabler = $this->createMock(ModuleEnableCommand::class); - $moduleDisabler = $this->createMock(ModuleDisableCommand::class); - $maintenanceDisabler = $this->createMock(MaintenanceDisableCommand::class); - $maintenanceEnabler = $this->createMock(MaintenanceEnableCommand::class); - - $updater = $this->createMock(Updater::class); - $queue = $this->createMock(Queue::class); - - $returnValueMap = [ - [Updater::class, $updater], - [Status::class, $status], - [UpgradeCommand::class, $upgradeCommand], - [ObjectManagerProvider::class, $objectManagerProvider], - [ModuleUninstaller::class, $moduleUninstaller], - [ModuleRegistryUninstaller::class, $moduleRegistryUninstaller], - [ModuleDisableCommand::class, $moduleDisabler], - [ModuleEnableCommand::class, $moduleEnabler], - [MaintenanceDisableCommand::class, $maintenanceDisabler], - [MaintenanceEnableCommand::class, $maintenanceEnabler], - [Queue::class, $queue] - ]; - - $serviceManager->expects($this->atLeastOnce()) - ->method('get') - ->willReturnMap($returnValueMap); - - $this->jobFactory = new JobFactory($serviceManager); - } - - public function testUpgrade() - { - $this->assertInstanceOf( - AbstractJob::class, - $this->jobFactory->create('setup:upgrade', []) - ); - } - - public function testRollback() - { - $valueMap = [ - [ - CleanupFiles::class, - $this->createMock(CleanupFiles::class) - ], - [ - Cache::class, - $this->createMock(Cache::class) - ], - [ - BackupRollbackFactory::class, - $this->createMock(BackupRollbackFactory::class) - ], - ]; - $this->objectManager->expects($this->any()) - ->method('get') - ->willReturnMap($valueMap); - - $this->assertInstanceOf( - AbstractJob::class, - $this->jobFactory->create('setup:rollback', []) - ); - } - - public function testComponentUninstall() - { - $valueMap = [ - [ - PackageInfoFactory::class, - $this->createMock(PackageInfoFactory::class) - ], - [ - ComposerInformation::class, - $this->createMock(ComposerInformation::class) - ], - [ - ThemeUninstaller::class, - $this->createMock(ThemeUninstaller::class) - ], - [ - ThemePackageInfo::class, - $this->createMock(ThemePackageInfo::class) - ], - ]; - $this->objectManager->expects($this->any()) - ->method('get') - ->willReturnMap($valueMap); - $this->assertInstanceOf( - JobComponentUninstall::class, - $this->jobFactory->create('setup:component:uninstall', []) - ); - } - - public function testCreateUnknownJob() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('job is not supported'); - $this->jobFactory->create('unknown', []); - } - - public function testCacheEnable() - { - $valueMap = [ - [ - CacheEnableCommand::class, - $this->getMockBuilder(CacheEnableCommand::class) - ->disableOriginalConstructor() - ->getMock() - ] - ]; - - $this->objectManager->expects($this->any()) - ->method('get') - ->willReturnMap($valueMap); - - $this->assertInstanceOf( - JobSetCache::class, - $this->jobFactory->create('setup:cache:enable', []) - ); - } - - public function testCacheDisable() - { - $valueMap = [ - [ - CacheDisableCommand::class, - $this->getMockBuilder(CacheDisableCommand::class) - ->disableOriginalConstructor() - ->getMock() - ] - ]; - $this->objectManager->expects($this->any())->method('get')->willReturnMap($valueMap); - - $this->assertInstanceOf( - JobSetCache::class, - $this->jobFactory->create('setup:cache:disable', []) - ); - } - - public function testMaintenanceModeEnable() - { - $this->assertInstanceOf( - JobSetMaintenanceMode::class, - $this->jobFactory->create(JobFactory::JOB_MAINTENANCE_MODE_ENABLE, []) - ); - } - - public function testMaintenanceModeDisable() - { - $this->assertInstanceOf( - JobSetMaintenanceMode::class, - $this->jobFactory->create(JobFactory::JOB_MAINTENANCE_MODE_DISABLE, []) - ); - } -} - -// functions to override native php functions -namespace Magento\Setup\Model\Cron; - -/** - * @return string - */ -function fopen() -{ - return 'filestream'; -} - -/** - * @return bool - */ -function is_resource() -{ - return true; -} - -/** - * @return string - */ -function get_resource_type() -{ - return 'stream'; -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobModuleTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobModuleTest.php deleted file mode 100644 index d19c239dc9b53..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobModuleTest.php +++ /dev/null @@ -1,91 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Cron; - -use Magento\Framework\App\Cache; -use Magento\Framework\App\State\CleanupFiles; -use Magento\Framework\Module\PackageInfoFactory; -use Magento\Framework\ObjectManagerInterface; -use Magento\Setup\Console\Command\ModuleDisableCommand; -use Magento\Setup\Console\Command\ModuleEnableCommand; -use Magento\Setup\Model\Cron\JobModule; -use Magento\Setup\Model\Cron\Status; -use Magento\Setup\Model\ObjectManagerProvider; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Output\OutputInterface; - -class JobModuleTest extends TestCase -{ - public function testExecuteModuleDisable() - { - $objectManagerProvider = $this->createMock(ObjectManagerProvider::class); - $objectManager = - $this->getMockForAbstractClass(ObjectManagerInterface::class, [], '', false); - $cleanupFiles = $this->createMock(CleanupFiles::class); - $cleanupFiles->expects($this->once())->method('clearCodeGeneratedFiles'); - $cache = $this->createMock(Cache::class); - $cache->expects($this->once())->method('clean'); - $valueMap = [ - [PackageInfoFactory::class], - [CleanupFiles::class, $cleanupFiles], - [Cache::class, $cache], - ]; - $objectManager->expects($this->atLeastOnce())->method('get')->willReturnMap($valueMap); - $objectManagerProvider->expects($this->once())->method('get')->willReturn($objectManager); - $command = $this->createMock(ModuleDisableCommand::class); - $command->expects($this->once())->method('run'); - $status = $this->createMock(Status::class); - $status->expects($this->atLeastOnce())->method('add'); - $output = - $this->getMockForAbstractClass(OutputInterface::class, [], '', false); - $params['components'][] = ['name' => 'vendor/module']; - $jobModuleDisable = new JobModule( - $command, - $objectManagerProvider, - $output, - $status, - 'setup:module:disable', - $params - ); - $jobModuleDisable->execute(); - } - - public function testExecuteModuleEnable() - { - $objectManagerProvider = $this->createMock(ObjectManagerProvider::class); - $objectManager = - $this->getMockForAbstractClass(ObjectManagerInterface::class, [], '', false); - $cleanupFiles = $this->createMock(CleanupFiles::class); - $cleanupFiles->expects($this->once())->method('clearCodeGeneratedFiles'); - $cache = $this->createMock(Cache::class); - $cache->expects($this->once())->method('clean'); - $valueMap = [ - [PackageInfoFactory::class], - [CleanupFiles::class, $cleanupFiles], - [Cache::class, $cache], - ]; - $objectManager->expects($this->atLeastOnce())->method('get')->willReturnMap($valueMap); - $objectManagerProvider->expects($this->once())->method('get')->willReturn($objectManager); - $command = $this->createMock(ModuleEnableCommand::class); - $command->expects($this->once())->method('run'); - $status = $this->createMock(Status::class); - $status->expects($this->atLeastOnce())->method('add'); - $output = - $this->getMockForAbstractClass(OutputInterface::class, [], '', false); - $params['components'][] = ['name' => 'vendor/module']; - $jobModuleEnable = new JobModule( - $command, - $objectManagerProvider, - $output, - $status, - 'setup:module:enable', - $params - ); - $jobModuleEnable->execute(); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobSetCacheTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobSetCacheTest.php deleted file mode 100644 index 3322862b46ac0..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobSetCacheTest.php +++ /dev/null @@ -1,96 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Cron; - -use Magento\Backend\Console\Command\CacheDisableCommand; -use Magento\Backend\Console\Command\CacheEnableCommand; -use Magento\Framework\App\Cache; -use Magento\Framework\App\State\CleanupFiles; -use Magento\Framework\Module\PackageInfoFactory; -use Magento\Framework\ObjectManagerInterface; -use Magento\Setup\Model\Cron\JobSetCache; -use Magento\Setup\Model\Cron\Status; -use Magento\Setup\Model\ObjectManagerProvider; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Input\ArrayInput; -use Symfony\Component\Console\Input\InputArgument; -use Symfony\Component\Console\Input\InputDefinition; -use Symfony\Component\Console\Output\OutputInterface; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class JobSetCacheTest extends TestCase -{ - /** - * @dataProvider setCacheDataProvider - * @param string $commandClass - * @param array $arrayInput - * @param string $jobName - * @param array $params - */ - public function testSetCache($commandClass, $arrayInput, $jobName, $params) - { - $arrayInput = new ArrayInput($arrayInput); - $objectManagerProvider = $this->createMock(ObjectManagerProvider::class); - $objectManager = - $this->getMockForAbstractClass(ObjectManagerInterface::class, [], '', false); - $cleanupFiles = $this->createMock(CleanupFiles::class); - $cache = $this->createMock(Cache::class); - $valueMap = [ - [ PackageInfoFactory::class], - [ CleanupFiles::class, $cleanupFiles], - [ Cache::class, $cache], - ]; - $objectManager->expects($this->atLeastOnce())->method('get')->willReturnMap($valueMap); - $objectManagerProvider->expects($this->once())->method('get')->willReturn($objectManager); - - $output = - $this->getMockForAbstractClass(OutputInterface::class, [], '', false); - $status = $this->createMock(Status::class); - $command = $this->createMock($commandClass); - - $command->expects($this->once()) - ->method('run') - ->with($arrayInput, $output); - - $definition = new InputDefinition([ - new InputArgument('types', InputArgument::REQUIRED), - new InputArgument('command', InputArgument::REQUIRED), - ]); - - $inputDef = $this->createMock(InputDefinition::class); - $inputDef->expects($this->any())->method('hasArgument')->willReturn(true); - $command->expects($this->any())->method('getDefinition')->willReturn($inputDef); - $command->expects($this->any())->method('setDefinition')->with($definition); - - $model = new JobSetCache($command, $objectManagerProvider, $output, $status, $jobName, $params); - $model->execute(); - } - - /** - * @return array - */ - public function setCacheDataProvider() - { - return [ - [ - CacheEnableCommand::class, - ['command' => 'cache:enable', 'types' => ['cache1']], - 'setup:cache:enable', - ['cache1'] - ], - [ - CacheDisableCommand::class, - ['command' => 'cache:disable'], - 'setup:cache:disable', - [] - ], - ]; - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobSetMaintenanceModeTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobSetMaintenanceModeTest.php deleted file mode 100644 index 6a9f05d9ef3c0..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobSetMaintenanceModeTest.php +++ /dev/null @@ -1,106 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Cron; - -use Magento\Framework\App\Cache; -use Magento\Framework\App\State\CleanupFiles; -use Magento\Framework\ObjectManagerInterface; -use Magento\Setup\Console\Command\MaintenanceDisableCommand; -use Magento\Setup\Console\Command\MaintenanceEnableCommand; -use Magento\Setup\Model\Cron\JobSetMaintenanceMode; -use Magento\Setup\Model\Cron\Status; -use Magento\Setup\Model\ObjectManagerProvider; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Output\OutputInterface; - -class JobSetMaintenanceModeTest extends TestCase -{ - /** - * @var Status|MockObject - */ - private $statusMock; - - /** - * @var OutputInterface|MockObject - */ - private $outputMock; - - /** - * @var ObjectManagerProvider|MockObject - */ - private $objectManagerProviderMock; - - protected function setUp(): void - { - $this->objectManagerProviderMock = $this->createMock(ObjectManagerProvider::class); - $objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class, [], '', false); - $cleanupFiles = $this->createMock(CleanupFiles::class); - $cache = $this->createMock(Cache::class); - $valueMap = [ - [CleanupFiles::class, $cleanupFiles], - [Cache::class, $cache], - - ]; - $objectManager->expects($this->atLeastOnce())->method('get')->willReturnMap($valueMap); - $this->objectManagerProviderMock->expects($this->once())->method('get')->willReturn($objectManager); - - $this->statusMock = $this->createMock(Status::class); - $this->outputMock = $this->getMockForAbstractClass(OutputInterface::class); - } - - public function testExecuteMaintenanceModeDisable() - { - $command = $this->createMock(MaintenanceDisableCommand::class); - $command->expects($this->once())->method('run'); - - $jobMaintenanceDisable = new JobSetMaintenanceMode( - $command, - $this->objectManagerProviderMock, - $this->outputMock, - $this->statusMock, - 'setup:maintenance:disable' - ); - $jobMaintenanceDisable->execute(); - } - - /** - * Test MaintenanceModeDisable job execution when maintenance mode is set manually by admin - */ - public function testExecuteMaintenanceModeDisableExeption() - { - $this->expectException('RuntimeException'); - $command = $this->createMock(MaintenanceDisableCommand::class); - $command->expects($this->once())->method('isSetAddressInfo')->willReturn(true); - $command->expects($this->never())->method('run'); - - $jobMaintenanceDisable = new JobSetMaintenanceMode( - $command, - $this->objectManagerProviderMock, - $this->outputMock, - $this->statusMock, - 'setup:maintenance:disable' - ); - $jobMaintenanceDisable->execute(); - } - - public function testExecuteMaintenanceModeEnable() - { - $command = $this->createMock(MaintenanceEnableCommand::class); - $command->expects($this->once())->method('run'); - - $jobMaintenanceEnable = new JobSetMaintenanceMode( - $command, - $this->objectManagerProviderMock, - $this->outputMock, - $this->statusMock, - 'setup:maintenance:enable' - ); - $jobMaintenanceEnable->execute(); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobStaticRegenerateTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobStaticRegenerateTest.php deleted file mode 100644 index 8b046f378ea27..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobStaticRegenerateTest.php +++ /dev/null @@ -1,223 +0,0 @@ -<?php - -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Cron; - -use Magento\Deploy\Model\Filesystem; -use Magento\Deploy\Model\Mode; -use Magento\Framework\App\State; -use Magento\Framework\App\State\CleanupFiles; -use Magento\Setup\Model\Cron\JobStaticRegenerate; -use Magento\Setup\Model\Cron\Status; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Output\OutputInterface; - -class JobStaticRegenerateTest extends TestCase -{ - /** - * @var MockObject|\Magento\Setup\Model\Cron\JobStaticRegenerate - */ - private $jobStaticRegenerate; - - protected function setUp(): void - { - $this->jobStaticRegenerate = $this->getJobStaticRegenerateMock(); - } - - /** - * @covers \Magento\Setup\Model\Cron\JobStaticRegenerate::execute - */ - public function testExecuteProductionMode() - { - $modeObjectMock = $this->getModeObjectMock(); - $modeObjectMock->expects($this->once()) - ->method('getMode') - ->willReturn(State::MODE_PRODUCTION); - - $filesystemMock = $this->getFilesystemObjectMock(); - $filesystemMock - ->expects($this->once()) - ->method('regenerateStatic'); - - $this->jobStaticRegenerate - ->expects($this->once()) - ->method('getFilesystem') - ->willReturn($filesystemMock); - - $this->jobStaticRegenerate - ->expects($this->once()) - ->method('getModeObject') - ->willReturn($modeObjectMock); - - $this->jobStaticRegenerate - ->expects($this->once()) - ->method('getOutputObject') - ->willReturn($this->getOutputObjectMock()); - - $this->jobStaticRegenerate->execute(); - } - - /** - * @covers \Magento\Setup\Model\Cron\JobStaticRegenerate::execute - */ - public function testExecuteDevelopernMode() - { - $modeObjectMock = $this->getModeObjectMock(['getMode']); - $modeObjectMock->expects($this->once()) - ->method('getMode') - ->willReturn(State::MODE_DEVELOPER); - - $this->jobStaticRegenerate - ->expects($this->once()) - ->method('getModeObject') - ->willReturn($modeObjectMock); - - $statusObject = $this->getStatusObjectMock(); - $statusObject - ->expects($this->exactly(3)) - ->method('add'); - $this->jobStaticRegenerate - ->expects($this->exactly(3)) - ->method('getStatusObject') - ->willReturn($statusObject); - - $cacheObject = $this->getCacheObjectMock(); - $cacheObject - ->expects($this->once()) - ->method('clean'); - $this->jobStaticRegenerate - ->expects($this->once()) - ->method('getCacheObject') - ->willReturn($cacheObject); - - $cleanFilesObject = $this->getCleanFilesObjectMock(); - $cleanFilesObject - ->expects($this->once()) - ->method('clearMaterializedViewFiles'); - $cleanFilesObject - ->expects($this->once()) - ->method('clearCodeGeneratedFiles'); - $this->jobStaticRegenerate - ->expects($this->exactly(2)) - ->method('getCleanFilesObject') - ->willReturn($cleanFilesObject); - - $this->jobStaticRegenerate->execute(); - } - - /** - * @covers \Magento\Setup\Model\Cron\JobStaticRegenerate::execute - */ - public function testExecuteWithException() - { - $this->expectException('RuntimeException'); - $modeObjectMock = $this->getModeObjectMock(['getMode']); - $modeObjectMock->expects($this->once()) - ->method('getMode') - ->willThrowException(new \Exception('error')); - $this->jobStaticRegenerate - ->expects($this->once()) - ->method('getModeObject') - ->willReturn($modeObjectMock); - - $statusObject = $this->getStatusObjectMock(); - $statusObject - ->expects($this->once()) - ->method('toggleUpdateError'); - $this->jobStaticRegenerate - ->expects($this->once()) - ->method('getStatusObject') - ->willReturn($statusObject); - - $this->jobStaticRegenerate->execute(); - } - - /** - * Gets JobStaticRegenerate mock - * - * @return MockObject|\Magento\Setup\Model\Cron\JobStaticRegenerate - */ - protected function getJobStaticRegenerateMock() - { - return $this->createPartialMock( - JobStaticRegenerate::class, - [ - 'getCacheObject', - 'getCleanFilesObject', - 'getStatusObject', - 'getOutputObject', - 'getModeObject', - 'getFilesystem', - ] - ); - } - - /** - * Gets ObjectManagerProvider mock - * - * @return MockObject|Filesystem - */ - protected function getFilesystemObjectMock() - { - return $this->createPartialMock(Filesystem::class, ['regenerateStatic']); - } - - /** - * Gets status object mock - * - * @return MockObject|Status - */ - protected function getStatusObjectMock() - { - return $this->createPartialMock(Status::class, ['add', 'toggleUpdateError']); - } - - /** - * Gets clean files object mock - * - * @return MockObject|CleanupFiles - */ - protected function getCleanFilesObjectMock() - { - return $this->createPartialMock(CleanupFiles::class, ['clearMaterializedViewFiles', 'clearCodeGeneratedFiles']); - } - - /** - * Gets cache object mock - * - * @return MockObject|CleanupFiles - */ - protected function getCacheObjectMock() - { - return $this->getMockBuilder(CleanupFiles::class) - ->addMethods(['clean']) - ->disableOriginalConstructor() - ->getMock(); - } - - /** - * Gets output object mock - * - * @return MockObject|OutputInterface - */ - protected function getOutputObjectMock() - { - return $this->getMockForAbstractClass(OutputInterface::class); - } - - /** - * Gets mode mock - * - * @return MockObject|Mode - */ - protected function getModeObjectMock() - { - return $this->createPartialMock(Mode::class, ['getMode']); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobUpgradeTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobUpgradeTest.php deleted file mode 100644 index 2b113039f865a..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Cron/JobUpgradeTest.php +++ /dev/null @@ -1,47 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Cron; - -use Magento\Framework\ObjectManagerInterface; -use Magento\Setup\Console\Command\UpgradeCommand; -use Magento\Setup\Model\Cron\JobUpgrade; -use Magento\Setup\Model\Cron\Queue; -use Magento\Setup\Model\Cron\Status; -use Magento\Setup\Model\ObjectManagerProvider; -use PHPUnit\Framework\TestCase; -use Symfony\Component\Console\Output\OutputInterface; - -class JobUpgradeTest extends TestCase -{ - public function testExecute() - { - $queue = $this->createMock(Queue::class); - $queue->expects($this->exactly(2))->method('addJobs'); - $command = $this->createMock(UpgradeCommand::class); - $command->expects($this->once())->method('run'); - $status = $this->createMock(Status::class); - $output = - $this->getMockForAbstractClass(OutputInterface::class, [], '', false); - $objectManager = - $this->getMockForAbstractClass(ObjectManagerInterface::class, [], '', false); - $objectManagerProvider = - $this->createPartialMock(ObjectManagerProvider::class, ['get']); - $objectManagerProvider->expects($this->once())->method('get')->willReturn($objectManager); - - $jobUpgrade = new JobUpgrade( - $command, - $objectManagerProvider, - $output, - $queue, - $status, - 'setup:upgrade', - [] - ); - $jobUpgrade->execute(); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Cron/Queue/ReaderTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Cron/Queue/ReaderTest.php deleted file mode 100644 index 75dc27d40b26f..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Cron/Queue/ReaderTest.php +++ /dev/null @@ -1,69 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Cron\Queue; - -use Magento\Framework\Filesystem; -use Magento\Framework\Filesystem\Directory\ReadInterface; -use Magento\Setup\Model\Cron\Queue\Reader; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class ReaderTest extends TestCase -{ - /** - * @var MockObject|Filesystem - */ - private $filesystem; - - /** - * @var MockObject|ReadInterface - */ - private $directoryRead; - - /** - * @var Reader - */ - private $reader; - - protected function setUp(): void - { - $this->filesystem = $this->createMock(Filesystem::class); - $this->directoryRead = $this->getMockForAbstractClass( - ReadInterface::class, - [], - '', - false - ); - $this->filesystem->expects($this->once())->method('getDirectoryRead')->willReturn($this->directoryRead); - $this->reader = new Reader($this->filesystem); - } - - public function testReadEmpty() - { - $this->directoryRead->expects($this->once())->method('isExist')->willReturn(false); - $this->assertEquals('', $this->reader->read()); - } - - public function testReadException() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('must be a valid JSON'); - $this->directoryRead->expects($this->once())->method('isExist')->willReturn(true); - $this->directoryRead->expects($this->once())->method('readFile')->willReturn('invalid json'); - $this->reader->read(); - } - - public function testRead() - { - $this->directoryRead->expects($this->once())->method('isExist')->willReturn(true); - $this->directoryRead->expects($this->once()) - ->method('readFile') - ->willReturn('{"jobs":[{"name": "job A", "params": []}]}'); - $this->assertEquals('{"jobs":[{"name": "job A", "params": []}]}', $this->reader->read()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Cron/Queue/WriterTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Cron/Queue/WriterTest.php deleted file mode 100644 index 25e1a1f83fe87..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Cron/Queue/WriterTest.php +++ /dev/null @@ -1,59 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Cron\Queue; - -use Magento\Framework\Filesystem; -use Magento\Framework\Filesystem\Directory\ReadInterface; -use Magento\Framework\Filesystem\Directory\WriteInterface; -use Magento\Setup\Model\Cron\Queue\Writer; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class WriterTest extends TestCase -{ - /** - * @var MockObject|Filesystem - */ - private $filesystem; - - /** - * @var MockObject|ReadInterface - */ - private $directoryWrite; - - /** - * @var Writer - */ - private $writer; - - protected function setUp(): void - { - $this->filesystem = $this->createMock(Filesystem::class); - $directoryRead = $this->getMockForAbstractClass( - ReadInterface::class, - [], - '', - false - ); - $this->directoryWrite = $this->getMockForAbstractClass( - WriteInterface::class, - [], - '', - false - ); - $this->filesystem->expects($this->once())->method('getDirectoryRead')->willReturn($directoryRead); - $this->filesystem->expects($this->once())->method('getDirectoryWrite')->willReturn($this->directoryWrite); - $this->writer = new Writer($this->filesystem); - } - - public function testWrite() - { - $this->directoryWrite->expects($this->once())->method('writeFile')->with('.update_queue.json', 'data'); - $this->writer->write('data'); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Cron/QueueTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Cron/QueueTest.php deleted file mode 100644 index c08b5c71437e6..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Cron/QueueTest.php +++ /dev/null @@ -1,167 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Cron; - -use Magento\Setup\Model\Cron\AbstractJob; -use Magento\Setup\Model\Cron\JobFactory; -use Magento\Setup\Model\Cron\Queue; -use Magento\Setup\Model\Cron\Queue\Reader; -use Magento\Setup\Model\Cron\Queue\Writer; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class QueueTest extends TestCase -{ - /** - * @var MockObject|Reader - */ - private $reader; - - /** - * @var MockObject|Writer - */ - private $writer; - - /** - * @var MockObject|JobFactory - */ - private $jobFactory; - - /** - * @var Queue - */ - private $queue; - - protected function setUp(): void - { - $this->reader = $this->createMock(Reader::class); - $this->writer = $this->createMock(Writer::class); - $this->jobFactory = $this->createMock(JobFactory::class); - $this->queue = new Queue($this->reader, $this->writer, $this->jobFactory); - } - - public function testPeek() - { - $this->reader->expects($this->once()) - ->method('read') - ->willReturn('{"jobs": [{"name": "job A", "params" : []}, {"name": "job B", "params" : []}]}'); - $this->assertEquals(['name' => 'job A', 'params' => []], $this->queue->peek()); - } - - public function testPeekEmpty() - { - $this->reader->expects($this->once()) - ->method('read') - ->willReturn(''); - $this->assertEquals([], $this->queue->peek()); - } - - public function testPeekException() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('"params" field is missing for one or more jobs'); - $this->reader->expects($this->once()) - ->method('read') - ->willReturn('{"jobs": [{"name": "job A"}, {"name": "job B"}]}'); - $this->queue->peek(); - } - - public function testPeekExceptionNoJobsKey() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('"jobs" field is missing or is not an array'); - $this->reader->expects($this->once()) - ->method('read') - ->willReturn('{"foo": "bar"}'); - $this->queue->peek(); - } - - public function testPopQueuedJob() - { - $this->reader->expects($this->once()) - ->method('read') - ->willReturn('{"jobs": [{"name": "job A", "params" : []}, {"name": "job B", "params" : []}]}'); - $job = $this->getMockForAbstractClass(AbstractJob::class, [], '', false); - $this->jobFactory->expects($this->once())->method('create')->with('job A', [])->willReturn($job); - $rawData = ['jobs' => [['name' => 'job B', 'params' => []]]]; - $this->writer->expects($this->once())->method('write')->with(json_encode($rawData, JSON_PRETTY_PRINT)); - $this->assertEquals($job, $this->queue->popQueuedJob()); - } - - public function testPopQueuedJobEmptyAfter() - { - $this->reader->expects($this->once()) - ->method('read') - ->willReturn('{"jobs": [{"name": "job A", "params" : []}]}'); - $job = $this->getMockForAbstractClass(AbstractJob::class, [], '', false); - $this->jobFactory->expects($this->once())->method('create')->with('job A', [])->willReturn($job); - $this->writer->expects($this->once())->method('write')->with(''); - $this->assertEquals($job, $this->queue->popQueuedJob()); - } - - public function testPopQueuedJobException() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('"params" field is missing for one or more jobs'); - $this->reader->expects($this->once()) - ->method('read') - ->willReturn('{"jobs": [{"name": "job A"}, {"name": "job B"}]}'); - $this->writer->expects($this->never())->method('write'); - $this->queue->popQueuedJob(); - } - - public function testPopQueuedJobExceptionNoJobsKey() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('"jobs" field is missing or is not an array'); - $this->reader->expects($this->once()) - ->method('read') - ->willReturn('{"foo": "bar"}'); - $this->writer->expects($this->never())->method('write'); - $this->queue->popQueuedJob(); - } - - public function testIsEmptyTrue() - { - $this->reader->expects($this->once())->method('read')->willReturn(''); - $this->assertTrue($this->queue->isEmpty()); - } - - public function testIsEmptyFalse() - { - $this->reader->expects($this->once()) - ->method('read') - ->willReturn('{"jobs": [{"name": "job A", "params" : []}, {"name": "job B", "params" : []}]}'); - $this->assertFalse($this->queue->isEmpty()); - } - - public function testAddJobs() - { - $queue = ['jobs' => []]; - $this->reader->expects($this->at(0))->method('read')->willReturn(''); - $queue['jobs'][] = ['name' => 'job A', 'params' => []]; - $this->writer->expects($this->at(0)) - ->method('write') - ->with(json_encode($queue, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); - $this->reader->expects($this->at(1)) - ->method('read') - ->willReturn(json_encode($queue, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); - $queue['jobs'][] = ['name' => 'job B', 'params' => []]; - $this->writer->expects($this->at(1)) - ->method('write') - ->with(json_encode($queue, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); - $this->queue->addJobs([['name' => 'job A', 'params' => []], ['name' => 'job B', 'params' => []]]); - } - - public function testAddJobsInvalidJobs() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('field is missing for one or more jobs'); - $this->queue->addJobs([['no_name' => 'no job', 'no_params' => []]]); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Cron/ReadinessCheckTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Cron/ReadinessCheckTest.php deleted file mode 100644 index efe6f4bc6e826..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Cron/ReadinessCheckTest.php +++ /dev/null @@ -1,222 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Cron; - -use Magento\Framework\App\DeploymentConfig; -use Magento\Framework\Config\ConfigOptionsListConstants; -use Magento\Framework\Filesystem; -use Magento\Framework\Filesystem\Directory\Write; -use Magento\Setup\Exception; -use Magento\Setup\Model\BasePackageInfo; -use Magento\Setup\Model\Cron\ReadinessCheck; -use Magento\Setup\Model\Cron\Status; -use Magento\Setup\Model\PhpReadinessCheck; -use Magento\Setup\Validator\DbValidator; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class ReadinessCheckTest extends TestCase -{ - /** - * @var MockObject|DbValidator - */ - private $dbValidator; - - /** - * @var MockObject|DeploymentConfig - */ - private $deploymentConfig; - - /** - * @var MockObject|Filesystem - */ - private $filesystem; - - /** - * @var MockObject|Write - */ - private $write; - - /** - * @var MockObject|PhpReadinessCheck - */ - private $phpReadinessCheck; - - /** - * @var ReadinessCheck - */ - private $readinessCheck; - - /** - * @var MockObject|BasePackageInfo - */ - private $basePackageInfo; - - /** - * @var array - */ - private $expected; - - /** - * @var MockObject|Status - */ - private $status; - - protected function setUp(): void - { - $this->dbValidator = $this->createMock(DbValidator::class); - $this->deploymentConfig = $this->createMock(DeploymentConfig::class); - $this->deploymentConfig->expects($this->once()) - ->method('get') - ->willReturn( - [ - ConfigOptionsListConstants::KEY_NAME => 'dbname', - ConfigOptionsListConstants::KEY_HOST => 'host', - ConfigOptionsListConstants::KEY_USER => 'username', - ConfigOptionsListConstants::KEY_PASSWORD => 'password' - ] - ); - $this->filesystem = $this->createMock(Filesystem::class); - $this->write = $this->createMock(Write::class); - $this->filesystem->expects($this->once())->method('getDirectoryWrite')->willReturn($this->write); - $this->phpReadinessCheck = $this->createMock(PhpReadinessCheck::class); - $this->basePackageInfo = $this->createMock(BasePackageInfo::class); - $this->basePackageInfo->expects($this->once())->method('getPaths')->willReturn([__FILE__]); - $this->status = $this->createMock(Status::class); - $this->readinessCheck = new ReadinessCheck( - $this->dbValidator, - $this->deploymentConfig, - $this->filesystem, - $this->phpReadinessCheck, - $this->basePackageInfo, - $this->status - ); - $this->phpReadinessCheck - ->expects($this->once()) - ->method('checkPhpVersion') - ->willReturn(['responseType' => 'success']); - $this->phpReadinessCheck - ->expects($this->once()) - ->method('checkPhpExtensions') - ->willReturn(['responseType' => 'success']); - $this->phpReadinessCheck - ->expects($this->once()) - ->method('checkPhpCronSettings') - ->willReturn(['responseType' => 'success']); - $this->expected = [ - ReadinessCheck::KEY_PHP_VERSION_VERIFIED => ['responseType' => 'success'], - ReadinessCheck::KEY_PHP_EXTENSIONS_VERIFIED => ['responseType' => 'success'], - ReadinessCheck::KEY_PHP_SETTINGS_VERIFIED => ['responseType' => 'success'] - ]; - } - - public function testRunReadinessCheckNoDbAccess() - { - $this->dbValidator->expects($this->once()) - ->method('checkDatabaseConnection') - ->willThrowException(new Exception('Connection failure')); - $this->write->expects($this->once())->method('isExist')->willReturn(false); - $this->write->expects($this->never())->method('readFile'); - $expected = [ - ReadinessCheck::KEY_READINESS_CHECKS => [ - ReadinessCheck::KEY_DB_WRITE_PERMISSION_VERIFIED => false, - 'error' => 'Connection failure' - ], - ReadinessCheck::KEY_PHP_CHECKS => $this->expected, - ReadinessCheck::KEY_FILE_PATHS => [ - ReadinessCheck::KEY_LIST => [__FILE__], - ReadinessCheck::KEY_ERROR => "" - ], - ReadinessCheck::KEY_CURRENT_TIMESTAMP => 100 - ]; - $expectedJson = json_encode($expected, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); - $this->write->expects($this->once()) - ->method('writeFile') - ->with(ReadinessCheck::SETUP_CRON_JOB_STATUS_FILE, $expectedJson); - $this->readinessCheck->runReadinessCheck(); - } - - public function testRunReadinessCheckNoDbWriteAccess() - { - $this->dbValidator->expects($this->once()) - ->method('checkDatabaseConnection') - ->willThrowException(new Exception('Database user username does not have write access.')); - $this->write->expects($this->once())->method('isExist')->willReturn(false); - $this->write->expects($this->never())->method('readFile'); - $expected = [ - ReadinessCheck::KEY_READINESS_CHECKS => [ - ReadinessCheck::KEY_DB_WRITE_PERMISSION_VERIFIED => false, - 'error' => 'Database user username does not have write access.' - ], - ReadinessCheck::KEY_PHP_CHECKS => $this->expected, - ReadinessCheck::KEY_FILE_PATHS => [ - ReadinessCheck::KEY_LIST => [__FILE__], - ReadinessCheck::KEY_ERROR => "" - ], - ReadinessCheck::KEY_CURRENT_TIMESTAMP => 100 - ]; - $expectedJson = json_encode($expected, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); - $this->write->expects($this->once()) - ->method('writeFile') - ->with(ReadinessCheck::SETUP_CRON_JOB_STATUS_FILE, $expectedJson); - $this->readinessCheck->runReadinessCheck(); - } - - public function testRunReadinessCheck() - { - $this->dbValidator->expects($this->once())->method('checkDatabaseConnection')->willReturn(true); - $this->write->expects($this->once())->method('isExist')->willReturn(false); - $this->write->expects($this->never())->method('readFile'); - $expected = [ - ReadinessCheck::KEY_READINESS_CHECKS => [ReadinessCheck::KEY_DB_WRITE_PERMISSION_VERIFIED => true], - ReadinessCheck::KEY_PHP_CHECKS => $this->expected, - ReadinessCheck::KEY_FILE_PATHS => [ - ReadinessCheck::KEY_LIST => [__FILE__], - ReadinessCheck::KEY_ERROR => "" - ], - ReadinessCheck::KEY_CURRENT_TIMESTAMP => 100 - ]; - $expectedJson = json_encode($expected, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); - $this->write->expects($this->once()) - ->method('writeFile') - ->with(ReadinessCheck::SETUP_CRON_JOB_STATUS_FILE, $expectedJson); - $this->readinessCheck->runReadinessCheck(); - } - - public function testRunReadinessCheckLastTimestamp() - { - $this->dbValidator->expects($this->once())->method('checkDatabaseConnection')->willReturn(true); - $this->write->expects($this->once())->method('isExist')->willReturn(true); - $this->write->expects($this->once())->method('readFile')->willReturn('{"current_timestamp": 50}'); - $expected = [ - ReadinessCheck::KEY_READINESS_CHECKS => [ReadinessCheck::KEY_DB_WRITE_PERMISSION_VERIFIED => true], - ReadinessCheck::KEY_PHP_CHECKS => $this->expected, - ReadinessCheck::KEY_FILE_PATHS => [ - ReadinessCheck::KEY_LIST => [__FILE__], - ReadinessCheck::KEY_ERROR => "" - ], - ReadinessCheck::KEY_LAST_TIMESTAMP => 50, - ReadinessCheck::KEY_CURRENT_TIMESTAMP => 100, - ]; - $expectedJson = json_encode($expected, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); - $this->write->expects($this->once()) - ->method('writeFile') - ->with(ReadinessCheck::SETUP_CRON_JOB_STATUS_FILE, $expectedJson); - $this->readinessCheck->runReadinessCheck(); - } -} - -namespace Magento\Setup\Model\Cron; - -/** - * @return int - */ -function time() -{ - return 100; -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Cron/StatusTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Cron/StatusTest.php deleted file mode 100644 index 031d924ea2caf..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Cron/StatusTest.php +++ /dev/null @@ -1,168 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Cron; - -use Magento\Framework\Exception\FileSystemException; -use Magento\Framework\Filesystem; -use Magento\Framework\Filesystem\Directory\WriteInterface; -use Magento\Framework\Phrase; -use Magento\Setup\Model\Cron\SetupLoggerFactory; -use Magento\Setup\Model\Cron\Status; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Psr\Log\LoggerInterface; -use Psr\Log\LogLevel; - -class StatusTest extends TestCase -{ - /** - * @var MockObject|Status - */ - private $status; - - /** - * @var MockObject|Filesystem - */ - private $filesystem; - - /** - * @var MockObject|WriteInterface - */ - private $varReaderWriter; - - /** - * @var MockObject|LoggerInterface - */ - private $logger; - - /** - * @var MockObject|SetupLoggerFactory - */ - private $setupLoggerFactory; - - protected function setUp(): void - { - $this->filesystem = $this->createMock(Filesystem::class); - $this->varReaderWriter = $this->getMockForAbstractClass( - WriteInterface::class, - [], - '', - false - ); - $this->filesystem->expects($this->once()) - ->method('getDirectoryWrite') - ->willReturn($this->varReaderWriter); - $this->logger = $this->getMockForAbstractClass(LoggerInterface::class, [], '', false); - $this->setupLoggerFactory = - $this->createMock(SetupLoggerFactory::class); - $this->setupLoggerFactory - ->expects($this->once()) - ->method('create') - ->with('setup-cron') - ->willReturn($this->logger); - $this->status = new Status($this->filesystem, $this->setupLoggerFactory); - } - - public function testGetStatusFilePath() - { - $this->varReaderWriter->expects($this->any()) - ->method('getAbsolutePath') - ->with('.update_status.txt') - ->willReturn('DIR/var/.update_status.txt'); - $this->assertEquals('DIR/var/.update_status.txt', $this->status->getStatusFilePath()); - } - - public function testGetLogFilePath() - { - $this->varReaderWriter->expects($this->any()) - ->method('getAbsolutePath') - ->with('log/update.log') - ->willReturn('DIR/var/log/update.log'); - $this->assertEquals('DIR/var/log/update.log', $this->status->getLogFilePath()); - } - - public function testAdd() - { - $this->varReaderWriter->expects($this->once())->method('isExist')->willReturn(false); - $this->varReaderWriter->expects($this->once())->method('writeFile'); - $this->logger->expects($this->once())->method('log')->with(LogLevel::ERROR, 'test1'); - $this->status->add('test1', LogLevel::ERROR); - } - - public function testToggleUpdateInProgressTrue() - { - $this->varReaderWriter->expects($this->once())->method('touch'); - $this->status->toggleUpdateInProgress(true); - } - - public function testToggleUpdateInProgressTrueException() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('".update_in_progress.flag" cannot be created'); - $this->varReaderWriter->expects($this->once()) - ->method('touch') - ->willThrowException(new FileSystemException(new Phrase('Exception'))); - $this->status->toggleUpdateInProgress(true); - } - - public function testToggleUpdateInProgressFalseFlagExist() - { - $this->varReaderWriter->expects($this->at(0))->method('isExist')->willReturn(true); - $this->varReaderWriter->expects($this->at(1))->method('delete'); - $this->status->toggleUpdateInProgress(false); - } - - public function testToggleUpdateInProgressFalseFlagNotExist() - { - $this->varReaderWriter->expects($this->at(0))->method('isExist')->willReturn(false); - $this->varReaderWriter->expects($this->never())->method('delete'); - $this->status->toggleUpdateInProgress(false); - } - - public function testToggleUpdateErrorTrue() - { - $this->varReaderWriter->expects($this->once())->method('touch'); - $this->status->toggleUpdateError(true); - } - - public function testToggleUpdateErrorTrueException() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('".update_error.flag" cannot be created'); - $this->varReaderWriter->expects($this->once()) - ->method('touch') - ->willThrowException(new FileSystemException(new Phrase('Exception'))); - $this->status->toggleUpdateError(true); - } - - public function testToggleUpdateErrorFalseFlagExist() - { - $this->varReaderWriter->expects($this->at(0))->method('isExist')->willReturn(true); - $this->varReaderWriter->expects($this->at(1))->method('delete'); - $this->status->toggleUpdateError(false); - } - - public function testToggleUpdateErrorFalseFlagNotExist() - { - $this->varReaderWriter->expects($this->at(0))->method('isExist')->willReturn(false); - $this->varReaderWriter->expects($this->never())->method('delete'); - $this->status->toggleUpdateError(false); - } - - public function testIsUpdateError() - { - $this->varReaderWriter->expects($this->once())->method('isExist')->willReturn(true); - $this->assertTrue($this->status->isUpdateError()); - } -} - -namespace Magento\Setup\Model\Cron; - -function chmod() -{ -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/CronScriptReadinessCheckTest.php b/setup/src/Magento/Setup/Test/Unit/Model/CronScriptReadinessCheckTest.php deleted file mode 100644 index 68e88b5f8173c..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/CronScriptReadinessCheckTest.php +++ /dev/null @@ -1,192 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model; - -use Magento\Framework\Exception\FileSystemException; -use Magento\Framework\Filesystem; -use Magento\Framework\Filesystem\Directory\Read; -use Magento\Framework\Phrase; -use Magento\Setup\Model\Cron\ReadinessCheck; -use Magento\Setup\Model\CronScriptReadinessCheck; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class CronScriptReadinessCheckTest extends TestCase -{ - /** - * @var MockObject|Read - */ - private $read; - - /** - * @var CronScriptReadinessCheck - */ - private $cronScriptReadinessCheck; - - protected function setUp(): void - { - $filesystem = $this->createMock(Filesystem::class); - $this->read = $this->createMock(Read::class); - $filesystem->expects($this->once())->method('getDirectoryRead')->willReturn($this->read); - $this->cronScriptReadinessCheck = new CronScriptReadinessCheck($filesystem); - } - - public function testCheckSetupNoStatusFile() - { - $this->read->expects($this->once()) - ->method('readFile') - ->willThrowException(new FileSystemException(new Phrase('message'))); - $expected = [ - 'success' => false, - 'error' => 'Cron job has not been configured yet' . CronScriptReadinessCheck::OTHER_CHECKS_WILL_FAIL_MSG - ]; - $this->assertEquals($expected, $this->cronScriptReadinessCheck->checkSetup()); - } - - public function testCheckSetupNoCronConfigured() - { - $this->read->expects($this->once())->method('readFile')->willReturn(''); - $expected = [ - 'success' => false, - 'error' => 'Cron job has not been configured yet' . CronScriptReadinessCheck::OTHER_CHECKS_WILL_FAIL_MSG - ]; - $this->assertEquals($expected, $this->cronScriptReadinessCheck->checkSetup()); - } - - public function testCheckSetupCronError() - { - $json = [ - ReadinessCheck::KEY_READINESS_CHECKS => [ - ReadinessCheck::KEY_DB_WRITE_PERMISSION_VERIFIED => false, - 'error' => 'error' - ] - ]; - $this->read->expects($this->once())->method('readFile')->willReturn(json_encode($json)); - $expected = ['success' => false, 'error' => 'error']; - $this->assertEquals($expected, $this->cronScriptReadinessCheck->checkSetup()); - } - - public function testCheckSetupBadTime() - { - $json = [ - ReadinessCheck::KEY_READINESS_CHECKS => [ReadinessCheck::KEY_DB_WRITE_PERMISSION_VERIFIED => true], - ReadinessCheck::KEY_CURRENT_TIMESTAMP => 200, - ReadinessCheck::KEY_LAST_TIMESTAMP => 100 - ]; - $this->read->expects($this->once())->method('readFile')->willReturn(json_encode($json)); - $expected = [ - 'success' => true, - 'notice' => 'We recommend you schedule cron to run every 1 minute' - ]; - $this->assertEquals($expected, $this->cronScriptReadinessCheck->checkSetup()); - } - - public function testCheckSetupUnknownTime() - { - $json = [ - ReadinessCheck::KEY_READINESS_CHECKS => [ReadinessCheck::KEY_DB_WRITE_PERMISSION_VERIFIED => true], - ReadinessCheck::KEY_CURRENT_TIMESTAMP => 200, - ]; - $this->read->expects($this->once())->method('readFile')->willReturn(json_encode($json)); - $expected = [ - 'success' => true, - 'notice' => 'Unable to determine cron time interval. ' . - 'We recommend you schedule cron to run every 1 minute' - ]; - $this->assertEquals($expected, $this->cronScriptReadinessCheck->checkSetup()); - } - - public function testCheckSetup() - { - $json = [ - ReadinessCheck::KEY_READINESS_CHECKS => [ReadinessCheck::KEY_DB_WRITE_PERMISSION_VERIFIED => true], - ReadinessCheck::KEY_CURRENT_TIMESTAMP => 200, - ReadinessCheck::KEY_LAST_TIMESTAMP => 140 - ]; - $this->read->expects($this->once())->method('readFile')->willReturn(json_encode($json)); - $expected = ['success' => true]; - $this->assertEquals($expected, $this->cronScriptReadinessCheck->checkSetup()); - } - - public function testCheckUpdaterNoStatusFile() - { - $this->read->expects($this->once()) - ->method('readFile') - ->willThrowException(new FileSystemException(new Phrase('message'))); - $expected = ['success' => false, 'error' => 'Cron job has not been configured yet']; - $this->assertEquals($expected, $this->cronScriptReadinessCheck->checkUpdater()); - } - - public function testCheckUpdaterNoCronConfigured() - { - $this->read->expects($this->once())->method('readFile')->willReturn(''); - $expected = ['success' => false, 'error' => 'Cron job has not been configured yet']; - $this->assertEquals($expected, $this->cronScriptReadinessCheck->checkUpdater()); - } - - public function testCheckUpdaterCronError() - { - $json = [ - ReadinessCheck::KEY_READINESS_CHECKS => [ - CronScriptReadinessCheck::UPDATER_KEY_FILE_PERMISSIONS_VERIFIED => false, - 'error' => 'error' - ] - ]; - $this->read->expects($this->once())->method('readFile')->willReturn(json_encode($json)); - $expected = ['success' => false, 'error' => 'error']; - $this->assertEquals($expected, $this->cronScriptReadinessCheck->checkUpdater()); - } - - public function testCheckUpdaterBadTime() - { - $json = [ - ReadinessCheck::KEY_READINESS_CHECKS => [ - CronScriptReadinessCheck::UPDATER_KEY_FILE_PERMISSIONS_VERIFIED => true - ], - ReadinessCheck::KEY_CURRENT_TIMESTAMP => 200, - ReadinessCheck::KEY_LAST_TIMESTAMP => 100 - ]; - $this->read->expects($this->once())->method('readFile')->willReturn(json_encode($json)); - $expected = [ - 'success' => true, - 'notice' => 'We recommend you schedule cron to run every 1 minute' - ]; - $this->assertEquals($expected, $this->cronScriptReadinessCheck->checkUpdater()); - } - - public function testCheckUpdaterUnknownTime() - { - $json = [ - ReadinessCheck::KEY_READINESS_CHECKS => [ - CronScriptReadinessCheck::UPDATER_KEY_FILE_PERMISSIONS_VERIFIED => true - ], - ReadinessCheck::KEY_CURRENT_TIMESTAMP => 200, - ]; - $this->read->expects($this->once())->method('readFile')->willReturn(json_encode($json)); - $expected = [ - 'success' => true, - 'notice' => 'Unable to determine cron time interval. ' . - 'We recommend you schedule cron to run every 1 minute' - ]; - $this->assertEquals($expected, $this->cronScriptReadinessCheck->checkUpdater()); - } - - public function testCheckUpdater() - { - $json = [ - ReadinessCheck::KEY_READINESS_CHECKS => [ - CronScriptReadinessCheck::UPDATER_KEY_FILE_PERMISSIONS_VERIFIED => true - ], - ReadinessCheck::KEY_CURRENT_TIMESTAMP => 200, - ReadinessCheck::KEY_LAST_TIMESTAMP => 140 - ]; - $this->read->expects($this->once())->method('readFile')->willReturn(json_encode($json)); - $expected = ['success' => true]; - $this->assertEquals($expected, $this->cronScriptReadinessCheck->checkUpdater()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/DependencyReadinessCheckTest.php b/setup/src/Magento/Setup/Test/Unit/Model/DependencyReadinessCheckTest.php deleted file mode 100644 index 9c7d8a9a4d51b..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/DependencyReadinessCheckTest.php +++ /dev/null @@ -1,89 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model; - -use Magento\Composer\RequireUpdateDryRunCommand; -use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Framework\Composer\ComposerJsonFinder; -use Magento\Framework\Composer\MagentoComposerApplicationFactory; -use Magento\Framework\Filesystem\Driver\File; -use Magento\Setup\Model\DependencyReadinessCheck; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class DependencyReadinessCheckTest extends TestCase -{ - /** - * @var MockObject|ComposerJsonFinder - */ - private $composerJsonFinder; - - /** - * @var MockObject|DirectoryList - */ - private $directoryList; - - /** - * @var MockObject|RequireUpdateDryRunCommand - */ - private $reqUpdDryRunCommand; - - /** - * @var MockObject|File - */ - private $file; - - /** - * @var DependencyReadinessCheck; - */ - private $dependencyReadinessCheck; - - protected function setUp(): void - { - $this->composerJsonFinder = - $this->createMock(ComposerJsonFinder::class); - $this->composerJsonFinder->expects($this->once())->method('findComposerJson')->willReturn('composer.json'); - $this->directoryList = - $this->createMock(DirectoryList::class); - $this->directoryList->expects($this->exactly(2))->method('getPath')->willReturn('var'); - $this->reqUpdDryRunCommand = - $this->createMock(RequireUpdateDryRunCommand::class); - $this->file = $this->createMock(File::class); - $this->file->expects($this->once())->method('copy')->with('composer.json', 'var/composer.json'); - $composerAppFactory = $this->createMock(MagentoComposerApplicationFactory::class); - $composerAppFactory->expects($this->once()) - ->method('createRequireUpdateDryRunCommand') - ->willReturn($this->reqUpdDryRunCommand); - $this->dependencyReadinessCheck = new DependencyReadinessCheck( - $this->composerJsonFinder, - $this->directoryList, - $this->file, - $composerAppFactory - ); - } - - public function testRunReadinessCheckFailed() - { - $this->reqUpdDryRunCommand->expects($this->once()) - ->method('run') - ->with([], 'var') - ->willThrowException(new \RuntimeException('Failed' . PHP_EOL . 'dependency readiness check')); - $expected = ['success' => false, 'error' => 'Failed<br/>dependency readiness check']; - $this->assertEquals($expected, $this->dependencyReadinessCheck->runReadinessCheck([])); - } - - public function testRunReadinessCheck() - { - $this->reqUpdDryRunCommand->expects($this->once()) - ->method('run') - ->with([], 'var') - ->willReturn('Success'); - $expected = ['success' => true]; - $this->assertEquals($expected, $this->dependencyReadinessCheck->runReadinessCheck([])); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Grid/ExtensionTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Grid/ExtensionTest.php deleted file mode 100644 index 7a16ac076ee06..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Grid/ExtensionTest.php +++ /dev/null @@ -1,112 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Grid; - -use Magento\Framework\Composer\ComposerInformation; -use Magento\Setup\Model\Grid\Extension; -use Magento\Setup\Model\PackagesData; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class ExtensionTest extends TestCase -{ - /** - * @var ComposerInformation|MockObject - */ - private $composerInformationMock; - - /** - * @var PackagesData|MockObject - */ - private $packagesDataMock; - - /** - * Extension - * - * @var Extension - */ - private $model; - - protected function setUp(): void - { - $this->composerInformationMock = $this->getMockBuilder(ComposerInformation::class) - ->disableOriginalConstructor() - ->getMock(); - $this->packagesDataMock = $this->getMockBuilder(PackagesData::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->model = new Extension( - $this->composerInformationMock, - $this->packagesDataMock - ); - } - - public function testGetList() - { - $this->composerInformationMock->expects($this->any()) - ->method('isPackageInComposerJson') - ->willReturn(true); - $this->packagesDataMock->expects($this->once()) - ->method('getInstalledPackages') - ->willReturn( - [ - 'magento/package-1' => [ - 'name' => 'magento/package-1', - 'type' => 'magento2-module', - 'package_title' => 'packageTitle', - 'package_type' => 'packageType', - 'package_link' => 'http://example.com', - 'version' => '1.0.0' - ], - 'magento/package-2' => [ - 'name' => 'magento/package-2', - 'type' => 'magento2-module', - 'package_title' => 'packageTitle', - 'package_type' => 'packageType', - 'package_link' => 'http://example.com', - 'version' => '1.0.1' - ], - ] - ); - $this->packagesDataMock->expects($this->once()) - ->method('getPackagesForUpdate') - ->willReturn( - [ - 'magento/package-1' => [] - ] - ); - - $expected = [ - [ - 'name' => 'magento/package-1', - 'type' => 'magento2-module', - 'package_title' => 'packageTitle', - 'package_type' => 'packageType', - 'version' => '1.0.0', - 'update' => true, - 'uninstall' => true, - 'vendor' => 'Magento', - 'package_link' => 'http://example.com' - ], - [ - 'name' => 'magento/package-2', - 'type' => 'magento2-module', - 'package_title' => 'packageTitle', - 'package_type' => 'packageType', - 'version' => '1.0.1', - 'update' => false, - 'uninstall' => true, - 'vendor' => 'Magento', - 'package_link' => 'http://example.com' - ], - ]; - - $this->assertEquals($expected, $this->model->getList()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Grid/ModuleTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Grid/ModuleTest.php deleted file mode 100644 index 04cb929edac93..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Grid/ModuleTest.php +++ /dev/null @@ -1,209 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Grid; - -use Magento\Framework\Composer\ComposerInformation; -use Magento\Framework\Module\FullModuleList; -use Magento\Framework\Module\ModuleList; -use Magento\Framework\Module\PackageInfo; -use Magento\Framework\Module\PackageInfoFactory; -use Magento\Framework\ObjectManagerInterface; -use Magento\Setup\Model\Grid\Module; -use Magento\Setup\Model\ObjectManagerProvider; -use Magento\Setup\Model\PackagesData; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class ModuleTest extends TestCase -{ - /** - * @var ComposerInformation|MockObject - */ - private $composerInformationMock; - - /** - * @var FullModuleList|MockObject - */ - private $fullModuleListMock; - - /** - * @var ModuleList|MockObject - */ - private $moduleListMock; - - /** - * @var PackageInfoFactory|MockObject - */ - private $packageInfoFactoryMock; - - /** - * Module package info - * - * @var PackageInfo|MockObject - */ - private $packageInfoMock; - - /** - * @var ObjectManagerProvider|MockObject - */ - private $objectManagerProvider; - - /** - * @var PackagesData|MockObject - */ - private $packagesDataMock; - - /** - * Model - * - * @var Module - */ - private $model; - - /** - * @var array - */ - private $moduleData = []; - - protected function setUp(): void - { - $this->moduleData = [ - 'magento/sample-module-one' => [ - 'name' => 'magento/sample-module-one', - 'type' => 'magento2-module', - 'version' => '1.0.0', - ], - ]; - - $fullModuleList = [ - 'Sample_ModuleOne', 'Sample_ModuleTwo', - ]; - - $this->composerInformationMock = $this->getMockBuilder(ComposerInformation::class) - ->disableOriginalConstructor() - ->getMock(); - $this->objectManagerProvider = $this->getMockBuilder(ObjectManagerProvider::class) - ->disableOriginalConstructor() - ->getMock(); - $this->packageInfoFactoryMock = $this->getMockBuilder(PackageInfoFactory::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->moduleListMock = $this->getMockBuilder(ModuleList::class) - ->disableOriginalConstructor() - ->getMock(); - $this->moduleListMock->expects(static::any()) - ->method('has') - ->willReturn(true); - - $this->fullModuleListMock = $this->getMockBuilder(FullModuleList::class) - ->disableOriginalConstructor() - ->getMock(); - $this->fullModuleListMock->expects(static::any()) - ->method('getNames') - ->willReturn($fullModuleList); - - $this->packageInfoMock = $this->getMockBuilder(PackageInfo::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->packagesDataMock = $this->getMockBuilder(PackagesData::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->model = new Module( - $this->composerInformationMock, - $this->fullModuleListMock, - $this->moduleListMock, - $this->objectManagerProvider, - $this->packagesDataMock - ); - } - - public function testGetList() - { - $objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $this->objectManagerProvider->expects($this->once()) - ->method('get') - ->willReturn($objectManager); - $objectManager->expects(static::once()) - ->method('get') - ->willReturnMap([ - [PackageInfoFactory::class, $this->packageInfoFactoryMock], - ]); - $this->packageInfoFactoryMock->expects(static::once()) - ->method('create') - ->willReturn($this->packageInfoMock); - - $this->packageInfoMock->expects(static::never()) - ->method('getModuleName'); - - $this->packageInfoMock->expects(static::once()) - ->method('getRequiredBy') - ->willReturn([]); - $this->packageInfoMock->expects(static::exactly(2)) - ->method('getPackageName') - ->willReturnMap([ - ['Sample_ModuleOne', 'magento/sample-module-one'], - ['Sample_ModuleTwo', ''], - ]); - $this->packageInfoMock->expects(static::exactly(2)) - ->method('getVersion') - ->willReturnMap([ - ['Sample_ModuleOne', '1.0.0'], - ['Sample_ModuleTwo', ''], - ]); - - $this->packagesDataMock->expects(static::exactly(2)) - ->method('addPackageExtraInfo') - ->willReturnCallback( - function ($package) { - $package['package_title'] = 'packageTitle'; - $package['package_type'] = 'packageType'; - return $package; - } - ); - - $this->moduleListMock->expects(static::exactly(2)) - ->method('has') - ->willReturn(true); - $this->composerInformationMock->expects(static::once()) - ->method('getInstalledMagentoPackages') - ->willReturn($this->moduleData); - - $expected = [ - [ - 'name' => 'magento/sample-module-one', - 'type' => 'magento2-module', - 'version' => '1.0.0', - 'vendor' => 'Magento', - 'moduleName' => 'Sample_ModuleOne', - 'enable' => true, - 'package_title' => 'packageTitle', - 'package_type' => 'packageType', - 'requiredBy' => [], - ], - [ - 'name' => Module::UNKNOWN_PACKAGE_NAME, - 'type' => 'magento2-module', - 'version' => Module::UNKNOWN_VERSION, - 'vendor' => 'Sample', - 'moduleName' => 'Sample_ModuleTwo', - 'enable' => true, - 'package_title' => 'packageTitle', - 'package_type' => 'packageType', - 'requiredBy' => [], - ], - ]; - - static::assertEquals($expected, $this->model->getList()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Grid/TypeMapperTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Grid/TypeMapperTest.php deleted file mode 100644 index aa0e555f8ed6e..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Grid/TypeMapperTest.php +++ /dev/null @@ -1,52 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Grid; - -use Magento\Framework\Composer\ComposerInformation; -use Magento\Setup\Model\Grid\TypeMapper; -use PHPUnit\Framework\TestCase; - -class TypeMapperTest extends TestCase -{ - /** - * Model - * - * @var TypeMapper - */ - private $model; - - protected function setUp(): void - { - $this->model = new TypeMapper(); - } - - /** - * @param string $packageType - * @param string $expected - * @dataProvider mapDataProvider - */ - public function testMap($packageType, $expected) - { - static::assertEquals( - $expected, - $this->model->map($packageType) - ); - } - - /** - * @return array - */ - public function mapDataProvider() - { - return [ - [ComposerInformation::THEME_PACKAGE_TYPE, TypeMapper::THEME_PACKAGE_TYPE], - [ComposerInformation::MODULE_PACKAGE_TYPE, TypeMapper::MODULE_PACKAGE_TYPE], - ['undefined', TypeMapper::UNDEFINED_PACKAGE_TYPE] - ]; - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/Installer/ProgressFactoryTest.php b/setup/src/Magento/Setup/Test/Unit/Model/Installer/ProgressFactoryTest.php deleted file mode 100644 index a229882de9103..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/Installer/ProgressFactoryTest.php +++ /dev/null @@ -1,34 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model\Installer; - -use Magento\Setup\Model\Installer\ProgressFactory; -use Magento\Setup\Model\WebLogger; -use PHPUnit\Framework\TestCase; - -class ProgressFactoryTest extends TestCase -{ - public function testCreateFromLog() - { - $contents = [ - '[Progress: 1 / 5] Installing A...', - 'Output from A...', - '[Progress: 2 / 5] Installing B...', - 'Output from B...', - '[Progress: 3 / 5] Installing C...', - 'Output from C...', - ]; - $logger = $this->createMock(WebLogger::class); - $logger->expects($this->once())->method('get')->willReturn($contents); - - $progressFactory = new ProgressFactory(); - $progress = $progressFactory->createFromLog($logger); - $this->assertEquals(3, $progress->getCurrent()); - $this->assertEquals(5, $progress->getTotal()); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/ModuleStatusFactoryTest.php b/setup/src/Magento/Setup/Test/Unit/Model/ModuleStatusFactoryTest.php deleted file mode 100644 index 020fcbb416410..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/ModuleStatusFactoryTest.php +++ /dev/null @@ -1,54 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model; - -use Magento\Framework\Module\Status; -use Magento\Framework\ObjectManagerInterface; -use Magento\Setup\Model\ModuleStatusFactory; -use Magento\Setup\Model\ObjectManagerProvider; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class ModuleStatusFactoryTest extends TestCase -{ - /** - * @var ModuleStatusFactory - */ - private $moduleStatusFactory; - - /** - * @var MockObject|ObjectManagerProvider - */ - private $objectManagerProvider; - - /** - * @var MockObject|ObjectManagerInterface - */ - private $objectManager; - - protected function setUp(): void - { - $this->objectManagerProvider = $this->createMock(ObjectManagerProvider::class); - $this->objectManager = $this->getMockForAbstractClass( - ObjectManagerInterface::class, - [], - '', - false - ); - } - - public function testCreate() - { - $this->objectManagerProvider->expects($this->once())->method('get')->willReturn($this->objectManager); - $this->objectManager->expects($this->once()) - ->method('get') - ->with(Status::class); - $this->moduleStatusFactory = new ModuleStatusFactory($this->objectManagerProvider); - $this->moduleStatusFactory->create(); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/ModuleStatusTest.php b/setup/src/Magento/Setup/Test/Unit/Model/ModuleStatusTest.php deleted file mode 100644 index 48405e048fc53..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/ModuleStatusTest.php +++ /dev/null @@ -1,150 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model; - -use Magento\Framework\App\DeploymentConfig; -use Magento\Framework\Module\DependencyChecker; -use Magento\Framework\Module\ModuleList\Loader; -use Magento\Framework\ObjectManagerInterface; -use Magento\Setup\Model\ModuleStatus; -use Magento\Setup\Model\ObjectManagerProvider; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class ModuleStatusTest extends TestCase -{ - /** - * @var MockObject|Loader - */ - private $moduleLoader; - - /** - * @var MockObject|DeploymentConfig - */ - private $deploymentConfig; - - /** - * @var MockObject|DependencyChecker - */ - private $dependencyChecker; - - /** - * @var MockObject|ObjectManagerInterface - */ - private $objectManager; - - /** - * @var MockObject|ObjectManagerProvider - */ - private $objectManagerProvider; - - protected function setUp(): void - { - $this->moduleLoader = $this->createMock(Loader::class); - $this->dependencyChecker = - $this->createMock(DependencyChecker::class); - $this->deploymentConfig = $this->createMock(DeploymentConfig::class); - $this->objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $this->objectManagerProvider = - $this->createMock(ObjectManagerProvider::class); - $this->objectManagerProvider->expects($this->once())->method('get')->willReturn($this->objectManager); - $this->objectManager->expects($this->once())->method('get')->willReturn($this->dependencyChecker); - } - - /** - * @param array $expectedAllModules - * @param array $expectedConfig - * @param array $expectedResult - * - * @dataProvider getAllModulesDataProvider - */ - public function testGetAllModules($expectedAllModules, $expectedConfig, $expectedResult) - { - $this->moduleLoader->expects($this->once())->method('load')->willReturn($expectedAllModules); - $this->deploymentConfig->expects($this->once())->method('get') - ->willReturn($expectedConfig); - $this->dependencyChecker->expects($this->any())->method('checkDependenciesWhenDisableModules')->willReturn( - ['module1' => [], 'module2' => [], 'module3' => [], 'module4' => []] - ); - - $moduleStatus = new ModuleStatus($this->moduleLoader, $this->deploymentConfig, $this->objectManagerProvider); - $allModules = $moduleStatus->getAllModules(); - $this->assertSame($expectedResult[0], $allModules['module1']['selected']); - $this->assertSame($expectedResult[1], $allModules['module2']['selected']); - $this->assertSame($expectedResult[2], $allModules['module3']['selected']); - $this->assertSame($expectedResult[3], $allModules['module4']['selected']); - } - - /** - * @param array $expectedAllModules - * @param array $expectedConfig - * @param array $expectedResult - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - * - * @dataProvider getAllModulesDataProvider - */ - public function testGetAllModulesWithInputs($expectedAllModules, $expectedConfig, $expectedResult) - { - $this->moduleLoader->expects($this->once())->method('load')->willReturn($expectedAllModules); - $this->deploymentConfig->expects($this->never())->method('get') - ->willReturn($expectedConfig); - $this->dependencyChecker->expects($this->any())->method('checkDependenciesWhenDisableModules')->willReturn( - ['module1' => [], 'module2' => [], 'module3' => [], 'module4' => []] - ); - - $moduleStatus = new ModuleStatus($this->moduleLoader, $this->deploymentConfig, $this->objectManagerProvider); - $allModules = $moduleStatus->getAllModules(['module1', 'module2']); - $this->assertTrue($allModules['module1']['selected']); - $this->assertTrue($allModules['module2']['selected']); - $this->assertFalse($allModules['module3']['selected']); - $this->assertFalse($allModules['module4']['selected']); - } - - /** - * @param array $expectedAllModules - * @param array $expectedConfig - * @param array $expectedResult - * - * @dataProvider getAllModulesDataProvider - */ - public function testSetIsEnabled($expectedAllModules, $expectedConfig, $expectedResult) - { - $this->moduleLoader->expects($this->once())->method('load')->willReturn($expectedAllModules); - $this->deploymentConfig->expects($this->once())->method('get') - ->willReturn($expectedConfig); - $this->dependencyChecker->expects($this->any())->method('checkDependenciesWhenDisableModules')->willReturn( - ['module1' => [], 'module2' => [], 'module3' => [], 'module4' => []] - ); - - $moduleStatus = new ModuleStatus($this->moduleLoader, $this->deploymentConfig, $this->objectManagerProvider); - $moduleStatus->setIsEnabled(false, 'module1'); - $allModules = $moduleStatus->getAllModules(); - $this->assertFalse($allModules['module1']['selected']); - $this->assertSame($expectedResult[1], $allModules['module2']['selected']); - $this->assertSame($expectedResult[2], $allModules['module3']['selected']); - $this->assertSame($expectedResult[3], $allModules['module4']['selected']); - } - - /** - * @return array - */ - public function getAllModulesDataProvider() - { - $expectedAllModules = [ - 'module1' => ['name' => 'module1'], - 'module2' => ['name' => 'module2'], - 'module3' => ['name' => 'module3'], - 'module4' => ['name' => 'module4'] - ]; - $expectedConfig = ['module1' => 0, 'module3' => 0]; - return [ - [$expectedAllModules, $expectedConfig, [false, true, false, true]], - [$expectedAllModules, [], [true, true, true, true]], - ]; - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/NavigationTest.php b/setup/src/Magento/Setup/Test/Unit/Model/NavigationTest.php index e7a0871290a53..21e8e11764d23 100644 --- a/setup/src/Magento/Setup/Test/Unit/Model/NavigationTest.php +++ b/setup/src/Magento/Setup/Test/Unit/Model/NavigationTest.php @@ -42,10 +42,10 @@ protected function setUp(): void ->with('config') ->willReturn( [ - 'navInstallerTitles' => [ + 'navLandingTitles' => [ 'install' => 'SomeTitle' ], - 'navInstaller' => [ + 'navLanding' => [ ['key1' => 'value1'], ['key2' => 'value2'], ['nav' => 'abc', 'key3' => 'value3'], @@ -63,7 +63,7 @@ protected function setUp(): void public function testGetType() { - $this->assertEquals(Navigation::NAV_INSTALLER, $this->navigation->getType()); + $this->assertEquals(Navigation::NAV_LANDING, $this->navigation->getType()); } public function testGetData() diff --git a/setup/src/Magento/Setup/Test/Unit/Model/PackagesAuthTest.php b/setup/src/Magento/Setup/Test/Unit/Model/PackagesAuthTest.php deleted file mode 100644 index 5bce3f11c2510..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/PackagesAuthTest.php +++ /dev/null @@ -1,141 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model; - -use Laminas\ServiceManager\ServiceLocatorInterface; -use Magento\Framework\Filesystem; -use Magento\Framework\Filesystem\Directory\ReadInterface; -use Magento\Framework\Filesystem\Directory\WriteInterface; -use Magento\Framework\HTTP\Client\Curl; -use Magento\Framework\Serialize\Serializer\Json; -use Magento\Setup\Model\PackagesAuth; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests Magento\Setup\Model\PackagesAuth - */ -class PackagesAuthTest extends TestCase -{ - /** - * @var MockObject|Curl - */ - private $curl; - - /** - * @var MockObject|Filesystem - */ - private $filesystem; - - /** - * @var PackagesAuth - */ - private $packagesAuth; - - /** @var Json|MockObject */ - private $serializerMock; - - protected function setUp(): void - { - $laminasServiceLocator = $this->getMockForAbstractClass(ServiceLocatorInterface::class); - $laminasServiceLocator - ->expects($this->any()) - ->method('get') - ->with('config') - ->willReturn([ - 'marketplace' => [ - 'check_credentials_url' => 'some_url' - ] - ]); - $this->curl = $this->createMock(Curl::class, [], [], '', false); - $this->filesystem = $this->createMock(Filesystem::class, [], [], '', false); - $this->serializerMock = $this->getMockBuilder(Json::class) - ->getMock(); - $this->serializerMock->expects($this->any()) - ->method('serialize') - ->willReturnCallback( - function ($serializedData) { - return json_encode($serializedData); - } - ); - $this->packagesAuth = new PackagesAuth( - $laminasServiceLocator, - $this->curl, - $this->filesystem, - $this->serializerMock - ); - } - - public function testCheckCredentialsActionBadCredentials() - { - $this->curl->expects($this->once())->method('setCredentials')->with('username', 'password'); - $this->curl->expects($this->once())->method('getStatus'); - $expectedValue = '{"success":false,"message":"Bad credentials"}'; - $returnValue = $this->packagesAuth->checkCredentials('username', 'password'); - $this->assertSame($expectedValue, $returnValue); - } - - public function testCheckCredentials() - { - $this->curl->expects($this->once())->method('setCredentials')->with('username', 'password'); - $this->curl->expects($this->once())->method('getStatus')->willReturn(200); - $this->curl->expects($this->once())->method('getBody')->willReturn("{'someJson'}"); - $directory = $this->getMockForAbstractClass(WriteInterface::class); - $this->filesystem->expects($this->once())->method('getDirectoryWrite')->willReturn($directory); - $directory->expects($this->once()) - ->method('writeFile') - ->with(PackagesAuth::PATH_TO_PACKAGES_FILE, "{'someJson'}"); - $expectedValue = '{"success":true}'; - $returnValue = $this->packagesAuth->checkCredentials('username', 'password'); - $this->assertSame($expectedValue, $returnValue); - } - - public function testCheckCredentialsActionWithException() - { - $this->curl->expects($this->once())->method('setCredentials')->with('username', 'password'); - $this->curl->expects($this->once()) - ->method('getStatus') - ->willThrowException(new \Exception("Test error")); - $this->curl->expects($this->never())->method('getBody')->willReturn("{'someJson}"); - - $expectedValue = '{"success":false,"message":"Test error"}'; - $returnValue = $this->packagesAuth->checkCredentials('username', 'password'); - $this->assertSame($expectedValue, $returnValue); - } - - public function testRemoveCredentials() - { - $directoryWrite = $this->getMockForAbstractClass(WriteInterface::class); - $directoryRead = $this->getMockForAbstractClass(ReadInterface::class); - $this->filesystem->expects($this->once())->method('getDirectoryRead')->willReturn($directoryRead); - $this->filesystem->expects($this->once()) - ->method('getDirectoryWrite') - ->willReturn($directoryWrite); - $directoryWrite->expects($this->once())->method('isExist')->willReturn(true); - $directoryWrite->expects($this->once())->method('isReadable')->willReturn(true); - $directoryWrite->expects($this->once())->method('delete')->willReturn(true); - $directoryRead->expects($this->once())->method('isExist')->willReturn(true); - $directoryRead->expects($this->once())->method('isReadable')->willReturn(true); - $directoryRead->expects($this->once()) - ->method('ReadFile') - ->willReturn('{"http-basic":{"some_url":{"username":"somename","password":"somepassword"}}}'); - - $this->assertTrue($this->packagesAuth->removeCredentials()); - } - - public function testSaveAuthJson() - { - $directoryWrite = $this->getMockForAbstractClass(WriteInterface::class); - $this->filesystem->expects($this->once()) - ->method('getDirectoryWrite') - ->willReturn($directoryWrite); - $directoryWrite->expects($this->once())->method('writeFile')->willReturn(true); - - $this->assertTrue($this->packagesAuth->saveAuthJson("testusername", "testpassword")); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/PackagesDataTest.php b/setup/src/Magento/Setup/Test/Unit/Model/PackagesDataTest.php deleted file mode 100644 index dbbdb6de90996..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/PackagesDataTest.php +++ /dev/null @@ -1,324 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model; - -use Composer\Package\RootPackage; -use Magento\Composer\MagentoComposerApplication; -use Magento\Framework\Composer\ComposerInformation; -use Magento\Framework\Composer\MagentoComposerApplicationFactory; -use Magento\Framework\Filesystem; -use Magento\Framework\Filesystem\Directory\ReadInterface; -use Magento\Framework\Filesystem\Directory\WriteInterface; -use Magento\Framework\ObjectManagerInterface; -use Magento\Framework\Stdlib\DateTime\Timezone; -use Magento\Setup\Model\DateTime\TimeZoneProvider; -use Magento\Setup\Model\Grid\TypeMapper; -use Magento\Setup\Model\ObjectManagerProvider; -use Magento\Setup\Model\PackagesAuth; -use Magento\Setup\Model\PackagesData; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * Tests Magento\Setup\Model\PackagesData - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class PackagesDataTest extends TestCase -{ - /** - * @var PackagesData - */ - private $packagesData; - - /** - * @var ComposerInformation|MockObject - */ - private $composerInformation; - - /** - * @var TimeZoneProvider|MockObject - */ - private $timeZoneProvider; - - /** - * @var PackagesAuth|MockObject - */ - private $packagesAuth; - - /** - * @var Filesystem|MockObject - */ - private $filesystem; - - /** - * @var ObjectManagerProvider|MockObject - */ - private $objectManagerProvider; - - /** - * @var TypeMapper|MockObject - */ - private $typeMapper; - - protected function setUp(): void - { - $this->composerInformation = $this->getComposerInformation(); - $this->timeZoneProvider = $this->getMockBuilder(TimeZoneProvider::class) - ->disableOriginalConstructor() - ->getMock(); - $timeZone = $this->createMock(Timezone::class); - $this->timeZoneProvider->expects($this->any())->method('get')->willReturn($timeZone); - $this->packagesAuth = $this->createMock(PackagesAuth::class); - $this->filesystem = $this->createMock(Filesystem::class); - $this->objectManagerProvider = $this->getMockBuilder(ObjectManagerProvider::class) - ->disableOriginalConstructor() - ->getMock(); - $objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $appFactory = $this->getMockBuilder(MagentoComposerApplicationFactory::class) - ->disableOriginalConstructor() - ->getMock(); - $application = $this->createMock(MagentoComposerApplication::class); - $application->expects($this->any()) - ->method('runComposerCommand') - ->willReturnMap([ - [ - [ - PackagesData::PARAM_COMMAND => PackagesData::COMPOSER_SHOW, - PackagesData::PARAM_PACKAGE => 'magento/package-1', - PackagesData::PARAM_AVAILABLE => true, - ], - null, - 'versions: 2.0.1' - ], - [ - [ - PackagesData::PARAM_COMMAND => PackagesData::COMPOSER_SHOW, - PackagesData::PARAM_PACKAGE => 'magento/package-2', - PackagesData::PARAM_AVAILABLE => true, - ], - null, - 'versions: 2.0.1' - ], - [ - [ - PackagesData::PARAM_COMMAND => PackagesData::COMPOSER_SHOW, - PackagesData::PARAM_PACKAGE => 'partner/package-3', - PackagesData::PARAM_AVAILABLE => true, - ], - null, - 'versions: 3.0.1' - ], - ]); - $appFactory->expects($this->any())->method('create')->willReturn($application); - $objectManager->expects($this->any()) - ->method('get') - ->with(MagentoComposerApplicationFactory::class) - ->willReturn($appFactory); - $this->objectManagerProvider->expects($this->any())->method('get')->willReturn($objectManager); - - $directoryWrite = $this->getMockForAbstractClass(WriteInterface::class); - $directoryRead = $this->getMockForAbstractClass(ReadInterface::class); - $this->filesystem->expects($this->any())->method('getDirectoryRead')->willReturn($directoryRead); - $this->filesystem->expects($this->any()) - ->method('getDirectoryWrite') - ->willReturn($directoryWrite); - $directoryWrite->expects($this->any())->method('isExist')->willReturn(true); - $directoryWrite->expects($this->any())->method('isReadable')->willReturn(true); - $directoryWrite->expects($this->any())->method('delete')->willReturn(true); - $directoryRead->expects($this->any())->method('isExist')->willReturn(true); - $directoryRead->expects($this->any())->method('isReadable')->willReturn(true); - $directoryRead->expects($this->any())->method('stat')->willReturn(['mtime' => '1462460216076']); - $directoryRead->expects($this->any()) - ->method('readFile') - ->willReturn( - '{"packages":{"magento\/package-1":{' - . '"1.0.0":{"name":"magento\/package-1","version":"1.0.0","vendor":"test","type":"metapackage",' - . '"require":{"magento\/package-3":"1.0.0"}},' - . '"1.0.1":{"name":"magento\/package-1","version":"1.0.1","vendor":"test","type":"magento2-module"},' - . '"1.0.2":{"name":"magento\/package-1","version":"1.0.2","vendor":"test","type":"magento2-module"}' - . '}, "magento\/package-2":{' - . '"1.0.0":{"name":"magento\/package-2","version":"1.0.0","vendor":"test","type":"magento2-module"},' - . '"1.0.1":{"name":"magento\/package-2","version":"1.0.1","vendor":"test","type":"magento2-module"}' - . '}, "magento\/package-3":{' - . '"1.0.0":{"name":"magento\/package-3","version":"1.0.0","vendor":"test","type":"magento2-module"},' - . '"1.0.1":{"name":"magento\/package-3","version":"1.0.1","vendor":"test","type":"magento2-module"},' - . '"1.0.2":{"name":"magento\/package-3","version":"1.0.2","vendor":"test","type":"magento2-module",' - . '"extra":{"x-magento-ext-title":"Package 3 title", "x-magento-ext-type":"Extension"}}' - . '}}}' - ); - - $this->typeMapper = $this->getMockBuilder(TypeMapper::class) - ->disableOriginalConstructor() - ->getMock(); - $this->typeMapper->expects(static::any()) - ->method('map') - ->willReturnMap([ - [ComposerInformation::MODULE_PACKAGE_TYPE, TypeMapper::MODULE_PACKAGE_TYPE], - ]); - - $this->createPackagesData(); - } - - private function createPackagesData() - { - $this->packagesData = new PackagesData( - $this->composerInformation, - $this->timeZoneProvider, - $this->packagesAuth, - $this->filesystem, - $this->objectManagerProvider, - $this->typeMapper - ); - } - - /** - * @param array $requiredPackages - * @param array $installedPackages - * @param array $repo - * @return ComposerInformation|MockObject - */ - private function getComposerInformation($requiredPackages = [], $installedPackages = [], $repo = []) - { - $composerInformation = $this->createMock(ComposerInformation::class); - $composerInformation->expects($this->any())->method('getInstalledMagentoPackages')->willReturn( - $installedPackages ?: - [ - 'magento/package-1' => [ - 'name' => 'magento/package-1', - 'type' => 'magento2-module', - 'version'=> '1.0.0' - ], - 'magento/package-2' => [ - 'name' => 'magento/package-2', - 'type' => 'magento2-module', - 'version'=> '1.0.1' - ], - 'partner/package-3' => [ - 'name' => 'partner/package-3', - 'type' => 'magento2-module', - 'version'=> '3.0.0' - ], - ] - ); - - $composerInformation->expects($this->any())->method('getRootRepositories') - ->willReturn($repo ?: ['repo1', 'repo2']); - $composerInformation->expects($this->any())->method('getPackagesTypes') - ->willReturn(['magento2-module']); - $rootPackage = $this->getMockBuilder(RootPackage::class) - ->setConstructorArgs(['magento/project', '2.1.0', '2']) - ->getMock(); - $rootPackage->expects($this->any()) - ->method('getRequires') - ->willReturn( - $requiredPackages ?: - [ - 'magento/package-1' => '1.0.0', - 'magento/package-2' => '1.0.1', - 'partner/package-3' => '3.0.0', - ] - ); - $composerInformation->expects($this->any()) - ->method('getRootPackage') - ->willReturn($rootPackage); - - return $composerInformation; - } - - public function testSyncPackagesData() - { - $latestData = $this->packagesData->syncPackagesData(); - $this->assertArrayHasKey('lastSyncDate', $latestData); - $this->assertArrayHasKey('date', $latestData['lastSyncDate']); - $this->assertArrayHasKey('time', $latestData['lastSyncDate']); - $this->assertArrayHasKey('packages', $latestData); - $this->assertCount(3, $latestData['packages']); - $this->assertSame(3, $latestData['countOfUpdate']); - $this->assertArrayHasKey('installPackages', $latestData); - $this->assertCount(1, $latestData['installPackages']); - $this->assertSame(1, $latestData['countOfInstall']); - } - - public function testGetPackagesForUpdateWithException() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('Couldn\'t get available versions for package partner/package-4'); - $requiredPackages = [ - 'partner/package-4' => '4.0.4', - ]; - $installedPackages = [ - 'partner/package-4' => [ - 'name' => 'partner/package-4', - 'type' => 'magento2-module', - 'version'=> '4.0.4' - ], - ]; - $this->composerInformation = $this->getComposerInformation($requiredPackages, $installedPackages); - $this->createPackagesData(); - $this->packagesData->getPackagesForUpdate(); - } - - public function testPackagesForUpdateFromJson() - { - $this->composerInformation = $this->getComposerInformation([], [], ['https://repo1']); - $this->packagesAuth->expects($this->atLeastOnce()) - ->method('getCredentialBaseUrl') - ->willReturn('repo1'); - $this->createPackagesData(); - $packages = $this->packagesData->getPackagesForUpdate(); - $this->assertCount(2, $packages); - $this->assertArrayHasKey('magento/package-1', $packages); - $this->assertArrayHasKey('partner/package-3', $packages); - $firstPackage = array_values($packages)[0]; - $this->assertArrayHasKey('latestVersion', $firstPackage); - $this->assertArrayHasKey('versions', $firstPackage); - } - - public function testGetPackagesForUpdate() - { - $packages = $this->packagesData->getPackagesForUpdate(); - $this->assertCount(3, $packages); - $this->assertArrayHasKey('magento/package-1', $packages); - $this->assertArrayHasKey('magento/package-2', $packages); - $this->assertArrayHasKey('partner/package-3', $packages); - $firstPackage = array_values($packages)[0]; - $this->assertArrayHasKey('latestVersion', $firstPackage); - $this->assertArrayHasKey('versions', $firstPackage); - } - - public function testGetInstalledPackages() - { - $installedPackages = $this->packagesData->getInstalledPackages(); - $this->assertCount(3, $installedPackages); - $this->assertArrayHasKey('magento/package-1', $installedPackages); - $this->assertArrayHasKey('magento/package-2', $installedPackages); - $this->assertArrayHasKey('partner/package-3', $installedPackages); - } - - public function testGetMetaPackagesMap() - { - static::assertEquals( - ['magento/package-3' => 'magento/package-1'], - $this->packagesData->getMetaPackagesMap() - ); - } - - public function testAddPackageExtraInfo() - { - static::assertEquals( - [ - 'package_title' => 'Package 3 title', - 'package_type' => 'Extension', - 'name' => 'magento/package-3', - 'version' => '1.0.2', - 'package_link' => '' - ], - $this->packagesData->addPackageExtraInfo(['name' => 'magento/package-3', 'version' => '1.0.2']) - ); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/PayloadValidatorTest.php b/setup/src/Magento/Setup/Test/Unit/Model/PayloadValidatorTest.php deleted file mode 100644 index 9f2187852bc64..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/PayloadValidatorTest.php +++ /dev/null @@ -1,100 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model; - -use Magento\Framework\Module\FullModuleList; -use Magento\Setup\Model\PayloadValidator; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class PayloadValidatorTest extends TestCase -{ - /** - * @var FullModuleList|MockObject - */ - private $fullModuleList; - - /** - * @var PayloadValidator - */ - private $model; - - protected function setUp(): void - { - $this->fullModuleList = $this->createMock(FullModuleList::class); - $this->model = new PayloadValidator($this->fullModuleList); - } - - /** - * @param string $type - * @param int $has - * @param bool $moduleExists - * @dataProvider validatePayLoadDataProvider - */ - public function testValidatePayLoad($type, $has, $moduleExists) - { - $this->fullModuleList->expects($this->exactly($has))->method('has')->willReturn($moduleExists); - $this->assertEquals('', $this->model->validatePayload($type)); - } - - /** - * @return array - */ - public function validatePayLoadDataProvider() - { - return [ - [['type' => 'uninstall', 'dataOption' => true], 0, false], - [['type' => 'update', 'packages' => [['name' => 'vendor\/package', 'version' => '1.0.1']]], 0, false], - [['type' => 'enable', 'packages' => [['name' => 'vendor\/package', 'version' => '1.0.1']]], 1, true], - [['type' => 'disable', 'packages' => [['name' => 'vendor\/package', 'version' => '1.0.1']]], 1, true], - ]; - } - - /** - * @param string $type - * @param int $has - * @param bool $moduleExists - * @param string $errorMessage - * @dataProvider validatePayLoadNegativeCasesDataProvider - */ - public function testValidatePayLoadNegativeCases($type, $has, $moduleExists, $errorMessage) - { - $this->fullModuleList->expects($this->exactly($has))->method('has')->willReturn($moduleExists); - $this->assertStringStartsWith($errorMessage, $this->model->validatePayload($type)); - } - - /** - * @return array - */ - public function validatePayLoadNegativeCasesDataProvider() - { - return [ - [['type' => 'uninstall'], 0, false, 'Missing dataOption'], - [['type' => 'update'], 0, false, 'Missing packages'], - [['type' => 'update', - 'packages' => [['name' => 'vendor\/package']]], - 0, - false, - 'Missing package information' - ], - [['type' => 'enable'], 0, false, 'Missing packages'], - [['type' => 'enable', - 'packages' => [['name' => 'vendor\/package']]], - 1, - false, - 'Invalid Magento module name' - ], - [['type' => 'disable', - 'packages' => [['name' => 'vendor\/package']]], - 1, - false, - 'Invalid Magento module name' - ] - ]; - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/SystemPackageTest.php b/setup/src/Magento/Setup/Test/Unit/Model/SystemPackageTest.php deleted file mode 100644 index 591a53c6dead9..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/SystemPackageTest.php +++ /dev/null @@ -1,360 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model; - -use Composer\Composer; -use Composer\Package\Link; -use Composer\Package\Locker; -use Composer\Package\Package; -use Composer\Repository\ArrayRepository; -use Composer\Semver\Constraint\Constraint; -use Magento\Composer\InfoCommand; -use Magento\Composer\MagentoComposerApplication; -use Magento\Framework\Composer\ComposerInformation; -use Magento\Framework\Composer\MagentoComposerApplicationFactory; -use Magento\Setup\Model\SystemPackage; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -/** - * @SuppressWarnings(PHPMD.CouplingBetweenObjects) - */ -class SystemPackageTest extends TestCase -{ - /** - * @var MockObject|InfoCommand - */ - private $infoCommand; - - /** - * @var MockObject|SystemPackage ; - */ - private $systemPackage; - - /** - * @var MockObject|ArrayRepository - */ - private $repository; - - /** - * @var MockObject|Locker - */ - private $locker; - - /** - * @var \PHPUnit\Framework\MockObject\MockObject|/Magento\Composer\MagentoComposerApplication - */ - private $magentoComposerApp; - - /** - * @var MockObject|MagentoComposerApplicationFactory - */ - private $composerAppFactory; - - /** - * @var MockObject|Composer - */ - private $composer; - - /** - * @var array - */ - private $expectedPackages = [ - [ - 'id' => '1.2.0', - 'name' => 'Version 1.2.0 EE (latest)', - 'package' => SystemPackage::EDITION_ENTERPRISE, - 'stable' => true, - 'current' => false, - ], - [ - 'id' => '1.2.0', - 'name' => 'Version 1.2.0 CE (latest)', - 'package' => SystemPackage::EDITION_COMMUNITY, - 'stable' => true, - 'current' => false, - ], - [ - 'id' => '1.1.0', - 'name' => 'Version 1.1.0 EE', - 'package' => SystemPackage::EDITION_ENTERPRISE, - 'stable' => true, - 'current' => false, - ], - [ - 'id' => '1.1.0', - 'name' => 'Version 1.1.0 CE', - 'package' => SystemPackage::EDITION_COMMUNITY, - 'stable' => true, - 'current' => false, - ], - [ - 'id' => '1.1.0-RC1', - 'name' => 'Version 1.1.0-RC1 EE (unstable version)', - 'package' => SystemPackage::EDITION_ENTERPRISE, - 'stable' => false, - 'current' => false, - ], - [ - 'id' => '1.1.0-RC1', - 'name' => 'Version 1.1.0-RC1 CE (unstable version)', - 'package' => SystemPackage::EDITION_COMMUNITY, - 'stable' => false, - 'current' => false, - ], - [ - 'id' => '1.0.0', - 'name' => 'Version 1.0.0 EE', - 'package' => SystemPackage::EDITION_ENTERPRISE, - 'stable' => true, - 'current' => true, - ], - [ - 'id' => '1.0.0', - 'name' => 'Version 1.0.0 CE', - 'package' => SystemPackage::EDITION_COMMUNITY, - 'stable' => true, - 'current' => true, - ], - ]; - - /** - * @var MockObject|ComposerInformation - */ - private $composerInformation; - - protected function setUp(): void - { - $this->composerAppFactory = $this->createMock( - MagentoComposerApplicationFactory::class - ); - - $this->infoCommand = $this->createMock( - InfoCommand::class - ); - - $this->magentoComposerApp = - $this->createMock(MagentoComposerApplication::class); - $this->locker = $this->createMock(Locker::class); - $this->repository = $this->createMock(ArrayRepository::class); - $this->composer = $this->createMock(Composer::class); - $this->composerInformation = $this->createMock( - ComposerInformation::class - ); - } - - public function testGetPackageVersions() - { - $communityPackage = $this->createMock(Package::class); - $communityPackage->expects($this->once())->method('getName')->willReturn(SystemPackage::EDITION_COMMUNITY); - $enterprisePackage = $this->createMock(Package::class); - $enterprisePackage->expects($this->once())->method('getName')->willReturn(SystemPackage::EDITION_ENTERPRISE); - $this->composerInformation->expects($this->any())->method('isSystemPackage')->willReturn(true); - $this->composerInformation->expects($this->once())->method('isPackageInComposerJson')->willReturn(true); - $this->repository - ->expects($this->once()) - ->method('getPackages') - ->willReturn([$communityPackage, $enterprisePackage]); - - $this->locker->expects($this->once())->method('getLockedRepository')->willReturn($this->repository); - - $this->composer->expects($this->once())->method('getLocker')->willReturn($this->locker); - $this->magentoComposerApp->expects($this->once())->method('createComposer')->willReturn($this->composer); - - $this->composerAppFactory->expects($this->once()) - ->method('createInfoCommand') - ->willReturn($this->infoCommand); - - $this->composerAppFactory->expects($this->once()) - ->method('create') - ->willReturn($this->magentoComposerApp); - - $this->composerAppFactory->expects($this->once()) - ->method('createInfoCommand') - ->willReturn($this->infoCommand); - - $this->systemPackage = new SystemPackage($this->composerAppFactory, $this->composerInformation); - - $this->infoCommand->expects($this->any()) - ->method('run') - ->willReturnMap([ - [ - SystemPackage::EDITION_COMMUNITY, - false, - [ - 'name' => SystemPackage::EDITION_COMMUNITY, - 'description' => 'eCommerce Platform for Growth (Enterprise Edition)', - 'keywords' => '', - 'versions' => '1.2.0, 1.1.0, 1.1.0-RC1, * 1.0.0', - 'type' => 'metapackage', - 'license' => 'OSL-3.0, AFL-3.0', - 'source' => '[]', - 'names' => SystemPackage::EDITION_COMMUNITY, - 'current_version' => '1.0.0', - InfoCommand::AVAILABLE_VERSIONS => [1 => '1.2.0', 2 => '1.1.0', 3 => '1.1.0-RC1', 4 => '1.0.0'], - 'new_versions' => ['1.2.0', '1.1.0', '1.1.0-RC1'], - ], - ], - [ - SystemPackage::EDITION_ENTERPRISE, - false, - [ - 'name' => SystemPackage::EDITION_ENTERPRISE, - 'description' => 'eCommerce Platform for Growth (Enterprise Edition)', - 'keywords' => '', - 'versions' => '1.2.0, 1.1.0, 1.1.0-RC1, * 1.0.0', - 'type' => 'metapackage', - 'license' => 'OSL-3.0, AFL-3.0', - 'source' => '[]', - 'names' => SystemPackage::EDITION_ENTERPRISE, - 'current_version' => '1.0.0', - InfoCommand::AVAILABLE_VERSIONS => [1 => '1.2.0', 2 => '1.1.0', 3 => '1.1.0-RC1', 4 => '1.0.0'], - 'new_versions' => ['1.2.0', '1.1.0', '1.1.0-RC1'], - ], - - ] - ]); - $this->assertEquals($this->expectedPackages, $this->systemPackage->getPackageVersions()); - } - - public function testGetPackageVersionGitCloned() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('no components are available because you cloned the Magento 2 GitHub repository'); - $package = $this->createMock(Package::class); - $this->repository - ->expects($this->once()) - ->method('getPackages') - ->willReturn([$package]); - - $this->locker->expects($this->once())->method('getLockedRepository')->willReturn($this->repository); - $this->composerInformation->expects($this->any())->method('isSystemPackage')->willReturn(false); - $this->composer->expects($this->once())->method('getLocker')->willReturn($this->locker); - $this->magentoComposerApp->expects($this->once())->method('createComposer')->willReturn($this->composer); - - $this->composerAppFactory->expects($this->once()) - ->method('create') - ->willReturn($this->magentoComposerApp); - - $this->composerAppFactory->expects($this->once()) - ->method('createInfoCommand') - ->willReturn($this->infoCommand); - - $this->systemPackage = new SystemPackage($this->composerAppFactory, $this->composerInformation); - $this->systemPackage->getPackageVersions(); - } - - public function testGetPackageVersionsFailed() - { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage('We cannot retrieve information on magento/product-community-edition.'); - $communityPackage = $this->createMock(Package::class); - $enterprisePackage = $this->createMock(Package::class); - - $communityPackage->expects($this->once())->method('getName')->willReturn(SystemPackage::EDITION_COMMUNITY); - $enterprisePackage->expects($this->once())->method('getName')->willReturn(SystemPackage::EDITION_ENTERPRISE); - $this->composerInformation->expects($this->any())->method('isSystemPackage')->willReturn(true); - $this->composerInformation->expects($this->once())->method('isPackageInComposerJson')->willReturn(true); - - $this->repository - ->expects($this->once()) - ->method('getPackages') - ->willReturn([$communityPackage, $enterprisePackage]); - - $this->locker->expects($this->once())->method('getLockedRepository')->willReturn($this->repository); - - $this->composer->expects($this->once())->method('getLocker')->willReturn($this->locker); - $this->magentoComposerApp->expects($this->once())->method('createComposer')->willReturn($this->composer); - - $this->composerAppFactory->expects($this->once()) - ->method('create') - ->willReturn($this->magentoComposerApp); - - $this->composerAppFactory->expects($this->once()) - ->method('createInfoCommand') - ->willReturn($this->infoCommand); - - $this->systemPackage = new SystemPackage($this->composerAppFactory, $this->composerInformation); - - $this->infoCommand->expects($this->once()) - ->method('run') - ->with(SystemPackage::EDITION_COMMUNITY) - ->willReturn(false); - - $this->systemPackage->getPackageVersions(); - } - - /** - * @param string $ceCurrentVersion - * @param array $expectedResult - * - * @dataProvider getAllowedEnterpriseVersionsDataProvider - */ - public function testGetAllowedEnterpriseVersions($ceCurrentVersion, $expectedResult) - { - $this->composerAppFactory->expects($this->once()) - ->method('createInfoCommand') - ->willReturn($this->infoCommand); - $this->systemPackage = new SystemPackage($this->composerAppFactory, $this->composerInformation); - $this->infoCommand->expects($this->once()) - ->method('run') - ->with(SystemPackage::EDITION_ENTERPRISE) - ->willReturn([InfoCommand::AVAILABLE_VERSIONS => ['1.0.0', '1.0.1', '1.0.2']]); - $require = $this->createMock(Link::class); - $constraintMock = $this->createMock(Constraint::class); - $constraintMock->expects($this->any())->method('getPrettyString') - ->willReturn('1.0.1'); - $require->expects($this->any()) - ->method('getConstraint') - ->willReturn($constraintMock); - - $this->composerInformation->expects($this->any()) - ->method('getPackageRequirements') - ->willReturn([SystemPackage::EDITION_COMMUNITY => $require]); - $this->assertEquals( - $expectedResult, - $this->systemPackage->getAllowedEnterpriseVersions($ceCurrentVersion) - ); - } - - /** - * @return array - */ - public function getAllowedEnterpriseVersionsDataProvider() - { - return [ - ['2.0.0', []], - [ - '1.0.0', - [ - [ - 'package' => SystemPackage::EDITION_ENTERPRISE, - 'versions' => [ - [ - 'id' => '1.0.2', - 'name' => 'Version 1.0.2 EE (latest)', - 'current' => false, - ], - [ - 'id' => '1.0.1', - 'name' => 'Version 1.0.1 EE', - 'current' => false, - ], - [ - - 'id' => '1.0.0', - 'name' => 'Version 1.0.0 EE', - 'current' => false, - ], - ], - ], - ], - ], - ]; - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/UninstallDependencyCheckTest.php b/setup/src/Magento/Setup/Test/Unit/Model/UninstallDependencyCheckTest.php deleted file mode 100644 index 944cf9bf18ea7..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/UninstallDependencyCheckTest.php +++ /dev/null @@ -1,108 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model; - -use Magento\Framework\Composer\ComposerInformation; -use Magento\Framework\Composer\DependencyChecker; -use Magento\Setup\Model\ThemeDependencyCheckerFactory; -use Magento\Setup\Model\UninstallDependencyCheck; -use Magento\Theme\Model\Theme\ThemeDependencyChecker; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class UninstallDependencyCheckTest extends TestCase -{ - /** - * @var UninstallDependencyCheck - */ - private $uninstallDependencyCheck; - - /** - * @var ComposerInformation|MockObject - */ - private $composerInfo; - - /** - * @var DependencyChecker|MockObject - */ - private $packageDependencyChecker; - - /** - * @var ThemeDependencyChecker|MockObject - */ - private $themeDependencyChecker; - - /** - * @var ThemeDependencyCheckerFactory|MockObject - */ - private $themeDependencyCheckerFactory; - - protected function setup(): void - { - $this->composerInfo = $this->createMock(ComposerInformation::class); - $this->packageDependencyChecker = $this->createMock(DependencyChecker::class); - $this->themeDependencyChecker = $this->createMock(ThemeDependencyChecker::class); - $this->themeDependencyCheckerFactory = - $this->createMock(ThemeDependencyCheckerFactory::class); - $this->themeDependencyCheckerFactory->expects($this->any())->method('create') - ->willReturn($this->themeDependencyChecker); - $this->uninstallDependencyCheck = new UninstallDependencyCheck( - $this->composerInfo, - $this->packageDependencyChecker, - $this->themeDependencyCheckerFactory - ); - } - - public function testRunUninstallReadinessCheck() - { - $packages = [ - 'verndor/module' => 'magento2-module', - 'verndor/theme' => 'magento2-theme', - 'verndor/metapackage' => 'metapackage', - 'verndor/language' => 'magento2-language', - ]; - - $this->composerInfo->expects($this->once())->method('getRootRequiredPackageTypesByName')->willReturn($packages); - $this->packageDependencyChecker->expects($this->once()) - ->method('checkDependencies') - ->with(array_keys($packages)) - ->willReturn([]); - - $this->themeDependencyChecker->expects($this->once()) - ->method('checkChildThemeByPackagesName') - ->with(['verndor/theme']) - ->willReturn([]); - - $result = $this->uninstallDependencyCheck->runUninstallReadinessCheck(array_keys($packages)); - $this->assertEquals(['success' => true], $result); - } - - public function testRunUninstallReadinessCheckWithError() - { - $packages = [ - 'verndor/module' => 'magento2-module', - 'verndor/theme' => 'magento2-theme', - 'verndor/metapackage' => 'metapackage', - 'verndor/language' => 'magento2-language', - ]; - - $this->composerInfo->expects($this->once())->method('getRootRequiredPackageTypesByName')->willReturn($packages); - $this->packageDependencyChecker->expects($this->once()) - ->method('checkDependencies') - ->with(array_keys($packages)) - ->willReturn([]); - - $this->themeDependencyChecker->expects($this->once()) - ->method('checkChildThemeByPackagesName') - ->with(['verndor/theme']) - ->willReturn(['Error message']); - - $result = $this->uninstallDependencyCheck->runUninstallReadinessCheck(array_keys($packages)); - $this->assertEquals(['success' => false, 'error' => 'Error message'], $result); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/UpdaterTaskCreatorTest.php b/setup/src/Magento/Setup/Test/Unit/Model/UpdaterTaskCreatorTest.php deleted file mode 100644 index 21f17f41870c4..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/UpdaterTaskCreatorTest.php +++ /dev/null @@ -1,115 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model; - -use Magento\Framework\App\Cache\Manager; -use Magento\Framework\Filesystem; -use Magento\Framework\Filesystem\Directory\WriteInterface; -use Magento\Framework\ObjectManagerInterface; -use Magento\Setup\Model\Navigation; -use Magento\Setup\Model\ObjectManagerProvider; -use Magento\Setup\Model\Updater; -use Magento\Setup\Model\UpdaterTaskCreator; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class UpdaterTaskCreatorTest extends TestCase -{ - /** - * @var Updater|MockObject - */ - private $updater; - - /** - * @var Filesystem|MockObject - */ - private $filesystem; - - /** - * @var Navigation|MockObject - */ - private $navigation; - - /** - * @var ObjectManagerProvider|MockObject - */ - private $objectManagerProvider; - - protected function setUp(): void - { - $this->updater = $this->createMock(Updater::class); - $this->objectManagerProvider = - $this->createMock(ObjectManagerProvider::class); - $this->filesystem = $this->createMock(Filesystem::class); - $this->navigation = $this->createMock(Navigation::class); - $this->model = new UpdaterTaskCreator( - $this->filesystem, - $this->navigation, - $this->updater, - $this->objectManagerProvider - ); - $this->navigation->expects($this->any()) - ->method('getMenuItems') - ->willReturn([ - ['title' => 'A', 'type' => 'update'], - ['title' => 'B', 'type' => 'upgrade'], - ['title' => 'C', 'type' => 'enable'], - ['title' => 'D', 'type' => 'disable'], - ]); - } - - /** - * @param array $payload - * @dataProvider createUpdaterTasksDataProvider - */ - public function testCreateUpdaterTasks($payload) - { - $write = $this->getMockForAbstractClass( - WriteInterface::class, - [], - '', - false - ); - $this->filesystem->expects($this->once())->method('getDirectoryWrite')->willReturn($write); - $write->expects($this->once())->method('writeFile'); - $cacheManager = $this->createMock(Manager::class); - $objectManager = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $objectManager->expects($this->once())->method('get')->willReturn($cacheManager); - $this->objectManagerProvider->expects($this->once())->method('get')->willReturn($objectManager); - - $cacheManager->expects($this->once())->method('getStatus')->willReturn([ - 'cache1' => 1, 'cache2' => 0, 'cache3' => 1 - ]); - $this->model->createUpdaterTasks($payload); - } - - /** - * @return array - */ - public function createUpdaterTasksDataProvider() - { - return [ - [['type' => 'uninstall', - 'packages' => [['name' => 'vendor\/package', 'version' => '1.0.1']], - 'headerTitle'=>'Uninstall Package1', 'dataOption' => true - ], 0, false], - [['type' => 'update', - 'packages' => [['name' => 'vendor\/package', 'version' => '1.0.1']], - 'headerTitle'=>'Uninstall Package1' - ], 0, false], - [['type' => 'enable', - 'packages' => [['name' => 'vendor\/package', 'version' => '1.0.1']], - 'headerTitle'=>'Uninstall Package1' - ], 1, true], - [['type' => 'disable', - 'packages' => [['name' => 'vendor\/package', 'version' => '1.0.1']], - 'headerTitle'=>'Uninstall Package1' - ], 1, true], - ]; - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/UpdaterTest.php b/setup/src/Magento/Setup/Test/Unit/Model/UpdaterTest.php deleted file mode 100644 index 2fdcb2c798e5f..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/UpdaterTest.php +++ /dev/null @@ -1,56 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model; - -use Magento\Setup\Model\Cron\Queue; -use Magento\Setup\Model\Updater; -use PHPUnit\Framework\TestCase; - -class UpdaterTest extends TestCase -{ - public function testCreateUpdaterTaskUpdate() - { - $queue = $this->createMock(Queue::class); - $queue->expects($this->once()) - ->method('addJobs') - ->with( - [ - [ - 'name' => 'update', - 'params' => ['components' => [['name' => 'vendor/package', 'version' => 'dev-master']]] - ] - ] - ); - $updater = new Updater($queue); - $updater->createUpdaterTask( - [['name' => 'vendor/package', 'version' => 'dev-master']], - Updater::TASK_TYPE_UPDATE - ); - } - - public function testCreateUpdaterTaskUninstall() - { - $queue = $this->createMock(Queue::class); - $queue->expects($this->once()) - ->method('addJobs') - ->with( - [ - [ - 'name' => 'uninstall', - 'params' => ['components' => [['name' => 'vendor/package']], 'dataOption' => true] - ] - ] - ); - $updater = new Updater($queue); - $updater->createUpdaterTask( - [['name' => 'vendor/package']], - Updater::TASK_TYPE_UNINSTALL, - ['dataOption' => true] - ); - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Model/WebLoggerTest.php b/setup/src/Magento/Setup/Test/Unit/Model/WebLoggerTest.php deleted file mode 100644 index c5c29c6c57a9f..0000000000000 --- a/setup/src/Magento/Setup/Test/Unit/Model/WebLoggerTest.php +++ /dev/null @@ -1,220 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -declare(strict_types=1); - -namespace Magento\Setup\Test\Unit\Model; - -use Magento\Framework\Filesystem; -use Magento\Framework\Filesystem\Directory\Write; -use Magento\Setup\Model\WebLogger; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; - -class WebLoggerTest extends TestCase -{ - /** - * @var MockObject|Write - */ - private $directoryWriteMock; - - /** - * @var MockObject|Filesystem - */ - private $filesystemMock; - - /** - * @var string - */ - private static $log; - - /** - * @var WebLogger - */ - private $webLogger; - - protected function setUp(): void - { - self::$log = ''; - - $this->directoryWriteMock = $this->createMock(Write::class); - $this->directoryWriteMock - ->expects($this->any()) - ->method('readFile') - ->with('install.log') - ->willReturnCallback([\Magento\Setup\Test\Unit\Model\WebLoggerTest::class, 'readLog']); - $this->directoryWriteMock - ->expects($this->any()) - ->method('writeFile') - ->with('install.log') - ->willReturnCallback([\Magento\Setup\Test\Unit\Model\WebLoggerTest::class, 'writeToLog']); - $this->directoryWriteMock - ->expects($this->any()) - ->method('isExist') - ->willReturnCallback([\Magento\Setup\Test\Unit\Model\WebLoggerTest::class, 'isExist']); - - $this->filesystemMock = $this->createMock(Filesystem::class); - $this->filesystemMock - ->expects($this->once()) - ->method('getDirectoryWrite') - ->willReturn($this->directoryWriteMock); - - $this->webLogger = new WebLogger($this->filesystemMock); - } - - public function testConstructorLogFileSpecified() - { - $logFile = 'custom.log'; - $directoryWriteMock = $this->createMock(Write::class); - $directoryWriteMock->expects($this->once())->method('readFile')->with($logFile); - $directoryWriteMock->expects($this->once())->method('writeFile')->with($logFile); - - $filesystemMock = $this->createMock(Filesystem::class); - $filesystemMock - ->expects($this->once()) - ->method('getDirectoryWrite') - ->willReturn($directoryWriteMock); - - $webLogger = new WebLogger($filesystemMock, $logFile); - - $webLogger->log('Message'); - $webLogger->get(); - } - - public function testLogSuccess() - { - $this->webLogger->logSuccess('Success1'); - $this->assertEquals('<span class="text-success">[SUCCESS] ' . 'Success1' . '</span><br>', self::$log); - - $this->webLogger->logSuccess('Success2'); - $this->assertEquals( - '<span class="text-success">[SUCCESS] ' . 'Success1' . '</span><br>' . - '<span class="text-success">[SUCCESS] ' . 'Success2' . '</span><br>', - self::$log - ); - } - - public function testLogError() - { - $e1 = new \Exception('Dummy Exception1'); - $e2 = new \Exception('Dummy Exception2'); - - $this->webLogger->logError($e1); - $this->assertStringContainsString('[ERROR]', self::$log); - $this->assertStringContainsString('Exception', self::$log); - $this->assertStringContainsString($e1->getMessage(), self::$log); - - $this->webLogger->logError($e2); - $this->assertStringContainsString('[ERROR]', self::$log); - $this->assertStringContainsString('Exception', self::$log); - $this->assertStringContainsString($e1->getMessage(), self::$log); - $this->assertStringContainsString($e2->getMessage(), self::$log); - } - - public function testLog() - { - $this->webLogger->log('Message1'); - $this->assertEquals('<span class="text-info">Message1</span><br>', self::$log); - - $this->webLogger->log('Message2'); - $this->assertEquals( - '<span class="text-info">Message1</span><br><span class="text-info">Message2</span><br>', - self::$log - ); - } - - public function testLogAfterInline() - { - $this->webLogger->logInline('*'); - $this->webLogger->log('Message'); - $this->assertEquals( - '<span class="text-info">*</span><br><span class="text-info">Message</span><br>', - self::$log - ); - } - - public function testLogInline() - { - $this->webLogger->logInline('*'); - $this->assertEquals('<span class="text-info">*</span>', self::$log); - - $this->webLogger->logInline('*'); - $this->assertEquals('<span class="text-info">*</span><span class="text-info">*</span>', self::$log); - } - - public function testLogMeta() - { - $this->webLogger->logMeta('Meta1'); - $this->assertEquals('<span class="hidden">Meta1</span><br>', self::$log); - - $this->webLogger->logMeta('Meta2'); - $this->assertEquals('<span class="hidden">Meta1</span><br><span class="hidden">Meta2</span><br>', self::$log); - } - - public function testGet() - { - $this->webLogger->log('Message1' . PHP_EOL); - $this->webLogger->log('Message2'); - - $expected = [ - '<span class="text-info">Message1', - '</span><br><span class="text-info">Message2</span><br>', - ]; - - $this->assertEquals($expected, $this->webLogger->get()); - } - - public function testClear() - { - $this->directoryWriteMock - ->expects($this->once()) - ->method('delete') - ->willReturnCallback([\Magento\Setup\Test\Unit\Model\WebLoggerTest::class, 'deleteLog']); - - $this->webLogger->log('Message1'); - $this->assertEquals('<span class="text-info">Message1</span><br>', self::$log); - - $this->webLogger->clear(); - $this->assertEquals('', self::$log); - } - - public function testClearNotExist() - { - $this->directoryWriteMock - ->expects($this->never()) - ->method('delete'); - - $this->webLogger->clear(); - } - - /** - * @return string - */ - public static function readLog() - { - return self::$log; - } - - /** - * @SuppressWarnings(PHPMD.UnusedFormalParameter) - */ - public static function writeToLog($logFile, $message) - { - self::$log .= $message; - } - - public static function deleteLog() - { - self::$log = ''; - } - - /** - * @return bool - */ - public static function isExist() - { - return self::$log != ''; - } -} diff --git a/setup/src/Magento/Setup/Test/Unit/Mvc/Bootstrap/InitParamListenerTest.php b/setup/src/Magento/Setup/Test/Unit/Mvc/Bootstrap/InitParamListenerTest.php index 430f3931227a9..b18345666af5e 100644 --- a/setup/src/Magento/Setup/Test/Unit/Mvc/Bootstrap/InitParamListenerTest.php +++ b/setup/src/Magento/Setup/Test/Unit/Mvc/Bootstrap/InitParamListenerTest.php @@ -278,231 +278,4 @@ private function prepareEventManager() return $eventManager; } - - /** - * @SuppressWarnings(PHPMD.ExcessiveMethodLength) - */ - public function testAuthPreDispatch() - { - $cookiePath = 'test'; - $eventMock = $this->getMockBuilder(MvcEvent::class) - ->disableOriginalConstructor() - ->getMock(); - $routeMatchMock = $this->getMockBuilder(RouteMatch::class) - ->disableOriginalConstructor() - ->getMock(); - $applicationMock = $this->getMockBuilder(Application::class) - ->disableOriginalConstructor() - ->getMock(); - $serviceManagerMock = $this->getMockBuilder(ServiceManager::class) - ->disableOriginalConstructor() - ->getMock(); - $deploymentConfigMock = $this->getMockBuilder(DeploymentConfig::class) - ->disableOriginalConstructor() - ->getMock(); - $deploymentConfigMock->expects($this->once()) - ->method('isAvailable') - ->willReturn(true); - $omProvider = $this->getMockBuilder(ObjectManagerProvider::class) - ->disableOriginalConstructor() - ->getMock(); - $objectManagerMock = $this->getMockForAbstractClass(ObjectManagerInterface::class); - $adminAppStateMock = $this->getMockBuilder(State::class) - ->disableOriginalConstructor() - ->getMock(); - $sessionConfigMock = $this->getMockBuilder(AdminConfig::class) - ->disableOriginalConstructor() - ->getMock(); - $backendAppListMock = $this->getMockBuilder(BackendAppList::class) - ->disableOriginalConstructor() - ->getMock(); - $backendAppMock = $this->getMockBuilder(BackendApp::class) - ->disableOriginalConstructor() - ->getMock(); - $urlMock = $this->getMockBuilder(Url::class) - ->disableOriginalConstructor() - ->getMock(); - $authenticationMock = $this->getMockBuilder(Auth::class) - ->disableOriginalConstructor() - ->getMock(); - $adminSessionMock = $this->getMockBuilder(Session::class) - ->disableOriginalConstructor() - ->getMock(); - $responseMock = $this->getMockBuilder(Response::class) - ->disableOriginalConstructor() - ->getMock(); - $headersMock = $this->getMockBuilder(Headers::class) - ->disableOriginalConstructor() - ->getMock(); - - $routeMatchMock->expects($this->exactly(2)) - ->method('getParam') - ->willReturnMap( - [ - [ - 'controller', - null, - 'testController' - ], - [ - 'action', - null, - 'testAction' - ] - ] - ); - $eventMock->expects($this->once()) - ->method('getRouteMatch') - ->willReturn($routeMatchMock); - $eventMock->expects($this->once()) - ->method('getApplication') - ->willReturn($applicationMock); - $serviceManagerMock->expects($this->any()) - ->method('get') - ->willReturnMap( - [ - [ - DeploymentConfig::class, - true, - $deploymentConfigMock, - ], - [ - ObjectManagerProvider::class, - true, - $omProvider, - ], - ] - ); - $objectManagerMock->expects($this->any()) - ->method('get') - ->willReturnMap( - [ - [ - State::class, - $adminAppStateMock, - ], - [ - AdminConfig::class, - $sessionConfigMock, - ], - [ - BackendAppList::class, - $backendAppListMock, - ], - [ - Auth::class, - $authenticationMock, - ], - ] - ); - $objectManagerMock->expects($this->any()) - ->method('create') - ->willReturnMap( - [ - [ - Session::class, - [ - 'sessionConfig' => $sessionConfigMock, - 'appState' => $adminAppStateMock - ], - $adminSessionMock, - ], - [ - Url::class, - [], - $urlMock, - ], - ] - ); - $omProvider->expects($this->once()) - ->method('get') - ->willReturn($objectManagerMock); - $adminAppStateMock->expects($this->once()) - ->method('setAreaCode') - ->with(Area::AREA_ADMINHTML); - $applicationMock->expects($this->once()) - ->method('getServiceManager') - ->willReturn($serviceManagerMock); - $backendAppMock->expects($this->once()) - ->method('getCookiePath') - ->willReturn($cookiePath); - $urlMock->expects($this->once()) - ->method('getBaseUrl') - ->willReturn('http://base-url/'); - $sessionConfigMock->expects($this->once()) - ->method('setCookiePath') - ->with('/' . $cookiePath); - $backendAppListMock->expects($this->once()) - ->method('getBackendApp') - ->willReturn($backendAppMock); - $authenticationMock->expects($this->once()) - ->method('isLoggedIn') - ->willReturn(true); - $adminSessionMock->expects($this->once()) - ->method('isAllowed') - ->with('Magento_Backend::setup_wizard', null) - ->willReturn(false); - $adminSessionMock->expects($this->once()) - ->method('destroy'); - $eventMock->expects($this->once()) - ->method('getResponse') - ->willReturn($responseMock); - $responseMock->expects($this->once()) - ->method('getHeaders') - ->willReturn($headersMock); - $headersMock->expects($this->once()) - ->method('addHeaderLine'); - $responseMock->expects($this->once()) - ->method('setStatusCode') - ->with(302); - $eventMock->expects($this->once()) - ->method('stopPropagation'); - - $this->assertSame( - $this->listener->authPreDispatch($eventMock), - $responseMock - ); - } - - public function testAuthPreDispatchSkip() - { - $eventMock = $this->getMockBuilder(MvcEvent::class) - ->disableOriginalConstructor() - ->getMock(); - $routeMatchMock = $this->getMockBuilder(RouteMatch::class) - ->disableOriginalConstructor() - ->getMock(); - $deploymentConfigMock = $this->getMockBuilder(DeploymentConfig::class) - ->disableOriginalConstructor() - ->getMock(); - - $deploymentConfigMock->expects($this->never()) - ->method('isAvailable'); - $routeMatchMock->expects($this->exactly(2)) - ->method('getParam') - ->willReturnMap( - [ - [ - 'controller', - null, - \Magento\Setup\Controller\Session::class - ], - [ - 'action', - null, - 'unlogin' - ] - ] - ); - $eventMock->expects($this->once()) - ->method('getRouteMatch') - ->willReturn($routeMatchMock); - $eventMock->expects($this->never()) - ->method('getApplication'); - - $this->assertSame( - $this->listener->authPreDispatch($eventMock), - false - ); - } } diff --git a/setup/src/Magento/Setup/Validator/AdminCredentialsValidator.php b/setup/src/Magento/Setup/Validator/AdminCredentialsValidator.php deleted file mode 100644 index 660c5ed893d59..0000000000000 --- a/setup/src/Magento/Setup/Validator/AdminCredentialsValidator.php +++ /dev/null @@ -1,91 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -namespace Magento\Setup\Validator; - -use Magento\Framework\App\ObjectManager; -use Magento\Framework\Config\ConfigOptionsListConstants as ConfigOption; -use Magento\Setup\Model\AdminAccount; -use Magento\Setup\Model\ConfigOptionsList\DriverOptions; - -/** - * Admin user credentials validator - */ -class AdminCredentialsValidator -{ - /** - * @var \Magento\Setup\Module\ConnectionFactory - */ - private $connectionFactory; - - /** - * @var \Magento\Setup\Model\AdminAccountFactory - */ - private $adminAccountFactory; - - /** - * @var \Magento\Setup\Module\SetupFactory - */ - private $setupFactory; - - /** - * @var DriverOptions - */ - private $driverOptions; - - /** - * Initialize dependencies. - * - * @param \Magento\Setup\Model\AdminAccountFactory $adminAccountFactory - * @param \Magento\Setup\Module\ConnectionFactory $connectionFactory - * @param \Magento\Setup\Module\SetupFactory $setupFactory - * @param DriverOptions|null $driverOptions - */ - public function __construct( - \Magento\Setup\Model\AdminAccountFactory $adminAccountFactory, - \Magento\Setup\Module\ConnectionFactory $connectionFactory, - \Magento\Setup\Module\SetupFactory $setupFactory, - DriverOptions $driverOptions = null - ) { - $this->connectionFactory = $connectionFactory; - $this->adminAccountFactory = $adminAccountFactory; - $this->setupFactory = $setupFactory; - $this->driverOptions = $driverOptions ?? ObjectManager::getInstance()->get(DriverOptions::class); - } - - /** - * Validate admin user name and email. - * - * @param array $data - * @return void - * @throws \Exception - */ - public function validate(array $data) - { - $driverOptions = $this->driverOptions->getDriverOptions($data); - $dbConnection = $this->connectionFactory->create( - [ - ConfigOption::KEY_NAME => $data[ConfigOption::INPUT_KEY_DB_NAME], - ConfigOption::KEY_HOST => $data[ConfigOption::INPUT_KEY_DB_HOST], - ConfigOption::KEY_USER => $data[ConfigOption::INPUT_KEY_DB_USER], - ConfigOption::KEY_PASSWORD => $data[ConfigOption::INPUT_KEY_DB_PASSWORD], - ConfigOption::KEY_PREFIX => $data[ConfigOption::INPUT_KEY_DB_PREFIX], - ConfigOption::KEY_DRIVER_OPTIONS => $driverOptions - ] - ); - - $adminAccount = $this->adminAccountFactory->create( - $dbConnection, - [ - AdminAccount::KEY_USER => $data[AdminAccount::KEY_USER], - AdminAccount::KEY_EMAIL => $data[AdminAccount::KEY_EMAIL], - AdminAccount::KEY_PASSWORD => $data[AdminAccount::KEY_PASSWORD], - AdminAccount::KEY_PREFIX => $data[ConfigOption::INPUT_KEY_DB_PREFIX] - ] - ); - - $adminAccount->validateUserMatches(); - } -} diff --git a/setup/view/error/401.phtml b/setup/view/error/401.phtml deleted file mode 100644 index 6fa12384d3b6a..0000000000000 --- a/setup/view/error/401.phtml +++ /dev/null @@ -1,20 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// @codingStandardsIgnoreFile - -?> -<script> - document.title = 'Magento Setup - 401 Unauthorized Access'; -</script> -<section class="page-landing"> - <img class="logo" src="<?= $this->basePath() ?>/pub/images/magento-logo.svg" alt="Magento"/> - <p class="text-welcome"> - Welcome to Magento Admin, your online store headquarters. - <br> - To use the Magento setup wizard sign into your Admin account and navigate to System => Tools => Web Setup Wizard - </p> -</section> diff --git a/setup/view/error/404.phtml b/setup/view/error/404.phtml deleted file mode 100644 index dd4a7d79a82bd..0000000000000 --- a/setup/view/error/404.phtml +++ /dev/null @@ -1,124 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// @codingStandardsIgnoreFile - -?> -<header class="header"> - <img class="logo" src="<?= $this->basePath() ?>/pub/images/magento-icon.svg" alt="Magento"/> - <h1 class="header-title">A 404 error occurred</h1> -</header> - -<h2>Page not found</h2> - -<?php if ( isset( $this->reason ) && $this->reason ): ?> - - <?php - $reasonMessage = ''; - switch ( $this->reason ) { - case 'error-controller-cannot-dispatch': - $reasonMessage = 'The requested controller was unable to dispatch the request.'; - break; - case 'error-controller-not-found': - $reasonMessage = 'The requested controller could not be mapped to an existing controller class.'; - break; - case 'error-controller-invalid': - $reasonMessage = 'The requested controller was not dispatchable.'; - break; - case 'error-router-no-match': - $reasonMessage = 'The requested URL could not be matched by routing.'; - break; - default: - $reasonMessage = 'We cannot determine at this time why a 404 was generated.'; - break; - } - ?> - - <p><?= $reasonMessage ?></p> - -<?php endif ?> - -<?php if ( isset( $this->controller ) && $this->controller ): ?> - - <dl> - <dt>Controller:</dt> - <dd><?= $this->escapeHtml( $this->controller ) ?> - <?php - if ( isset( $this->controller_class ) - && $this->controller_class - && $this->controller_class != $this->controller - ) { - echo '(' . sprintf( 'resolves to %s', $this->escapeHtml( $this->controller_class ) ) . ')'; - } - ?> - </dd> - </dl> - -<?php endif ?> - -<?php if ( isset( $this->display_exceptions ) && $this->display_exceptions ): ?> - - <?php if ( isset( $this->exception ) && $this->exception instanceof Exception ): ?> - <hr/> - <h2>Additional information:</h2> - <h3><?= get_class( $this->exception ) ?></h3> - <dl> - <dt>File:</dt> - <dd> - <pre class="prettyprint linenums"><?= $this->exception->getFile() ?>:<?= $this->exception->getLine() ?></pre> - </dd> - - <dt>Message:</dt> - <dd> - <pre class="prettyprint linenums"><?= $this->exception->getMessage() ?></pre> - </dd> - - <dt>Stack trace:</dt> - <dd> - <pre class="prettyprint linenums"><?= $this->exception->getTraceAsString() ?></pre> - </dd> - </dl> - <?php - $e = $this->exception->getPrevious(); - if ( $e ) : - ?> - <hr/> - <h2>Previous exceptions:</h2> - <ul class="unstyled"> - <?php while ( $e ) : ?> - <li> - <h3><?= get_class( $e ) ?></h3> - <dl> - <dt>File:</dt> - <dd> - <pre class="prettyprint linenums"><?= $e->getFile() ?>:<?= $e->getLine() ?></pre> - </dd> - - <dt>Message:</dt> - <dd> - <pre class="prettyprint linenums"><?= $e->getMessage() ?></pre> - </dd> - - <dt>Stack trace:</dt> - <dd> - <pre class="prettyprint linenums"><?= $e->getTraceAsString() ?></pre> - </dd> - </dl> - </li> - <?php - $e = $e->getPrevious(); - endwhile; - ?> - </ul> - <?php endif; ?> - - <?php else: ?> - - <p>No Exception available</p> - - <?php endif ?> - -<?php endif ?> diff --git a/setup/view/error/index.phtml b/setup/view/error/index.phtml deleted file mode 100644 index 40f8bd4968b4e..0000000000000 --- a/setup/view/error/index.phtml +++ /dev/null @@ -1,79 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// @codingStandardsIgnoreFile - -?> -<header class="header"> - <img class="logo" src="<?= $this->basePath() ?>/pub/images/magento-icon.svg" alt="Magento"/> - <h1 class="header-title">An error occurred</h1> -</header> - -<h2><?= $this->message ?></h2> - -<?php if ( isset( $this->display_exceptions ) && $this->display_exceptions ): ?> - - <?php if ( isset( $this->exception ) && $this->exception instanceof Exception ): ?> - <hr/> - <h2>Additional information:</h2> - <h3><?= get_class( $this->exception ) ?></h3> - <dl> - <dt>File:</dt> - <dd> - <pre class="prettyprint linenums"><?= $this->exception->getFile() ?>:<?= $this->exception->getLine() ?></pre> - </dd> - - <dt>Message:</dt> - <dd> - <pre class="prettyprint linenums"><?= $this->escapeHtml( $this->exception->getMessage() ) ?></pre> - </dd> - - <dt>Stack trace:</dt> - <dd> - <pre class="prettyprint linenums"><?= $this->escapeHtml( $this->exception->getTraceAsString() ) ?></pre> - </dd> - </dl> - <?php - $e = $this->exception->getPrevious(); - if ( $e ) : - ?> - <hr/> - <h2>Previous exceptions:</h2> - <ul class="unstyled"> - <?php while ( $e ) : ?> - <li> - <h3><?= get_class( $e ) ?></h3> - <dl> - <dt>File:</dt> - <dd> - <pre class="prettyprint linenums"><?= $e->getFile() ?>:<?= $e->getLine() ?></pre> - </dd> - - <dt>Message:</dt> - <dd> - <pre class="prettyprint linenums"><?= $this->escapeHtml( $e->getMessage() ) ?></pre> - </dd> - - <dt>Stack trace:</dt> - <dd> - <pre class="prettyprint linenums"><?= $this->escapeHtml( $e->getTraceAsString() ) ?></pre> - </dd> - </dl> - </li> - <?php - $e = $e->getPrevious(); - endwhile; - ?> - </ul> - <?php endif; ?> - - <?php else: ?> - - <h3>No Exception available</h3> - - <?php endif ?> - -<?php endif ?> diff --git a/setup/view/layout/layout.phtml b/setup/view/layout/layout.phtml index 5a42d30181726..9b2d6703c16bc 100644 --- a/setup/view/layout/layout.phtml +++ b/setup/view/layout/layout.phtml @@ -9,7 +9,7 @@ ?> <?= $this->doctype() ?> <!--[if !IE]><!--> -<html lang="en" ng-app="magentoSetup"> +<html lang="en" ng-app="magento"> <!--<![endif]--> <head> <meta charset="utf-8"> @@ -29,29 +29,6 @@ ->appendFile($this->basePath() . '/pub/magento/setup/app.js') ->appendFile($this->basePath() . '/pub/magento/setup/main.js') ->appendFile($this->basePath() . '/pub/magento/setup/landing.js') - ->appendFile($this->basePath() . '/pub/magento/setup/module-grid.js') - ->appendFile($this->basePath() . '/pub/magento/setup/extension-grid.js') - ->appendFile($this->basePath() . '/pub/magento/setup/readiness-check.js') - ->appendFile($this->basePath() . '/pub/magento/setup/add-database.js') - ->appendFile($this->basePath() . '/pub/magento/setup/web-configuration.js') - ->appendFile($this->basePath() . '/pub/magento/setup/customize-your-store.js') - ->appendFile($this->basePath() . '/pub/magento/setup/configure-catalog-search.js') - ->appendFile($this->basePath() . '/pub/magento/setup/create-admin-account.js') - ->appendFile($this->basePath() . '/pub/magento/setup/install.js') - ->appendFile($this->basePath() . '/pub/magento/setup/success.js') - ->appendFile($this->basePath() . '/pub/magento/setup/create-backup.js') - ->appendFile($this->basePath() . '/pub/magento/setup/complete-backup.js') - ->appendFile($this->basePath() . '/pub/magento/setup/data-option.js') - ->appendFile($this->basePath() . '/pub/magento/setup/start-updater.js') - ->appendFile($this->basePath() . '/pub/magento/setup/updater-success.js') - ->appendFile($this->basePath() . '/pub/magento/setup/select-version.js') - ->appendFile($this->basePath() . '/pub/magento/setup/home.js') - ->appendFile($this->basePath() . '/pub/magento/setup/auth-dialog.js') - ->appendFile($this->basePath() . '/pub/magento/setup/remove-dialog.js') - ->appendFile($this->basePath() . '/pub/magento/setup/system-config.js') - ->appendFile($this->basePath() . '/pub/magento/setup/marketplace-credentials.js') - ->appendFile($this->basePath() . '/pub/magento/setup/install-extension-grid.js') - ->appendFile($this->basePath() . '/pub/magento/setup/update-extension-grid.js'); ?> <link rel="icon" diff --git a/setup/view/magento/setup/add-database.phtml b/setup/view/magento/setup/add-database.phtml deleted file mode 100644 index 5ba15cf0c1ec8..0000000000000 --- a/setup/view/magento/setup/add-database.phtml +++ /dev/null @@ -1,565 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// @codingStandardsIgnoreFile - -?> -<div class="nav-bar-outer-actions"> - <div class="outer-actions-inner-wrap"> - <div class="btn-wrap btn-wrap-triangle-right btn-wrap-next"> - <button - type="button" - class="btn btn-prime" - ng-click="testConnection()" - >Next</button> - </div> - <div class="btn-wrap btn-wrap-triangle-left btn-wrap-prev"> - <button - type="button" - class="btn" - ng-click="previousState()" - >Back</button> - </div> - </div> -</div> - -<h2 class="page-sub-title">{{$state.current.header}}</h2> - -<div - class="message message-success" - ng-show="testConnection.result.success && testConnection.pressed" - > - <span class="message-text">Test connection successful.</span> -</div> -<div - class="message message-error" - ng-show="testConnection.result.success === false && testConnection.result !== undefined" - > - <span class="message-text">{{testConnection.result.error}}</span> -</div> -<div - class="message message-error" - ng-show="testConnection.failed !== undefined" - > - <span class="message-text">{{testConnection.failed}}</span> -</div> - -<form - novalidate - name="database" - role="form" - autocomplete="off" - > - -<?php -/* Hide "Create database" option - -<fieldset class="form-fieldset"> - - <legend class="form-legend-light"> - Did you want to use an existing or create a new database? - </legend> - - <div class="form-row"> - <input - id="useExistingDb" - class="form-el-radio" - type="radio" - name="useExistingDb" - ng-model="db.useExistingDb" - value="1" - > - <label class="form-label" for="useExistingDb"> - Use my existing database - </label> - </div> - - <div class="form-row"> - <input - id="useNotExistingDb" - class="form-el-radio" - type="radio" - name="useExistingDb" - ng-model="db.useExistingDb" - value="0" - > - <label class="form-label" for="useNotExistingDb"> - Create a database for me - </label> - </div> - */ -?> -<div class="row form-row"> - <div class="col-m-3"> - <label class="form-label" for="dbDriverOptionsSslKey"> - Driver Options - SSL Key - </label> - </div> - <div class="col-m-4"> - <input - id="dbDriverOptionsSslKey" - class="form-el-input" - tooltip-placement="right" - tooltip="File that contains X509 key" - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="text" - name="dbDriverOptionsSslKey" - ng-model="db.driverOptionsSslKey" - placeholder="/path/to/client-key.pem" - > - </div> -</div> - -<div class="row form-row"> - <div class="col-m-3"> - <label class="form-label" for="dbDriverOptionsSslCert"> - Driver Options - SSL Certificate - </label> - </div> - <div class="col-m-4"> - <input - id="dbDriverOptionsSslCert" - class="form-el-input" - tooltip-placement="right" - tooltip="File that contains X509 certificate" - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="text" - name="dbDriverOptionsSslCert" - ng-model="db.driverOptionsSslCert" - placeholder="/path/to/client-cert.pem" - > - </div> -</div> - -<div class="row form-row"> - <div class="col-m-3"> - <label class="form-label" for="dbDriverOptionsSslCa"> - Driver Options - SSL Certificate Authorities - </label> - </div> - <div class="col-m-4"> - <input - id="dbDriverOptionsSslCa" - class="form-el-input" - tooltip-placement="right" - tooltip="File that contains list of trusted SSL Certificate Authorities" - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="text" - name="dbDriverOptionsSslCa" - ng-model="db.driverOptionsSslCa" - placeholder="/path/to/ca.pem" - > - </div> -</div> - -<div class="row form-row"> - <div class="col-m-3"> - <label class="form-label"> - Driver Options - SSL Verification - </label> - </div> - <div class="col-m-4"> - <div class="form-row"> - <input - id="dbDriverOptionsSslVerify" - class="form-el-checkbox" - type="checkbox" - ng-model="db.driverOptionsSslVerify" - ng-checked="db.driverOptionsSslVerify" - > - <label class="form-label" for="dbDriverOptionsSslVerify"> - Perform verification against the server CA certificate and against the server host name in its certificate - </label> - </div> - </div> -</div> -</fieldset> - -<fieldset class="form-fieldset"> - -<?php -/* Hide "Create database" option - -<legend class="form-legend" ng-if="db.useExistingDb==1"> - Use my existing database -</legend> -<legend class="form-legend" ng-if="db.useExistingDb==0"> - Create a database for me -</legend> - -*/ -?> - -<div - class="row form-row" - ng-class="{'has-error': database.dbHost.$invalid && database.submitted}" - > - <div class="col-m-3"> - <label class="form-label required" for="dbHost"> - Database Server Host - </label> - </div> - <div class="col-m-4"> - <input - id="dbHost" - class="form-el-input" - tooltip-placement="right" - tooltip="Name and location of the server that hosts your store's database." - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="text" - name="dbHost" - ng-model="db.host" - ng-class="{'invalid': database.dbHost.$invalid && database.submitted}" - required - > - <div class="error-container"> - <span ng-show="database.dbHost.$error.required"> - You must enter a valid host name. Please check the syntax and try again. - </span> - </div> - </div> -</div> - -<div - class="row form-row" - ng-class="{'has-error': database.dbUser.$invalid && database.submitted}" - > - <div class="col-m-3"> - <label class="form-label required" for="dbUser"> - Database Server Username - </label> - </div> - <div class="col-m-4"> - <?php - /* Hide "Create database" option - - ng-switch="db.useExistingDb" - - <input - id="dbUser" - ng-switch-when="1" - tooltip-placement="right" - tooltip="Sign-in credentials for your store's database on the database server (does not need to be admin-level credentials)." - tooltip-trigger="focus" - tooltip-append-to-body="true" - class="form-el-input" - type="text" - name="dbUser" - ng-model="db.user" - required - > - */ - ?> - <input - id="dbUser" - tooltip-placement="right" - tooltip="Sign-in credentials for your store's database on the database server (does not need to be admin-level credentials)." - tooltip-trigger="focus" - tooltip-append-to-body="true" - class="form-el-input" - ng-class="{'invalid': database.dbUser.$invalid && database.submitted}" - type="text" - name="dbUser" - ng-model="db.user" - required - > - <div class="error-container"> - <span ng-show="database.dbUser.$error.required"> - Please enter a username to continue. - </span> - </div> - </div> -</div> - -<div class="row form-row"> - <div class="col-m-3"> - <label class="form-label" for="dbPassword"> - Database Server Password - </label> - </div> - <div class="col-m-4" ng-switch="db.useExistingDb"> - <input - id="dbPassword" - class="form-el-input" - ng-switch-when="1" - tooltip-placement="right" - tooltip="Sign-in credentials for your store's database on the database server (does not need to be admin-level credentials)." - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="password" - name="dbPassword" - ng-model="db.password" - placeholder="(not always necessary)" - > - <input - id="dbPassword" - class="form-el-input" - ng-switch-when="0" - tooltip-placement="right" - tooltip="Administrator credentials to sign in to the server that will host your store's database." - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="password" - name="dbPassword" - ng-model="db.password" - placeholder="(not always necessary)" - > - </div> -</div> - -<div class="row form-row" ng-if="db.useExistingDb"> - <div class="col-m-3"> - <label class="form-label required" for="dbname"> - Database Name - </label> - </div> - <div class="col-m-4"> - <input - id="dbname" - class="form-el-input" - tooltip-placement="right" - tooltip="Enter the name of your store's database." - tooltip-trigger="focus" - tooltip-append-to-body="true" - ng-class="{'invalid': database.dbname.$invalid && database.submitted}" - type="text" - name="dbname" - ng-model="db.name" - required - > - <div class="error-container"> - <span ng-show="database.dbname.$error.required"> - You must enter a valid database name. Please check the syntax and try again. - </span> - </div> - </div> -</div> - -<?php -/* Hide "Create database" option - -<div class="row form-row" ng-if="db.useExistingDb==0"> - <div class="col-m-3"> - <label class="form-label required" for="dbNewName"> - New Database Name - </label> - </div> - <div class="col-m-4"> - <input - id="dbNewName" - class="form-el-input" - tooltip-placement="right" - tooltip="Create sign-in credentials for your store's database." - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="text" - name="dbNewName" - ng-model="db.newName" - required - > - </div> -</div> - -*/ -?> - -<?php -/* Hide "Create database" option -<div class="row form-row"> - <div class="col-m-offset-3 col-m-4"> - <button - class="btn btn-secondary" - type="button" - ng-click="testConnection()" - > - Test Connection and Authentication - </button> - </div> - <div class="col-m-5"> - <div - class="check-result-message" - ng-show="testConnection.result.success && testConnection.pressed" - > - <span class="icon-success-round"></span> - <span class="check-result-text">Test connection successful.</span> - </div> - <div - class="check-result-message" - ng-show="testConnection.result.success === false && testConnection.result !== undefined" - > - <span class="icon-failed-round"></span> - <span class="check-result-text">{{testConnection.result.error}}</span> - </div> - <div - class="check-result-message" - ng-show="testConnection.result.success === undefined && testConnection.result !== undefined" - > - <span class="icon-failed-round"></span> - <span class="check-result-text">Unknown Database Server Host.</span> - </div> - </div> -</div> -*/ -?> - -<div class="row form-row"> - <div class="col-m-3"> - <label class="form-label" for="dbTablePrefix"> - Table prefix - </label> - </div> - <div class="col-m-4"> - <input - id="dbTablePrefix" - class="form-el-input" - tooltip-placement="right" - tooltip="Enter a prefix for database tables created in this installation. Use letters, numbers or underscores, and begin with a letter (Ex: ‘mg1_’). Table prefix length can't be more than 5 characters." - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="text" - name="dbTablePrefix" - ng-model="db.tablePrefix" - placeholder="(optional)" - > - </div> -</div> - -<?php -/* Hide "Create database" option - -<div ng-if="db.useExistingDb==0"> - - <p class="form-legend-light"> - Data Access - </p> - - <div class="form-row"> - <input - id="dbUseAccess" - class="form-el-radio" - type="radio" - name="db.useAccess" - ng-model="db.useAccess" - value="0" - > - <label class="form-label" for="dbUseAccess"> - Enter existing credentials to create the Magento database - </label> - </div> - - <div class="row form-row" ng-if="db.useAccess==0"> - <div class="col-m-3"> - <label class="form-label required" for="dbGrandUsername"> - Username - </label> - </div> - <div class="col-m-4"> - <input - id="dbGrandUsername" - class="form-el-input" - type="text" - name="dbGrandUsername" - ng-model="dbGrandUsername" - required - > - </div> - </div> - - <div class="row form-row" ng-if="db.useAccess==0"> - <div class="col-m-3"> - <label class="form-label" for="dbGrandPassword"> - Password - </label> - </div> - <div class="col-m-4"> - <input - id="dbGrandPassword" - class="form-el-input" - type="password" - name="dbGrandPassword" - ng-model="db.grandPassword" - placeholder="(optional)" - > - </div> - </div> - - <div class="form-row"> - <input - id="useAccess" - class="form-el-radio" - type="radio" - name="useAccess" - ng-model="db.useAccess" - value="1" - > - <label class="form-label" for="useAccess"> - Enter new credentials to create the Magento database - </label> - </div> - - <div class="row form-row" ng-if="db.useAccess"> - <div class="col-m-3"> - <label class="form-label required" for="dbNewUsername"> - New Username - </label> - </div> - <div class="col-m-4"> - <input - id="dbNewUsername" - class="form-el-input" - type="text" - name="dbNewUsername" - ng-model="db.newUsername" - required - > - </div> - </div> - - <div class="row form-row" ng-if="db.useAccess"> - <div class="col-m-3"> - <label class="form-label" for="dbNewPassword"> - New Password - </label> - </div> - <div class="col-m-4"> - <input - id="dbNewPassword" - class="form-el-input" - type="password" - name="dbNewPassword" - ng-model="db.newPassword" - placeholder="(optional)" - > - </div> - </div> - <div class="row form-row" ng-if="db.useAccess"> - <div class="col-m-3"> - <label class="form-label" for="dbConfirmPassword"> - Confirm Password - </label> - </div> - <div class="col-m-4"> - <input - id="dbConfirmPassword" - class="form-el-input" - type="password" - name="dbConfirmPassword" - ng-model="db.confirmPassword" - > - </div> - </div> - -</div> - -*/ -?> -</fieldset> - -</form> diff --git a/setup/view/magento/setup/complete-backup/progress.phtml b/setup/view/magento/setup/complete-backup/progress.phtml deleted file mode 100644 index 0dd45cadaa6c2..0000000000000 --- a/setup/view/magento/setup/complete-backup/progress.phtml +++ /dev/null @@ -1,161 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// @codingStandardsIgnoreFile - -?> - -<div ng-switch="isCompleted()"> - - <div ng-switch-when="true" ng-switch="hasErrors"> - - <div class="message message-error" ng-switch-when="true"> - <span class="message-text"> - <strong>Completed!</strong> You need to resolve these issues to continue. - </span> - </div> - - <div class="message message-success" ng-switch-default> - <span class="message-text"> - <strong>Completed!</strong> You can now move on to the next step. - </span> - </div> - - </div> - - <div class="message message-spinner" ng-switch-default> - <span class="spinner"> - <span></span><span></span><span></span><span></span> - <span></span><span></span><span></span><span></span> - </span> - <span class="message-text">Checking and Creating Backup...</span> - </div> - -</div> - -<div id="backup-check" class="readiness-check-item" ng-show="check.visible"> - <div ng-hide="check.processed"> - <span class="spinner side"> - <span></span><span></span><span></span><span></span> - <span></span><span></span><span></span><span></span> - </span> - <h3 class="readiness-check-title">Checking available disk space for backups</h3> - </div> - <div ng-show="check.processed" ng-switch="check.responseType"> - - <div ng-switch-when="success" ng-init="updateOnSuccess(check)"> - - <span class="readiness-check-icon icon-success-round"></span> - - <div class="readiness-check-content"> - <h3 class="readiness-check-title">Disk space available</h3> - <p> - You have enough space available in disk for taking your selected backups. - </p> - </div> - - </div> - - <div class="readiness-check-item" ng-switch-default ng-init="updateOnError(check)"> - - <span class="readiness-check-icon icon-failed-round"></span> - - <div class="readiness-check-content"> - <h3 class="readiness-check-title">Check disk space availability</h3> - <p> - Insufficient disk space available. Free up some space and try the backup again. - </p> - <p> - Error received from server: - <br> - {{check.error}} - </p> - </div> - </div> - - </div> - -</div> - -<div id="store-maintenance" class="readiness-check-item" ng-show="maintenance.visible"> - <div ng-hide="maintenance.processed"> - <span class="spinner side"> - <span></span><span></span><span></span><span></span> - <span></span><span></span><span></span><span></span> - </span> - <h3 class="readiness-check-title">Putting store in maintenance mode...</h3> - </div> - <div ng-show="maintenance.processed" ng-switch="maintenance.responseType"> - - <div ng-switch-when="success" ng-init="updateOnSuccess(maintenance)"> - - <span class="readiness-check-icon icon-success-round"></span> - - <div class="readiness-check-content"> - <h3 class="readiness-check-title">Store in maintenance mode</h3> - <p> - Your store is in maintenance mode and will automatically - return online after the {{type}}. - </p> - </div> - - </div> - - <div class="readiness-check-item" ng-switch-default ng-init="updateOnError(maintenance)"> - - <span class="readiness-check-icon icon-failed-round"></span> - - <div class="readiness-check-content"> - <h3 class="readiness-check-title">Check store maintenance availability</h3> - <p> - Cannot put your store in maintenance mode. Please fix that, and try again. - </p> - <p> - Error received from server: - <br> {{maintenance.error}} - </p> - </div> - </div> - - </div> - -</div> - -<div id="backup-create" class="readiness-check-item" ng-show="create.visible"> - <div ng-hide="create.processed"> - <span class="spinner side"> - <span></span><span></span><span></span><span></span> - <span></span><span></span><span></span><span></span> - </span> - <h3 class="readiness-check-title">Creating Backup...</h3> - </div> - <div ng-show="create.processed" ng-switch="create.responseType"> - - <div ng-switch-when="success" ng-init="updateOnSuccess(create)"> - - <span class="readiness-check-icon icon-success-round"></span> - - <div class="readiness-check-content" ng-show="backupInfoPassed.options.code || backupInfoPassed.options.media || backupInfoPassed.options.db"> - <h3 class="readiness-check-title">Backup created</h3> - <p>The backup files can be found in Magento Admin's backup management.</p> - <p>The backup files are located in:</p> - <p> {{files}} </p> - </div> - </div> - <div class="readiness-check-item" ng-switch-default ng-init="updateOnError(create)"> - - <span class="readiness-check-icon icon-failed-round"></span> - - <div class="readiness-check-content"> - <h3 class="readiness-check-title">Backup failed</h3> - <p> - Error received from server: - <br> {{create.error}} - </p> - </div> - </div> - </div> -</div> diff --git a/setup/view/magento/setup/configure-catalog-search.phtml b/setup/view/magento/setup/configure-catalog-search.phtml deleted file mode 100644 index 598470210821d..0000000000000 --- a/setup/view/magento/setup/configure-catalog-search.phtml +++ /dev/null @@ -1,242 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// @codingStandardsIgnoreFile - -?> -<div class="nav-bar-outer-actions"> - <div class="outer-actions-inner-wrap"> - <div class="btn-wrap btn-wrap-triangle-right btn-wrap-next"> - <button - type="button" - class="btn btn-prime" - ng-click="testConnection(true)" - >Next</button> - </div> - <div class="btn-wrap btn-wrap-triangle-left btn-wrap-prev"> - <button - type="button" - class="btn" - ng-click="previousState()" - >Back</button> - </div> - </div> -</div> - -<h2 class="page-sub-title">{{$state.current.header}}</h2> - -<div - class="message message-success" - ng-show="search.testConnection.result.success && search.testConnection.result.message" -> - <span class="message-text">{{search.testConnection.result.message}}</span> -</div> -<div - class="message message-error" - ng-show="search.testConnection.result.success === false && search.testConnection.result.message" -> - <span class="message-text">{{search.testConnection.result.message}}</span> -</div> - -<form novalidate name="searchConfig" role="form"> - - <fieldset class="form-fieldset configure-catalog-search"> - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label required" for="searchEngine"> - Search Engine - </label> - </div> - <div class="col-m-4"> - <label class="form-select-label" for="searchEngine"> - <select - id="searchEngine" - class="form-el-select" - ng-model="search.config.engine" - tooltip-placement="right" - tooltip="Select your version of Elasticsearch." - tooltip-trigger="focus" - tooltip-append-to-body="true" - > - <?php foreach ( $this->availableSearchEngines as $value => $label ): ?> - <?= "<option value=\"" . $value . "\">" . $label . "</option>" ?> - <?php endforeach; ?> - </select> - </label> - </div> - </div> - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label required" for="elasticsearchHost"> - Elasticsearch Hostname - </label> - </div> - <div class="col-m-4"> - <input - id="elasticsearchHost" - class="form-el-input" - tooltip-placement="right" - tooltip="The host name or IP address of the Elasticsearch server." - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="text" - ng-class="{'invalid' : searchConfig.elasticsearchHost.$invalid && searchConfig.submitted}" - name="elasticsearchHost" - ng-model="search.config.elasticsearch.hostname" - required - > - <div class="error-container"> - <span ng-show="searchConfig.elasticsearchHost.$invalid"> - Hostname is required. - </span> - </div> - </div> - </div> - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label required" for="elasticsearchPort"> - Elasticsearch Port - </label> - </div> - <div class="col-m-4"> - <input - id="elasticsearchPort" - class="form-el-input" - tooltip-placement="right" - tooltip="The port for incoming HTTP requests. The default is 9200." - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="text" - ng-pattern="/^[0-9]+$/" - ng-class="{'invalid' : searchConfig.elasticsearchPort.$invalid && searchConfig.submitted}" - name="elasticsearchPort" - ng-model="search.config.elasticsearch.port" - required - > - <div class="error-container"> - <span ng-show="searchConfig.elasticsearchPort.$invalid"> - Port is required and must be a numeric value. - </span> - </div> - </div> - </div> - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label" for="elasticsearchEnableAuth"> - Elasticsearch HTTP Authentication - </label> - </div> - <div class="col-m-4"> - <input - id="elasticsearchEnableAuth" - class="form-el-checkbox" - type="checkbox" - name="elasticsearchEnableAuth" - ng-model="search.config.elasticsearch.enableAuth" - ng-checked="search.config.elasticsearch.enableAuth" - > - <label class="form-label" for="elasticsearchEnableAuth"> - Enable HTTP Authentication - </label> - </div> - </div> - <div class="row form-row" ng-show="search.config.elasticsearch.enableAuth"> - <div class="col-m-3"> - <label class="form-label" for="elasticsearchUsername"> - Elasticsearch Username - </label> - </div> - <div class="col-m-4"> - <input - id="elasticsearchUsername" - class="form-el-input" - tooltip-placement="right" - tooltip="Elasticsearch username. Only applicable if HTTP authentication is enabled." - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="text" - name="elasticsearchUsername" - ng-model="search.config.elasticsearch.username" - > - </div> - </div> - <div class="row form-row" ng-show="search.config.elasticsearch.enableAuth"> - <div class="col-m-3"> - <label class="form-label" for="elasticsearchPassword"> - Elasticsearch Password - </label> - </div> - <div class="col-m-4"> - <input - id="elasticsearchPassword" - class="form-el-input" - tooltip-placement="right" - tooltip="Elasticsearch password. Only applicable if HTTP authentication is enabled." - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="password" - name="elasticsearchPassword" - ng-model="search.config.elasticsearch.password" - > - </div> - </div> - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label" for="elasticsearchIndexPrefix"> - Elasticsearch Index Prefix - </label> - </div> - <div class="col-m-4"> - <input - id="elasticsearchIndexPrefix" - class="form-el-input" - tooltip-placement="right" - tooltip="A prefix that identifies the Elasticsearch index." - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="text" - name="elasticsearchIndexPrefix" - ng-model="search.config.elasticsearch.indexPrefix" - > - </div> - </div> - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label" for="elasticsearchTimeout"> - Elasticsearch Timeout (seconds) - </label> - </div> - <div class="col-m-4"> - <input - id="elasticsearchTimeout" - class="form-el-input" - tooltip-placement="right" - tooltip="The number of seconds to wait for an Elasticsearch request to complete before it times out." - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="text" - ng-pattern="/^[0-9]+$/" - ng-class="{'invalid' : searchConfig.elasticsearchTimeout.$invalid && searchConfig.submitted}" - name="elasticsearchTimeout" - ng-model="search.config.elasticsearch.timeout" - required - > - <div class="error-container"> - <span ng-show="searchConfig.elasticsearchTimeout.$invalid"> - Please enter a number greater than 0. - </span> - </div> - </div> - </div> - <div class="row form-row"> - <div class="col-m-3"> - </div> - <div class="col-m-4"> - <button name="testConnection" ng-click="testConnection()" ng-disabled="{{checking}}">Test Connection</button> - </div> - </div> - </fieldset> -</form> diff --git a/setup/view/magento/setup/create-admin-account.phtml b/setup/view/magento/setup/create-admin-account.phtml deleted file mode 100644 index 5c55bd729d770..0000000000000 --- a/setup/view/magento/setup/create-admin-account.phtml +++ /dev/null @@ -1,215 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// @codingStandardsIgnoreFile - -?> -<?php -$passwordWizard = sprintf( - '<p><b>%s</b> {{admin.passwordStatus.label}}</p> - <div class=\'password-strength password-strength-{{admin.passwordStatus.class}}\'> - <div class=\'password-strength-item\'></div> - <div class=\'password-strength-item\'></div> - <div class=\'password-strength-item\'></div> - <div class=\'password-strength-item\'></div> - <div class=\'password-strength-item\'></div> - </div> - <p>%s</p>', - 'Password Strength:', - 'Enter a mix of 7 or more numbers and letters. For a stronger password, include at least one small letter, big letter, and symbol.' -); -?> - -<div class="nav-bar-outer-actions"> - <div class="outer-actions-inner-wrap"> - <div class="btn-wrap btn-wrap-triangle-right btn-wrap-next"> - <button - type="button" - class="btn btn-prime" - ng-click="validateCredentials()" - ng-disabled="account.$invalid && account.submitted" - >Next</button> - </div> - <div class="btn-wrap btn-wrap-triangle-left btn-wrap-prev"> - <button type="button" class="btn" ng-click="previousState()">Back</button> - </div> - </div> -</div> - -<h2 class="page-sub-title">{{$state.current.header}}</h2> - -<div - class="message message-success" - ng-show="validateCredentials.result.success && validateCredentials.pressed" -> - <span class="message-text">Credentials validation successfully passed.</span> -</div> -<div - class="message message-error" - ng-show="validateCredentials.result.success === false && validateCredentials.result !== undefined" -> - <span class="message-text">{{validateCredentials.result.error}}</span> -</div> -<div - class="message message-error" - ng-show="validateCredentials.failed !== undefined" -> - <span class="message-text">{{validateCredentials.failed}}</span> -</div> - -<p> - Create a new Admin account to manage your store. -</p> - -<form - novalidate - name="account" - role="form" - autocomplete="off" - > - - <div - class="row form-row" - ng-class="{'has-error': account.adminUsername.$invalid && account.submitted}" - > - <div class="col-m-3"> - <label class="form-label required" for="adminUsername"> - New Username - </label> - </div> - <div class="col-m-4"> - <input - id="adminUsername" - class="form-el-input" - tooltip-placement="right" - tooltip="Must be 1 to 40 characters." - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="text" - name="adminUsername" - ng-model="admin.username" - ng-class="{'invalid': account.adminUsername.$invalid && account.submitted}" - ng-maxlength="40" - required - > - <div class="error-container"> - <span ng-show="account.adminUsername.$error.required"> - Please enter your new username. - </span> - <span ng-show="account.adminUsername.$error.maxlength"> - Please enter a username between 1 and 40 characters. - </span> - </div> - </div> - </div> - - <div - class="row form-row" - ng-class="{'has-error': account.adminEmail.$invalid && account.submitted}" - > - <div class="col-m-3"> - <label class="form-label required" for="adminEmail">New Email</label> - </div> - <div class="col-m-4"> - <input - id="adminEmail" - class="form-el-input" - tooltip-placement="right" - tooltip="Must be a correct email." - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="email" - name="adminEmail" - ng-model="admin.email" - ng-class="{'invalid': account.adminEmail.$invalid && account.submitted}" - required - > - <div class="error-container"> - <span ng-show="account.adminEmail.$error.required"> - Please enter your new email. - </span> - <span ng-show="account.adminEmail.$error.email"> - Please enter a correct email. - </span> - </div> - </div> - </div> - - <div - class="row form-row" - ng-class="{'has-error': account.adminPassword.$invalid && account.submitted}" - > - <div class="col-m-3"> - <label class="form-label required" for="adminPassword"> - New Password - </label> - </div> - <div class="col-m-4"> - <input - id="adminPassword" - class="form-el-input" - ng-change="passwordStatusChange()" - tooltip-placement="right" - tooltip-html-unsafe="<?= $passwordWizard ?>" - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="password" - name="adminPassword" - ng-model="admin.password" - ng-class="{'invalid': account.adminPassword.$invalid && account.submitted}" - required - check-Password - check-User-Name-Password - > - <div class="error-container"> - <span ng-show="account.adminPassword.$error.checkPassword"> - Please enter a mix of at least 7 alpha-numeric characters. - </span> - <span ng-show="account.adminPassword.$error.checkUserNamePasswordDifferent"> - Password cannot be the same as the user name. - </span> - <span ng-show="account.adminPassword.$error.required"> - Please enter your new password. - </span> - </div> - </div> - </div> - - <div - class="row form-row" - ng-class="{'has-error': account.adminConfirm.$invalid && account.submitted}" - > - <div class="col-m-3"> - <label class="form-label required" for="adminConfirm"> - Confirm Password - </label> - </div> - <div class="col-m-4"> - <input - id="adminConfirm" - class="form-el-input" - tooltip-placement="right" - tooltip="Please re-enter your password." - tooltip-trigger="focus" - tooltip-append-to-body="true" - type="password" - name="adminConfirm" - ng-model="admin.confirm" - ng-class="{'invalid': account.adminConfirm.$invalid && account.submitted}" - confirm-password="admin.password" - required/> - <div class="error-container"> - <span ng-show="account.adminConfirm.$error.required"> - Please re-enter your password. - </span> - <span ng-show="account.adminConfirm.$error.confirmPassword"> - Please make sure your passwords match. - </span> - </div> - </div> - </div> - -</form> diff --git a/setup/view/magento/setup/create-backup.phtml b/setup/view/magento/setup/create-backup.phtml deleted file mode 100644 index c0fed48973e4e..0000000000000 --- a/setup/view/magento/setup/create-backup.phtml +++ /dev/null @@ -1,113 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -?> -<div class="nav-bar-outer-actions"> - <div class="outer-actions-inner-wrap"> - <div class="btn-wrap btn-wrap-triangle-right btn-wrap-next"> - <button - type="button" - class="btn btn-prime" - ng-click="goToStartUpdater()" - ng-disabled="checkingInProgress() - || (hasErrors && ($state.is('root.create-backup-' + $state.current.type + '.progress'))) - || (!nextButtonStatus && ($state.is('root.create-backup-' + $state.current.type)))" - >Next</button> - </div> - <div class="btn-wrap btn-wrap-triangle-left btn-wrap-prev"> - <button - type="button" - class="btn" - ng-click="previousState()" - ng-disabled="checkingInProgress() && !hasErrors" - >Back</button> - </div> - <div class="btn-wrap btn-wrap-try-again" - ng-show="$state.is('root.create-backup-' + $state.current.type + '.progress')"> - <button - type="button" - class="btn btn-secondary" - ng-click="$state.forceReload()" - ng-disabled="checkingInProgress()" - >Try Again</button> - </div> - </div> -</div> - -<h2 class="page-title">{{$state.current.header}}</h2> - -<div ng-show="$state.is('root.create-backup-' + $state.current.type)"> - <form - novalidate - name="backup" - role="form" - > - <fieldset class="form-fieldset"> - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label"> - Backup Options - </label> - </div> - <div class="col-m-4"> - <div class="form-row"> - <input - id="optionsCode" - class="form-el-checkbox" - type="checkbox" - ng-model="backupInfo.options.code" - ng-checked="backupInfo.options.code" - > - <label class="form-label" for="optionsCode"> - Code - </label> - </div> - <div class="form-row"> - <input - id="optionsMedia" - class="form-el-checkbox" - type="checkbox" - ng-model="backupInfo.options.media" - ng-checked="backupInfo.options.media" - > - <label class="form-label" for="optionsMedia"> - Media - </label> - </div> - <div class="form-row"> - <input - id="optionsDb" - class="form-el-checkbox" - type="checkbox" - ng-model="backupInfo.options.db" - ng-checked="backupInfo.options.db" - > - <label class="form-label" for="optionsDb"> - Database - </label> - </div> - </div> - </div> - </fieldset> - </form> -</div> -<div ng-show="$state.is('root.create-backup-' + $state.current.type) && (backupInfo.options.code -|| backupInfo.options.media || backupInfo.options.db)" class="accent-box"> - <p>Let's check your disk space availability for taking selected backups, and then create the backups.</p> - <button - class="btn btn-large btn-prime" - ng-click="$state.go('.progress')" - type="button" - >Create Backup</button> -</div> -<div class="message message-warning" ng-show="optionsSelected()"> - <span class="message-text"> - <strong> - We noticed you didn’t select anything to back up. We strongly recommend you back up before continuing. - </strong> - </span> -</div> -<div ui-view></div> diff --git a/setup/view/magento/setup/customize-your-store.phtml b/setup/view/magento/setup/customize-your-store.phtml deleted file mode 100644 index 97ecf38d5f490..0000000000000 --- a/setup/view/magento/setup/customize-your-store.phtml +++ /dev/null @@ -1,217 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// @codingStandardsIgnoreFile - -?> -<div class="nav-bar-outer-actions"> - <div class="outer-actions-inner-wrap"> - <div class="btn-wrap btn-wrap-triangle-right btn-wrap-next"> - <button type="button" class="btn btn-prime" ng-click="checkModuleConstraints()">Next</button> - </div> - <div class="btn-wrap btn-wrap-triangle-left btn-wrap-prev"> - <button type="button" class="btn" ng-click="previousState()">Back</button> - </div> - </div> -</div> - -<h2 class="page-sub-title">{{$state.current.header}}</h2> - -<form class="customize-your-store" name="customizeStore" role="form"> - <fieldset class="form-fieldset customize-your-store-default"> - <legend class="legend"> - Customize Your Store - </legend> - <?php if ($this->isSampleDataInstalled || $this->isSampleDataErrorInstallation): ?> - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label">Sample Data</label> - </div> - <div class="col-m-6"> - <div class="customize-database-clean"> - <p> - <?php if ($this->isSampleDataInstalled): ?> - You have already installed sample data. If you want to re-install it, your database has to be cleaned up - <?php endif; ?> - <?php if ($this->isSampleDataErrorInstallation): ?> - Your sample data is broken. If you want to re-install it, your database has to be cleaned up - <?php endif; ?> - </p> - <input - type="checkbox" - ng-model="store.cleanUpDatabase" - class="form-el-checkbox" - id="cleanUpDatabase" - > - <label class="form-label" for="cleanUpDatabase"> - Clean up automatically - </label> - </div> - </div> - </div> - <?php endif; ?> - - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label required" for="storeTimezone">Store Default Time Zone</label> - </div> - <div class="col-m-4"> - <label class="form-select-label" for="storeTimezone"> - <select - id="storeTimezone" - class="form-el-select" - ng-model="store.timezone" - tooltip-placement="right" - tooltip-html-unsafe="The time zone in which your online store operates. You can change this later in Magento Admin." - tooltip-trigger="focus" - tooltip-append-to-body="true"> - <?php foreach ( $this->timezone as $value => $label ): ?> - <?= "<option value=\"" . $value . "\">" . $label . "</option>" ?> - <?php endforeach; ?> - </select> - </label> - </div> - </div> - - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label required" for="storeCurrency"> - Store Default Currency - </label> - </div> - <div class="col-m-4"> - <label class="form-select-label" for="storeCurrency"> - <select - id="storeCurrency" - class="form-el-select" - ng-model="store.currency" - tooltip-placement="right" - tooltip-html-unsafe="The currency your store uses for price labeling, checkout, returns, credit and gift cards. You can change this later in Magento Admin." - tooltip-trigger="focus" - tooltip-append-to-body="true"> - <?php foreach ( $this->currency as $value => $label ): ?> - <?= "<option value=\"" . $value . "\">" . $label . "</option>" ?> - <?php endforeach; ?> - </select> - </label> - </div> - </div> - - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label required" for="storeLanguage"> - Store Default Language - </label> - </div> - <div class="col-m-4"> - <label class="form-select-label" for="storeLanguage"> - <select - id="storeLanguage" - class="form-el-select" - ng-model="store.language" - tooltip-placement="right" - tooltip-html-unsafe="The language customers will see in your store. You can change this later in Magento Set Up Tool." - tooltip-trigger="focus" - tooltip-append-to-body="true"> - <?php foreach ( $this->language as $value => $label ): ?> - <?= "<option value=\"" . $value . "\">" . $label . "</option>" ?> - <?php endforeach; ?> - </select> - </label> - </div> - </div> - </fieldset> - - <fieldset class="form-fieldset customize-your-store-advanced" ng-show="store.showModulesControl"> - <legend - class="form-legend-expand" - ng-click="updateOnExpand(store.advanced)" - ng-class="{'expanded' : store.advanced.expanded}" - > - Advanced Modules Configurations - </legend> - - <div ng-show="store.advanced.expanded"> - - <div - class="message message-error" - ng-show="store.errorMessage !== ''&& store.errorMessage !== false" - > - <div class="message-text"> - <p> - An error has occurred. - <a href="#" - ng-click="expandError()" - ng-class="{'expanded' : store.errorFlag}" - > - {{store.errorFlag ? 'Hide' : 'Show';}} details - </a> - </p> - <p ng-show="store.errorMessage !== '' && store.errorFlag === true" - ng-bind-html="store.errorMessage"> - </p> - <p class="advanced-modules-skip"> - <input id="skipDependency" - class="form-el-checkbox" - type="checkbox" - ng-model="store.force" - ng-click="toggleForce()" - > - <label class="form-label" for="skipDependency"> - Skip dependency check for individual modules - </label> - </p> - </div> - </div> - - <div class="message message-spinner" ng-show="loading"> - <span class="spinner"> - <span></span><span></span><span></span><span></span> - <span></span><span></span><span></span><span></span> - </span> - <span class="message-text">Validating Constraints for enabling/disabling modules...</span> - </div> - - <p class="advanced-modules-select"> - <input id="selectAll" type="checkbox" - class="form-el-checkbox" - ng-checked="store.selectAll" - ng-click="toggleAllModules()"> - <label class="form-label" for="selectAll"> - Select All - </label> - </p> - - <div class="multiselect multiselect-custom"> - <ul> - <li ng-repeat="module in store.allModules" - class="item" - ng-class="store.selectedModules.indexOf(module) > -1 ? 'selected' : 'notSelected'; " - > - <input - class="form-el-checkbox" - type="checkbox" - ng-click="toggleModule(module)" - ng-disabled="store.disabledModules.indexOf(module) > -1" - ng-checked="store.selectedModules.indexOf(module) > -1" - id="{{module}}" - > - <label class="form-label" - for="{{module}}" - > - {{module}} - </label> - </li> - </ul> - </div> - - <p class="advanced-modules-count"> - {{store.selectedModules.length}} out of {{store.allModules.length}} selected - </p> - - </div> - </fieldset> -</form> diff --git a/setup/view/magento/setup/data-option.phtml b/setup/view/magento/setup/data-option.phtml deleted file mode 100644 index 656b04876c414..0000000000000 --- a/setup/view/magento/setup/data-option.phtml +++ /dev/null @@ -1,69 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -?> - -<div class="nav-bar-outer-actions"> - <div class="outer-actions-inner-wrap"> - <div class="btn-wrap btn-wrap-triangle-right btn-wrap-next"> - <button - type="button" - class="btn btn-prime" - ng-click="nextState()" - >Next</button> - </div> - <div class="btn-wrap btn-wrap-triangle-left btn-wrap-prev"> - <button - type="button" - class="btn" - ng-click="goToBackup()" - >Back</button> - </div> - </div> -</div> - -<h2 class="page-title">{{$state.current.header}}</h2> - -<div ng-controller="dataOptionController"> - <div class="message" ng-hide="component.hasUninstall"> - The selected component has no data to remove. - </div> - <div ng-show="component.hasUninstall"> - <div class="form-row"> - What do you want to do with {{moduleName}}'s data?<br/> - </div> - <div class="form-row"> - <input - id="keepData" - class="form-el-radio" - type="radio" - ng-model="component.dataOption" - value="false" - > - <label class="form-label" for="keepData"> - <strong>Keep data</strong> - <br/><br/> - Note: You can see the associated data in your database, - however your customer will not see this in your online store. - </label> - - </div> - <div class="form-row"> - <input - id="removeData" - class="form-el-radio" - type="radio" - ng-model="component.dataOption" - value="true" - > - <label class="form-label" for="removeData"> - <strong>Remove data</strong> - <br/><br/> - Did you back up first? Choosing to remove data means the data is unavailable unless you - recover it from a backup in the preceding step. - </label> - </div> - </div> -</div> diff --git a/setup/view/magento/setup/extension-grid.phtml b/setup/view/magento/setup/extension-grid.phtml deleted file mode 100644 index 4800d45e12d4f..0000000000000 --- a/setup/view/magento/setup/extension-grid.phtml +++ /dev/null @@ -1,180 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// @codingStandardsIgnoreFile - -?> -<h2 class="page-title">{{$state.current.header}}</h2> - -<div class="message message-error" ng-show="syncError"> - <span class="message-text"> - {{ErrorMessage}} - </span> -</div> -<div ng-show="$root.isMarketplaceAuthorized" class="extension-manager-wrap"> - <div class="extension-manager-title"> - Magento Marketplace Account - <div class="extension-manager-account"> - <a ng-click="reset()" href="#" class="sign-in-out">Disconnect</a> - </div> - </div> - <div class="extension-manager-content"> - <ul class="extension-manager-items row"> - <li class="item col-m-4"> - <div class="item-number">{{countOfUpdate}}</div> - <div class="item-title">Updates<br />Available</div> - <button ui-sref="root.update" href="#update-extension-grid" - ng-class="{'disabled' : !countOfUpdate, 'goUpdate' : countOfUpdate}" - type="button" class="btn"> - Review Updates - </button> - </li> - <li class="item col-m-4"> - <div class="item-number">{{countOfInstall}}</div> - <div class="item-title">Extensions<br />Ready to Install</div> - <div class="item-install"> - <button ui-sref="root.install" href="#install-extension-grid" - ng-class="{'disabled' : !enabledInstall, 'goInstall' : enabledInstall}" - type="button" class="btn"> - Review and Install - </button> - </div> - </li> - <li class="item col-m-4"> - <div ng-hide="isOutOfSync" - class="item-title item-date-title" - >Last Refresh at {{lastSyncTime}} on </div> - <div ng-hide="isOutOfSync" class="item-date"> - {{lastSyncDate}} - </div> - <span ng-show="isOutOfSync">No sync history</span> - <button type="button" ng-click="sync()" class="btn">Refresh</button> - </li> - </ul> - </div> -</div> - -<div ng-show="logout===true" id="messages"> - <div class="messages"> - <div class="message message-success success"> - <div data-ui-id="messages-message-success"> - You have logged out - </div> - </div> - </div> -</div> - -<div class="row" ng-show="$root.isMarketplaceAuthorized && extensionsProcessed && total == 0"> - <label class="form-label not-found"> - <strong>You haven't purchased any extensions yet. Visit <a href="https://marketplace.magento.com">Marketplace</a> - for purchasing extensions.</strong><br/> - </label> -</div> -<div class="admin__data-grid-outer-wrap" - ng-show="$root.isMarketplaceAuthorized && extensionsProcessed && total > 0" - id="extensionGrid" -> - <div class="admin__data-grid-header"> - <div class="admin__data-grid-header-row row row-gutter"> - <div class="col-xs-3 module-summary"> - <span class="module-summary-title">Installed Extensions</span> - <span class="module-summary-count">{{total}} extensions</span> - </div> - <div class="col-xs-9 admin__data-grid-pager-wrap" - ng-include="'<?= $this->basePath() ?>/pub/magento/setup/view/pagination.html'"> - </div> - </div> - </div> - <div class="admin__data-grid-wrap" ng-show="$state.is('root.extension')"> - <table class="data-grid extension-manager-grid"> - <thead data-part="head"> - <tr> - <th ng-click="order('name')" - ng-class="{'_ascend' : predicate === 'name' && !reverse, - '_descend' : predicate === 'name' && reverse}" - class="data-grid-th _sortable"> - <span>Extension Name</span> - </th> - <th ng-click="order('type')" - ng-class="{'_ascend' : predicate === 'type' && !reverse, - '_descend' : predicate === 'type' && reverse}" - class="data-grid-th _sortable"> - <span>Type</span> - </th> - <th ng-click="order('version')" - ng-class="{'_ascend' : predicate === 'version' && !reverse, - '_descend' : predicate === 'version' && reverse}" - class="data-grid-th _sortable"> - <span>Version</span> - </th> - <th ng-click="order('vendor')" - ng-class="{'_ascend' : predicate === 'vendor' && !reverse, - '_descend' : predicate === 'vendor' && reverse}" - class="data-grid-th _sortable"> - <span>Vendor</span> - </th> - <th class="data-grid-actions-cell data-grid-th"> - <span>Actions</span> - </th> - </tr> - </thead> - <tbody> - <tr ng-repeat="extension in extensions | orderBy:predicate:reverse - | startFrom:(currentPage - 1) * rowLimit | limitTo:rowLimit" - ng-class="{'_odd-row' : $index % 2}" - > - <td class="col-manager-item-name"> - <span class="component-indicator" - ng-show="isAvailableUpdatePackage(extension.name)" - ng-class="getIndicatorInfo(extension, 'icon')" - data-label="{{getIndicatorInfo(extension, 'label')}}" - ><span>{{getIndicatorInfo(extension, 'label')}}</span> - </span> - <span class="data-grid-data">{{extension.package_title}}</span> - </td> - <td> - <span class="data-grid-data">{{extension.package_type}}</span> - </td> - <td> - <span class="data-grid-data" data-type="version">{{extension.version}}</span> - </td> - <td> - <span class="data-grid-data">{{extension.vendor}}</span> - </td> - <td class="data-grid-actions-cell"> - <div class="action-select-wrap" ng-class="{'_active' : isActiveActionsCell(extension)}"> - <button class="action-select" - ng-click="toggleActiveActionsCell(extension)" - ng-blur="closeActiveActionsCell(extension)"> - <span>Select</span> - </button> - <ul class="action-menu" ng-class="{'_active' : isActiveActionsCell(extension)}"> - <li ng-class="{'_disabled': !isAvailableUpdatePackage(extension.name)}" - ng-mousedown="isAvailableUpdatePackage(extension.name) && update(extension)"> - <a class="action-menu-item">Update</a> - </li> - <li ng-class="{'hide': !extension.uninstall}" - ng-mousedown="uninstall(extension)"> - <a class="action-menu-item">Uninstall</a> - </li> - </ul> - </div> - </td> - </tr> - </tbody> - </table> - </div> -</div> - -<div ng-show="!isHiddenSpinner || $root.saveAuthProccessed || -(!$root.extensionsProcessed)" class="loading-mask ng-scope" data-role="loader"> - <div class="popup popup-loading"> - <div class="popup-inner"> - <img alt="Loading..." src="<?= $this->basePath() ?>/pub/images/loader-1.gif"> - Please wait... - </div> - </div> -</div> diff --git a/setup/view/magento/setup/home.phtml b/setup/view/magento/setup/home.phtml deleted file mode 100644 index e446964605273..0000000000000 --- a/setup/view/magento/setup/home.phtml +++ /dev/null @@ -1,39 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -?> - -<section class="home-page-inner-wrap ng-scope"> - <p class="setup-home-title"> - Welcome to the Magento Setup Tool. Please choose a task below. - </p> - - <div class="row"> - <div class="col-m-3"> - <a href="" class="setup-home-item setup-home-item-extension" ui-sref="root.extension-auth"> - <span class="setup-home-item-title">Extension Manager</span> - <span class="setup-home-item-description">I want to manage my extensions and themes</span> - </a> - </div> - <div class="col-m-3"> - <a href="" class="setup-home-item setup-home-item-module" ui-sref="root.module"> - <span class="setup-home-item-title">Module Manager </span> - <span class="setup-home-item-description">I want to manage my modules</span> - </a> - </div> - <div class="col-m-3"> - <a href="" class="setup-home-item setup-home-item-upgrade" ui-sref="root.upgrade"> - <span class="setup-home-item-title">System Upgrade</span> - <span class="setup-home-item-description">I want to upgrade my Magento Admin version</span> - </a> - </div> - <div class="col-m-3"> - <a href="" class="setup-home-item setup-home-item-configuration" ui-sref="root.system-config"> - <span class="setup-home-item-title">System Configuration</span> - <span class="setup-home-item-description">I want to change my Magento system configurations</span> - </a> - </div> - </div> -</section> diff --git a/setup/view/magento/setup/index.phtml b/setup/view/magento/setup/index.phtml index 648345beec7f7..5436f59546454 100644 --- a/setup/view/magento/setup/index.phtml +++ b/setup/view/magento/setup/index.phtml @@ -3,15 +3,14 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ + +// phpcs:disable Magento2.Templates.ThisInTemplate ?> -<div ng-include="'index.php/navigation/side-menu'" style="display: inline-block"></div> -<div class="{{$state.current.type == 'install' && !$state.current.wrapper ? 'container' : 'page-wrapper'}}"> - <div ng-include="'index.php/navigation/header-bar'"></div> +<div class="container"> <main id="anchor-content" class="page-content"> - <?= $this->render('navigation/menu.phtml') ?> + <?= /* @noEscape */ $this->render('navigation/menu.phtml') ?> <div id="main" - class="{{class}}" ng-controller="mainController" > <div ui-view="root"> diff --git a/setup/view/magento/setup/install-extension-grid.phtml b/setup/view/magento/setup/install-extension-grid.phtml deleted file mode 100644 index 8e2ecd8ec2558..0000000000000 --- a/setup/view/magento/setup/install-extension-grid.phtml +++ /dev/null @@ -1,145 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -?> -<a href="" ui-sref="root.extension">< Back</a> -<h2 class="page-title">{{$state.current.header}}</h2> -<div class="messages"> - <div ng-show="error === true" class="message message-error error"> - <span class="message-text"> - {{errorMessage}} - </span> - </div> -</div> -<div class="admin__data-grid-outer-wrap" id="installExtensionGrid"> - <div class="admin__data-grid-header"> - <div class="admin__data-grid-header-row row row-gutter"> - <div class="col-xs-3"> - <button type="button" class="btn" ng-click="installAll()">Install</button> - <div class="admin__control-support-text"> - <span>{{total}}</span> extensions - </div> - </div> - <div class="col-xs-9 admin__data-grid-pager-wrap" - ng-include="'<?= $this->basePath() ?>/pub/magento/setup/view/pagination.html'"> - </div> - </div> - </div> - <div class="admin__data-grid-wrap" ng-show="$state.is('root.install')"> - <table class="data-grid"> - <thead data-part="head"> - <tr> - <th class="data-grid-multicheck-cell"> - <div class="action-multicheck-wrap" - ng-class="{'_active':multipleChoiceService.isNewExtensionsMenuVisible}" - click-out="multipleChoiceService.hideNewExtensionsMenu()" - > - <input type="checkbox" - style="visibility: hidden;" - class="admin__control-checkbox" - ng-class="{'_indeterminate':multipleChoiceService.someExtensionsSelected}" - ng-checked="multipleChoiceService.allExtensionsSelected" - > - <label></label> - <button class="action-multicheck-toggle" - ng-class="{'_active':multipleChoiceService.isNewExtensionsMenuVisible}" - ng-click="multipleChoiceService.toggleNewExtensionsMenu()" - > - <span>Options</span> - </button> - <ul class="action-menu"> - <li ng-show="!multipleChoiceService.allExtensionsSelected" - ng-click="multipleChoiceService.selectAllExtensions()" - > - <span class="action-menu-item">Select all</span> - </li> - <li ng-show="multipleChoiceService.allExtensionsSelected - || multipleChoiceService.someExtensionsSelected" - ng-click="multipleChoiceService.deselectAllExtensions()"> - <span class="action-menu-item">Deselect all</span> - </li> - </ul> - </div> - </th> - <th ng-click="order('name')" ng-class="{'_ascend' : predicate === 'name' - && !reverse,'_descend' : predicate === 'name' && reverse}" class="data-grid-th _sortable"> - <span>Extension Name</span> - </th> - <th ng-click="order('type')" ng-class="{'_ascend' : predicate === 'type' && - !reverse,'_descend' : predicate === 'type' && reverse}" class="data-grid-th _sortable"> - <span>Type</span> - </th> - <th ng-click="order('vendor')" ng-class="{'_ascend' : predicate === 'vendor' && - !reverse,'_descend' : predicate === 'vendor' && reverse}" class="data-grid-th _sortable _ascend"> - <span>Vendor</span> - </th> - <th ng-click="order('version')" ng-class="{'_ascend' : predicate === 'version' - && !reverse,'_descend' : predicate === 'version' && reverse}" class="data-grid-th _sortable"> - <span>Latest version</span> - </th> - <th class="data-grid-actions-cell data-grid-th"> - <span>Action</span> - </th> - </tr> - </thead> - <tbody> - <tr ng-repeat="extension in extensions | orderBy:predicate:reverse - | startFrom:(currentPage - 1) * rowLimit | limitTo:rowLimit" - > - <td class="data-grid-checkbox-cell"> - <label class="data-grid-checkbox-cell-inner"> - <input type="checkbox" - class="admin__control-checkbox" - ng-checked="multipleChoiceService.selectedExtensions.hasOwnProperty(extension.name)" - ng-click="multipleChoiceService.updateSelectedExtensions($event, extension.name, - extension.version)" - > - <label></label> - </label> - </td> - <td> - <span class="data-grid-data">{{extension.package_title}}</span> - </td> - <td> - <span class="data-grid-data">{{extension.package_type}}</span> - </td> - <td> - <span class="data-grid-data">{{extension.vendor}}</span> - </td> - <td> - <span class="data-grid-data"> - <select id="selectedVersion" ng-model="extension.version"> - <option ng-repeat="version in extension.versions" - value="{{version}}">Version {{version}}</option> - </select> - </span> - <span class="component-indicator _tooltip" - ng-show="extension.package_link" - data-label="View info on Marketplace" - ><a href="{{extension.package_link}}" target="_blank"></a> - </span> - </td> - <td class="data-grid-data"> - <div class="action-wrap" ng-class="_active"> - <button class="action-select" - ng-click="install(extension)"> - <span>Install</span> - </button> - </div> - </td> - </tr> - </tbody> - </table> - </div> -</div> -<!-- loading indicator overlay and loader --> -<div ng-show="!isHiddenSpinner" class="loading-mask ng-scope" data-role="loader"> - <div class="popup popup-loading"> - <div class="popup-inner"> - <img alt="Loading..." src="<?= $this->basePath() ?>/pub/images/loader-1.gif"> - Please wait... - </div> - </div> -</div> diff --git a/setup/view/magento/setup/install.phtml b/setup/view/magento/setup/install.phtml deleted file mode 100644 index 8ddf98013668c..0000000000000 --- a/setup/view/magento/setup/install.phtml +++ /dev/null @@ -1,101 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// @codingStandardsIgnoreFile - -?> -<div class="nav-bar-outer-actions"> - <div class="outer-actions-inner-wrap"> - <div class="btn-wrap btn-wrap-triangle-right btn-wrap-next"> - <button - type="button" - class="btn btn-prime" - disabled - >Next</button> - </div> - <div class="btn-wrap btn-wrap-triangle-left btn-wrap-prev"> - <button - type="button" - class="btn" - ng-disabled="isDisabled" - ng-click="previousState()" - >Back</button> - </div> - <div class="btn-wrap btn-wrap-try-again" ng-show="isStarted"> - <button - type="button" - class="btn btn-secondary" - ng-disabled="isDisabled" - ng-click="start()" - >Try Again</button> - </div> - </div> -</div> - -<h2 class="page-sub-title">{{$state.current.header}}</h2> - -<div ng-show="!isStarted" class="accent-box"> - <p>You're ready!</p> - <button ng-click="start()" class="btn btn-large btn-prime">Install Now</button> -</div> - -<div ng-show="isStarted" class="content-install"> - <p class="text-right">Installing... {{progressText}}</p> - <div class="progress"> - <div - class="progress-bar" - role="progressbar" - aria-valuenow="{{progress}}" - aria-valuemin="0" - aria-valuemax="100" - ng-style="barStyle(progress)" - > - </div> - </div> - <div ng-show="isFailed" class="message message-error"> - <span class="message-text"> - <strong>Installation is incomplete.</strong> - <br> - Check the console log for errors before trying again. - </span> - </div> - <button - type="button" - class="btn btn-expand" - ng-click="toggleConsole()" - ng-class="{'expanded': isConsole}" - > - Console Log - </button> - <div ng-show="isConsole" id="console"> - <div class="console" ng-bind-html="log"></div> - </div> -</div> - -<div class="install-database-clean" ng-show="isShowCleanUpBox"> - <p>To install sample data you should clean up you database</p> - <button - type="button" - class="btn btn-secondary" - ng-disabled="isDisabled" - ng-click="startCleanup(true)"> - Clean up automatically - </button> - <button - type="button" - class="btn btn-secondary" - ng-disabled="isDisabled" - ng-click="startCleanup(false)"> - Proceed without clean up - </button> - <button - type="button" - class="btn" - ng-disabled="isDisabled" - ng-click="hideCleanUpBox()"> - Cancel - </button> -</div> diff --git a/setup/view/magento/setup/landing.phtml b/setup/view/magento/setup/landing.phtml index a470456e377b1..508fd86de46fd 100644 --- a/setup/view/magento/setup/landing.phtml +++ b/setup/view/magento/setup/landing.phtml @@ -15,14 +15,6 @@ <p class="text-welcome"> Welcome to Magento Admin, your online store headquarters. <br> - Click 'Agree and Set Up Magento' or read <a href="https://devdocs.magento.com/guides/v2.3/install-gde/install/web/install-web.html" target="_blank">Getting Started</a> to learn more. + Please review <a href="" ng-click="previousState()">Terms & Agreement</a> and read <a href="https://devdocs.magento.com/guides/v2.4/install-gde/install/cli/install-cli.html" target="_blank">Getting Started</a> to learn how to install Magento using the command line. </p> - <p class="text-terms"> - <a href="" ng-click="previousState()">Terms & Agreement</a> - </p> - <button - type="button" - class="btn btn-large btn-prime btn-submit" - ng-click="nextState()" - >Agree and Setup Magento</button> </section> diff --git a/setup/view/magento/setup/marketplace-credentials.phtml b/setup/view/magento/setup/marketplace-credentials.phtml deleted file mode 100644 index 8bd0bb0438d61..0000000000000 --- a/setup/view/magento/setup/marketplace-credentials.phtml +++ /dev/null @@ -1,113 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -?> - <div class="sync-login-wrap"> - <div class="login-header" ng-show="showCredsForm || upgradeProcessError"> - <img class="logo-img" - src="<?= $this->basePath() ?>/pub/images//magento-logo.svg" alt="Magento" width="214"/> - <span>Marketplace</span> - </div> - <div class="messages"> - <div ng-show="saveAuthJson.result.success === false && saveAuthJson.result !== undefined" - class="message message-error error"> - <span class="message-text"> - {{saveAuthJson.result.message}} - </span> - </div> - </div> - <div class="message message-error" ng-show="upgradeProcessError"> - <span class="message-text" ng-bind-html="upgradeProcessErrorMessage"></span> - </div> - <form name="auth" - role="form" - autocomplete="off" - ng-show="showCredsForm" - > - <fieldset class="fieldset"> - <legend ng-show="errors==false" class="legend"> - <span>To {{actionMessage}} purchases, enter your access keys</span> - </legend> - <br/> - <table> - <tr> - <th>Need to find your keys?</th> - </tr> - <tr> - <td>1. Go to your - <a href="https://marketplace.magento.com" - target="_blank">Magento Marketplace account page</a>. - </td> - </tr> - <tr> - <td>2. On the "Access keys" page, copy your public and private keys.</td> - </tr> - <tr> - <td>3. Enter keys below:</td> - </tr> - </table> - <div class="row form-row"> - <div class="col-m-12"> - <label for="username" class="form-label required">Public Key</label> - </div> - <div class="col-m-12"> - <input id="username" - class="form-el-input" - type="text" - name="username" - ng-model="user.username" - ng-maxlength="40" - ng-class="{ 'invalid' : (auth.username.$error.required - && !auth.username.$pristine) - || (auth.username.$error.required && user.submitted) }" - autofocus - required - autocomplete="off" - > - <div class="error-container"> - This is a required field. - </div> - </div> - </div> - <div class="row form-row"> - <div class="col-m-12"> - <label for="token" class="form-label required">Private Key</label> - </div> - <div class="col-m-12"> - <input id="password" - class="form-el-input" - type="password" - name="password" - ng-model="user.password" - ng-maxlength="40" - ng-class="{ 'invalid' : (auth.password.$error.required - && !auth.password.$pristine) - || (auth.password.$error.required && user.submitted) }" - required - autocomplete="new-password" - > - <div class="error-container"> - This is a required field. - </div> - </div> - </div> - <div class="form-actions"> - <div class="actions"> - <button ng-click="saveAuthJson()" class="btn btn-large btn-prime"> - <span>Submit</span> - </button> - </div> - </div> - </fieldset> - </form> - </div> -<div ng-show="!isHiddenSpinner" class="loading-mask ng-scope" data-role="loader"> - <div class="popup popup-loading"> - <div class="popup-inner"> - <img alt="Loading..." src="<?= $this->basePath() ?>/pub/images/loader-1.gif"> - Please wait... - </div> - </div> -</div> diff --git a/setup/view/magento/setup/module-grid.phtml b/setup/view/magento/setup/module-grid.phtml deleted file mode 100644 index 3bf9377104df1..0000000000000 --- a/setup/view/magento/setup/module-grid.phtml +++ /dev/null @@ -1,160 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -?> -<h2 class="page-title">{{$state.current.header}}</h2> - -<div class="row" ng-show="modulesProcessed && total == 0"> - <label class="form-label"> - <strong>We didn't find any modules at this time. Please try later.</strong><br/> - </label> -</div> -<div class="admin__data-grid-outer-wrap" ng-show="modulesProcessed && total > 0"> - <div class="admin__data-grid-header"> - <div class="admin__data-grid-header-row row row-gutter"> - <div class="col-xs-3"> - <div class="admin__control-support-text module-summary"> - <span class="module-summary-title">Available modules</span> - <span class="module-summary-count">{{total}} modules</span> - </div> - </div> - <div class="col-xs-9 admin__data-grid-pager-wrap" - ng-include="'<?= $this->basePath() ?>/pub/magento/setup/view/pagination.html'"> - </div> - </div> - </div> - <div class="admin__data-grid-wrap" ng-show="$state.is('root.module')"> - <table class="data-grid"> - <thead data-part="head"> - <tr> - <th class="data-grid-th _col-xs"> - <span></span> - </th> - <th ng-click="order('name')" - ng-class="{'_ascend' : predicate === 'name' && !reverse, - '_descend' : predicate === 'name' && reverse}" - class="data-grid-th _sortable"> - <span>Component Name</span> - </th> - <th ng-click="order('moduleName')" - ng-class="{'_ascend' : predicate === 'moduleName' && !reverse, - '_descend' : predicate === 'moduleName' && reverse}" - class="data-grid-th _sortable"> - <span>Module Name</span> - </th> - <th ng-click="order('version')" - ng-class="{'_ascend' : predicate === 'version' && !reverse, - '_descend' : predicate === 'version' && reverse}" - class="data-grid-th _sortable"> - <span>Version</span> - </th> - <th ng-click="order('vendor')" - ng-class="{'_ascend' : predicate === 'vendor' && !reverse, - '_descend' : predicate === 'vendor' && reverse}" - class="data-grid-th _sortable"> - <span>Vendor</span> - </th> - <th class="data-grid-actions-cell data-grid-th"> - <span>Action</span> - </th> - </tr> - </thead> - <tbody> - <tr ng-repeat="item in modules | orderBy:predicate:reverse - | startFrom:(currentPage - 1) * rowLimit | limitTo:rowLimit" - ng-class="{'_odd-row' : $index % 2}"> - <td class="data-grid-indicator-cell"> - <span class="component-indicator" - ng-class="getIndicatorInfo(item, 'icon')" - data-label="{{getIndicatorInfo(item, 'label')}}" - ><span>{{getIndicatorInfo(item, 'label')}}</span> - </span> - </td> - <td class="col-manager-item-name"> - <div class="data-grid-data" - ng-click="showDependencies = !showDependencies" - ng-class="{'_show-dependencies': item.requiredBy.length > 0 && showDependencies, - '_hide-dependencies': item.requiredBy.length > 0 && !showDependencies, - '_no-dependencies': item.requiredBy.length == 0}"> - {{item.package_title}} - </div> - <div class="product-modules-block" ng-show="item.requiredBy.length > 0 && showDependencies"> - <div class="product-modules-title"> - Packages currently using module - </div> - <div class="product-modules-descriprion"> - Module Name - </div> - <ul class="product-modules-list"> - <li ng-repeat="product in item.requiredBy"> - <span class="component-indicator" - ng-class="getIndicatorInfo(product, 'icon')" - data-label="{{getIndicatorInfo(product, 'label')}}"> - <span>{{getIndicatorInfo(product, 'label')}}</span> - </span> - {{product.package_title}} - </li> - </ul> - </div> - </td> - <td> - <div class="data-grid-data">{{item.moduleName}}</div> - <div class="product-modules-block" ng-show="item.requiredBy.length > 0 && showDependencies"> - <div class="product-modules-title"> -   - </div> - <div class="product-modules-descriprion"> - Package Type - </div> - <ul class="product-modules-list"> - <li ng-repeat="product in item.requiredBy"> - {{product.package_type}} - </li> - </ul> - </div> - </td> - <td> - <div class="data-grid-data">{{item.version}}</div> - <div class="product-modules-block" ng-show="item.requiredBy.length > 0 && showDependencies"> - <div class="product-modules-title"> -   - </div> - <div class="product-modules-descriprion"> - Version - </div> - <ul class="product-modules-list"> - <li ng-repeat="product in item.requiredBy"> - {{product.version}} - </li> - </ul> - </div> - </td> - <td> - <span class="data-grid-data">{{item.vendor}}</span> - </td> - <td class="data-grid-actions-cell"> - <div class="action-select-wrap" ng-class="{'_active' : isActiveActionsCell(item)}"> - <button class="action-select" - ng-click="toggleActiveActionsCell(item)" - ng-blur="closeActiveActionsCell(item)"> - <span>Select</span> - </button> - <ul class="action-menu" ng-class="{'_active' : isActiveActionsCell(item)}"> - <li ng-class="{'hide': item.enable}" - ng-mousedown="enableDisable('enable', item)"> - <a class="action-menu-item item-enable">Enable</a> - </li> - <li ng-class="{'hide': !item.enable}" - ng-mousedown="enableDisable('disable', item)"> - <a class="action-menu-item item-disable">Disable</a> - </li> - </ul> - </div> - </td> - </tr> - </tbody> - </table> - </div> -</div> diff --git a/setup/view/magento/setup/navigation/header-bar.phtml b/setup/view/magento/setup/navigation/header-bar.phtml deleted file mode 100644 index 03fb55d46cc4e..0000000000000 --- a/setup/view/magento/setup/navigation/header-bar.phtml +++ /dev/null @@ -1,87 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// @codingStandardsIgnoreFile - -?> -<header ng-controller="headerController" class="page-header row" - data-ng-init="redirectTo('<?= $this->redirect ?>')" - ng-hide="$state.current.main"> - <div class="page-header-hgroup col-l-8 col-m-6"> - <div class="page-title-wrapper"> - <h1 class="page-title"> - {{$state.current.noMenu ? $state.current.title : $root.titles[$state.current.type]}}</h1> - </div> - </div> - <div class="page-header-actions col-l-4 col-m-6" style="display: none"> - <div class="admin-user admin__action-dropdown-wrap"> - <a - href="#index" - class="admin__action-dropdown" - title="My Account"> - <span class="admin__action-dropdown-text"> - <span class="admin-user-account-text">username</span> - </span> - </a> - <ul class="admin__action-dropdown-menu"> - <li> - <a - href="#settings" - title="Account Setting"> - Account Setting (<span class="admin-user-name">admin</span>) - </a> - </li> - <li> - <a - href="#customerView" - title="Customer View" - target="_blank" - class="store-front"> - Customer View - </a> - </li> - <li> - <a - href="#signout" - class="account-signout" - title="Sign Out"> - Sign Out - </a> - </li> - </ul> - </div> - <div class="notifications-wrapper admin__action-dropdown-wrap"> - <a - class="notifications-action admin__action-dropdown" - href="#notification" - title="Notifications"></a> - </div> - <div class="search-global"> - <form - action="#" - id="form-search"> - <div class="search-global-field"> - <label class="search-global-label" for="search-global"></label> - <input type="hidden" name="query"> - <div class="mage-suggest"> - <div class="mage-suggest-inner"> - <input - type="text" - class="search-global-input" - id="search-global" - autocomplete="off"> - <div class="autocomplete-results"></div> - </div> - </div> - <button - type="submit" - class="search-global-action" - title="Search"><span>Search</span></button> - </div> - </form> - </div> - </div> -</header> diff --git a/setup/view/magento/setup/navigation/side-menu.phtml b/setup/view/magento/setup/navigation/side-menu.phtml deleted file mode 100644 index b731881e8bf4f..0000000000000 --- a/setup/view/magento/setup/navigation/side-menu.phtml +++ /dev/null @@ -1,57 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// @codingStandardsIgnoreFile - -?> -<?php $expressions = []; foreach ( $this->main as $item ): ?> - <?php $expressions[] = '!$state.is(\'' . $item['id'] . '\')'; - ?> -<?php endforeach; ?> -<?php - $expressions[] = '!$state.is(\'\')'; - $expressions[] = !$this->isInstaller ? 'true' : 'false'; -?> - -<div class="menu-wrapper" - ng-show="<?= implode( '&&', $expressions) ?>" - > -<nav class="admin__menu" ng-controller="mainController"> - <a href="<?= $this->backendUrl ?>" class="logo" data-edition="Community Edition"> - <span> - <img class="logo-img" src="<?= $this->basePath() ?>/pub/images/logo.svg" alt="Magento Admin Panel"> - </span> - </a> - <ul id="nav" role="menubar"> - <li class="item-home level-0" ng-class="{_active: $state.current.name === 'root.home'}"> - <a href="" ui-sref="root.home"> - <span>Home</span> - </a> - </li> - <li class="item-extension level-0" ng-class="{_active: $state.current.type === 'extension' - || ['install', 'uninstall', 'update'].indexOf($state.current.type) !== -1}"> - <a href="" ui-sref="root.extension-auth"> - <span>Extension Manager</span> - </a> - </li> - <li class="item-module level-0" ng-class="{_active: $state.current.type === 'module'}"> - <a href="" ui-sref="root.module"> - <span>Module Manager</span> - </a> - </li> - <li class="item-upgrade level-0" ng-class="{_active: $state.current.type === 'upgrade'}"> - <a href="" ui-sref="root.upgrade"> - <span>System Upgrade</span> - </a> - </li> - <li class="item-system-config level-0" ng-class="{_active: state.current.name === 'root.system-config'}"> - <a href="" ui-sref="root.system-config"> - <span>System Config</span> - </a> - </li> - </ul> -</nav> -</div> diff --git a/setup/view/magento/setup/popupauth.phtml b/setup/view/magento/setup/popupauth.phtml deleted file mode 100644 index 3ffca7ba49bab..0000000000000 --- a/setup/view/magento/setup/popupauth.phtml +++ /dev/null @@ -1,110 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -?> - -<div class="modals-wrapper"> - <aside class="modal-popup modal-connect-signin _show" data-role="modal"> - <div class="modal-inner-wrap"> - <header class="modal-header"> - <button ng-click="closeThisDialog()" class="action-close" data-role="closeBtn" type="button"> - <span>Close</span> - </button> - </header> - <div class="modal-content" data-role="content"> - <div class="sync-login-wrap"> - <div class="login-header"> - <img class="logo-img" - src="<?= $this->basePath() ?>/pub/images//magento-logo.svg" - alt="Magento" - width="214"/> - <span>Marketplace</span> - </div> - <div class="messages"> - <div ng-show="saveAuthJson.result.success === false && saveAuthJson.result !== undefined" - class="message message-error error"> - <span class="message-text"> - {{saveAuthJson.result.message}} - </span> - </div> - </div> - - <form - name="auth" - role="form" - autocomplete="off" - > - <fieldset class="fieldset"> - <legend ng-show="errors==false" class="legend"> - <span>To upgrade or install purchases, enter your access keys</span> - </legend> - <br/> - <h4>Need to find your keys?</h4> - <ol class="sync-login-steps"> - <li>Go to your - <a href="https://marketplace.magento.com" - target="_blank">Magento Marketplace account page</a>.</li> - <li>On the "Access keys" page, copy your public and private keys.</li> - <li>Enter keys below:</li> - </ol> - <div class="row form-row"> - <div class="col-m-12"> - <label for="username" class="form-label required">Public Access Key</label> - </div> - <div class="col-m-12"> - <input id="username" - class="form-el-input" - type="text" - name="username" - ng-model="user.username" - ng-maxlength="40" - ng-class="{ 'invalid' : (auth.username.$error.required - && !auth.username.$pristine) - || (auth.username.$error.required && user.submitted) }" - autofocus - required - autocomplete="off" - > - <div class="error-container"> - This is a required field. - </div> - </div> - </div> - <div class="row form-row"> - <div class="col-m-12"> - <label for="token" class="form-label required">Private Access Key</label> - </div> - <div class="col-m-12"> - <input id="password" - class="form-el-input" - type="password" - name="password" - ng-model="user.password" - ng-maxlength="40" - ng-class="{ 'invalid' : (auth.password.$error.required - && !auth.password.$pristine) - || (auth.password.$error.required && user.submitted) }" - required - autocomplete="new-password" - > - <div class="error-container"> - This is a required field. - </div> - </div> - </div> - <div class="form-actions"> - <div class="actions"> - <button ng-click="saveAuthJson()" class="btn btn-large btn-prime"> - <span>Sign in</span> - </button> - </div> - </div> - </fieldset> - </form> - </div> - </div> - </div> - </aside> -</div> diff --git a/setup/view/magento/setup/readiness-check.phtml b/setup/view/magento/setup/readiness-check.phtml deleted file mode 100644 index 71044ab371888..0000000000000 --- a/setup/view/magento/setup/readiness-check.phtml +++ /dev/null @@ -1,47 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -?> -<div class="nav-bar-outer-actions"> - <div class="outer-actions-inner-wrap"> - <div class="btn-wrap btn-wrap-triangle-right btn-wrap-next"> - <button - type="button" - class="btn btn-prime" - ng-click="nextState()" - ng-disabled="needReCheck || checkingInProgress() || hasErrors" - >Next</button> - </div> - <div class="btn-wrap btn-wrap-triangle-left btn-wrap-prev"> - <button - type="button" - class="btn" - disabled="disabled" - >Back</button> - </div> - <div class="btn-wrap btn-wrap-try-again" - ng-show="$state.is('root.readiness-check-' + $state.current.type + '.progress')"> - <button - type="button" - class="btn btn-secondary" - ng-click="$state.forceReload()" - ng-disabled="checkingInProgress()" - >Try Again</button> - </div> - </div> -</div> - -<h2 class="page-sub-title">{{$state.current.header}}</h2> -<div ng-show="$state.is('root.readiness-check-' + $state.current.type)" - ng-init="actionFrom='<?= $this->actionFrom ?>'" class="accent-box"> - <p>Let's check your environment for the correct PHP version, PHP extensions, file permissions and compatibility.</p> - <button - class="btn btn-large btn-prime" - ng-click="$state.go('.progress')" - type="button" - >Start Readiness Check</button> -</div> - -<div ui-view></div> diff --git a/setup/view/magento/setup/readiness-check/progress.phtml b/setup/view/magento/setup/readiness-check/progress.phtml deleted file mode 100644 index 1a443ee2b23ee..0000000000000 --- a/setup/view/magento/setup/readiness-check/progress.phtml +++ /dev/null @@ -1,582 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// @codingStandardsIgnoreFile - -?> -<div ng-switch="isCompleted()"> - - <div ng-switch-when="true" ng-switch="hasErrors"> - - <div class="message message-error" ng-switch-when="true"> - <span class="message-text"> - <strong>Error!</strong> You need to resolve these issues to continue. - </span> - </div> - - <div class="message message-success" ng-switch-default> - <span class="message-text"> - <strong>Completed!</strong> You can now move on to the next step. - </span> - </div> - - </div> - - <div class="message message-spinner" ng-switch-default> - <span class="spinner"> - <span></span><span></span><span></span><span></span> - <span></span><span></span><span></span><span></span> - </span> - <span class="message-text" ng-bind-html="wordingOfReadinessCheckAction()"></span> - </div> - -</div> - -<div class="extensions-information" ng-if="$state.current.type == 'update' && getObjectSize(getExtensionsList()) > 0"> - <div class="message message-warning" - ng-show="componentDependency.processed && componentDependency.responseType != 'success'" - > - We found some extensions with available version updates. We recommend that you update to the recommended - versions or remove these extensions from the installation process. We found some extensions with available - version updates. We recommend that you update to the recommended versions or remove these extensions from - the installation process. - </div> - <div class="extensions-container"> - <h3>Update these extension(s)</h3> - <ul class="list"> - <li ng-repeat="extension in getExtensionsList()"> - {{extension.name}} {{getCurrentVersion(extension.name)}} to - <select ng-change="versionChanged()" - ng-model="extension.version" - ng-disabled="checkingInProgress()" - > - <option ng-repeat="version in getVersionsList(extension.name)" - ng-selected="version == extension.version" - value="{{version}}" - >Version {{version}}</option> - </select> - <button class="extension-delete" - title="Delete" - ng-click="openDialog(extension.name)" - ng-show="!checkingInProgress() && getObjectSize(getExtensionsList()) > 1"> - <span>Delete</span> - </button> - </li> - </ul> - - <div ng-show="(needReCheck || hasErrors) && !checkingInProgress()"> - <button ng-click="$state.forceReload()" class="btn btn-medium btn-secondary"> - <span>Try Again</span> - </button> - </div> - <div ng-show="!needReCheck && !checkingInProgress() && !hasErrors"> - <button ng-click="nextState()" class="btn btn-medium btn-prime"> - <span>Update</span> - </button> - </div> - </div> -</div> - -<div id="updater-application" class="readiness-check-item" ng-show="updater.visible"> - <div ng-hide="updater.processed"> - <span class="spinner side"> - <span></span><span></span><span></span><span></span> - <span></span><span></span><span></span><span></span> - </span> - <h3 class="readiness-check-title">Checking Updater Application Availability...</h3> - </div> - - <div ng-show="updater.processed" ng-switch="updater.responseType"> - - <div ng-switch-when="success" ng-init="updateOnSuccess(version)"> - - <span class="readiness-check-icon icon-success-round"></span> - - <div class="readiness-check-content"> - <h3 class="readiness-check-title">Check Updater Application Availability</h3> - <p> - Updater application is available. - </p> - </div> - - </div> - - <div class="readiness-check-item" ng-switch-default ng-init="updateOnError(updater)"> - - <span class="readiness-check-icon icon-failed-round"></span> - - <div class="readiness-check-content"> - <h3 class="readiness-check-title">Check Updater Application Availability</h3> - <p> - Updater application is not available. - <a href="#updater-application" ng-click="updateOnExpand(updater)"> - <span ng-hide="updater.expanded">Show detail</span> - <span ng-show="updater.expanded">Hide detail</span> - </a> - </p> - <p ng-show="updater.expanded"> - Download and install the updater. - </p> - <p ng-show="updater.expanded">For additional assistance, see - <a href="https://devdocs.magento.com/guides/v2.3/comp-mgr/trouble/cman/updater.html" - target="_blank">updater application help</a>. - </p> - </div> - - </div> - - </div> - -</div> - -<div id="cron-script" class="readiness-check-item" ng-show="cronScript.visible"> - <div ng-hide="cronScript.processed"> - <span class="spinner side"> - <span></span><span></span><span></span><span></span> - <span></span><span></span><span></span><span></span> - </span> - <h3 class="readiness-check-title">Checking Cron Scripts...</h3> - </div> - - <div ng-show="cronScript.processed" ng-switch="cronScript.responseType"> - <div ng-switch-when="success" ng-init="updateOnSuccess(cronScript)"> - <span class="readiness-check-icon icon-success-round"></span> - <div class="readiness-check-content"> - <h3 class="readiness-check-title">Check Cron Scripts</h3> - <p> - Cron script readiness check passed. - </p> - <p ng-show="cronScript.notice" ng-bind-html="cronScript.setupNoticeMessage"> - </p> - <p ng-show="cronScript.notice" ng-bind-html="cronScript.updaterNoticeMessage"> - </p> - </div> - </div> - - <div class="readiness-check-item" ng-switch-default ng-init="updateOnError(cronScript)"> - <span class="readiness-check-icon icon-failed-round"></span> - <div class="readiness-check-content"> - <h3 class="readiness-check-title">Check Cron Scripts</h3> - <p> - Cron script readiness check failed. - <a href="#cron-script" ng-click="updateOnExpand(cronScript)"> - <span ng-hide="cronScript.expanded">Show detail</span> - <span ng-show="cronScript.expanded">Hide detail</span> - </a> - </p> - <p ng-show="cronScript.expanded" ng-bind-html="cronScript.setupErrorMessage"> - </p> - <p ng-show="cronScript.expanded" ng-bind-html="cronScript.updaterErrorMessage"> - </p> - <p ng-show="cronScript.expanded">For additional assistance, see - <a href="https://devdocs.magento.com/guides/v2.3/comp-mgr/trouble/cman/cron.html" - target="_blank">cron scripts help</a>. - </p> - </div> - </div> - </div> -</div> - -<div id="component-dependency" class="readiness-check-item" ng-show="componentDependency.visible"> - <div ng-hide="componentDependency.processed"> - <span class="spinner side"> - <span></span><span></span><span></span><span></span> - <span></span><span></span><span></span><span></span> - </span> - <h3 class="readiness-check-title">Checking Component Dependency...</h3> - </div> - - <div ng-show="componentDependency.processed" ng-switch="componentDependency.responseType"> - <div ng-switch-when="success" ng-init="updateOnSuccess(componentDependency)"> - <span class="readiness-check-icon icon-success-round"></span> - <div class="readiness-check-content"> - <h3 class="readiness-check-title">Check Component Dependency</h3> - <p> - Component dependency is correct. - </p> - </div> - </div> - - <div class="readiness-check-item" ng-switch-default ng-init="updateOnError(componentDependency)"> - <span class="readiness-check-icon icon-failed-round"></span> - <div class="readiness-check-content"> - <h3 class="readiness-check-title">Check Component Dependency</h3> - <p> - We found conflicting component dependencies. - <a href="#component-dependency" ng-click="updateOnExpand(componentDependency)"> - <span ng-hide="componentDependency.expanded">Show detail</span> - <span ng-show="componentDependency.expanded">Hide detail</span> - </a> - </p> - <p ng-show="componentDependency.expanded" ng-bind-html="componentDependency.errorMessage"> - </p> - <p ng-show="componentDependency.expanded">For additional assistance, see - <a href="https://devdocs.magento.com/guides/v2.3/comp-mgr/trouble/cman/component-depend.html" - target="_blank">component dependency help - </a>. - </p> - </div> - </div> - </div> -</div> - -<div id="php-version" class="readiness-check-item" ng-show="version.visible"> - <div ng-hide="version.processed"> - <span class="spinner side"> - <span></span><span></span><span></span><span></span> - <span></span><span></span><span></span><span></span> - </span> - <h3 class="readiness-check-title">Checking PHP Version...</h3> - </div> - - <div ng-show="version.processed" ng-switch="version.responseType"> - - <div ng-switch-when="success" ng-init="updateOnSuccess(version)"> - - <span class="readiness-check-icon icon-success-round"></span> - - <div class="readiness-check-content"> - <h3 class="readiness-check-title">PHP Version Check</h3> - <p> - Your PHP version is correct ({{version.data.current}}). - </p> - </div> - - </div> - - <div class="readiness-check-item" ng-switch-default ng-init="updateOnError(version)"> - - <div class="readiness-check-side"> - <p class="side-title">Need Help?</p> - <a href="http://www.php.net/docs.php" target="_blank">PHP Documentation</a> - </div> - - <span class="readiness-check-icon icon-failed-round"></span> - - <div class="readiness-check-content"> - <h3 class="readiness-check-title">PHP Version Check</h3> - <div ng-show="version.isRequestError"> - <p>Server failed to respond. Please try again.</p> - </div> - <div ng-hide="version.isRequestError"> - <p> - Your PHP version is {{version.data.current}}. The required PHP version is {{version.data.required}}. - <a href="#php-version" ng-click="updateOnExpand(version)"> - <span ng-hide="version.expanded">Show detail</span> - <span ng-show="version.expanded">Hide detail</span> - </a> - </p> - <p ng-show="version.expanded"> - Download and install PHP from <a href="http://www.php.net" target="_blank">www.php.net</a> using this <a href="http://www.php.net/docs.php" target="_blank">PHP Documentation</a>. - </p> - <p ng-show="version.expanded">For additional assistance, contact your hosting provider.</p> - </div> - </div> - - </div> - - </div> - -</div> - -<div id="php-settings" class="readiness-check-item" ng-show="settings.visible"> - <div ng-hide="settings.processed"> - <span class="spinner side"> - <span></span><span></span><span></span><span></span> - <span></span><span></span><span></span><span></span> - </span> - <h3 class="readiness-check-title">Checking PHP Settings *....</h3> - </div> - - <div ng-show="settings.processed" ng-switch="settings.responseType"> - - <div ng-switch-when="success" ng-init="updateOnSuccess(settings)"> - - <span class="readiness-check-icon icon-success-round"></span> - - <div class="readiness-check-content"> - <h3 class="readiness-check-title">PHP Settings Check *</h3> - <p> - Your PHP settings are correct. - </p> - </div> - - <div ng-repeat="setting in settings.data"> - <div class="message" ng-show="setting.warning"> - <p> - {{setting.message}} - </p> - </div> - </div> - - </div> - - <div class="readiness-check-item" ng-switch-default ng-init="updateOnError(settings)"> - - <span class="readiness-check-icon icon-failed-round"></span> - <div class="readiness-check-content"> - <h3 class="readiness-check-title">PHP Settings Check *</h3> - - <div ng-show="settings.isRequestError"> - <p>Server failed to respond. Please try again.</p> - </div> - <div ng-hide="settings.isRequestError" ng-repeat="setting in settings.data"> - <div ng-show="setting.error && setting.helpUrl" class="readiness-check-side"> - <p class="side-title">Need Help?</p> - <a href="{{setting.helpUrl}}" target="_blank">PHP Documentation</a> - </div> - <div ng-show="setting.error"> - <p> - {{setting.message}} - </p> - </div> - </div> - - <p ng-show="componentDependency.expanded">For additional assistance, see - <a href="https://devdocs.magento.com/guides/v2.3/install-gde/trouble/php/tshoot_php-set.html" - target="_blank">PHP settings check help - </a>. - </p> - - </div> - </div> - - </div> - -</div> - -<div id="php-extensions" class="readiness-check-item" ng-show="extensions.visible"> - <div ng-hide="extensions.processed"> - <span class="spinner side"> - <span></span><span></span><span></span><span></span> - <span></span><span></span><span></span><span></span> - </span> - <h3 class="readiness-check-title">Checking PHP Extensions...</h3> - </div> - <div ng-show="extensions.processed" ng-switch="extensions.responseType"> - - <div ng-switch-when="success" ng-init="updateOnSuccess(extensions)"> - - <span class="readiness-check-icon icon-success-round"></span> - - <div class="readiness-check-content"> - <h3 class="readiness-check-title">PHP Extensions Check</h3> - <p> - You meet {{extensions.length}} out of {{extensions.length}} PHP extensions requirements. - <a href="#php-extensions" ng-click="updateOnExpand(extensions)"> - <span ng-hide="extensions.expanded">Show detail</span> - <span ng-show="extensions.expanded">Hide detail</span> - </a> - </p> - <ul class="list" ng-show="extensions.expanded"> - <li class="list-item-success" - ng-repeat="name in extensions.data.required" - >PHP Extension {{name}}.</li> - </ul> - </div> - - </div> - - <div ng-switch-default ng-init="updateOnError(extensions)"> - - <div ng-switch="extensions.data.error"> - - <div ng-switch-when="phpExtensionError" class="message message-error"> - <span class="message-text"> - {{extensions.data.message}} - </span> - </div> - - <div class="readiness-check-side"> - <p class="side-title">Need Help?</p> - <a href="https://devdocs.magento.com/guides/v2.3/install-gde/system-requirements.html" target="_blank">PHP Extension Help</a> - </div> - - <span class="readiness-check-icon icon-failed-round"></span> - - <div class="readiness-check-content"> - <h3 class="readiness-check-title">PHP Extensions Check</h3> - <div ng-show="extensions.isRequestError"> - <p>Server failed to respond. Please try again.</p> - </div> - <div ng-hide="extensions.isRequestError"> - <p> - {{extensions.data.missing.length}} missing PHP extensions. - <a href="#php-extensions" ng-click="updateOnExpand(extensions)"> - <span ng-hide="extensions.expanded">Show detail</span> - <span ng-show="extensions.expanded">Hide detail</span> - </a> - </p> - <p> - The best way to resolve this is to install the correct missing extensions. The exact fix depends on our server, your host, and other system variables. - <br> - Our <a href="https://devdocs.magento.com/guides/v2.3/install-gde/system-requirements.html" target="_blank">PHP extension help</a> can get you started. - </p> - <p> - For additional assistance, contact your hosting provider. - </p> - <ul class="list" ng-show="extensions.expanded"> - <li - class="list-item-icon" - ng-repeat="name in extensions.data.required" - ng-switch="extensions.data.missing.indexOf(name) >= 0" - > - <span ng-switch-when="true" class="icon-failed"></span> - <span ng-switch-default class="icon-success"></span> - PHP Extension {{name}}. - </li> - </ul> - </div> - </div> - - </div> - - </div> - - </div> - -</div> - -<div class="readiness-check-item" id="php-permissions" ng-show="permissions.visible"> - <div ng-hide="permissions.processed"> - <span class="spinner side"> - <span></span><span></span><span></span><span></span> - <span></span><span></span><span></span><span></span> - </span> - <h3 class="readiness-check-title">Checking File Permissions...</h3> - </div> - - <div ng-show="permissions.processed" ng-switch="permissions.responseType"> - - <div ng-switch-when="success" ng-init="updateOnSuccess(permissions)"> - - <span class="readiness-check-icon icon-success-round"></span> - - <div class="readiness-check-content"> - <h3 class="readiness-check-title">File Permission Check</h3> - <p> - You meet {{permissions.data.current.length}} out of {{permissions.data.required.length}} writable file permission requirements. - <a href="#php-permissions" ng-click="updateOnExpand(permissions)"> - <span ng-hide="permissions.expanded">Show detail</span> - <span ng-show="permissions.expanded">Hide detail</span> - </a> - </p> - <ul class="list" ng-show="permissions.expanded"> - <li class="list-item-success" ng-repeat="name in permissions.data.required"> - "{{name}}" writable directory permission. - </li> - </ul> - </div> - - </div> - - <div ng-switch-default ng-init="updateOnError(permissions)"> - - <div class="readiness-check-side"> - <p class="side-title">Need Help?</p> - <a href="https://devdocs.magento.com/guides/v2.3/install-gde/prereq/file-system-perms.html" target="_blank">File Permission Help</a> - </div> - - <span class="readiness-check-icon icon-failed-round"></span> - - <div class="readiness-check-content"> - - <h3 class="readiness-check-title">File Permission Check</h3> - <div ng-show="permissions.isRequestError"> - <p>Server failed to respond. Please try again.</p> - </div> - <div ng-hide="permissions.isRequestError"> - <p> - {{permissions.data.required.length - permissions.data.current.length}} file permission not met. - <a href="#php-permissions" ng-click="updateOnExpand(permissions)"> - <span ng-hide="permissions.expanded">Show detail</span> - <span ng-show="permissions.expanded">Hide detail</span> - </a> - </p> - <p ng-show="permissions.expanded"> - The best way to resolve this is to allow write permissions for files in the following Magento directories and subdirectories. The exact fix depends on your server, your host, - and other system variables. - <br> - For help, see our <a href="https://devdocs.magento.com/guides/v2.3/install-gde/prereq/file-system-perms.html" target="_blank">File Permission Help</a> or call your hosting provider. - </p> - <ul class="list" ng-show="permissions.expanded" ng-init="showDetails=false"> - <li - class="list-item-icon" - ng-repeat="name in permissions.data.required" - ng-switch="hasItem(permissions.data.current, name.path)"> - <span ng-switch-when="true" class="icon-success"></span> - <span ng-switch-default class="icon-failed"></span> - <span>"{{name.path}}"</span> - <span ng-switch-when="true"> - - Writable. - </span> - <span ng-switch-default ng-hide="permission.expanded"> - - Not writable, change the permissions. - <a href="#" ng-click="showDetails = !showDetails""> - <span ng-hide="showDetails">Show details</span> - <span ng-show="showDetails">Hide details</span> - </a> - <ul ng-show="showDetails" ng-repeat="file in name.missing"> - <li class="icon-failed"> - {{file}}<br> - </li> - </ul> - </span> - </li> - </ul> - - </div> - - </div> - - </div> - - </div> - -</div> - -<div class="readiness-check-item" id="warning-message" ng-show="true"> - * - In some cases, you might have two PHP configuration files: one for the PHP command line and for the web server. If so, make the change in both php.ini files. For details, see the <a href="http://php.net/manual/en/configuration.file.php">php.ini reference</a>. -</div> - -<script type="text/ng-template" id="removeDialog"> - <div class="modals-wrapper"> - <aside class="modal-popup modal-connect-signin _show" data-role="modal"> - <div class="modal-inner-wrap"> - <header class="modal-header"> - <button ng-click="closeThisDialog()" - title="Close" - class="action-close" - data-role="closeBtn" - type="button"> - <span>Close</span> - </button> - </header> - <div class="modal-content" data-role="content"> - <div class="delete-modal-wrap"> - <h3>Remove Extension</h3> - - <p>Are you sure you want to remove “{{extensionToRemove}}” from - the list?</p> - <p> - Please be aware that removing this extension will remove it from the current - update wizard flow. You can update this extension at a later time by selecting - the extension in the update grid. - </p> - <div class="actions"> - <button ng-click="removeExtension(extensionToRemove)" class="btn btn-large btn-prime"> - <span>Remove</span> - </button> - <button ng-click="closeThisDialog()" class="btn btn-large btn-secondary"> - <span>Cancel</span> - </button> - </div> - </div> - </div> - </div> - </aside> - </div> -</script> diff --git a/setup/view/magento/setup/select-version.phtml b/setup/view/magento/setup/select-version.phtml deleted file mode 100644 index 66264e46d50ad..0000000000000 --- a/setup/view/magento/setup/select-version.phtml +++ /dev/null @@ -1,256 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -?> - -<div class="nav-bar-outer-actions"> - - <div class="outer-actions-inner-wrap"> - <div class="btn-wrap btn-wrap-triangle-right btn-wrap-next"> - <button - type="button" - class="btn btn-prime" - ng-click="update()" - ng-disabled="!upgradeReadyForNext || (!componentsReadyForNext && updateComponents.yes) - || upgradeProcessError || componentsProcessError" - >Next</button> - </div> - <div class="btn-wrap btn-wrap-try-again"> - <button - type="button" - class="btn btn-secondary" - ng-click="$state.forceReload()" - ng-disabled="!tryAgainEnabled()" - >Try Again</button> - </div> - </div> -</div> - -<h2 class="page-sub-title">{{$state.current.header}}</h2> - -<div class="row form-row"> - <div class="message message-spinner" ng-show="!upgradeProcessed"> - <span class="spinner"> - <span></span><span></span><span></span><span></span> - <span></span><span></span><span></span><span></span> - </span> - <span class="message-text">Checking for a new version...</span> - </div> - <div - class="message" - ng-class="upgradeAlreadyLatestVersion ? 'message-success' : 'message-error'" - ng-show="upgradeProcessError"> - <span class="message-text" ng-bind-html="upgradeProcessErrorMessage"></span> - </div> - <div class="message" ng-show="upgradeProcessed && !upgradeProcessError && currentVersion"> - Your Magento version is {{currentVersion}}. - <span ng-show="versions">You are about to upgrade to a newer version.</span> - </div> - <div class="row" ng-show="upgradeProcessed && !upgradeProcessError"> - <div class="col-m-3"> - <label class="form-label"> - Magento Core Components - </label> - </div> - <div class="col-m-4"> - <select - id="selectVersion" - class="form-el-select" - ng-model="selectedOption" - ng-options="item.versionInfo as item.version.name for item in versions"> - </select> - </div> - </div> - <div class="row" ng-show="upgradeProcessed && !upgradeProcessError"> - <div class="col-m-3"> - <label class="form-label" for="showUnstable"> - Show All Versions - </label> - </div> - <div class="col-m-4"> - <input - id="showUnstable" - type="checkbox" - ng-model="showUnstable" - ng-change="showUnstableClick()" - > - </div> - </div> -</div> - -<div class="row form-row" ng-show="!upgradeProcessError"> - <div class="col-m-3"> - <label class="form-label"> - Other Components - </label> - </div> - <div class="col-m-4"> - <div class="form-column"> - <input - id="yesUpdateComponents" - class="form-el-radio" - type="radio" - ng-model="updateComponents.yes" - ng-value="true"> - <label class="form-label" for="yesUpdateComponents"> - Yes - </label> - </div> - <div class="form-column"> - <input - id="noUpdateComponents" - class="form-el-radio" - type="radio" - ng-model="updateComponents.no" - ng-value="true" - checked> - <label class="form-label" for="noUpdateComponents"> - No - </label> - </div> - </div> -</div> - -<div ng-show="updateComponents.yes && !upgradeProcessError"> - <div class="message message-spinner" ng-show="!componentsProcessed"> - <span class="spinner"> - <span></span><span></span><span></span><span></span> - <span></span><span></span><span></span><span></span> - </span> - <span class="message-text">Retrieving information for other components...</span> - </div> - <div class="message message-error" ng-show="componentsProcessError"> - <span class="message-text"> - Sorry, we can't retrieve data for the table right now. - </span> - </div> - <div class="row" ng-show="componentsProcessed && total == 0"> - <label class="form-label"> - <strong>We didn't find any components to upgrade. Click "Next" to continue.</strong><br/> - </label> - </div> - <div class="admin__data-grid-outer-wrap" ng-show="componentsProcessed && total > 0"> - <div class="row" ng-show="!upgradeProcessError"> - <label class="form-label"> - We'll update the following components for you at the same time. <br/> - If you don't want some components updated, change the slider to No. - </label> - <br/> - <br/> - </div> - <div class="admin__data-grid-header"> - <div class="admin__data-grid-header-row row row-gutter"> - <div class="col-xs-3"> - <div class="admin__control-support-text"> - <span>{{totalForGrid}} of {{total}} </span> components are selected. - </div> - </div> - <div class="col-xs-9 admin__data-grid-pager-wrap"> - <select id="perPage" class="admin__control-select" ng-model="rowLimit"> - <option value="20">20</option> - <option value="30">30</option> - <option value="50">50</option> - <option value="100">100</option> - <option value="200">200</option> - </select> - <label class="admin__control-support-text" for="perPage">per page</label> - <div class="admin__data-grid-pager"> - <button class="action-previous" - ng-disabled="currentPage == 1" - ng-click="currentPage = currentPage - 1; start = start - rowLimit" - type="button" - > - <span>Previous page</span> - </button> - <input id="pageCurrent" - class="admin__control-text" - type="number" - ng-value="currentPage" - ng-model="currentPage" - > - <label class="admin__control-support-text" for="pageCurrent"> - of {{numberOfPages}} - </label> - <button class="action-next" - ng-disabled="currentPage >= numberOfPages" - ng-click="currentPage = currentPage + 1; start = start + rowLimit" - type="button" - > - <span>Next page</span> - </button> - </div> - </div> - </div> - </div> - <div class="admin__data-grid-wrap" ng-show="componentsProcessed"> - <table class="data-grid"> - <thead data-part="head"> - <tr> - <th class="data-grid-th _sortable _col-xs"> - <span>Upgrade</span> - </th> - <th class="data-grid-th _sortable _ascend"> - <span>Component Name</span> - </th> - <th class="data-grid-th _sortable"> - <span>Type</span> - </th> - <th class="data-grid-th _sortable"> - <span>Vendor</span> - </th> - <th class="data-grid-th _sortable"> - <span>Current Version</span> - </th> - <th class="data-grid-actions-cell data-grid-th"> - <span>Update Version</span> - </th> - </tr> - </thead> - <tbody> - <tr ng-repeat="component in displayComponents | limitTo:rowLimit"> - <td class="data-grid-indicator-cell"> - <div class="admin__actions-switch"> - <input class="admin__actions-switch-checkbox" - name="{{component.checkboxId}}" - type="checkbox" - ng-click="AddRemoveComponentOnSliderMove(component)" - ng-checked="isSelected(component.name)"> - <label class="admin__actions-switch-label" - for="{{component.checkboxId}}"> - <span data-text-on="Yes" - data-text-off="No" - class="admin__actions-switch-text"></span> - </label> - </div> - </td> - <td> - <span class="data-grid-data">{{component.name}}</span> - </td> - <td> - <span class="data-grid-data">{{component.type.replace("magento2-", "")}}</span> - </td> - <td> - <span class="data-grid-data">{{component.vendor}}</span> - </td> - <td> - <span class="data-grid-data">{{component.version}}</span> - </td> - <td> - <select ng-model="component.dropdownId" ng-init="component.dropdownId=component.updates[0].id" - ng-options="item.id as item.name for item in component.updates" - ng-change="setComponentVersion(component.name, component.dropdownId)"> - </select> - </td> - </tr> - </tbody> - </table> - </div> - </div> -</div> - -<!-- loading indicator overlay and loader --> -<div data-role="spinner" class="admin__data-grid-loading-mask hide" ng-class="{'hide':isHiddenSpinner}"> - <div class="grid-loader"></div> -</div> diff --git a/setup/view/magento/setup/start-updater.phtml b/setup/view/magento/setup/start-updater.phtml deleted file mode 100644 index 6534df529e155..0000000000000 --- a/setup/view/magento/setup/start-updater.phtml +++ /dev/null @@ -1,52 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -?> - -<div class="nav-bar-outer-actions"> - <div class="outer-actions-inner-wrap"> - <div class="btn-wrap btn-wrap-triangle-left btn-wrap-prev"> - <button - type="button" - class="btn" - ng-click="goToPreviousState()" - >Back</button> - </div> - </div> -</div> - -<h2 class="page-title">{{$state.current.header}}</h2> - -<div class="message message-warning"> - <span class="message-text"> - <strong> - We will take your store offline to protect shoppers during the duration of the {{type}} activity. - </strong> - <div ng-show="type == 'upgrade'"> - Before you start upgrade, you can optionally - <a href="https://devdocs.magento.com/guides/v2.3/comp-mgr/trouble/cman/maint-mode.html"> - configure a custom maintenance page</a> that informs shoppers the store is offline. - (Magento provides a default page.) - </div> - </span> -</div> - -<form - novalidate - name="start-updater" - > - - <div ng-repeat="package in packages"> - <div>We're ready to {{type}} {{package.name}}{{package.version ? ' to ' + package.version : ''}}. </div> - </div> - <br/> - <button - class="btn btn-large btn-prime" - ng-click="update()" - type="button" - >{{buttonText}}</button> - <br/> - <div ng-show="started">{{errorMessage}}</div> -</form> diff --git a/setup/view/magento/setup/success.phtml b/setup/view/magento/setup/success.phtml deleted file mode 100644 index c6d4a05bdc556..0000000000000 --- a/setup/view/magento/setup/success.phtml +++ /dev/null @@ -1,82 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// @codingStandardsIgnoreFile - -?> -<div class="content-success"> - - <h1 class="jumbo-title"> - <span class="jumbo-icon icon-success-round"></span> - Success - </h1> - - <p>Please keep this information for your records:</p> - - <p><strong>Magento Admin Info:</strong></p> - - <dl class="list-definition" id="admin-info"> - <dt>Username:</dt> - <dd>{{admin.username}}</dd> - - <dt>Email:</dt> - <dd>{{admin.email}}</dd> - - <dt>Password:</dt> - <dd>******</dd> - - <dt>Your Store Address:</dt> - <dd> - <a href="{{url.front}}" target="_blank">{{url.front}}</a> - </dd> - - <dt>Magento Admin Address:</dt> - <dd> - <a href="{{url.admin}}" target="_blank">{{url.admin}}</a> - </dd> - - <div class="message message-notice"> - <span class="message-text"> - Be sure to bookmark your unique URL and record it offline. - </span> - </div> - - <dt>Encryption Key:</dt> - <dd>{{config.encrypt.key}}</dd> - </dl> - - <p> - <strong>Database Info:</strong> - </p> - - <dl id="db-info" class="list-definition"> - <dt>Database Name:</dt> - <dd>{{db.name}}</dd> - - <dt>Username:</dt> - <dd>{{db.user}}</dd> - - <dt>Password:</dt> - <dd>******</dd> - </dl> - - <p class="bold" ng-repeat="message in messages">{{message}}</p> - <?php if ($this->isSampleDataErrorInstallation) : ?> - <div class="message message-warning"> - <span class="message-text"><strong>Something went wrong while installing sample data.</strong> Please check <code>var/log/system.log</code> for details. You can retry installing the data now or just start using Magento.</span> - </div> - <?php endif; ?> - <div ng-show="config.address.actual_base_url"> - <a - class="btn btn-large btn-prime" - href="{{url.admin}}" - target="_blank" - > - Launch Magento Admin - </a> - </div> - -</div> diff --git a/setup/view/magento/setup/system-config.phtml b/setup/view/magento/setup/system-config.phtml deleted file mode 100644 index 9f7f051436f83..0000000000000 --- a/setup/view/magento/setup/system-config.phtml +++ /dev/null @@ -1,131 +0,0 @@ -<!-- -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ ---> -<div class="page-main-actions" ng-show="!$root.isMarketplaceAuthorized"> - <div class="page-actions"> - <div class="page-actions-inner"> - <div class="page-actions-buttons"> - <button ng-click="saveAuthJson()" title="Save Config" type="button" class="action-primary"> - <span>Save Config</span> - </button> - </div> - </div> - </div> -</div> - -<div class="messages"> - <div ng-show="saveAuthJson.result.success === false && saveAuthJson.result !== undefined" - class="message message-error error"> - <span class="message-text"> - {{saveAuthJson.result.message}} - </span> - </div> -</div> - -<div ng-show="logout===true" class="messages"> - <div class="message message-success success"> - <div data-ui-id="messages-message-success"> - You have logged out - </div> - </div> -</div> - -<div ng-show="logout===false" class="messages"> - <div class="message message-success success"> - <div data-ui-id="messages-message-success"> - Credentials Saved - </div> - </div> -</div> - -<section class="page-inner page-columns"> - <div class="page-inner-sidebar"> - <div class="admin__page-nav _collapsed _show"> - <ul class="admin__page-nav-items"> - <li class="admin__page-nav-item item _active"> - <a href="javascript:void(0);" class="admin__page-nav-link"> - <span>Magento Marketplace</span> - </a> - </li> - </ul> - </div> - </div> - <div class="page-inner-content"> - <h2 class="page-sub-title">Magento Marketplace</h2> - <p>Sign in to sync your Magento Marketplace purchases.</p> - <fieldset class="form-fieldset"> - <form ng-submit="saveAuthJson();" name="auth" role="form" autocomplete="off"> - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label required" for="username">Public Access Key</label> - </div> - <div class="col-m-4"> - <div ng-show="!$root.isMarketplaceAuthorized" class="form-row"> - <input id="username" - class="form-el-input" - type="text" - name="username" - ng-model="user.username" - ng-maxlength="40" - ng-class="{ 'invalid' : (auth.username.$error.required && !auth.username.$pristine) - || (auth.username.$error.required && user.submitted)}" - autofocus - required - autocomplete="off" - > - <div class="error-container"> - This is a required field. - </div> - </div> - <div ng-show="$root.isMarketplaceAuthorized" class="form-row form-row-text"> - <span>{{user.username}}</span> - <a href="" class="action-sign-out" ng-click="reset()">Reset</a> - </div> - </div> - </div> - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label required" for="password">Private Access Key</label> - </div> - <div class="col-m-4"> - <div ng-show="!$root.isMarketplaceAuthorized" class="form-row"> - <input id="password" - class="form-el-input" - type="password" - name="password" - ng-model="user.password" - ng-maxlength="40" - ng-class="{ 'invalid' : (auth.password.$error.required && !auth.password.$pristine) - || (auth.password.$error.required && user.submitted) }" - required - autocomplete="new-password" - > - <div class="error-container"> - This is a required field. - </div> - </div> - - <div ng-show="$root.isMarketplaceAuthorized" class="form-row form-row-text"> - <span>******</span> - </div> - </div> - </div> - <input type="submit" style="display:none;"> - </form> - </fieldset> - </div> -</section> - -<!-- loading indicator overlay and loader --> -<div ng-show="!isHiddenSpinner" class="loading-mask ng-scope" data-role="loader"> - <div class="popup popup-loading"> - <div class="popup-inner"> - <img alt="Loading..." src="<?= $this->basePath() ?>/pub/images/loader-1.gif"> - Please wait... - </div> - </div> -</div> - diff --git a/setup/view/magento/setup/update-extension-grid.phtml b/setup/view/magento/setup/update-extension-grid.phtml deleted file mode 100644 index b02fbf1a4aae5..0000000000000 --- a/setup/view/magento/setup/update-extension-grid.phtml +++ /dev/null @@ -1,153 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -?> -<a href="" ui-sref="root.extension">< Back</a> -<h2 class="page-title">{{$state.current.header}}</h2> -<div class="messages"> - <div ng-show="error === true" class="message message-error error"> - <span class="message-text"> - {{errorMessage}} - </span> - </div> -</div> -<div class="admin__data-grid-outer-wrap" id="updateExtensionGrid"> - <div class="admin__data-grid-header"> - <div class="admin__data-grid-header-row row row-gutter"> - <div class="col-xs-3"> - <button type="button" class="btn" ng-click="updateAll()">Update</button> - <div class="admin__control-support-text"> - <span>{{total}}</span> extensions - </div> - </div> - <div class="col-xs-9 admin__data-grid-pager-wrap" - ng-include="'<?= $this->basePath() ?>/pub/magento/setup/view/pagination.html'"> - </div> - </div> - </div> - <div class="admin__data-grid-wrap" ng-show="$state.is('root.update')"> - <table class="data-grid"> - <thead data-part="head"> - <tr> - <th class="data-grid-multicheck-cell"> - <div class="action-multicheck-wrap" - ng-class="{'_active':multipleChoiceService.isNewExtensionsMenuVisible}" - click-out="multipleChoiceService.hideNewExtensionsMenu()" - > - <input type="checkbox" - style="visibility: hidden;" - class="admin__control-checkbox" - ng-class="{'_indeterminate':multipleChoiceService.someExtensionsSelected}" - ng-checked="multipleChoiceService.allExtensionsSelected" - > - <label></label> - <button class="action-multicheck-toggle" - ng-class="{'_active':multipleChoiceService.isNewExtensionsMenuVisible}" - ng-click="multipleChoiceService.toggleNewExtensionsMenu()" - > - <span>Options</span> - </button> - <ul class="action-menu"> - <li ng-show="!multipleChoiceService.allExtensionsSelected" - ng-click="multipleChoiceService.selectAllExtensions()" - > - <span class="action-menu-item">Select all</span> - </li> - <li ng-show="multipleChoiceService.allExtensionsSelected - || multipleChoiceService.someExtensionsSelected" - ng-click="multipleChoiceService.deselectAllExtensions()" - > - <span class="action-menu-item">Deselect all</span> - </li> - </ul> - </div> - </th> - <th ng-click="order('name')" ng-class="{'_ascend' : predicate === 'name' - && !reverse,'_descend' : predicate === 'name' && reverse}" class="data-grid-th _sortable"> - <span>Extension Name</span> - </th> - <th ng-click="order('type')" ng-class="{'_ascend' : predicate === 'type' && - !reverse,'_descend' : predicate === 'type' && reverse}" class="data-grid-th _sortable"> - <span>Type</span> - </th> - <th ng-click="order('vendor')" ng-class="{'_ascend' : predicate === 'vendor' && - !reverse,'_descend' : predicate === 'vendor' && reverse}" class="data-grid-th _sortable _ascend"> - <span>Vendor</span> - </th> - <th ng-click="order('version')" ng-class="{'_ascend' : predicate === 'version' - && !reverse,'_descend' : predicate === 'version' && reverse}" class="data-grid-th _sortable"> - <span>Version</span> - </th> - <th class="data-grid-th"> - <span>Update version</span> - </th> - <th class="data-grid-actions-cell data-grid-th"> - <span>Action</span> - </th> - </tr> - </thead> - <tbody> - <tr ng-repeat="extension in extensions | orderBy:predicate:reverse - | startFrom:(currentPage - 1) * rowLimit | limitTo:rowLimit" - > - <td class="data-grid-checkbox-cell"> - <label class="data-grid-checkbox-cell-inner"> - <input type="checkbox" - class="admin__control-checkbox" - ng-checked="multipleChoiceService.selectedExtensions.hasOwnProperty(extension.name)" - ng-click="multipleChoiceService.updateSelectedExtensions($event, extension.name, - extension.latestVersion)" - > - <label></label> - </label> - </td> - <td> - <span class="data-grid-data">{{extension.package_title}}</span> - </td> - <td> - <span class="data-grid-data">{{extension.package_type}}</span> - </td> - <td> - <span class="data-grid-data">{{extension.vendor}}</span> - </td> - <td> - <span class="data-grid-data">{{extension.version}}</span> - </td> - <td> - <span class="data-grid-data"> - <select id="selectedVersion" ng-model="extension.updateVersion"> - <option ng-repeat="version in extension.versions" - value="{{version}}" - >Version {{version}}</option> - </select> - </span> - <span class="component-indicator _tooltip" - ng-show="extension.package_link" - data-label="View info on Marketplace" - ><a href="{{extension.package_link}}" target="_blank"></a> - </span> - </td> - <td class="data-grid-data"> - <div class="action-wrap" ng-class="_active"> - <button class="action-select" - ng-click="update(extension)"> - <span>Update</span> - </button> - </div> - </td> - </tr> - </tbody> - </table> - </div> -</div> - -<div ng-show="!isHiddenSpinner" class="loading-mask ng-scope" data-role="loader"> - <div class="popup popup-loading"> - <div class="popup-inner"> - <img alt="Loading..." src="<?= $this->basePath() ?>/pub/images/loader-1.gif"> - Please wait... - </div> - </div> -</div> diff --git a/setup/view/magento/setup/updater-success.phtml b/setup/view/magento/setup/updater-success.phtml deleted file mode 100644 index 0e4c108d8495c..0000000000000 --- a/setup/view/magento/setup/updater-success.phtml +++ /dev/null @@ -1,37 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ -?> -<div class="content-success"> - <h1 class="jumbo-title"> - <span class="jumbo-icon icon-success-round"></span> - Success - </h1> - <p>Your store is no longer in maintenance mode.</p> - <div ng-hide="rollbackStarted"> - <p>You {{successPageActionMessage}}:</p> - <br/> - <ul ng-repeat="package in packages"> - <li>{{package.name}}</li> - </ul> - </div> - <div ng-show="rollbackStarted"> - Rollback performed successfully. - </div> - - <button - class="btn btn-large btn-prime" - ng-click="back()" - type="button" - >Back to Setup Tool</button> -</div> -<div ng-show="!isHiddenSpinner" class="loading-mask ng-scope" data-role="loader"> - <div class="popup popup-loading"> - <div class="popup-inner"> - <img alt="Loading..." src="<?= $this->basePath() ?>/pub/images/loader-1.gif"> - Please wait... - </div> - </div> -</div> diff --git a/setup/view/magento/setup/web-configuration.phtml b/setup/view/magento/setup/web-configuration.phtml deleted file mode 100644 index 4018694dfd0c3..0000000000000 --- a/setup/view/magento/setup/web-configuration.phtml +++ /dev/null @@ -1,335 +0,0 @@ -<?php -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - -// @codingStandardsIgnoreFile - -?> -<?php -$hints = [ - 'base_url' => sprintf( - '<div><p>%s</p><p>%s</p></div>', - 'Enter the base URL that brings shoppers to your store (Ex. http://example.com/).', - 'Leave empty for automatic detection (not recommended for production environment).' - ), - 'encrypt_key' => sprintf( - '<p>%s</p>', - 'Key to encrypt sensitive data such as passwords and personally identifiable customer information in the Magento database. The encryption key is stored in [your Magento install dir]/app/etc/env.php' - ), - 'admin' => sprintf( - '<p>%s</p>', - 'A unique URL helps keep your store and customers safer. Use only letters, numbers, and underscore characters.' - ) -]; -?> - -<div class="page-web-configuration"> - -<div class="nav-bar-outer-actions"> - <div class="outer-actions-inner-wrap"> - <div class="btn-wrap btn-wrap-triangle-right btn-wrap-next"> - <button type="button" class="btn btn-prime" ng-click="validateUrl()" dis>Next</button> - </div> - <div class="btn-wrap btn-wrap-triangle-left btn-wrap-prev"> - <button type="button" class="btn" ng-click="previousState()">Back</button> - </div> - </div> -</div> - -<h2 class="page-sub-title">{{$state.current.header}}</h2> - -<div - class="message message-error" - ng-show="validateUrl.failed !== undefined" -> - <span class="message-text">{{validateUrl.failed}}</span> -</div> - -<form - name="webconfig" - role="form" - novalidate - > - -<fieldset class="form-fieldset"> - - <div - class="row form-row" - ng-class="{'has-error': webconfig.base_url.$invalid && webconfig.submitted}" - > - <div class="col-m-3"> - <label class="form-label" for="baseUrl"> - Your Store Address - </label> - </div> - <div class="col-m-4"> - <input - id="baseUrl" - class="form-el-input" - type="url" - name="base_url" - ng-model="config.address.base_url" - ng-class="{'invalid': webconfig.base_url.$invalid && webconfig.submitted}" - ng-init="config.address.auto_base_url = '<?= $this->autoBaseUrl ?>'; fillBaseURL();" - ng-blur="addSlash()" - ng-change="populateHttps()" - ng-pattern="/^(https?:\/\/).*$/" - tooltip-placement="right" - tooltip-html-unsafe="<?= $hints['base_url'] ?>" - tooltip-trigger="focus" - tooltip-append-to-body="true" - > - <div class="error-container"> - <span ng-show="!webconfig.base_url.valid - || webconfig.base_url.$error.required - || webconfig.base_url.$error.url" - > - Please enter a valid base URL path. (ex: http://www.example.com/) - </span> - </div> - </div> - </div> - - <div - class="row form-row" - ng-class="{'has-error': webconfig.admin.$invalid && webconfig.submitted}" - > - <div class="col-m-3"> - <label class="form-label required" for="admin"> - Magento Admin Address - </label> - </div> - <div class="col-m-4"> - <div class="form-el-insider-wrap"> - <div class="form-el-insider"> - {{config.address.actual_base_url}} - </div> - <div class="form-el-insider-input"> - <input - id="admin" - class="form-el-input" - type="text" - name="admin" - ng-pattern="/^[a-zA-Z0-9_]+$/" - ng-model="config.address.admin" - ng-class="{'invalid' : webconfig.admin.$invalid && webconfig.submitted }" - ng-init="config.address.admin = '<?= $this->autoAdminPath ?>';" - required - tooltip-placement="right" - tooltip-html-unsafe="<?= $hints['admin'] ?>" - tooltip-trigger="focus" - tooltip-append-to-body="true" - > - <div class="error-container"> - <span ng-show="webconfig.admin.$error"> - Please enter a valid admin URL path. Use only letters, numbers, and underscore characters. - </span> - </div> - </div> - </div> - </div> - </div> - -</fieldset> - -<fieldset class="form-fieldset"> - - <legend - class="form-legend-expand" - ng-click="updateOnExpand(config.advanced)" - ng-class="{'expanded' : config.advanced.expanded}" - > - Advanced Options - </legend> - - <div ng-show="config.advanced.expanded"> - - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label"> - HTTPS Options - </label> - </div> - <div class="col-m-4"> - <div class="form-row"> - <input - id="httpsFront" - class="form-el-checkbox" - type="checkbox" - ng-model="config.https.front" - ng-checked="config.https.front" - > - <label class="form-label" for="httpsFront"> - Use HTTPS for Magento Storefront - </label> - </div> - <div class="form-row"> - <input - id="httpsAdmin" - class="form-el-checkbox" - type="checkbox" - ng-model="config.https.admin" - ng-checked="config.https.admin" - > - <label class="form-label" for="httpsAdmin"> - Use HTTPS for Magento Admin - </label> - </div> - </div> - </div> - - <div class="row form-row" ng-show="showHttpsField()"> - <div class="col-m-3"> - <label - ng-show="config.https.front || config.https.admin" - class="form-label" - for="https" - > - Your HTTPS Store address: - </label> - </div> - <div class="col-m-4"> - <input - id="https" - class="form-el-input" - type="url" - name="https" - ng-model="config.https.text" - ng-class="{'invalid': webconfig.https.$invalid && webconfig.submitted}" - ng-if="config.https.front || config.https.admin" - ng-focus="" - ng-pattern="/^(https?:\/\/).*$/" - required - > - <div class="error-container"> - <span ng-show="!webconfig.https.$error.valid - || webconfig.https.$error.required - || webconfig.https.$error.url" - > - Please enter a valid HTTPS base URL path. (ex: https://www.example.com/) - </span> - </div> - </div> - </div> - - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label"> - Apache Rewrites - </label> - </div> - <div class="col-m-4"> - <input - id="apacheRewrites" - class="form-el-checkbox" - type="checkbox" - ng-model="config.rewrites.allowed" - > - <label class="form-label" for="apacheRewrites"> - Use Apache Web Server Rewrites - </label> - </div> - </div> - - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label required"> - Encryption Key - </label> - </div> - <div class="col-m-4"> - - <div class="form-row"> - <input - id="encryptionKey" - class="form-el-radio" - type="radio" - ng-model="config.encrypt.type" - value="magento" - > - <label class="form-label" for="encryptionKey"> - I want to use a Magento generated key - </label> - </div> - - <div class="form-row"> - <input - id="encryptionType" - class="form-el-radio" - type="radio" - ng-model="config.encrypt.type" - value="user" - > - <label class="form-label" for="encryptionType"> - I want to use my own encryption key - </label> - </div> - - <div - class="form-row" - ng-class="{'has-error': webconfig.key.$invalid && webconfig.submitted}" - ng-if="showEncryptKey()" - > - <input - class="form-el-input" - type="text" - name="key" - ng-model="config.encrypt.key" - ng-class="{'invalid': webconfig.key.$invalid && webconfig.submitted}" - tooltip-placement="right" - tooltip-html-unsafe="<?= $hints['encrypt_key'] ?>" - tooltip-trigger="focus" - tooltip-append-to-body="true" - ng-minlength="32" - ng-maxlength="32" - ng-pattern="/^\S+$/" - required - > - <div class="error-container"> - <span ng-show="webconfig.key.$error.required"> - You must enter an encryption key. - </span> - <span ng-show="webconfig.key.$error.minlength - || webconfig.key.$error.maxlength - || webconfig.key.$error.pattern" - > - Encryption key must be 32 character string without any white space. - </span> - </div> - </div> - - </div> - </div> - - <div class="row form-row"> - <div class="col-m-3"> - <label class="form-label required"> - Session Save - </label> - </div> - <div class="col-m-4"> - <select - name="session" - class="form-el-select" - ng-model="config.sessionSave.type" - ng-class="{'invalid': webconfig.session.$invalid && webconfig.submitted}" - tooltip-placement="right" - tooltip-html-unsafe="The location of session. You can change this later in Magento Admin." - tooltip-trigger="focus" - tooltip-append-to-body="true" - > - <?php foreach ($this->sessionSave as $value):?> - <?= "<option value=\"" . $value . "\">" . ucfirst($value) . "</option>" ?> - <?php endforeach; ?> - </select> - </div> - </div> - </div> - -</fieldset> - -</form> - -</div>