diff --git a/app/code/Magento/Backend/Model/Session/Quote.php b/app/code/Magento/Backend/Model/Session/Quote.php index 12a4d4d138f53..6ca269488294a 100644 --- a/app/code/Magento/Backend/Model/Session/Quote.php +++ b/app/code/Magento/Backend/Model/Session/Quote.php @@ -7,8 +7,6 @@ use Magento\Customer\Api\CustomerRepositoryInterface; use Magento\Customer\Api\GroupManagementInterface; -use Magento\Framework\App\ObjectManager; -use Magento\Quote\Api\CartManagementInterface; /** * Adminhtml quote session @@ -81,11 +79,6 @@ class Quote extends \Magento\Framework\Session\SessionManager */ protected $quoteFactory; - /** - * @var \Magento\Quote\Api\CartManagementInterface; - */ - private $cartManagement; - /** * @param \Magento\Framework\App\Request\Http $request * @param \Magento\Framework\Session\SidResolverInterface $sidResolver diff --git a/app/code/Magento/Backend/Model/Url.php b/app/code/Magento/Backend/Model/Url.php index c1aa03a457cac..f09c9c04ee6bb 100644 --- a/app/code/Magento/Backend/Model/Url.php +++ b/app/code/Magento/Backend/Model/Url.php @@ -5,6 +5,8 @@ */ namespace Magento\Backend\Model; +use Magento\Framework\Url\HostChecker; +use Magento\Framework\App\ObjectManager; /** * Class \Magento\Backend\Model\UrlInterface @@ -77,6 +79,8 @@ class Url extends \Magento\Framework\Url implements \Magento\Backend\Model\UrlIn protected $_scope; /** + * Constructor + * * @param \Magento\Framework\App\Route\ConfigInterface $routeConfig * @param \Magento\Framework\App\RequestInterface $request * @param \Magento\Framework\Url\SecurityInfoInterface $urlSecurityInfo @@ -96,7 +100,7 @@ class Url extends \Magento\Framework\Url implements \Magento\Backend\Model\UrlIn * @param \Magento\Store\Model\StoreFactory $storeFactory * @param \Magento\Framework\Data\Form\FormKey $formKey * @param array $data - * + * @param HostChecker|null $hostChecker * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -118,9 +122,11 @@ public function __construct( \Magento\Framework\Encryption\EncryptorInterface $encryptor, \Magento\Store\Model\StoreFactory $storeFactory, \Magento\Framework\Data\Form\FormKey $formKey, - array $data = [] + array $data = [], + HostChecker $hostChecker = null ) { $this->_encryptor = $encryptor; + $hostChecker = $hostChecker ?: ObjectManager::getInstance()->get(HostChecker::class); parent::__construct( $routeConfig, $request, @@ -133,7 +139,8 @@ public function __construct( $scopeConfig, $routeParamsPreprocessor, $scopeType, - $data + $data, + $hostChecker ); $this->_backendHelper = $backendHelper; $this->_menuConfig = $menuConfig; diff --git a/app/code/Magento/Backend/Test/Unit/Model/Session/QuoteTest.php b/app/code/Magento/Backend/Test/Unit/Model/Session/QuoteTest.php index 5db3c2e41c04a..99d7fdfab21de 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/Session/QuoteTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/Session/QuoteTest.php @@ -12,6 +12,11 @@ */ class QuoteTest extends \PHPUnit_Framework_TestCase { + /** + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + */ + private $objectManager; + /** * @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ @@ -92,11 +97,6 @@ class QuoteTest extends \PHPUnit_Framework_TestCase */ protected $quoteFactoryMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $cartManagementMock; - /** * Set up * @@ -105,6 +105,7 @@ class QuoteTest extends \PHPUnit_Framework_TestCase */ protected function setUp() { + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->customerRepositoryMock = $this->getMockForAbstractClass( \Magento\Customer\Api\CustomerRepositoryInterface::class, [], @@ -197,13 +198,6 @@ protected function setUp() ); $this->quoteFactoryMock = $this->getMock(\Magento\Quote\Model\QuoteFactory::class, ['create'], [], '', false); - $this->cartManagementMock = $this->getMock( - \Magento\Quote\Api\CartManagementInterface::class, - [], - [], - '', - false - ); $this->quote = $this->getMock( \Magento\Backend\Model\Session\Quote::class, @@ -226,10 +220,6 @@ protected function setUp() 'quoteFactory' => $this->quoteFactoryMock ] ); - - $this->prepareObjectManager([ - [\Magento\Quote\Api\CartManagementInterface::class, $this->cartManagementMock] - ]); } /** @@ -416,19 +406,4 @@ public function getQuoteDataProvider() 'customer ids same' => [66, 66, 'never'], ]; } - - /** - * @param array $map - * @deprecated - */ - private function prepareObjectManager($map) - { - $objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); - $objectManagerMock->expects($this->any())->method('getInstance')->willReturnSelf(); - $objectManagerMock->expects($this->any())->method('get')->will($this->returnValueMap($map)); - $reflectionClass = new \ReflectionClass(\Magento\Framework\App\ObjectManager::class); - $reflectionProperty = $reflectionClass->getProperty('_instance'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($objectManagerMock); - } } diff --git a/app/code/Magento/Backend/Test/Unit/Model/UrlTest.php b/app/code/Magento/Backend/Test/Unit/Model/UrlTest.php index 2bc3d86e74d69..4eda145156c6d 100644 --- a/app/code/Magento/Backend/Test/Unit/Model/UrlTest.php +++ b/app/code/Magento/Backend/Test/Unit/Model/UrlTest.php @@ -3,16 +3,13 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - -/** - * Test class for \Magento\Backend\Model\Url - */ namespace Magento\Backend\Test\Unit\Model; +use Magento\Framework\Url\HostChecker; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * @codingStandardsIgnoreFile */ class UrlTest extends \PHPUnit_Framework_TestCase { @@ -21,10 +18,12 @@ class UrlTest extends \PHPUnit_Framework_TestCase */ protected $_model; + /** + * @var string + */ protected $_areaFrontName = 'backendArea'; /** - * Mock menu model * @var \PHPUnit_Framework_MockObject_MockObject */ protected $_menuMock; @@ -62,7 +61,7 @@ class UrlTest extends \PHPUnit_Framework_TestCase /** * @var \PHPUnit_Framework_MockObject_MockObject */ - protected $_paramsResolverMock; + protected $routeParamsResolverFactoryMock; /** * @var \Magento\Framework\Encryption\EncryptorInterface @@ -75,6 +74,7 @@ class UrlTest extends \PHPUnit_Framework_TestCase */ protected function setUp() { + $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->_menuMock = $this->getMock( \Magento\Backend\Model\Menu::class, [], @@ -141,25 +141,21 @@ protected function setUp() false, false ); - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->_encryptor = $this->getMock(\Magento\Framework\Encryption\Encryptor::class, null, [], '', false); - $this->_paramsResolverMock = $this->getMock( + $routeParamsResolver = $this->getMock(\Magento\Framework\Url\RouteParamsResolver::class, [], [], '', false); + $this->routeParamsResolverFactoryMock = $this->getMock( \Magento\Framework\Url\RouteParamsResolverFactory::class, [], [], '', false ); - $this->_paramsResolverMock->expects( - $this->any() - )->method( - 'create' - )->will( - $this->returnValue( - $this->getMock(\Magento\Framework\Url\RouteParamsResolver::class, [], [], '', false) - ) - ); - $this->_model = $helper->getObject( + $this->routeParamsResolverFactoryMock->expects($this->any()) + ->method('create') + ->willReturn($routeParamsResolver); + /** @var HostChecker|\PHPUnit_Framework_MockObject_MockObject $hostCheckerMock */ + $hostCheckerMock = $this->getMock(HostChecker::class, [], [], '', false); + $this->_model = $objectManager->getObject( \Magento\Backend\Model\Url::class, [ 'scopeConfig' => $this->_scopeConfigMock, @@ -168,31 +164,10 @@ protected function setUp() 'menuConfig' => $this->_menuConfigMock, 'authSession' => $this->_authSessionMock, 'encryptor' => $this->_encryptor, - 'routeParamsResolverFactory' => $this->_paramsResolverMock + 'routeParamsResolverFactory' => $this->routeParamsResolverFactoryMock, + 'hostChecker' => $hostCheckerMock ] ); - $this->_paramsResolverMock->expects( - $this->any() - )->method( - 'create' - )->will( - $this->returnValue( - $this->getMock(\Magento\Framework\Url\RouteParamsResolver::class, [], [], '', false) - ) - ); - $this->_model = $helper->getObject( - \Magento\Backend\Model\Url::class, - [ - 'scopeConfig' => $this->_scopeConfigMock, - 'backendHelper' => $helperMock, - 'formKey' => $this->_formKey, - 'menuConfig' => $this->_menuConfigMock, - 'authSession' => $this->_authSessionMock, - 'encryptor' => $this->_encryptor, - 'routeParamsResolverFactory' => $this->_paramsResolverMock - ] - ); - $this->_requestMock = $this->getMock(\Magento\Framework\App\Request\Http::class, [], [], '', false); $this->_model->setRequest($this->_requestMock); } @@ -262,7 +237,7 @@ public function testGetAreaFrontName() [ 'backendHelper' => $helperMock, 'authSession' => $this->_authSessionMock, - 'routeParamsResolverFactory' => $this->_paramsResolverMock + 'routeParamsResolverFactory' => $this->routeParamsResolverFactoryMock ] ); $urlModel->getAreaFrontName(); diff --git a/app/code/Magento/BundleImportExport/Model/Import/Product/Type/Bundle.php b/app/code/Magento/BundleImportExport/Model/Import/Product/Type/Bundle.php index 2d0f1264b6b8a..6a99c02af9da6 100644 --- a/app/code/Magento/BundleImportExport/Model/Import/Product/Type/Bundle.php +++ b/app/code/Magento/BundleImportExport/Model/Import/Product/Type/Bundle.php @@ -9,7 +9,6 @@ namespace Magento\BundleImportExport\Model\Import\Product\Type; use \Magento\Bundle\Model\Product\Price as BundlePrice; -use \Magento\BundleImportExport\Model\Export\RowCustomizer; use \Magento\Catalog\Model\Product\Type\AbstractType; /** @@ -55,20 +54,6 @@ class Bundle extends \Magento\CatalogImportExport\Model\Import\Product\Type\Abst */ const SELECTION_PRICE_TYPE_PERCENT = 1; - /** - * Instance of database adapter. - * - * @var \Magento\Framework\DB\Adapter\AdapterInterface - */ - protected $connection; - - /** - * Instance of application resource. - * - * @var \Magento\Framework\App\ResourceConnection - */ - protected $_resource; - /** * Array of cached options. * @@ -144,23 +129,6 @@ class Bundle extends \Magento\CatalogImportExport\Model\Import\Product\Type\Abst 'multiselect' => 'multi', ]; - /** - * @param \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory $attrSetColFac - * @param \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory $prodAttrColFac - * @param \Magento\Framework\App\ResourceConnection $resource - * @param array $params - */ - public function __construct( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory $attrSetColFac, - \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory $prodAttrColFac, - \Magento\Framework\App\ResourceConnection $resource, - array $params - ) { - parent::__construct($attrSetColFac, $prodAttrColFac, $resource, $params); - $this->_resource = $resource; - $this->connection = $resource->getConnection(\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION); - } - /** * Parse selections. * diff --git a/app/code/Magento/BundleImportExport/composer.json b/app/code/Magento/BundleImportExport/composer.json index 2f5e3afdbff86..ad849b6f31182 100644 --- a/app/code/Magento/BundleImportExport/composer.json +++ b/app/code/Magento/BundleImportExport/composer.json @@ -7,7 +7,6 @@ "magento/module-import-export": "100.2.*", "magento/module-catalog-import-export": "100.2.*", "magento/module-bundle": "100.2.*", - "magento/module-eav": "100.2.*", "magento/framework": "100.2.*" }, "type": "magento2-module", diff --git a/app/code/Magento/Catalog/Model/Attribute/Config/Data.php b/app/code/Magento/Catalog/Model/Attribute/Config/Data.php index 032970a7461b6..1fac4e58c75c9 100644 --- a/app/code/Magento/Catalog/Model/Attribute/Config/Data.php +++ b/app/code/Magento/Catalog/Model/Attribute/Config/Data.php @@ -1,22 +1,31 @@ _scopeConfig = $scopeConfig; $this->_configFactory = $configFactory; @@ -157,7 +160,14 @@ public function __construct( $this->_storeManager = $storeManager; $this->_eavConfig = $eavConfig; - parent::__construct($cache, $entityTypeFactory, $entityTypeCollectionFactory, $cacheState, $universalFactory); + parent::__construct( + $cache, + $entityTypeFactory, + $entityTypeCollectionFactory, + $cacheState, + $universalFactory, + $serializer + ); } /** diff --git a/app/code/Magento/Catalog/Model/Product/Attribute/Source/Countryofmanufacture.php b/app/code/Magento/Catalog/Model/Product/Attribute/Source/Countryofmanufacture.php index 7b45d162b5e98..8bcf01ba3db38 100644 --- a/app/code/Magento/Catalog/Model/Product/Attribute/Source/Countryofmanufacture.php +++ b/app/code/Magento/Catalog/Model/Product/Attribute/Source/Countryofmanufacture.php @@ -35,6 +35,11 @@ class Countryofmanufacture extends AbstractSource implements OptionSourceInterfa */ protected $_countryFactory; + /** + * @var \Magento\Framework\Serialize\SerializerInterface + */ + private $serializer; + /** * Construct * @@ -61,15 +66,30 @@ public function getAllOptions() { $cacheKey = 'COUNTRYOFMANUFACTURE_SELECT_STORE_' . $this->_storeManager->getStore()->getCode(); if ($cache = $this->_configCacheType->load($cacheKey)) { - $options = unserialize($cache); + $options = $this->getSerializer()->unserialize($cache); } else { /** @var \Magento\Directory\Model\Country $country */ $country = $this->_countryFactory->create(); /** @var \Magento\Directory\Model\ResourceModel\Country\Collection $collection */ $collection = $country->getResourceCollection(); $options = $collection->load()->toOptionArray(); - $this->_configCacheType->save(serialize($options), $cacheKey); + $this->_configCacheType->save($this->getSerializer()->serialize($options), $cacheKey); } return $options; } + + /** + * Get serializer + * + * @return \Magento\Framework\Serialize\SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if ($this->serializer === null) { + $this->serializer = \Magento\Framework\App\ObjectManager::getInstance() + ->get(\Magento\Framework\Serialize\SerializerInterface::class); + } + return $this->serializer; + } } diff --git a/app/code/Magento/Catalog/Model/ProductOptions/Config.php b/app/code/Magento/Catalog/Model/ProductOptions/Config.php index bd55304e03bef..fa828832bf4a7 100644 --- a/app/code/Magento/Catalog/Model/ProductOptions/Config.php +++ b/app/code/Magento/Catalog/Model/ProductOptions/Config.php @@ -5,20 +5,29 @@ */ namespace Magento\Catalog\Model\ProductOptions; +use Magento\Framework\Serialize\SerializerInterface; + +/** + * Provides product options configuration + */ class Config extends \Magento\Framework\Config\Data implements \Magento\Catalog\Model\ProductOptions\ConfigInterface { /** + * Constructor + * * @param \Magento\Catalog\Model\ProductOptions\Config\Reader $reader * @param \Magento\Framework\Config\CacheInterface $cache - * @param string $cacheId + * @param string|null $cacheId + * @param SerializerInterface|null $serializer */ public function __construct( \Magento\Catalog\Model\ProductOptions\Config\Reader $reader, \Magento\Framework\Config\CacheInterface $cache, - $cacheId = 'product_options_config' + $cacheId = 'product_options_config', + SerializerInterface $serializer = null ) { - parent::__construct($reader, $cache, $cacheId); + parent::__construct($reader, $cache, $cacheId, $serializer); } /** diff --git a/app/code/Magento/Catalog/Model/ProductTypes/Config.php b/app/code/Magento/Catalog/Model/ProductTypes/Config.php index a80692cfaf945..f691e08a34b57 100644 --- a/app/code/Magento/Catalog/Model/ProductTypes/Config.php +++ b/app/code/Magento/Catalog/Model/ProductTypes/Config.php @@ -5,19 +5,28 @@ */ namespace Magento\Catalog\Model\ProductTypes; +use Magento\Framework\Serialize\SerializerInterface; + +/** + * Provides product types configuration + */ class Config extends \Magento\Framework\Config\Data implements \Magento\Catalog\Model\ProductTypes\ConfigInterface { /** - * @param \Magento\Catalog\Model\ProductTypes\Config\Reader $reader + * Constructor + * + * @param Config\Reader $reader * @param \Magento\Framework\Config\CacheInterface $cache - * @param string $cacheId + * @param string|null $cacheId + * @param SerializerInterface|null $serializer */ public function __construct( \Magento\Catalog\Model\ProductTypes\Config\Reader $reader, \Magento\Framework\Config\CacheInterface $cache, - $cacheId = 'product_types_config' + $cacheId = 'product_types_config', + SerializerInterface $serializer = null ) { - parent::__construct($reader, $cache, $cacheId); + parent::__construct($reader, $cache, $cacheId, $serializer); } /** diff --git a/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php b/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php index c24460981afbf..1cf18fc998ef9 100644 --- a/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php +++ b/app/code/Magento/Catalog/Model/ResourceModel/Product/Collection.php @@ -17,6 +17,7 @@ use Magento\Framework\EntityManager\MetadataPool; use Magento\Store\Model\Store; use Magento\Catalog\Model\Product\Gallery\ReadHandler as GalleryReadHandler; +use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory; /** * Product collection @@ -261,6 +262,8 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Collection\Abstrac private $metadataPool; /** + * Collection constructor + * * @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory * @param \Psr\Log\LoggerInterface $logger * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy @@ -280,7 +283,9 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Collection\Abstrac * @param \Magento\Customer\Model\Session $customerSession * @param \Magento\Framework\Stdlib\DateTime $dateTime * @param GroupManagementInterface $groupManagement - * @param \Magento\Framework\DB\Adapter\AdapterInterface $connection + * @param \Magento\Framework\DB\Adapter\AdapterInterface|null $connection + * @param ProductLimitationFactory|null $productLimitationFactory + * @param MetadataPool|null $metadataPool * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ @@ -304,7 +309,9 @@ public function __construct( \Magento\Customer\Model\Session $customerSession, \Magento\Framework\Stdlib\DateTime $dateTime, GroupManagementInterface $groupManagement, - \Magento\Framework\DB\Adapter\AdapterInterface $connection = null + \Magento\Framework\DB\Adapter\AdapterInterface $connection = null, + ProductLimitationFactory $productLimitationFactory = null, + MetadataPool $metadataPool = null ) { $this->moduleManager = $moduleManager; $this->_catalogProductFlatState = $catalogProductFlatState; @@ -316,7 +323,11 @@ public function __construct( $this->_resourceHelper = $resourceHelper; $this->dateTime = $dateTime; $this->_groupManagement = $groupManagement; - $this->_productLimitationFilters = $this->createLimitationFilters(); + $productLimitationFactory = $productLimitationFactory ?: ObjectManager::getInstance()->get( + \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory::class + ); + $this->_productLimitationFilters = $productLimitationFactory->create(); + $this->metadataPool = $metadataPool ?: ObjectManager::getInstance()->get(MetadataPool::class); parent::__construct( $entityFactory, $logger, @@ -2181,7 +2192,7 @@ public function addMediaGalleryData() ); $mediaGalleries = []; - $linkField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField(); + $linkField = $this->getProductEntityMetadata()->getLinkField(); $items = $this->getItems(); $select->where('entity.' . $linkField . ' IN (?)', array_map(function ($item) { @@ -2202,15 +2213,13 @@ public function addMediaGalleryData() } /** - * Get MetadataPool instance - * @return MetadataPool + * Get product entity metadata + * + * @return \Magento\Framework\EntityManager\EntityMetadataInterface */ - private function getMetadataPool() + public function getProductEntityMetadata() { - if (!$this->metadataPool) { - $this->metadataPool = ObjectManager::getInstance()->get(MetadataPool::class); - } - return $this->metadataPool; + return $this->metadataPool->getMetadata(ProductInterface::class); } /** @@ -2334,13 +2343,4 @@ public function getPricesCount() return $this->_pricesCount; } - - /** - * @return Collection\ProductLimitation - */ - private function createLimitationFilters() - { - return \Magento\Framework\App\ObjectManager::getInstance() - ->create(\Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class); - } } diff --git a/app/code/Magento/Catalog/Model/ResourceModel/Product/Link/Product/Collection.php b/app/code/Magento/Catalog/Model/ResourceModel/Product/Link/Product/Collection.php index 239f94e1286b8..116f454cd5e75 100644 --- a/app/code/Magento/Catalog/Model/ResourceModel/Product/Link/Product/Collection.php +++ b/app/code/Magento/Catalog/Model/ResourceModel/Product/Link/Product/Collection.php @@ -5,11 +5,6 @@ */ namespace Magento\Catalog\Model\ResourceModel\Product\Link\Product; -use Magento\Catalog\Api\Data\ProductInterface; -use Magento\Customer\Api\GroupManagementInterface; -use Magento\Framework\App\ObjectManager; -use Magento\Framework\EntityManager\MetadataPool; - /** * Catalog product linked products collection * @@ -53,80 +48,6 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection */ protected $_hasLinkFilter = false; - /** - * @var MetadataPool - */ - private $metadataPool; - - /** - * @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory - * @param \Psr\Log\LoggerInterface $logger - * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy - * @param \Magento\Framework\Event\ManagerInterface $eventManager - * @param \Magento\Eav\Model\Config $eavConfig - * @param \Magento\Framework\App\ResourceConnection $resource - * @param \Magento\Eav\Model\EntityFactory $eavEntityFactory - * @param \Magento\Catalog\Model\ResourceModel\Helper $resourceHelper - * @param \Magento\Framework\Validator\UniversalFactory $universalFactory - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Framework\Module\Manager $moduleManager - * @param \Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState - * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig - * @param \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory - * @param \Magento\Catalog\Model\ResourceModel\Url $catalogUrl - * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate - * @param \Magento\Customer\Model\Session $customerSession - * @param \Magento\Framework\Stdlib\DateTime $dateTime - * @param GroupManagementInterface $groupManagement - * @param \Magento\Framework\DB\Adapter\AdapterInterface|null $connection - * @SuppressWarnings(PHPMD.ExcessiveParameterList) - */ - public function __construct( - \Magento\Framework\Data\Collection\EntityFactory $entityFactory, - \Psr\Log\LoggerInterface $logger, - \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy, - \Magento\Framework\Event\ManagerInterface $eventManager, - \Magento\Eav\Model\Config $eavConfig, - \Magento\Framework\App\ResourceConnection $resource, - \Magento\Eav\Model\EntityFactory $eavEntityFactory, - \Magento\Catalog\Model\ResourceModel\Helper $resourceHelper, - \Magento\Framework\Validator\UniversalFactory $universalFactory, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Framework\Module\Manager $moduleManager, - \Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState, - \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, - \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory, - \Magento\Catalog\Model\ResourceModel\Url $catalogUrl, - \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate, - \Magento\Customer\Model\Session $customerSession, - \Magento\Framework\Stdlib\DateTime $dateTime, - GroupManagementInterface $groupManagement, - \Magento\Framework\DB\Adapter\AdapterInterface $connection = null - ) { - parent::__construct( - $entityFactory, - $logger, - $fetchStrategy, - $eventManager, - $eavConfig, - $resource, - $eavEntityFactory, - $resourceHelper, - $universalFactory, - $storeManager, - $moduleManager, - $catalogProductFlatState, - $scopeConfig, - $productOptionFactory, - $catalogUrl, - $localeDate, - $customerSession, - $dateTime, - $groupManagement, - $connection - ); - } - /** * Declare link model and initialize type attributes join * @@ -219,7 +140,7 @@ public function addProductFilter($products) if (!is_array($products)) { $products = [$products]; } - $identifierField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getIdentifierField(); + $identifierField = $this->getProductEntityMetadata()->getIdentifierField(); $this->getSelect()->where("product_entity_table.$identifierField IN (?)", $products); $this->_hasLinkFilter = true; } @@ -279,7 +200,7 @@ protected function _joinLinks() $connection->quoteInto('links.link_type_id = ?', $this->_linkTypeId), ]; $joinType = 'join'; - $linkField = $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField(); + $linkField = $this->getProductEntityMetadata()->getLinkField(); if ($this->getProduct() && $this->getProduct()->getId()) { $linkFieldId = $this->getProduct()->getData( $linkField @@ -422,19 +343,6 @@ public function addLinkAttributeToFilter($code, $condition) return $this; } - /** - * Get MetadataPool instance - * @return MetadataPool - * @deprecated - */ - private function getMetadataPool() - { - if (!$this->metadataPool) { - $this->metadataPool = ObjectManager::getInstance()->get(MetadataPool::class); - } - return $this->metadataPool; - } - /** * Join Product To Links * @return void @@ -442,11 +350,15 @@ private function getMetadataPool() private function joinProductsToLinks() { if ($this->_hasLinkFilter) { - $metaDataPool = $this->getMetadataPool()->getMetadata(ProductInterface::class); + $metaDataPool = $this->getProductEntityMetadata(); $linkField = $metaDataPool->getLinkField(); $entityTable = $metaDataPool->getEntityTable(); $this->getSelect() - ->join(['product_entity_table' => $entityTable], "links.product_id = product_entity_table.$linkField", []); + ->join( + ['product_entity_table' => $entityTable], + "links.product_id = product_entity_table.$linkField", + [] + ); } } } diff --git a/app/code/Magento/Catalog/Model/ResourceModel/Product/Option/Collection.php b/app/code/Magento/Catalog/Model/ResourceModel/Product/Option/Collection.php index 2d50ead9d56d9..68280d5a1d597 100644 --- a/app/code/Magento/Catalog/Model/ResourceModel/Product/Option/Collection.php +++ b/app/code/Magento/Catalog/Model/ResourceModel/Product/Option/Collection.php @@ -7,6 +7,7 @@ use Magento\Catalog\Api\Data\ProductInterface; use Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface; +use Magento\Framework\EntityManager\MetadataPool; /** * Catalog product options collection @@ -49,6 +50,7 @@ class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\Ab * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Magento\Framework\DB\Adapter\AdapterInterface $connection * @param \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource + * @param MetadataPool $metadataPool * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -59,10 +61,13 @@ public function __construct( \Magento\Catalog\Model\ResourceModel\Product\Option\Value\CollectionFactory $optionValueCollectionFactory, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\DB\Adapter\AdapterInterface $connection = null, - \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null + \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null, + MetadataPool $metadataPool = null ) { $this->_optionValueCollectionFactory = $optionValueCollectionFactory; $this->_storeManager = $storeManager; + $this->metadataPool = $metadataPool ?: \Magento\Framework\App\ObjectManager::getInstance() + ->get(\Magento\Framework\EntityManager\MetadataPool::class); parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $connection, $resource); } @@ -248,7 +253,7 @@ protected function _initSelect() ['cpe' => $this->getTable('catalog_product_entity')], sprintf( 'cpe.%s = main_table.product_id', - $this->getMetadataPool()->getMetadata(ProductInterface::class)->getLinkField() + $this->metadataPool->getMetadata(ProductInterface::class)->getLinkField() ), [] ); @@ -318,18 +323,6 @@ public function reset() return $this->_reset(); } - /** - * @return \Magento\Framework\EntityManager\MetadataPool - */ - private function getMetadataPool() - { - if (null === $this->metadataPool) { - $this->metadataPool = \Magento\Framework\App\ObjectManager::getInstance() - ->get(\Magento\Framework\EntityManager\MetadataPool::class); - } - return $this->metadataPool; - } - /** * @return JoinProcessorInterface */ diff --git a/app/code/Magento/Catalog/Plugin/Model/ResourceModel/Config.php b/app/code/Magento/Catalog/Plugin/Model/ResourceModel/Config.php index 699feef76c67e..69c693f4fd01a 100644 --- a/app/code/Magento/Catalog/Plugin/Model/ResourceModel/Config.php +++ b/app/code/Magento/Catalog/Plugin/Model/ResourceModel/Config.php @@ -5,6 +5,9 @@ */ namespace Magento\Catalog\Plugin\Model\ResourceModel; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Serialize\SerializerInterface; + class Config { /**#@+ @@ -20,16 +23,24 @@ class Config /** @var bool|null */ protected $isCacheEnabled = null; + /** + * @var SerializerInterface + */ + private $serializer; + /** * @param \Magento\Framework\App\CacheInterface $cache * @param \Magento\Framework\App\Cache\StateInterface $cacheState + * @param SerializerInterface $serializer */ public function __construct( \Magento\Framework\App\CacheInterface $cache, - \Magento\Framework\App\Cache\StateInterface $cacheState + \Magento\Framework\App\Cache\StateInterface $cacheState, + SerializerInterface $serializer = null ) { $this->cache = $cache; $this->isCacheEnabled = $cacheState->isEnabled(\Magento\Eav\Model\Cache\Type::TYPE_IDENTIFIER); + $this->serializer = $serializer ?: ObjectManager::getInstance()->get(SerializerInterface::class); } /** @@ -43,12 +54,12 @@ public function aroundGetAttributesUsedInListing( ) { $cacheId = self::PRODUCT_LISTING_ATTRIBUTES_CACHE_ID . $config->getEntityTypeId() . '_' . $config->getStoreId(); if ($this->isCacheEnabled && ($attributes = $this->cache->load($cacheId))) { - return unserialize($attributes); + return $this->serializer->unserialize($attributes); } $attributes = $proceed(); if ($this->isCacheEnabled) { $this->cache->save( - serialize($attributes), + $this->serializer->serialize($attributes), $cacheId, [ \Magento\Eav\Model\Cache\Type::CACHE_TAG, @@ -71,12 +82,12 @@ public function aroundGetAttributesUsedForSortBy( $cacheId = self::PRODUCT_LISTING_SORT_BY_ATTRIBUTES_CACHE_ID . $config->getEntityTypeId() . '_' . $config->getStoreId(); if ($this->isCacheEnabled && ($attributes = $this->cache->load($cacheId))) { - return unserialize($attributes); + return $this->serializer->unserialize($attributes); } $attributes = $proceed(); if ($this->isCacheEnabled) { $this->cache->save( - serialize($attributes), + $this->serializer->serialize($attributes), $cacheId, [ \Magento\Eav\Model\Cache\Type::CACHE_TAG, diff --git a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/CountryofmanufactureTest.php b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/CountryofmanufactureTest.php index 2888a0a84f230..9ae3f94924855 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/CountryofmanufactureTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/Product/Attribute/Source/CountryofmanufactureTest.php @@ -5,6 +5,8 @@ */ namespace Magento\Catalog\Test\Unit\Model\Product\Attribute\Source; +use Magento\Framework\Serialize\SerializerInterface; + class CountryofmanufactureTest extends \PHPUnit_Framework_TestCase { /** @@ -27,12 +29,34 @@ class CountryofmanufactureTest extends \PHPUnit_Framework_TestCase */ protected $objectManagerHelper; + /** @var \Magento\Catalog\Model\Product\Attribute\Source\Countryofmanufacture */ + private $countryOfManufacture; + + /** + * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $serializerMock; + protected function setUp() { $this->storeManagerMock = $this->getMock(\Magento\Store\Model\StoreManagerInterface::class); $this->storeMock = $this->getMock(\Magento\Store\Model\Store::class, [], [], '', false); $this->cacheConfig = $this->getMock(\Magento\Framework\App\Cache\Type\Config::class, [], [], '', false); $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->countryOfManufacture = $this->objectManagerHelper->getObject( + \Magento\Catalog\Model\Product\Attribute\Source\Countryofmanufacture::class, + [ + 'storeManager' => $this->storeManagerMock, + 'configCacheType' => $this->cacheConfig, + ] + ); + + $this->serializerMock = $this->getMock(SerializerInterface::class, [], [], '', false); + $this->objectManagerHelper->setBackwardCompatibleProperty( + $this->countryOfManufacture, + 'serializer', + $this->serializerMock + ); } /** @@ -51,15 +75,10 @@ public function testGetAllOptions($cachedDataSrl, $cachedDataUnsrl) ->method('load') ->with($this->equalTo('COUNTRYOFMANUFACTURE_SELECT_STORE_store_code')) ->will($this->returnValue($cachedDataSrl)); - - $countryOfManufacture = $this->objectManagerHelper->getObject( - \Magento\Catalog\Model\Product\Attribute\Source\Countryofmanufacture::class, - [ - 'storeManager' => $this->storeManagerMock, - 'configCacheType' => $this->cacheConfig, - ] - ); - $this->assertEquals($cachedDataUnsrl, $countryOfManufacture->getAllOptions()); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->willReturn($cachedDataUnsrl); + $this->assertEquals($cachedDataUnsrl, $this->countryOfManufacture->getAllOptions()); } /** @@ -71,7 +90,7 @@ public function testGetAllOptionsDataProvider() { return [ - ['cachedDataSrl' => 'a:1:{s:3:"key";s:4:"data";}', 'cachedDataUnsrl' => ['key' => 'data']] + ['cachedDataSrl' => json_encode(['key' => 'data']), 'cachedDataUnsrl' => ['key' => 'data']] ]; } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/ConfigTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/ConfigTest.php index af0c1625f9cb6..852eb11c5cfb9 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/ConfigTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ProductTypes/ConfigTest.php @@ -8,22 +8,33 @@ class ConfigTest extends \PHPUnit_Framework_TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ - protected $readerMock; + private $objectManager; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Catalog\Model\ProductTypes\Config\Reader|\PHPUnit_Framework_MockObject_MockObject */ - protected $cacheMock; + private $readerMock; + + /** + * @var \Magento\Framework\Config\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $cacheMock; + + /** + * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $serializerMock; /** * @var \Magento\Catalog\Model\ProductTypes\Config */ - protected $model; + private $config; protected function setUp() { + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->readerMock = $this->getMock( \Magento\Catalog\Model\ProductTypes\Config\Reader::class, [], @@ -32,19 +43,35 @@ protected function setUp() false ); $this->cacheMock = $this->getMock(\Magento\Framework\Config\CacheInterface::class); + $this->serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); } /** - * @dataProvider getTypeDataProvider - * * @param array $value * @param mixed $expected + * @dataProvider getTypeDataProvider */ public function testGetType($value, $expected) { - $this->cacheMock->expects($this->any())->method('load')->will($this->returnValue(serialize($value))); - $this->model = new \Magento\Catalog\Model\ProductTypes\Config($this->readerMock, $this->cacheMock, 'cache_id'); - $this->assertEquals($expected, $this->model->getType('global')); + $this->cacheMock->expects($this->any()) + ->method('load') + ->willReturn('serializedData'); + + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with('serializedData') + ->willReturn($value); + + $this->config = $this->objectManager->getObject( + \Magento\Catalog\Model\ProductTypes\Config::class, + [ + 'reader' => $this->readerMock, + 'cache' => $this->cacheMock, + 'cacheId' => 'cache_id', + 'serializer' => $this->serializerMock, + ] + ); + $this->assertEquals($expected, $this->config->getType('global')); } public function getTypeDataProvider() @@ -58,22 +85,43 @@ public function getTypeDataProvider() public function testGetAll() { $expected = ['Expected Data']; - $this->cacheMock->expects( - $this->once() - )->method( - 'load' - )->will( - $this->returnValue(serialize(['types' => $expected])) + $this->cacheMock->expects($this->once()) + ->method('load') + ->willReturn(json_encode('"types":["Expected Data"]]')); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->willReturn(['types' => $expected]); + + $this->config = $this->objectManager->getObject( + \Magento\Catalog\Model\ProductTypes\Config::class, + [ + 'reader' => $this->readerMock, + 'cache' => $this->cacheMock, + 'cacheId' => 'cache_id', + 'serializer' => $this->serializerMock, + ] ); - $this->model = new \Magento\Catalog\Model\ProductTypes\Config($this->readerMock, $this->cacheMock, 'cache_id'); - $this->assertEquals($expected, $this->model->getAll()); + $this->assertEquals($expected, $this->config->getAll()); } public function testIsProductSet() { - $this->cacheMock->expects($this->once())->method('load')->will($this->returnValue(serialize([]))); - $this->model = new \Magento\Catalog\Model\ProductTypes\Config($this->readerMock, $this->cacheMock, 'cache_id'); + $this->cacheMock->expects($this->once()) + ->method('load') + ->willReturn(''); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->willReturn([]); - $this->assertEquals(false, $this->model->isProductSet('typeId')); + $this->config = $this->objectManager->getObject( + \Magento\Catalog\Model\ProductTypes\Config::class, + [ + 'reader' => $this->readerMock, + 'cache' => $this->cacheMock, + 'cacheId' => 'cache_id', + 'serializer' => $this->serializerMock, + ] + ); + $this->assertEquals(false, $this->config->isProductSet('typeId')); } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CollectionTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CollectionTest.php index b97b7d2f98423..f19b2c15c8ab2 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CollectionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/CollectionTest.php @@ -3,18 +3,20 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ - namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory; /** - * Class CollectionTest - * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class CollectionTest extends \PHPUnit_Framework_TestCase { + /** + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + */ + private $objectManager; + /** * @var \PHPUnit_Framework_MockObject_MockObject */ @@ -55,6 +57,7 @@ class CollectionTest extends \PHPUnit_Framework_TestCase */ protected function setUp() { + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $entityFactory = $this->getMock(\Magento\Framework\Data\Collection\EntityFactory::class, [], [], '', false); $logger = $this->getMockBuilder(\Psr\Log\LoggerInterface::class) ->disableOriginalConstructor() @@ -145,27 +148,14 @@ protected function setUp() $this->entityMock->expects($this->once())->method('getDefaultAttributes')->willReturn([]); $this->entityMock->expects($this->any())->method('getTable')->willReturnArgument(0); $this->connectionMock->expects($this->atLeastOnce())->method('select')->willReturn($this->selectMock); - $helper = new ObjectManager($this); - $this->prepareObjectManager([ - [ - \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class, - $this->getMock(\Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class) - ], - [ - \Magento\Catalog\Model\ResourceModel\Product\Gallery::class, - $this->galleryResourceMock - ], - [ - \Magento\Framework\EntityManager\MetadataPool::class, - $this->metadataPoolMock - ], - [ - \Magento\Catalog\Model\Product\Gallery\ReadHandler::class, - $this->galleryReadHandlerMock - ] - ]); - $this->collection = $helper->getObject( + $productLimitationMock = $this->getMock( + \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class + ); + $productLimitationFactoryMock = $this->getMock(ProductLimitationFactory::class, ['create']); + $productLimitationFactoryMock->method('create') + ->willReturn($productLimitationMock); + $this->collection = $this->objectManager->getObject( \Magento\Catalog\Model\ResourceModel\Product\Collection::class, [ 'entityFactory' => $entityFactory, @@ -187,10 +177,22 @@ protected function setUp() 'customerSession' => $customerSession, 'dateTime' => $dateTime, 'groupManagement' => $groupManagement, - 'connection' => $this->connectionMock + 'connection' => $this->connectionMock, + 'productLimitationFactory' => $productLimitationFactoryMock, + 'metadataPool' => $this->metadataPoolMock, ] ); $this->collection->setConnection($this->connectionMock); + $this->objectManager->setBackwardCompatibleProperty( + $this->collection, + 'mediaGalleryResource', + $this->galleryResourceMock + ); + $this->objectManager->setBackwardCompatibleProperty( + $this->collection, + 'productGalleryReadHandler', + $this->galleryReadHandlerMock + ); } public function testAddProductCategoriesFilter() @@ -259,20 +261,4 @@ public function testAddMediaGalleryData() $this->assertSame($this->collection, $this->collection->addMediaGalleryData()); } - - /** - * @param $map - */ - private function prepareObjectManager($map) - { - $objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); - $objectManagerMock->expects($this->any())->method('getInstance')->willReturnSelf(); - $objectManagerMock->expects($this->any()) - ->method('get') - ->will($this->returnValueMap($map)); - $reflectionClass = new \ReflectionClass(\Magento\Framework\App\ObjectManager::class); - $reflectionProperty = $reflectionClass->getProperty('_instance'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($objectManagerMock); - } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Link/Product/CollectionTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Link/Product/CollectionTest.php index 3c92cde30012d..fe244d01eea80 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Link/Product/CollectionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Link/Product/CollectionTest.php @@ -3,10 +3,10 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ - namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Link\Product; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory; +use \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -17,8 +17,8 @@ class CollectionTest extends \PHPUnit_Framework_TestCase /** @var \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection */ protected $collection; - /** @var ObjectManagerHelper */ - protected $objectManagerHelper; + /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + private $objectManager; /** @var \Magento\Framework\Data\Collection\EntityFactory|\PHPUnit_Framework_MockObject_MockObject */ protected $entityFactoryMock; @@ -76,6 +76,7 @@ class CollectionTest extends \PHPUnit_Framework_TestCase protected function setUp() { + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->entityFactoryMock = $this->getMock( \Magento\Framework\Data\Collection\EntityFactory::class, [], @@ -133,14 +134,11 @@ function ($store) { $this->timezoneInterfaceMock = $this->getMock(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::class); $this->sessionMock = $this->getMock(\Magento\Customer\Model\Session::class, [], [], '', false); $this->dateTimeMock = $this->getMock(\Magento\Framework\Stdlib\DateTime::class); - $this->objectManagerHelper = new ObjectManagerHelper($this); - $this->prepareObjectManager([ - [\Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class, - $this->getMock(\Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class) - ] - ]); + $productLimitationFactoryMock = $this->getMock(ProductLimitationFactory::class, ['create']); + $productLimitationFactoryMock->method('create') + ->willReturn($this->getMock(ProductLimitation::class)); - $this->collection = $this->objectManagerHelper->getObject( + $this->collection = $this->objectManager->getObject( \Magento\Catalog\Model\ResourceModel\Product\Link\Product\Collection::class, [ 'entityFactory' => $this->entityFactoryMock, @@ -160,7 +158,8 @@ function ($store) { 'catalogUrl' => $this->urlMock, 'localeDate' => $this->timezoneInterfaceMock, 'customerSession' => $this->sessionMock, - 'dateTime' => $this->dateTimeMock + 'dateTime' => $this->dateTimeMock, + 'productLimitationFactory' => $productLimitationFactoryMock, ] ); } @@ -175,20 +174,4 @@ public function testSetProduct() $this->collection->setProduct($product); $this->assertEquals(33, $this->collection->getStoreId()); } - - /** - * @param $map - */ - public function prepareObjectManager($map) - { - $objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); - $objectManagerMock->expects($this->any())->method('getInstance')->willReturnSelf(); - $objectManagerMock->expects($this->any()) - ->method('get') - ->will($this->returnValueMap($map)); - $reflectionClass = new \ReflectionClass(\Magento\Framework\App\ObjectManager::class); - $reflectionProperty = $reflectionClass->getProperty('_instance'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($objectManagerMock); - } } diff --git a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Option/CollectionTest.php b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Option/CollectionTest.php index decf8e66f6738..36afda6287fb9 100644 --- a/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Option/CollectionTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Model/ResourceModel/Product/Option/CollectionTest.php @@ -3,20 +3,22 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - namespace Magento\Catalog\Test\Unit\Model\ResourceModel\Product\Option; use \Magento\Catalog\Model\ResourceModel\Product\Option\Collection; use \Magento\Catalog\Model\ResourceModel\Product\Option\Value; /** - * Class CollectionTest * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * @codingStandardsIgnoreFile */ class CollectionTest extends \PHPUnit_Framework_TestCase { + /** + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + */ + private $objectManager; + /** * @var \Magento\Framework\EntityManager\MetadataPool */ @@ -79,6 +81,7 @@ class CollectionTest extends \PHPUnit_Framework_TestCase protected function setUp() { + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->entityFactoryMock = $this->getMock( \Magento\Framework\Data\Collection\EntityFactory::class, ['create'], [], '', false ); @@ -147,11 +150,6 @@ protected function setUp() $this->metadataPoolMock->expects($this->any())->method('getMetadata')->willReturn($metadata); $this->selectMock->expects($this->exactly(2))->method('join'); - $this->prepareObjectManager([ - [\Magento\Framework\EntityManager\MetadataPool::class, $this->metadataPoolMock], - [\Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface::class, $this->joinProcessor] - ]); - $this->collection = new Collection( $this->entityFactoryMock, $this->loggerMock, @@ -160,7 +158,13 @@ protected function setUp() $this->optionsFactoryMock, $this->storeManagerMock, null, - $this->resourceMock + $this->resourceMock, + $this->metadataPoolMock + ); + $this->objectManager->setBackwardCompatibleProperty( + $this->collection, + 'joinProcessor', + $this->joinProcessor ); } @@ -168,20 +172,4 @@ public function testReset() { $this->collection->reset(); } - - /** - * @param $map - */ - private function prepareObjectManager($map) - { - $objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); - $objectManagerMock->expects($this->any())->method('getInstance')->willReturnSelf(); - $objectManagerMock->expects($this->any()) - ->method('get') - ->will($this->returnValueMap($map)); - $reflectionClass = new \ReflectionClass(\Magento\Framework\App\ObjectManager::class); - $reflectionProperty = $reflectionClass->getProperty('_instance'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($objectManagerMock); - } } diff --git a/app/code/Magento/Catalog/Test/Unit/Plugin/Model/ResourceModel/ConfigTest.php b/app/code/Magento/Catalog/Test/Unit/Plugin/Model/ResourceModel/ConfigTest.php index 01f9964f2d83e..b6f0dcf52bb1e 100644 --- a/app/code/Magento/Catalog/Test/Unit/Plugin/Model/ResourceModel/ConfigTest.php +++ b/app/code/Magento/Catalog/Test/Unit/Plugin/Model/ResourceModel/ConfigTest.php @@ -6,26 +6,29 @@ namespace Magento\Catalog\Test\Unit\Plugin\Model\ResourceModel; +use Magento\Catalog\Plugin\Model\ResourceModel\Config; +use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; class ConfigTest extends \PHPUnit_Framework_TestCase { - /** @var \Magento\Catalog\Plugin\Model\ResourceModel\Config */ - protected $config; - /** @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $cache; + private $cache; /** @var \Magento\Framework\App\Cache\StateInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $cacheState; + private $cacheState; + + /** @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject */ + private $serializer; /** @var \Magento\Catalog\Model\ResourceModel\Config|\PHPUnit_Framework_MockObject_MockObject */ - protected $subject; + private $subject; protected function setUp() { $this->cache = $this->getMock(\Magento\Framework\App\CacheInterface::class); $this->cacheState = $this->getMock(\Magento\Framework\App\Cache\StateInterface::class); + $this->serializer = $this->getMock(SerializerInterface::class); $this->subject = $this->getMock(\Magento\Catalog\Model\ResourceModel\Config::class, [], [], '', false); } @@ -47,12 +50,17 @@ public function testGetAttributesUsedInListingFromCache() $entityTypeId = 'type'; $storeId = 'store'; $attributes = ['attributes']; + $serializedAttributes = '["attributes"]'; $this->subject->expects($this->any())->method('getEntityTypeId')->willReturn($entityTypeId); $this->subject->expects($this->any())->method('getStoreId')->willReturn($storeId); $cacheId = \Magento\Catalog\Plugin\Model\ResourceModel\Config::PRODUCT_LISTING_ATTRIBUTES_CACHE_ID . $entityTypeId . '_' . $storeId; - $this->cache->expects($this->any())->method('load')->with($cacheId)->willReturn(serialize($attributes)); + $this->cache->expects($this->any())->method('load')->with($cacheId)->willReturn($serializedAttributes); + $this->serializer->expects($this->once()) + ->method('unserialize') + ->with($serializedAttributes) + ->willReturn($attributes); $this->assertEquals( $attributes, @@ -68,14 +76,21 @@ public function testGetAttributesUsedInListingWithCacheSave() $entityTypeId = 'type'; $storeId = 'store'; $attributes = ['attributes']; + $serializedAttributes = '["attributes"]'; $this->subject->expects($this->any())->method('getEntityTypeId')->willReturn($entityTypeId); $this->subject->expects($this->any())->method('getStoreId')->willReturn($storeId); $cacheId = \Magento\Catalog\Plugin\Model\ResourceModel\Config::PRODUCT_LISTING_ATTRIBUTES_CACHE_ID . $entityTypeId . '_' . $storeId; $this->cache->expects($this->any())->method('load')->with($cacheId)->willReturn(false); + $this->serializer->expects($this->never()) + ->method('unserialize'); + $this->serializer->expects($this->once()) + ->method('serialize') + ->with($attributes) + ->willReturn($serializedAttributes); $this->cache->expects($this->any())->method('save')->with( - serialize($attributes), + $serializedAttributes, $cacheId, [ \Magento\Eav\Model\Cache\Type::CACHE_TAG, @@ -110,11 +125,16 @@ public function testGetAttributesUsedForSortByFromCache() $entityTypeId = 'type'; $storeId = 'store'; $attributes = ['attributes']; + $serializedAttributes = '["attributes"]'; $this->subject->expects($this->any())->method('getEntityTypeId')->willReturn($entityTypeId); $this->subject->expects($this->any())->method('getStoreId')->willReturn($storeId); $cacheId = \Magento\Catalog\Plugin\Model\ResourceModel\Config::PRODUCT_LISTING_SORT_BY_ATTRIBUTES_CACHE_ID . $entityTypeId . '_' . $storeId; - $this->cache->expects($this->any())->method('load')->with($cacheId)->willReturn(serialize($attributes)); + $this->cache->expects($this->any())->method('load')->with($cacheId)->willReturn($serializedAttributes); + $this->serializer->expects($this->once()) + ->method('unserialize') + ->with($serializedAttributes) + ->willReturn($attributes); $this->assertEquals( $attributes, @@ -130,13 +150,20 @@ public function testGetAttributesUsedForSortByWithCacheSave() $entityTypeId = 'type'; $storeId = 'store'; $attributes = ['attributes']; + $serializedAttributes = '["attributes"]'; $this->subject->expects($this->any())->method('getEntityTypeId')->willReturn($entityTypeId); $this->subject->expects($this->any())->method('getStoreId')->willReturn($storeId); $cacheId = \Magento\Catalog\Plugin\Model\ResourceModel\Config::PRODUCT_LISTING_SORT_BY_ATTRIBUTES_CACHE_ID . $entityTypeId . '_' . $storeId; $this->cache->expects($this->any())->method('load')->with($cacheId)->willReturn(false); + $this->serializer->expects($this->never()) + ->method('unserialize'); + $this->serializer->expects($this->once()) + ->method('serialize') + ->with($attributes) + ->willReturn($serializedAttributes); $this->cache->expects($this->any())->method('save')->with( - serialize($attributes), + $serializedAttributes, $cacheId, [ \Magento\Eav\Model\Cache\Type::CACHE_TAG, @@ -165,7 +192,8 @@ protected function getConfig($cacheEnabledFlag) \Magento\Catalog\Plugin\Model\ResourceModel\Config::class, [ 'cache' => $this->cache, - 'cacheState' => $this->cacheState + 'cacheState' => $this->cacheState, + 'serializer' => $this->serializer, ] ); } diff --git a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Categories.php b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Categories.php index 0e46b5899851f..0ee761646616e 100644 --- a/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Categories.php +++ b/app/code/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/Categories.php @@ -11,6 +11,7 @@ use Magento\Framework\App\CacheInterface; use Magento\Framework\DB\Helper as DbHelper; use Magento\Catalog\Model\Category as CategoryModel; +use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\UrlInterface; use Magento\Framework\Stdlib\ArrayManager; @@ -62,25 +63,33 @@ class Categories extends AbstractModifier */ private $cacheManager; + /** + * @var SerializerInterface + */ + private $serializer; + /** * @param LocatorInterface $locator * @param CategoryCollectionFactory $categoryCollectionFactory * @param DbHelper $dbHelper * @param UrlInterface $urlBuilder * @param ArrayManager $arrayManager + * @param SerializerInterface $serializer */ public function __construct( LocatorInterface $locator, CategoryCollectionFactory $categoryCollectionFactory, DbHelper $dbHelper, UrlInterface $urlBuilder, - ArrayManager $arrayManager + ArrayManager $arrayManager, + SerializerInterface $serializer = null ) { $this->locator = $locator; $this->categoryCollectionFactory = $categoryCollectionFactory; $this->dbHelper = $dbHelper; $this->urlBuilder = $urlBuilder; $this->arrayManager = $arrayManager; + $this->serializer = $serializer ?: ObjectManager::getInstance()->get(SerializerInterface::class); } /** @@ -286,7 +295,7 @@ protected function getCategoriesTree($filter = null) { $categoryTree = $this->getCacheManager()->load(self::CATEGORY_TREE_ID . '_' . $filter); if ($categoryTree) { - return unserialize($categoryTree); + return $this->serializer->unserialize($categoryTree); } $storeId = $this->locator->getStore()->getId(); @@ -340,7 +349,7 @@ protected function getCategoriesTree($filter = null) } $this->getCacheManager()->save( - serialize($categoryById[CategoryModel::TREE_ROOT_ID]['optgroup']), + $this->serializer->serialize($categoryById[CategoryModel::TREE_ROOT_ID]['optgroup']), self::CATEGORY_TREE_ID . '_' . $filter, [ \Magento\Catalog\Model\Category::CACHE_TAG, diff --git a/app/code/Magento/CatalogImportExport/Model/Import/Product/Type/AbstractType.php b/app/code/Magento/CatalogImportExport/Model/Import/Product/Type/AbstractType.php index 0d19b9fcbedc8..ac39cea10cbe3 100644 --- a/app/code/Magento/CatalogImportExport/Model/Import/Product/Type/AbstractType.php +++ b/app/code/Magento/CatalogImportExport/Model/Import/Product/Type/AbstractType.php @@ -8,6 +8,7 @@ use Magento\Framework\App\ResourceConnection; use Magento\CatalogImportExport\Model\Import\Product\RowValidatorInterface; use Magento\CatalogImportExport\Model\Import\Product; +use Magento\Framework\EntityManager\MetadataPool; /** * Import entity abstract product type model @@ -142,22 +143,27 @@ abstract class AbstractType private $productEntityLinkField; /** + * AbstractType constructor + * * @param \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory $attrSetColFac * @param \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory $prodAttrColFac - * @param \Magento\Framework\App\ResourceConnection $resource + * @param ResourceConnection $resource * @param array $params + * @param MetadataPool|null $metadataPool * @throws \Magento\Framework\Exception\LocalizedException */ public function __construct( \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory $attrSetColFac, \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory $prodAttrColFac, \Magento\Framework\App\ResourceConnection $resource, - array $params + array $params, + MetadataPool $metadataPool = null ) { $this->_attrSetColFac = $attrSetColFac; $this->_prodAttrColFac = $prodAttrColFac; $this->_resource = $resource; - $this->_connection = $resource->getConnection(); + $this->connection = $resource->getConnection(); + $this->metadataPool = $metadataPool ?: $this->getMetadataPool(); if ($this->isSuitable()) { if (!isset($params[0]) || !isset($params[1]) @@ -246,8 +252,8 @@ protected function _initAttributes() { // temporary storage for attributes' parameters to avoid double querying inside the loop $entityId = $this->_entityModel->getEntityTypeId(); - $entityAttributes = $this->_connection->fetchAll( - $this->_connection->select()->from( + $entityAttributes = $this->connection->fetchAll( + $this->connection->select()->from( ['attr' => $this->_resource->getTableName('eav_entity_attribute')], ['attr.attribute_id'] )->joinLeft( @@ -255,7 +261,7 @@ protected function _initAttributes() 'set.attribute_set_id = attr.attribute_set_id', ['set.attribute_set_name'] )->where( - $this->_connection->quoteInto('attr.entity_type_id IN (?)', $entityId) + $this->connection->quoteInto('attr.entity_type_id IN (?)', $entityId) ) ); $absentKeys = []; @@ -563,7 +569,7 @@ protected function getMetadataPool() protected function getProductEntityLinkField() { if (!$this->productEntityLinkField) { - $this->productEntityLinkField = $this->getMetadataPool() + $this->productEntityLinkField = $this->metadataPool ->getMetadata(\Magento\Catalog\Api\Data\ProductInterface::class) ->getLinkField(); } diff --git a/app/code/Magento/CatalogRule/Model/Rule.php b/app/code/Magento/CatalogRule/Model/Rule.php index 0da658be4cc21..4e8b95607de4b 100644 --- a/app/code/Magento/CatalogRule/Model/Rule.php +++ b/app/code/Magento/CatalogRule/Model/Rule.php @@ -7,6 +7,8 @@ use Magento\Catalog\Model\Product; use Magento\CatalogRule\Api\Data\RuleInterface; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\ExtensionAttributesFactory; use Magento\Framework\DataObject\IdentityInterface; /** @@ -137,7 +139,8 @@ class Rule extends \Magento\Rule\Model\AbstractModel implements RuleInterface, I protected $ruleConditionConverter; /** - * Rule constructor. + * Rule constructor + * * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry * @param \Magento\Framework\Data\FormFactory $formFactory @@ -157,6 +160,8 @@ class Rule extends \Magento\Rule\Model\AbstractModel implements RuleInterface, I * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection * @param array $relatedCacheTypes * @param array $data + * @param ExtensionAttributesFactory|null $extensionFactory + * @param AttributeValueFactory|null $customAttributeFactory * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ @@ -179,7 +184,9 @@ public function __construct( \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, array $relatedCacheTypes = [], - array $data = [] + array $data = [], + ExtensionAttributesFactory $extensionFactory = null, + AttributeValueFactory $customAttributeFactory = null ) { $this->_productCollectionFactory = $productCollectionFactory; $this->_storeManager = $storeManager; @@ -201,7 +208,9 @@ public function __construct( $localeDate, $resource, $resourceCollection, - $data + $data, + $extensionFactory, + $customAttributeFactory ); } diff --git a/app/code/Magento/CatalogRule/Test/Unit/Model/RuleTest.php b/app/code/Magento/CatalogRule/Test/Unit/Model/RuleTest.php index a624b87ebbe13..b3f35dbe98e0d 100644 --- a/app/code/Magento/CatalogRule/Test/Unit/Model/RuleTest.php +++ b/app/code/Magento/CatalogRule/Test/Unit/Model/RuleTest.php @@ -3,14 +3,9 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ - namespace Magento\CatalogRule\Test\Unit\Model; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - /** - * Class RuleTest - * @package Magento\CatalogRule\Test\Unit\Model * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class RuleTest extends \PHPUnit_Framework_TestCase @@ -18,8 +13,8 @@ class RuleTest extends \PHPUnit_Framework_TestCase /** @var \Magento\CatalogRule\Model\Rule */ protected $rule; - /** @var ObjectManagerHelper */ - protected $objectManagerHelper; + /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + private $objectManager; /** @var \Magento\Store\Model\StoreManagerInterface|\PHPUnit_Framework_MockObject_MockObject */ protected $storeManager; @@ -63,6 +58,7 @@ class RuleTest extends \PHPUnit_Framework_TestCase */ protected function setUp() { + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->storeManager = $this->getMock(\Magento\Store\Model\StoreManagerInterface::class); $this->storeModel = $this->getMock(\Magento\Store\Model\Store::class, ['__wakeup', 'getId'], [], '', false); $this->combineFactory = $this->getMock( @@ -128,20 +124,22 @@ protected function setUp() false ); - $this->objectManagerHelper = new ObjectManagerHelper($this); - - $this->prepareObjectManager([ - [ - \Magento\Framework\Api\ExtensionAttributesFactory::class, - $this->getMock(\Magento\Framework\Api\ExtensionAttributesFactory::class, [], [], '', false) - ], - [ - \Magento\Framework\Api\AttributeValueFactory::class, - $this->getMock(\Magento\Framework\Api\AttributeValueFactory::class, [], [], '', false) - ], - ]); + $extensionFactoryMock = $this->getMock( + \Magento\Framework\Api\ExtensionAttributesFactory::class, + [], + [], + '', + false + ); + $attributeValueFactoryMock = $this->getMock( + \Magento\Framework\Api\AttributeValueFactory::class, + [], + [], + '', + false + ); - $this->rule = $this->objectManagerHelper->getObject( + $this->rule = $this->objectManager->getObject( \Magento\CatalogRule\Model\Rule::class, [ 'storeManager' => $this->storeManager, @@ -149,6 +147,8 @@ protected function setUp() 'ruleProductProcessor' => $this->_ruleProductProcessor, 'productCollectionFactory' => $this->_productCollectionFactory, 'resourceIterator' => $this->_resourceIterator, + 'extensionFactory' => $extensionFactoryMock, + 'customAttributeFactory' => $attributeValueFactoryMock, ] ); } @@ -375,20 +375,4 @@ public function testGetConditionsFieldSetId() $expectedResult = 'form_namerule_conditions_fieldset_100'; $this->assertEquals($expectedResult, $this->rule->getConditionsFieldSetId($formName)); } - - /** - * @param $map - */ - private function prepareObjectManager($map) - { - $objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); - $objectManagerMock->expects($this->any())->method('getInstance')->willReturnSelf(); - $objectManagerMock->expects($this->any()) - ->method('get') - ->will($this->returnValueMap($map)); - $reflectionClass = new \ReflectionClass(\Magento\Framework\App\ObjectManager::class); - $reflectionProperty = $reflectionClass->getProperty('_instance'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($objectManagerMock); - } } diff --git a/app/code/Magento/CatalogSearch/Model/ResourceModel/Advanced/Collection.php b/app/code/Magento/CatalogSearch/Model/ResourceModel/Advanced/Collection.php index a8ada4d409f61..f63e06efc18d5 100644 --- a/app/code/Magento/CatalogSearch/Model/ResourceModel/Advanced/Collection.php +++ b/app/code/Magento/CatalogSearch/Model/ResourceModel/Advanced/Collection.php @@ -9,10 +9,12 @@ use Magento\Framework\Api\FilterBuilder; use Magento\Framework\Api\Search\SearchCriteriaBuilder; use Magento\Framework\Api\Search\SearchResultFactory; +use Magento\Framework\EntityManager\MetadataPool; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Search\Adapter\Mysql\TemporaryStorage; use Magento\Framework\Search\Request\EmptyRequestDataException; use Magento\Framework\Search\Request\NonExistingRequestNameException; +use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory; /** * Collection Advanced @@ -54,7 +56,8 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection private $filterBuilder; /** - * Collection constructor. + * Collection constructor + * * @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory * @param \Psr\Log\LoggerInterface $logger * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy @@ -77,8 +80,11 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection * @param \Magento\CatalogSearch\Model\Advanced\Request\Builder $requestBuilder * @param \Magento\Search\Model\SearchEngine $searchEngine * @param \Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory $temporaryStorageFactory - * @param \Zend_Db_Adapter_Abstract $connection - * @param SearchResultFactory $searchResultFactory + * @param \Magento\Framework\DB\Adapter\AdapterInterface|null $connection + * @param SearchResultFactory|null $searchResultFactory + * @param ProductLimitationFactory|null $productLimitationFactory + * @param MetadataPool|null $metadataPool + * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -104,8 +110,10 @@ public function __construct( \Magento\CatalogSearch\Model\Advanced\Request\Builder $requestBuilder, \Magento\Search\Model\SearchEngine $searchEngine, \Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory $temporaryStorageFactory, - $connection = null, - SearchResultFactory $searchResultFactory = null + \Magento\Framework\DB\Adapter\AdapterInterface $connection = null, + SearchResultFactory $searchResultFactory = null, + ProductLimitationFactory $productLimitationFactory = null, + MetadataPool $metadataPool = null ) { $this->requestBuilder = $requestBuilder; $this->searchEngine = $searchEngine; @@ -134,7 +142,9 @@ public function __construct( $customerSession, $dateTime, $groupManagement, - $connection + $connection, + $productLimitationFactory, + $metadataPool ); } diff --git a/app/code/Magento/CatalogSearch/Model/ResourceModel/Fulltext/Collection.php b/app/code/Magento/CatalogSearch/Model/ResourceModel/Fulltext/Collection.php index 8a9e2b1917407..bc7568a471160 100644 --- a/app/code/Magento/CatalogSearch/Model/ResourceModel/Fulltext/Collection.php +++ b/app/code/Magento/CatalogSearch/Model/ResourceModel/Fulltext/Collection.php @@ -7,6 +7,7 @@ use Magento\CatalogSearch\Model\Search\RequestGenerator; use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\MetadataPool; use Magento\Framework\Exception\StateException; use Magento\Framework\Search\Adapter\Mysql\TemporaryStorage; use Magento\Framework\Search\Response\QueryResponse; @@ -15,6 +16,7 @@ use Magento\Framework\Api\Search\SearchResultFactory; use Magento\Framework\Exception\LocalizedException; use Magento\Framework\App\ObjectManager; +use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory; /** * Fulltext Collection @@ -94,6 +96,8 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection private $filterBuilder; /** + * Collection constructor + * * @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory * @param \Psr\Log\LoggerInterface $logger * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy @@ -117,9 +121,12 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection * @param \Magento\Framework\Search\Request\Builder $requestBuilder * @param \Magento\Search\Model\SearchEngine $searchEngine * @param \Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory $temporaryStorageFactory - * @param \Magento\Framework\DB\Adapter\AdapterInterface $connection + * @param \Magento\Framework\DB\Adapter\AdapterInterface|null $connection * @param string $searchRequestName - * @param SearchResultFactory $searchResultFactory + * @param SearchResultFactory|null $searchResultFactory + * @param ProductLimitationFactory|null $productLimitationFactory + * @param MetadataPool|null $metadataPool + * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -148,7 +155,9 @@ public function __construct( \Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory $temporaryStorageFactory, \Magento\Framework\DB\Adapter\AdapterInterface $connection = null, $searchRequestName = 'catalog_view_container', - SearchResultFactory $searchResultFactory = null + SearchResultFactory $searchResultFactory = null, + ProductLimitationFactory $productLimitationFactory = null, + MetadataPool $metadataPool = null ) { $this->queryFactory = $catalogSearchData; if ($searchResultFactory === null) { @@ -175,7 +184,9 @@ public function __construct( $customerSession, $dateTime, $groupManagement, - $connection + $connection, + $productLimitationFactory, + $metadataPool ); $this->requestBuilder = $requestBuilder; $this->searchEngine = $searchEngine; diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Advanced/CollectionTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Advanced/CollectionTest.php index 96580c6764e93..4b04e7d66ab56 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Advanced/CollectionTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Advanced/CollectionTest.php @@ -7,7 +7,7 @@ use Magento\Catalog\Model\Product; use Magento\CatalogSearch\Test\Unit\Model\ResourceModel\BaseCollectionTest; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory; /** * Tests Magento\CatalogSearch\Model\ResourceModel\Advanced\Collection @@ -16,6 +16,11 @@ */ class CollectionTest extends BaseCollectionTest { + /** + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + */ + private $objectManager; + /** * @var \Magento\CatalogSearch\Model\ResourceModel\Advanced\Collection */ @@ -51,8 +56,7 @@ class CollectionTest extends BaseCollectionTest */ protected function setUp() { - $helper = new ObjectManagerHelper($this); - + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->eavConfig = $this->getMock(\Magento\Eav\Model\Config::class, [], [], '', false); $storeManager = $this->getStoreManager(); $universalFactory = $this->getUniversalFactory(); @@ -67,13 +71,14 @@ protected function setUp() ); $this->search = $this->getMock(\Magento\Search\Api\SearchInterface::class, [], [], '', false); - $this->prepareObjectManager([ - [\Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class, - $this->getMock(\Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class) - ], - ]); + $productLimitationMock = $this->getMock( + \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class + ); + $productLimitationFactoryMock = $this->getMock(ProductLimitationFactory::class, ['create']); + $productLimitationFactoryMock->method('create') + ->willReturn($productLimitationMock); - $this->advancedCollection = $helper->getObject( + $this->advancedCollection = $this->objectManager->getObject( \Magento\CatalogSearch\Model\ResourceModel\Advanced\Collection::class, [ 'eavConfig' => $this->eavConfig, @@ -83,6 +88,7 @@ protected function setUp() 'filterBuilder' => $this->filterBuilder, 'temporaryStorageFactory' => $this->temporaryStorageFactory, 'search' => $this->search, + 'productLimitationFactory' => $productLimitationFactoryMock, ] ); } @@ -150,20 +156,4 @@ protected function getCriteriaBuilder() ->getMock(); return $criteriaBuilder; } - - /** - * @param $map - */ - private function prepareObjectManager($map) - { - $objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); - $objectManagerMock->expects($this->any())->method('getInstance')->willReturnSelf(); - $objectManagerMock->expects($this->any()) - ->method('get') - ->will($this->returnValueMap($map)); - $reflectionClass = new \ReflectionClass(\Magento\Framework\App\ObjectManager::class); - $reflectionProperty = $reflectionClass->getProperty('_instance'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($objectManagerMock); - } } diff --git a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Fulltext/CollectionTest.php b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Fulltext/CollectionTest.php index 84430c56476c0..5e56a25356359 100644 --- a/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Fulltext/CollectionTest.php +++ b/app/code/Magento/CatalogSearch/Test/Unit/Model/ResourceModel/Fulltext/CollectionTest.php @@ -8,12 +8,18 @@ use Magento\CatalogSearch\Test\Unit\Model\ResourceModel\BaseCollectionTest; use Magento\Framework\Search\Adapter\Mysql\TemporaryStorageFactory; use PHPUnit_Framework_MockObject_MockObject as MockObject; +use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class CollectionTest extends BaseCollectionTest { + /** + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + */ + private $objectManager; + /** * @var \Magento\Framework\Search\Adapter\Mysql\TemporaryStorage|\PHPUnit_Framework_MockObject_MockObject */ @@ -64,22 +70,19 @@ class CollectionTest extends BaseCollectionTest */ protected function setUp() { - $helper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->storeManager = $this->getStoreManager(); $this->universalFactory = $this->getUniversalFactory(); $this->scopeConfig = $this->getScopeConfig(); $this->criteriaBuilder = $this->getCriteriaBuilder(); $this->filterBuilder = $this->getFilterBuilder(); - $this->prepareObjectManager( - [ - [ - \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class, - $this->getMock(\Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class) - ], - ] + $productLimitationMock = $this->getMock( + \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class ); + $productLimitationFactoryMock = $this->getMock(ProductLimitationFactory::class, ['create']); + $productLimitationFactoryMock->method('create') + ->willReturn($productLimitationMock); $this->temporaryStorage = $this->getMockBuilder(\Magento\Framework\Search\Adapter\Mysql\TemporaryStorage::class) ->disableOriginalConstructor() @@ -92,13 +95,14 @@ protected function setUp() ->method('create') ->willReturn($this->temporaryStorage); - $this->model = $helper->getObject( + $this->model = $this->objectManager->getObject( \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection::class, [ 'storeManager' => $this->storeManager, 'universalFactory' => $this->universalFactory, 'scopeConfig' => $this->scopeConfig, - 'temporaryStorageFactory' => $temporaryStorageFactory + 'temporaryStorageFactory' => $temporaryStorageFactory, + 'productLimitationFactory' => $productLimitationFactoryMock ] ); @@ -110,6 +114,13 @@ protected function setUp() $this->model->setFilterBuilder($this->filterBuilder); } + protected function tearDown() + { + $reflectionProperty = new \ReflectionProperty(\Magento\Framework\App\ObjectManager::class, '_instance'); + $reflectionProperty->setAccessible(true); + $reflectionProperty->setValue(null); + } + /** * @expectedException \Exception * @expectedExceptionCode 333 @@ -208,22 +219,6 @@ protected function addFiltersToFilterBuilder(MockObject $filterBuilder, array $f return $filterBuilder; } - /** - * @param $map - */ - private function prepareObjectManager($map) - { - $objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); - $objectManagerMock->expects($this->any())->method('getInstance')->willReturnSelf(); - $objectManagerMock->expects($this->any()) - ->method('get') - ->will($this->returnValueMap($map)); - $reflectionClass = new \ReflectionClass(\Magento\Framework\App\ObjectManager::class); - $reflectionProperty = $reflectionClass->getProperty('_instance'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($objectManagerMock); - } - protected function createFilter() { $filter = $this->getMockBuilder(\Magento\Framework\Api\Filter::class) diff --git a/app/code/Magento/CatalogWidget/Model/Rule.php b/app/code/Magento/CatalogWidget/Model/Rule.php index 8258d3f1a8b4f..06bc8cba74dd6 100644 --- a/app/code/Magento/CatalogWidget/Model/Rule.php +++ b/app/code/Magento/CatalogWidget/Model/Rule.php @@ -5,6 +5,8 @@ */ namespace Magento\CatalogWidget\Model; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\ExtensionAttributesFactory; /** * Class Rule @@ -17,6 +19,8 @@ class Rule extends \Magento\Rule\Model\AbstractModel protected $conditionsFactory; /** + * Rule constructor + * * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry * @param \Magento\Framework\Data\FormFactory $formFactory @@ -25,6 +29,9 @@ class Rule extends \Magento\Rule\Model\AbstractModel * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection * @param array $data + * @param ExtensionAttributesFactory|null $extensionFactory + * @param AttributeValueFactory|null $customAttributeFactory + * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -35,7 +42,9 @@ public function __construct( \Magento\CatalogWidget\Model\Rule\Condition\CombineFactory $conditionsFactory, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [] + array $data = [], + ExtensionAttributesFactory $extensionFactory = null, + AttributeValueFactory $customAttributeFactory = null ) { $this->conditionsFactory = $conditionsFactory; parent::__construct( @@ -45,7 +54,9 @@ public function __construct( $localeDate, $resource, $resourceCollection, - $data + $data, + $extensionFactory, + $customAttributeFactory ); } diff --git a/app/code/Magento/CatalogWidget/Test/Unit/Model/RuleTest.php b/app/code/Magento/CatalogWidget/Test/Unit/Model/RuleTest.php index afcc540a37545..a6468cc77a47f 100644 --- a/app/code/Magento/CatalogWidget/Test/Unit/Model/RuleTest.php +++ b/app/code/Magento/CatalogWidget/Test/Unit/Model/RuleTest.php @@ -3,13 +3,15 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ - namespace Magento\CatalogWidget\Test\Unit\Model; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; - class RuleTest extends \PHPUnit_Framework_TestCase { + /** + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + */ + private $objectManager; + /** * @var \Magento\CatalogWidget\Model\Rule */ @@ -22,25 +24,13 @@ class RuleTest extends \PHPUnit_Framework_TestCase protected function setUp() { + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->combineFactory = $this->getMockBuilder(\Magento\CatalogWidget\Model\Rule\Condition\CombineFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $objectManagerHelper = new ObjectManagerHelper($this); - - $this->prepareObjectManager([ - [ - \Magento\Framework\Api\ExtensionAttributesFactory::class, - $this->getMock(\Magento\Framework\Api\ExtensionAttributesFactory::class, [], [], '', false) - ], - [ - \Magento\Framework\Api\AttributeValueFactory::class, - $this->getMock(\Magento\Framework\Api\AttributeValueFactory::class, [], [], '', false) - ], - ]); - - $this->rule = $objectManagerHelper->getObject( + $this->rule = $this->objectManager->getObject( \Magento\CatalogWidget\Model\Rule::class, [ 'conditionsFactory' => $this->combineFactory @@ -62,20 +52,4 @@ public function testGetActionsInstance() { $this->assertNull($this->rule->getActionsInstance()); } - - /** - * @param $map - */ - private function prepareObjectManager($map) - { - $objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); - $objectManagerMock->expects($this->any())->method('getInstance')->willReturnSelf(); - $objectManagerMock->expects($this->any()) - ->method('get') - ->will($this->returnValueMap($map)); - $reflectionClass = new \ReflectionClass(\Magento\Framework\App\ObjectManager::class); - $reflectionProperty = $reflectionClass->getProperty('_instance'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($objectManagerMock); - } } diff --git a/app/code/Magento/Checkout/Test/Unit/Model/ShippingInformationManagementTest.php b/app/code/Magento/Checkout/Test/Unit/Model/ShippingInformationManagementTest.php index 04d347ec237a9..402a0c8228356 100644 --- a/app/code/Magento/Checkout/Test/Unit/Model/ShippingInformationManagementTest.php +++ b/app/code/Magento/Checkout/Test/Unit/Model/ShippingInformationManagementTest.php @@ -11,6 +11,11 @@ */ class ShippingInformationManagementTest extends \PHPUnit_Framework_TestCase { + /** + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + */ + private $objectManager; + /** * @var \PHPUnit_Framework_MockObject_MockObject */ @@ -31,26 +36,6 @@ class ShippingInformationManagementTest extends \PHPUnit_Framework_TestCase */ protected $quoteRepositoryMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $addressValidatorMock; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $loggerMock; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $addressRepositoryMock; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $scopeConfigMock; - /** * @var \PHPUnit_Framework_MockObject_MockObject */ @@ -61,11 +46,6 @@ class ShippingInformationManagementTest extends \PHPUnit_Framework_TestCase */ protected $quoteMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $totalsCollectorMock; - /** * @var \Magento\Checkout\Model\ShippingInformationManagement */ @@ -103,6 +83,7 @@ class ShippingInformationManagementTest extends \PHPUnit_Framework_TestCase protected function setUp() { + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->paymentMethodManagementMock = $this->getMock(\Magento\Quote\Api\PaymentMethodManagementInterface::class); $this->paymentDetailsFactoryMock = $this->getMock( \Magento\Checkout\Model\PaymentDetailsFactory::class, @@ -113,18 +94,6 @@ protected function setUp() ); $this->cartTotalsRepositoryMock = $this->getMock(\Magento\Quote\Api\CartTotalRepositoryInterface::class); $this->quoteRepositoryMock = $this->getMock(\Magento\Quote\Api\CartRepositoryInterface::class); - $this->addressValidatorMock = $this->getMock( - \Magento\Quote\Model\QuoteAddressValidator::class, - [], - [], - '', - false - ); - $this->loggerMock = $this->getMock(\Psr\Log\LoggerInterface::class); - $this->addressRepositoryMock = $this->getMock(\Magento\Customer\Api\AddressRepositoryInterface::class); - $this->scopeConfigMock = $this->getMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->totalsCollectorMock = - $this->getMock(\Magento\Quote\Model\Quote\TotalsCollector::class, [], [], '', false); $this->shippingAddressMock = $this->getMock( \Magento\Quote\Model\Quote\Address::class, [ @@ -175,22 +144,29 @@ protected function setUp() $this->shippingFactoryMock = $this->getMock(\Magento\Quote\Model\ShippingFactory::class, ['create'], [], '', false); - $this->prepareObjectManager([ - [\Magento\Quote\Model\ShippingAssignmentFactory::class, $this->shippingAssignmentFactoryMock], - [\Magento\Quote\Api\Data\CartExtensionFactory::class, $this->cartExtensionFactoryMock], - [\Magento\Quote\Model\ShippingFactory::class, $this->shippingFactoryMock], - ]); - - $this->model = new \Magento\Checkout\Model\ShippingInformationManagement( - $this->paymentMethodManagementMock, - $this->paymentDetailsFactoryMock, - $this->cartTotalsRepositoryMock, - $this->quoteRepositoryMock, - $this->addressValidatorMock, - $this->loggerMock, - $this->addressRepositoryMock, - $this->scopeConfigMock, - $this->totalsCollectorMock + $this->model = $this->objectManager->getObject( + \Magento\Checkout\Model\ShippingInformationManagement::class, + [ + 'paymentMethodManagement' => $this->paymentMethodManagementMock, + 'paymentDetailsFactory' => $this->paymentDetailsFactoryMock, + 'cartTotalsRepository' => $this->cartTotalsRepositoryMock, + 'quoteRepository' => $this->quoteRepositoryMock, + ] + ); + $this->objectManager->setBackwardCompatibleProperty( + $this->model, + 'shippingAssignmentFactory', + $this->shippingAssignmentFactoryMock + ); + $this->objectManager->setBackwardCompatibleProperty( + $this->model, + 'cartExtensionFactory', + $this->cartExtensionFactoryMock + ); + $this->objectManager->setBackwardCompatibleProperty( + $this->model, + 'shippingFactory', + $this->shippingFactoryMock ); } @@ -457,20 +433,4 @@ public function testSaveAddressInformation() $this->model->saveAddressInformation($cartId, $addressInformationMock) ); } - - /** - * @param array $map - */ - private function prepareObjectManager($map) - { - $objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); - $objectManagerMock->expects($this->any())->method('getInstance')->willReturnSelf(); - $objectManagerMock->expects($this->any()) - ->method('get') - ->will($this->returnValueMap($map)); - $reflectionClass = new \ReflectionClass(\Magento\Framework\App\ObjectManager::class); - $reflectionProperty = $reflectionClass->getProperty('_instance'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($objectManagerMock); - } } diff --git a/app/code/Magento/Config/Model/Config/Structure/Data.php b/app/code/Magento/Config/Model/Config/Structure/Data.php index 414addf5b6f06..6c926e7c1da1a 100644 --- a/app/code/Magento/Config/Model/Config/Structure/Data.php +++ b/app/code/Magento/Config/Model/Config/Structure/Data.php @@ -5,21 +5,30 @@ */ namespace Magento\Config\Model\Config\Structure; +use Magento\Framework\Serialize\SerializerInterface; + +/** + * Provides configuration + */ class Data extends \Magento\Framework\Config\Data\Scoped { /** + * Constructor + * * @param Reader $reader * @param \Magento\Framework\Config\ScopeInterface $configScope * @param \Magento\Framework\Config\CacheInterface $cache * @param string $cacheId + * @param SerializerInterface|null $serializer */ public function __construct( Reader $reader, \Magento\Framework\Config\ScopeInterface $configScope, \Magento\Framework\Config\CacheInterface $cache, - $cacheId + $cacheId, + SerializerInterface $serializer = null ) { - parent::__construct($reader, $configScope, $cache, $cacheId); + parent::__construct($reader, $configScope, $cache, $cacheId, $serializer); } /** diff --git a/app/code/Magento/ConfigurableImportExport/Model/Import/Product/Type/Configurable.php b/app/code/Magento/ConfigurableImportExport/Model/Import/Product/Type/Configurable.php index 29e670e9f7f4f..9eedf22fbc1ae 100644 --- a/app/code/Magento/ConfigurableImportExport/Model/Import/Product/Type/Configurable.php +++ b/app/code/Magento/ConfigurableImportExport/Model/Import/Product/Type/Configurable.php @@ -12,6 +12,7 @@ use Magento\Catalog\Api\Data\ProductInterface; use Magento\CatalogImportExport\Model\Import\Product as ImportProduct; +use Magento\Framework\EntityManager\MetadataPool; /** * Importing configurable products @@ -140,6 +141,7 @@ class Configurable extends \Magento\CatalogImportExport\Model\Import\Product\Typ * Instance of database adapter. * * @var \Magento\Framework\DB\Adapter\AdapterInterface + * @deprecated */ protected $_connection; @@ -200,6 +202,7 @@ class Configurable extends \Magento\CatalogImportExport\Model\Import\Product\Typ * @param \Magento\Catalog\Model\ProductTypes\ConfigInterface $productTypesConfig * @param \Magento\ImportExport\Model\ResourceModel\Helper $resourceHelper * @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $_productColFac + * @param MetadataPool $metadataPool */ public function __construct( \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory $attrSetColFac, @@ -208,12 +211,12 @@ public function __construct( array $params, \Magento\Catalog\Model\ProductTypes\ConfigInterface $productTypesConfig, \Magento\ImportExport\Model\ResourceModel\Helper $resourceHelper, - \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $_productColFac + \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $_productColFac, + MetadataPool $metadataPool = null ) { - parent::__construct($attrSetColFac, $prodAttrColFac, $resource, $params); + parent::__construct($attrSetColFac, $prodAttrColFac, $resource, $params, $metadataPool); $this->_productTypesConfig = $productTypesConfig; $this->_resourceHelper = $resourceHelper; - $this->_resource = $resource; $this->_productColFac = $_productColFac; $this->_connection = $this->_entityModel->getConnection(); } @@ -379,14 +382,14 @@ protected function _loadSkuSuperDataForBunch(array $bunch) if (!empty($productIds)) { $mainTable = $this->_resource->getTableName('catalog_product_super_attribute'); $optionTable = $this->_resource->getTableName('eav_attribute_option'); - $select = $this->_connection->select()->from( + $select = $this->connection->select()->from( ['m' => $mainTable], ['product_id', 'attribute_id', 'product_super_attribute_id'] )->joinLeft( ['o' => $optionTable], - $this->_connection->quoteIdentifier( + $this->connection->quoteIdentifier( 'o.attribute_id' - ) . ' = ' . $this->_connection->quoteIdentifier( + ) . ' = ' . $this->connection->quoteIdentifier( 'o.attribute_id' ), ['option_id'] @@ -395,7 +398,7 @@ protected function _loadSkuSuperDataForBunch(array $bunch) $productIds ); - foreach ($this->_connection->fetchAll($select) as $row) { + foreach ($this->connection->fetchAll($select) as $row) { $attrId = $row['attribute_id']; $productId = $row['product_id']; if ($row['option_id']) { @@ -448,8 +451,8 @@ protected function _processSuperData() 'product_id' => $this->_productSuperData['assoc_entity_ids'][$assocId], 'parent_id' => $this->_productSuperData['product_id'], ]; - $subEntityId = $this->_connection->fetchOne( - $this->_connection->select()->from( + $subEntityId = $this->connection->fetchOne( + $this->connection->select()->from( ['cpe' => $this->_resource->getTableName('catalog_product_entity')], ['entity_id'] )->where($metadata->getLinkField() . ' = ?', $assocId) ); @@ -557,10 +560,10 @@ protected function _deleteData() && !empty($this->_productSuperData['product_id']) && !empty($this->_simpleIdsToDelete) ) { - $quoted = $this->_connection->quoteInto('IN (?)', [$this->_productSuperData['product_id']]); - $quotedChildren = $this->_connection->quoteInto('IN (?)', $this->_simpleIdsToDelete); - $this->_connection->delete($linkTable, "parent_id {$quoted} AND product_id {$quotedChildren}"); - $this->_connection->delete($relationTable, "parent_id {$quoted} AND child_id {$quotedChildren}"); + $quoted = $this->connection->quoteInto('IN (?)', [$this->_productSuperData['product_id']]); + $quotedChildren = $this->connection->quoteInto('IN (?)', $this->_simpleIdsToDelete); + $this->connection->delete($linkTable, "parent_id {$quoted} AND product_id {$quotedChildren}"); + $this->connection->delete($relationTable, "parent_id {$quoted} AND child_id {$quotedChildren}"); } return $this; } @@ -587,16 +590,16 @@ protected function _insertData() } } if ($mainData) { - $this->_connection->insertOnDuplicate($mainTable, $mainData); + $this->connection->insertOnDuplicate($mainTable, $mainData); } if ($this->_superAttributesData['labels']) { - $this->_connection->insertOnDuplicate($labelTable, $this->_superAttributesData['labels']); + $this->connection->insertOnDuplicate($labelTable, $this->_superAttributesData['labels']); } if ($this->_superAttributesData['super_link']) { - $this->_connection->insertOnDuplicate($linkTable, $this->_superAttributesData['super_link']); + $this->connection->insertOnDuplicate($linkTable, $this->_superAttributesData['super_link']); } if ($this->_superAttributesData['relation']) { - $this->_connection->insertOnDuplicate($relationTable, $this->_superAttributesData['relation']); + $this->connection->insertOnDuplicate($relationTable, $this->_superAttributesData['relation']); } return $this; } diff --git a/app/code/Magento/ConfigurableImportExport/Test/Unit/Model/Import/Product/Type/ConfigurableTest.php b/app/code/Magento/ConfigurableImportExport/Test/Unit/Model/Import/Product/Type/ConfigurableTest.php index 8ce7489db932e..4cc4e6648a0ef 100644 --- a/app/code/Magento/ConfigurableImportExport/Test/Unit/Model/Import/Product/Type/ConfigurableTest.php +++ b/app/code/Magento/ConfigurableImportExport/Test/Unit/Model/Import/Product/Type/ConfigurableTest.php @@ -312,15 +312,10 @@ protected function setUp() 'prodAttrColFac' => $this->attrCollectionFactory, 'params' => $this->params, 'resource' => $this->resource, - 'productColFac' => $this->productCollectionFactory + 'productColFac' => $this->productCollectionFactory, + 'metadataPool' => $metadataPoolMock, ] ); - $reflection = new \ReflectionClass( - \Magento\ConfigurableImportExport\Model\Import\Product\Type\Configurable::class - ); - $reflectionProperty = $reflection->getProperty('metadataPool'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($this->configurable, $metadataPoolMock); } /** diff --git a/app/code/Magento/ConfigurableProduct/Model/ResourceModel/Product/Type/Configurable/Product/Collection.php b/app/code/Magento/ConfigurableProduct/Model/ResourceModel/Product/Type/Configurable/Product/Collection.php index 5216f13355970..44a4d468cd097 100644 --- a/app/code/Magento/ConfigurableProduct/Model/ResourceModel/Product/Type/Configurable/Product/Collection.php +++ b/app/code/Magento/ConfigurableProduct/Model/ResourceModel/Product/Type/Configurable/Product/Collection.php @@ -7,10 +7,6 @@ */ namespace Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Product; -use Magento\Customer\Api\GroupManagementInterface; -use Magento\Framework\EntityManager\MetadataPool; -use Magento\Catalog\Api\Data\ProductInterface; - /** * Class Collection * @@ -25,84 +21,6 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection */ protected $_linkTable; - /** - * @var MetadataPool - */ - private $metadataPool; - - /** - * @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory - * @param \Psr\Log\LoggerInterface $logger - * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy - * @param \Magento\Framework\Event\ManagerInterface $eventManager - * @param \Magento\Eav\Model\Config $eavConfig - * @param \Magento\Framework\App\ResourceConnection $resource - * @param \Magento\Eav\Model\EntityFactory $eavEntityFactory - * @param \Magento\Catalog\Model\ResourceModel\Helper $resourceHelper - * @param \Magento\Framework\Validator\UniversalFactory $universalFactory - * @param \Magento\Store\Model\StoreManagerInterface $storeManager - * @param \Magento\Framework\Module\Manager $moduleManager - * @param \Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState - * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig - * @param \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory - * @param \Magento\Catalog\Model\ResourceModel\Url $catalogUrl - * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate - * @param \Magento\Customer\Model\Session $customerSession - * @param \Magento\Framework\Stdlib\DateTime $dateTime - * @param GroupManagementInterface $groupManagement - * @param MetadataPool $metadataPool - * @param \Magento\Framework\DB\Adapter\AdapterInterface|null $connection - * - * @SuppressWarnings(PHPMD.ExcessiveParameterList) - */ - public function __construct( - \Magento\Framework\Data\Collection\EntityFactory $entityFactory, - \Psr\Log\LoggerInterface $logger, - \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy, - \Magento\Framework\Event\ManagerInterface $eventManager, - \Magento\Eav\Model\Config $eavConfig, - \Magento\Framework\App\ResourceConnection $resource, - \Magento\Eav\Model\EntityFactory $eavEntityFactory, - \Magento\Catalog\Model\ResourceModel\Helper $resourceHelper, - \Magento\Framework\Validator\UniversalFactory $universalFactory, - \Magento\Store\Model\StoreManagerInterface $storeManager, - \Magento\Framework\Module\Manager $moduleManager, - \Magento\Catalog\Model\Indexer\Product\Flat\State $catalogProductFlatState, - \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, - \Magento\Catalog\Model\Product\OptionFactory $productOptionFactory, - \Magento\Catalog\Model\ResourceModel\Url $catalogUrl, - \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate, - \Magento\Customer\Model\Session $customerSession, - \Magento\Framework\Stdlib\DateTime $dateTime, - GroupManagementInterface $groupManagement, - MetadataPool $metadataPool, - \Magento\Framework\DB\Adapter\AdapterInterface $connection = null - ) { - $this->metadataPool = $metadataPool; - parent::__construct( - $entityFactory, - $logger, - $fetchStrategy, - $eventManager, - $eavConfig, - $resource, - $eavEntityFactory, - $resourceHelper, - $universalFactory, - $storeManager, - $moduleManager, - $catalogProductFlatState, - $scopeConfig, - $productOptionFactory, - $catalogUrl, - $localeDate, - $customerSession, - $dateTime, - $groupManagement, - $connection - ); - } - /** * Assign link table name * @@ -139,7 +57,7 @@ protected function _initSelect() */ public function setProductFilter($product) { - $metadata = $this->metadataPool->getMetadata(ProductInterface::class); + $metadata = $this->getProductEntityMetadata(); $this->getSelect()->where('link_table.parent_id = ?', $product->getData($metadata->getLinkField())); return $this; diff --git a/app/code/Magento/Cron/Model/Config/Data.php b/app/code/Magento/Cron/Model/Config/Data.php index d09b830d1b539..bcfaef37ece7b 100644 --- a/app/code/Magento/Cron/Model/Config/Data.php +++ b/app/code/Magento/Cron/Model/Config/Data.php @@ -3,29 +3,32 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ +namespace Magento\Cron\Model\Config; + +use Magento\Framework\Serialize\SerializerInterface; /** - * Prepare cron jobs data + * Provides cron configuration */ -namespace Magento\Cron\Model\Config; - class Data extends \Magento\Framework\Config\Data { /** - * Initialize parameters + * Constructor * - * @param \Magento\Cron\Model\Config\Reader\Xml $reader - * @param \Magento\Framework\Config\CacheInterface $cache - * @param \Magento\Cron\Model\Config\Reader\Db $dbReader - * @param string $cacheId + * @param Reader\Xml $reader + * @param \Magento\Framework\Config\CacheInterface $cache + * @param Reader\Db $dbReader + * @param string|null $cacheId + * @param SerializerInterface|null $serializer */ public function __construct( \Magento\Cron\Model\Config\Reader\Xml $reader, \Magento\Framework\Config\CacheInterface $cache, \Magento\Cron\Model\Config\Reader\Db $dbReader, - $cacheId = 'crontab_config_cache' + $cacheId = 'crontab_config_cache', + SerializerInterface $serializer = null ) { - parent::__construct($reader, $cache, $cacheId); + parent::__construct($reader, $cache, $cacheId, $serializer); $this->merge($dbReader->get()); } diff --git a/app/code/Magento/Cron/Model/Groups/Config/Data.php b/app/code/Magento/Cron/Model/Groups/Config/Data.php index 29b70b90195bc..82c35abff22b0 100644 --- a/app/code/Magento/Cron/Model/Groups/Config/Data.php +++ b/app/code/Magento/Cron/Model/Groups/Config/Data.php @@ -3,25 +3,30 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ +namespace Magento\Cron\Model\Groups\Config; + +use Magento\Framework\Serialize\SerializerInterface; /** - * Prepare cron jobs data + * Provides cron groups configuration */ -namespace Magento\Cron\Model\Groups\Config; - class Data extends \Magento\Framework\Config\Data { /** + * Constructor + * * @param \Magento\Cron\Model\Groups\Config\Reader\Xml $reader * @param \Magento\Framework\Config\CacheInterface $cache - * @param string $cacheId + * @param string|null $cacheId + * @param SerializerInterface|null $serializer */ public function __construct( \Magento\Cron\Model\Groups\Config\Reader\Xml $reader, \Magento\Framework\Config\CacheInterface $cache, - $cacheId = 'cron_groups_config_cache' + $cacheId = 'cron_groups_config_cache', + SerializerInterface $serializer = null ) { - parent::__construct($reader, $cache, $cacheId); + parent::__construct($reader, $cache, $cacheId, $serializer); } /** diff --git a/app/code/Magento/Cron/Test/Unit/Model/Config/DataTest.php b/app/code/Magento/Cron/Test/Unit/Model/Config/DataTest.php index 1803deb002f6d..e25fdfe71d2d1 100644 --- a/app/code/Magento/Cron/Test/Unit/Model/Config/DataTest.php +++ b/app/code/Magento/Cron/Test/Unit/Model/Config/DataTest.php @@ -30,19 +30,18 @@ public function testGetJobs() 'job2' => ['schedule' => '* * * * *', 'instance' => 'JobModel2', 'method' => 'method2'], ]; - $cache->expects( - $this->any() - )->method( - 'load' - )->with( - $this->equalTo('test_cache_id') - )->will( - $this->returnValue(serialize($jobs)) - ); + $cache->expects($this->any()) + ->method('load') + ->with('test_cache_id') + ->willReturn(json_encode($jobs)); $dbReader->expects($this->once())->method('get')->will($this->returnValue($dbReaderData)); - $configData = new \Magento\Cron\Model\Config\Data($reader, $cache, $dbReader, 'test_cache_id'); + $serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); + $serializerMock->method('unserialize') + ->willReturn($jobs); + + $configData = new \Magento\Cron\Model\Config\Data($reader, $cache, $dbReader, 'test_cache_id', $serializerMock); $expected = [ 'job1' => ['schedule' => '* * * * *', 'instance' => 'JobModel1', 'method' => 'method1'], diff --git a/app/code/Magento/Customer/Model/Address/Config.php b/app/code/Magento/Customer/Model/Address/Config.php index cd76fd253f499..18a043bc019bb 100644 --- a/app/code/Magento/Customer/Model/Address/Config.php +++ b/app/code/Magento/Customer/Model/Address/Config.php @@ -7,12 +7,11 @@ use Magento\Framework\Config\Data as ConfigData; use Magento\Framework\DataObject; +use Magento\Framework\Serialize\SerializerInterface; use Magento\Store\Model\ScopeInterface; /** - * Customer address config - * - * @author Magento Core Team + * Customer address configuration */ class Config extends ConfigData { @@ -23,7 +22,7 @@ class Config extends ConfigData const DEFAULT_ADDRESS_FORMAT = 'oneline'; /** - * Customer Address Templates per store + * Customer address templates per store * * @var array */ @@ -37,8 +36,7 @@ class Config extends ConfigData protected $_store = null; /** - * Default types per store - * Using for invalid code + * Default types per store, used for invalid code * * @var array */ @@ -60,12 +58,15 @@ class Config extends ConfigData protected $_scopeConfig; /** - * @param \Magento\Customer\Model\Address\Config\Reader $reader + * Constructor + * + * @param Config\Reader $reader * @param \Magento\Framework\Config\CacheInterface $cache * @param \Magento\Store\Model\StoreManagerInterface $storeManager * @param \Magento\Customer\Helper\Address $addressHelper * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig - * @param string $cacheId + * @param string|null $cacheId + * @param SerializerInterface|null $serializer */ public function __construct( \Magento\Customer\Model\Address\Config\Reader $reader, @@ -73,9 +74,10 @@ public function __construct( \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Customer\Helper\Address $addressHelper, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, - $cacheId = 'address_format' + $cacheId = 'address_format', + SerializerInterface $serializer = null ) { - parent::__construct($reader, $cache, $cacheId); + parent::__construct($reader, $cache, $cacheId, $serializer); $this->_storeManager = $storeManager; $this->_addressHelper = $addressHelper; $this->_scopeConfig = $scopeConfig; diff --git a/app/code/Magento/Customer/Model/Customer/NotificationStorage.php b/app/code/Magento/Customer/Model/Customer/NotificationStorage.php index 93cb2e24d40f3..67ee60971d98a 100644 --- a/app/code/Magento/Customer/Model/Customer/NotificationStorage.php +++ b/app/code/Magento/Customer/Model/Customer/NotificationStorage.php @@ -6,6 +6,7 @@ namespace Magento\Customer\Model\Customer; use Magento\Framework\Cache\FrontendInterface; +use Magento\Framework\Serialize\SerializerInterface; class NotificationStorage { @@ -19,6 +20,16 @@ class NotificationStorage /** * @param FrontendInterface $cache */ + + /** + * @var SerializerInterface + */ + private $serializer; + + /** + * NotificationStorage constructor. + * @param FrontendInterface $cache + */ public function __construct(FrontendInterface $cache) { $this->cache = $cache; @@ -34,7 +45,7 @@ public function __construct(FrontendInterface $cache) public function add($notificationType, $customerId) { $this->cache->save( - serialize([ + $this->getSerializer()->serialize([ 'customer_id' => $customerId, 'notification_type' => $notificationType ]), @@ -77,4 +88,19 @@ private function getCacheKey($notificationType, $customerId) { return 'notification_' . $notificationType . '_' . $customerId; } + + /** + * Get serializer + * + * @return SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if ($this->serializer === null) { + $this->serializer = \Magento\Framework\App\ObjectManager::getInstance() + ->get(SerializerInterface::class); + } + return $this->serializer; + } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Address/ConfigTest.php b/app/code/Magento/Customer/Test/Unit/Model/Address/ConfigTest.php index 5c2aeec636cec..2b4a93084c7ac 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Address/ConfigTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Address/ConfigTest.php @@ -10,122 +10,110 @@ class ConfigTest extends \PHPUnit_Framework_TestCase /** * @var \PHPUnit_Framework_MockObject_MockObject */ - protected $_readerMock; + protected $addressHelperMock; /** * @var \PHPUnit_Framework_MockObject_MockObject */ - protected $_cacheMock; + protected $storeMock; /** * @var \PHPUnit_Framework_MockObject_MockObject */ - protected $_storeManagerMock; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $_addressHelperMock; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $_storeMock; - - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - protected $_scopeConfigMock; + protected $scopeConfigMock; /** * @var \Magento\Customer\Model\Address\Config */ - protected $_model; - - /** - * @var string - */ - protected $_cacheId = 'cache_id'; + protected $model; protected function setUp() { - $this->_storeMock = $this->getMock(\Magento\Store\Model\Store::class, [], [], '', false); - $this->_scopeConfigMock = $this->getMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); + $cacheId = 'cache_id'; + $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->storeMock = $this->getMock(\Magento\Store\Model\Store::class, [], [], '', false); + $this->scopeConfigMock = $this->getMock(\Magento\Framework\App\Config\ScopeConfigInterface::class); - $this->_readerMock = $this->getMock( + $readerMock = $this->getMock( \Magento\Customer\Model\Address\Config\Reader::class, [], [], '', false ); - $this->_cacheMock = $this->getMock(\Magento\Framework\Config\CacheInterface::class); - $this->_storeManagerMock = $this->getMock(\Magento\Store\Model\StoreManager::class, [], [], '', false); - $this->_storeManagerMock->expects( + $cacheMock = $this->getMock(\Magento\Framework\Config\CacheInterface::class); + $storeManagerMock = $this->getMock(\Magento\Store\Model\StoreManager::class, [], [], '', false); + $storeManagerMock->expects( $this->once() )->method( 'getStore' )->will( - $this->returnValue($this->_storeMock) + $this->returnValue($this->storeMock) ); - $this->_addressHelperMock = $this->getMock(\Magento\Customer\Helper\Address::class, [], [], '', false); + $this->addressHelperMock = $this->getMock(\Magento\Customer\Helper\Address::class, [], [], '', false); - $this->_cacheMock->expects( + $cacheMock->expects( $this->once() )->method( 'load' )->with( - $this->_cacheId + $cacheId )->will( $this->returnValue(false) ); $fixtureConfigData = require __DIR__ . '/Config/_files/formats_merged.php'; - $this->_readerMock->expects($this->once())->method('read')->will($this->returnValue($fixtureConfigData)); - - $this->_cacheMock->expects( - $this->once() - )->method( - 'save' - )->with( - serialize($fixtureConfigData), - $this->_cacheId - ); - - $this->_model = new \Magento\Customer\Model\Address\Config( - $this->_readerMock, - $this->_cacheMock, - $this->_storeManagerMock, - $this->_addressHelperMock, - $this->_scopeConfigMock, - $this->_cacheId + $readerMock->expects($this->once())->method('read')->will($this->returnValue($fixtureConfigData)); + + $cacheMock->expects($this->once()) + ->method('save') + ->with( + json_encode($fixtureConfigData), + $cacheId + ); + + $serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); + $serializerMock->method('serialize') + ->willReturn(json_encode($fixtureConfigData)); + $serializerMock->method('unserialize') + ->willReturn($fixtureConfigData); + + $this->model = $objectManagerHelper->getObject( + \Magento\Customer\Model\Address\Config::class, + [ + 'reader' => $readerMock, + 'cache' => $cacheMock, + 'storeManager' => $storeManagerMock, + 'scopeConfig' => $this->scopeConfigMock, + 'cacheId' => $cacheId, + 'serializer' => $serializerMock, + 'addressHelper' => $this->addressHelperMock, + ] ); } public function testGetStore() { - $this->assertEquals($this->_storeMock, $this->_model->getStore()); + $this->assertEquals($this->storeMock, $this->model->getStore()); } public function testSetStore() { - $this->_model->setStore($this->_storeMock); - - //no call to $_storeManagerMock's method - $this->assertEquals($this->_storeMock, $this->_model->getStore()); + $this->model->setStore($this->storeMock); + $this->assertEquals($this->storeMock, $this->model->getStore()); } public function testGetFormats() { - $this->_storeMock->expects($this->once())->method('getId'); + $this->storeMock->expects($this->once())->method('getId'); - $this->_scopeConfigMock->expects($this->any())->method('getValue')->will($this->returnValue('someValue')); + $this->scopeConfigMock->expects($this->any())->method('getValue')->will($this->returnValue('someValue')); $rendererMock = $this->getMock(\Magento\Framework\DataObject::class); - $this->_addressHelperMock->expects( + $this->addressHelperMock->expects( $this->any() )->method( 'getRenderer' @@ -160,6 +148,6 @@ public function testGetFormats() ); $expectedResult = [$firstExpected, $secondExpected]; - $this->assertEquals($expectedResult, $this->_model->getFormats()); + $this->assertEquals($expectedResult, $this->model->getFormats()); } } diff --git a/app/code/Magento/Customer/Test/Unit/Model/Customer/NotificationStorageTest.php b/app/code/Magento/Customer/Test/Unit/Model/Customer/NotificationStorageTest.php index 0d2b32f747a80..644d0a2d70122 100644 --- a/app/code/Magento/Customer/Test/Unit/Model/Customer/NotificationStorageTest.php +++ b/app/code/Magento/Customer/Test/Unit/Model/Customer/NotificationStorageTest.php @@ -7,81 +7,87 @@ use Magento\Customer\Model\Customer\NotificationStorage; -/** - * Class NotificationStorageTest - * - * Test for class \Magento\Customer\Model\Customer\NotificationStorage - */ class NotificationStorageTest extends \PHPUnit_Framework_TestCase { /** - * @var NotificationStorage|\PHPUnit_Framework_MockObject_MockObject + * @var NotificationStorage */ - protected $model; + private $notificationStorage; /** * @var \Magento\Framework\Cache\FrontendInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $cache; + private $cacheMock; /** - * Set up - * - * @return void + * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject */ + private $serializerMock; + protected function setUp() { - $this->cache = $this->getMockBuilder(\Magento\Framework\Cache\FrontendInterface::class) - ->getMockForAbstractClass(); - $this->model = new NotificationStorage($this->cache); + $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->cacheMock = $this->getMock(\Magento\Framework\Cache\FrontendInterface::class); + $this->notificationStorage = $objectManager->getObject( + NotificationStorage::class, + ['cache' => $this->cacheMock] + ); + $this->serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); + $objectManager->setBackwardCompatibleProperty($this->notificationStorage, 'serializer', $this->serializerMock); } public function testAdd() { $customerId = 1; $notificationType = 'some_type'; - $this->cache->expects($this->once()) + $data = [ + 'customer_id' => $customerId, + 'notification_type' => $notificationType + ]; + $serializedData = 'serialized data'; + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->with($data) + ->willReturn($serializedData); + $this->cacheMock->expects($this->once()) ->method('save') ->with( - serialize([ - 'customer_id' => $customerId, - 'notification_type' => $notificationType - ]), + $serializedData, $this->getCacheKey($notificationType, $customerId) ); - $this->model->add($notificationType, $customerId); + $this->notificationStorage->add($notificationType, $customerId); } public function testIsExists() { $customerId = 1; $notificationType = 'some_type'; - $this->cache->expects($this->once()) + $this->cacheMock->expects($this->once()) ->method('test') ->with($this->getCacheKey($notificationType, $customerId)) ->willReturn(true); - $this->assertTrue($this->model->isExists($notificationType, $customerId)); + $this->assertTrue($this->notificationStorage->isExists($notificationType, $customerId)); } public function testRemove() { $customerId = 1; $notificationType = 'some_type'; - $this->cache->expects($this->once()) + $this->cacheMock->expects($this->once()) ->method('remove') ->with($this->getCacheKey($notificationType, $customerId)); - $this->model->remove($notificationType, $customerId); + $this->notificationStorage->remove($notificationType, $customerId); } /** - * Retrieve cache key + * Get cache key * * @param string $notificationType * @param string $customerId * @return string */ - protected function getCacheKey($notificationType, $customerId) + private function getCacheKey($notificationType, $customerId) { return 'notification_' . $notificationType . '_' . $customerId; } diff --git a/app/code/Magento/Directory/Block/Data.php b/app/code/Magento/Directory/Block/Data.php index 627e34d9ff404..3c8b682d1a1e8 100644 --- a/app/code/Magento/Directory/Block/Data.php +++ b/app/code/Magento/Directory/Block/Data.php @@ -5,6 +5,9 @@ */ namespace Magento\Directory\Block; +/** + * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + */ class Data extends \Magento\Framework\View\Element\Template { /** @@ -32,6 +35,11 @@ class Data extends \Magento\Framework\View\Element\Template */ protected $directoryHelper; + /** + * @var \Magento\Framework\Serialize\SerializerInterface + */ + private $serializer; + /** * @param \Magento\Framework\View\Element\Template\Context $context * @param \Magento\Directory\Helper\Data $directoryHelper @@ -110,12 +118,12 @@ public function getCountryHtmlSelect($defValue = null, $name = 'country_id', $id $cacheKey = 'DIRECTORY_COUNTRY_SELECT_STORE_' . $this->_storeManager->getStore()->getCode(); $cache = $this->_configCacheType->load($cacheKey); if ($cache) { - $options = unserialize($cache); + $options = $this->getSerializer()->unserialize($cache); } else { $options = $this->getCountryCollection() ->setForegroundCountries($this->getTopDestinations()) ->toOptionArray(); - $this->_configCacheType->save(serialize($options), $cacheKey); + $this->_configCacheType->save($this->getSerializer()->serialize($options), $cacheKey); } $html = $this->getLayout()->createBlock( \Magento\Framework\View\Element\Html\Select::class @@ -160,10 +168,10 @@ public function getRegionHtmlSelect() $cacheKey = 'DIRECTORY_REGION_SELECT_STORE' . $this->_storeManager->getStore()->getId(); $cache = $this->_configCacheType->load($cacheKey); if ($cache) { - $options = unserialize($cache); + $options = $this->getSerializer()->unserialize($cache); } else { $options = $this->getRegionCollection()->toOptionArray(); - $this->_configCacheType->save(serialize($options), $cacheKey); + $this->_configCacheType->save($this->getSerializer()->serialize($options), $cacheKey); } $html = $this->getLayout()->createBlock( \Magento\Framework\View\Element\Html\Select::class @@ -224,4 +232,19 @@ public function getRegionsJs() \Magento\Framework\Profiler::stop('TEST: ' . __METHOD__); return $regionsJs; } + + /** + * Get serializer + * + * @return \Magento\Framework\Serialize\SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if ($this->serializer === null) { + $this->serializer = \Magento\Framework\App\ObjectManager::getInstance() + ->get(\Magento\Framework\Serialize\SerializerInterface::class); + } + return $this->serializer; + } } diff --git a/app/code/Magento/Directory/Model/Country/Postcode/Config/Data.php b/app/code/Magento/Directory/Model/Country/Postcode/Config/Data.php index 879eccd987919..c24da536e779c 100644 --- a/app/code/Magento/Directory/Model/Country/Postcode/Config/Data.php +++ b/app/code/Magento/Directory/Model/Country/Postcode/Config/Data.php @@ -5,16 +5,27 @@ */ namespace Magento\Directory\Model\Country\Postcode\Config; +use Magento\Framework\Serialize\SerializerInterface; + +/** + * Provides country postcodes configuration + */ class Data extends \Magento\Framework\Config\Data { /** - * @param \Magento\Directory\Model\Country\Postcode\Config\Reader $reader + * Constructor + * + * @param Reader $reader * @param \Magento\Framework\Config\CacheInterface $cache + * @param string|null $cacheId + * @param SerializerInterface|null $serializer */ public function __construct( \Magento\Directory\Model\Country\Postcode\Config\Reader $reader, - \Magento\Framework\Config\CacheInterface $cache + \Magento\Framework\Config\CacheInterface $cache, + $cacheId = 'country_postcodes', + SerializerInterface $serializer = null ) { - parent::__construct($reader, $cache, 'country_postcodes'); + parent::__construct($reader, $cache, $cacheId, $serializer); } } diff --git a/app/code/Magento/Directory/Test/Unit/Block/DataTest.php b/app/code/Magento/Directory/Test/Unit/Block/DataTest.php index 165a369b119b9..8bad1c1efee37 100644 --- a/app/code/Magento/Directory/Test/Unit/Block/DataTest.php +++ b/app/code/Magento/Directory/Test/Unit/Block/DataTest.php @@ -9,10 +9,9 @@ use Magento\Directory\Helper\Data as HelperData; use Magento\Directory\Model\ResourceModel\Country\Collection as CountryCollection; use Magento\Directory\Model\ResourceModel\Country\CollectionFactory as CountryCollectionFactory; -use Magento\Directory\Model\ResourceModel\Region\CollectionFactory as RegionCollectionFactory; use Magento\Framework\App\Cache\Type\Config; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Framework\Json\EncoderInterface; +use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\View\Element\Template\Context; use Magento\Framework\View\LayoutInterface; use Magento\Store\Model\ScopeInterface; @@ -25,117 +24,114 @@ class DataTest extends \PHPUnit_Framework_TestCase { /** @var Data */ - protected $model; + private $block; /** @var Context |\PHPUnit_Framework_MockObject_MockObject */ - protected $context; + private $contextMock; /** @var HelperData |\PHPUnit_Framework_MockObject_MockObject */ - protected $helperData; - - /** @var EncoderInterface |\PHPUnit_Framework_MockObject_MockObject */ - protected $jsonEncoder; + private $helperDataMock; /** @var Config |\PHPUnit_Framework_MockObject_MockObject */ - protected $cacheTypeConfig; - - /** @var RegionCollectionFactory |\PHPUnit_Framework_MockObject_MockObject */ - protected $regionCollectionFactory; + private $cacheTypeConfigMock; /** @var CountryCollectionFactory |\PHPUnit_Framework_MockObject_MockObject */ - protected $countryCollectionFactory; + private $countryCollectionFactoryMock; /** @var ScopeConfigInterface |\PHPUnit_Framework_MockObject_MockObject */ - protected $scopeConfig; + private $scopeConfigMock; /** @var StoreManagerInterface |\PHPUnit_Framework_MockObject_MockObject */ - protected $storeManager; + private $storeManagerMock; /** @var Store |\PHPUnit_Framework_MockObject_MockObject */ - protected $store; + private $storeMock; /** @var CountryCollection |\PHPUnit_Framework_MockObject_MockObject */ - protected $countryCollection; + private $countryCollectionMock; /** @var LayoutInterface |\PHPUnit_Framework_MockObject_MockObject */ - protected $layout; + private $layoutMock; + + /** @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject */ + private $serializerMock; protected function setUp() { + $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->prepareContext(); - $this->helperData = $this->getMockBuilder(\Magento\Directory\Helper\Data::class) + $this->helperDataMock = $this->getMockBuilder(\Magento\Directory\Helper\Data::class) ->disableOriginalConstructor() ->getMock(); - $this->jsonEncoder = $this->getMockBuilder(\Magento\Framework\Json\EncoderInterface::class) - ->getMockForAbstractClass(); - - $this->cacheTypeConfig = $this->getMockBuilder(\Magento\Framework\App\Cache\Type\Config::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->regionCollectionFactory = $this->getMockBuilder( - \Magento\Directory\Model\ResourceModel\Region\CollectionFactory::class - ) + $this->cacheTypeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Cache\Type\Config::class) ->disableOriginalConstructor() ->getMock(); $this->prepareCountryCollection(); - $this->model = new Data( - $this->context, - $this->helperData, - $this->jsonEncoder, - $this->cacheTypeConfig, - $this->regionCollectionFactory, - $this->countryCollectionFactory + $this->block = $objectManagerHelper->getObject( + Data::class, + [ + 'context' => $this->contextMock, + 'directoryHelper' => $this->helperDataMock, + 'configCacheType' => $this->cacheTypeConfigMock, + 'countryCollectionFactory' => $this->countryCollectionFactoryMock + ] + ); + + $this->serializerMock = $this->getMock(SerializerInterface::class, [], [], '', false); + $objectManagerHelper->setBackwardCompatibleProperty( + $this->block, + 'serializer', + $this->serializerMock ); } protected function prepareContext() { - $this->store = $this->getMockBuilder(\Magento\Store\Model\Store::class) + $this->storeMock = $this->getMockBuilder(\Magento\Store\Model\Store::class) ->disableOriginalConstructor() ->getMock(); - $this->scopeConfig = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) + $this->scopeConfigMock = $this->getMockBuilder(\Magento\Framework\App\Config\ScopeConfigInterface::class) ->getMockForAbstractClass(); - $this->storeManager = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) + $this->storeManagerMock = $this->getMockBuilder(\Magento\Store\Model\StoreManagerInterface::class) ->getMockForAbstractClass(); - $this->storeManager->expects($this->any()) + $this->storeManagerMock->expects($this->any()) ->method('getStore') - ->willReturn($this->store); + ->willReturn($this->storeMock); - $this->layout = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) + $this->layoutMock = $this->getMockBuilder(\Magento\Framework\View\LayoutInterface::class) ->getMockForAbstractClass(); - $this->context = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) + $this->contextMock = $this->getMockBuilder(\Magento\Framework\View\Element\Template\Context::class) ->disableOriginalConstructor() ->getMock(); - $this->context->expects($this->any()) + $this->contextMock->expects($this->any()) ->method('getScopeConfig') - ->willReturn($this->scopeConfig); + ->willReturn($this->scopeConfigMock); - $this->context->expects($this->any()) + $this->contextMock->expects($this->any()) ->method('getStoreManager') - ->willReturn($this->storeManager); + ->willReturn($this->storeManagerMock); - $this->context->expects($this->any()) + $this->contextMock->expects($this->any()) ->method('getLayout') - ->willReturn($this->layout); + ->willReturn($this->layoutMock); } protected function prepareCountryCollection() { - $this->countryCollection = $this->getMockBuilder( + $this->countryCollectionMock = $this->getMockBuilder( \Magento\Directory\Model\ResourceModel\Country\Collection::class )->disableOriginalConstructor()->getMock(); - $this->countryCollectionFactory = $this->getMockBuilder( + $this->countryCollectionFactoryMock = $this->getMockBuilder( \Magento\Directory\Model\ResourceModel\Country\CollectionFactory::class ) ->disableOriginalConstructor() @@ -144,9 +140,9 @@ protected function prepareCountryCollection() ]) ->getMock(); - $this->countryCollectionFactory->expects($this->any()) + $this->countryCollectionFactoryMock->expects($this->any()) ->method('create') - ->willReturn($this->countryCollection); + ->willReturn($this->countryCollectionMock); } /** @@ -166,46 +162,50 @@ public function testGetCountryHtmlSelect( $options, $resultHtml ) { - $this->helperData->expects($this->once()) + $this->helperDataMock->expects($this->once()) ->method('getDefaultCountry') ->willReturn($defaultCountry); - $this->store->expects($this->once()) + $this->storeMock->expects($this->once()) ->method('getCode') ->willReturn($storeCode); - $this->cacheTypeConfig->expects($this->once()) + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->willReturn('serializedData'); + + $this->cacheTypeConfigMock->expects($this->once()) ->method('load') ->with('DIRECTORY_COUNTRY_SELECT_STORE_' . $storeCode) ->willReturn(false); - $this->cacheTypeConfig->expects($this->once()) + $this->cacheTypeConfigMock->expects($this->once()) ->method('save') - ->with(serialize($options), 'DIRECTORY_COUNTRY_SELECT_STORE_' . $storeCode) + ->with('serializedData', 'DIRECTORY_COUNTRY_SELECT_STORE_' . $storeCode) ->willReturnSelf(); - $this->scopeConfig->expects($this->once()) + $this->scopeConfigMock->expects($this->once()) ->method('getValue') ->with('general/country/destinations', ScopeInterface::SCOPE_STORE) ->willReturn($destinations); - $this->countryCollection->expects($this->once()) + $this->countryCollectionMock->expects($this->once()) ->method('loadByStore') ->willReturnSelf(); - $this->countryCollection->expects($this->any()) + $this->countryCollectionMock->expects($this->any()) ->method('setForegroundCountries') ->with($expectedDestinations) ->willReturnSelf(); - $this->countryCollection->expects($this->once()) + $this->countryCollectionMock->expects($this->once()) ->method('toOptionArray') ->willReturn($options); $elementHtmlSelect = $this->mockElementHtmlSelect($defaultCountry, $options, $resultHtml); - $this->layout->expects($this->once()) + $this->layoutMock->expects($this->once()) ->method('createBlock') ->willReturn($elementHtmlSelect); - $this->assertEquals($resultHtml, $this->model->getCountryHtmlSelect()); + $this->assertEquals($resultHtml, $this->block->getCountryHtmlSelect()); } /** diff --git a/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/DataTest.php b/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/DataTest.php index c4681d88d28e7..57c86ab58c91b 100644 --- a/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/DataTest.php +++ b/app/code/Magento/Directory/Test/Unit/Model/Country/Postcode/Config/DataTest.php @@ -8,31 +8,54 @@ class DataTest extends \PHPUnit_Framework_TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Directory\Model\Country\Postcode\Config\Reader|\PHPUnit_Framework_MockObject_MockObject */ - protected $readerMock; + private $readerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Cache\Type\Config|\PHPUnit_Framework_MockObject_MockObject */ - protected $cacheMock; + private $cacheMock; + + /** + * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $serializerMock; protected function setUp() { - $this->readerMock = $this->getMockBuilder( - \Magento\Directory\Model\Country\Postcode\Config\Reader::class - )->disableOriginalConstructor()->getMock(); - $this->cacheMock = $this->getMockBuilder( - \Magento\Framework\App\Cache\Type\Config::class - )->disableOriginalConstructor()->getMock(); + $this->readerMock = $this->getMock( + \Magento\Directory\Model\Country\Postcode\Config\Reader::class, + [], + [], + '', + false + ); + $this->cacheMock = $this->getMock( + \Magento\Framework\App\Cache\Type\Config::class, + [], + [], + '', + false + ); + $this->serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); } public function testGet() { $expected = ['someData' => ['someValue', 'someKey' => 'someValue']]; - $this->cacheMock->expects($this->any())->method('load')->will($this->returnValue(serialize($expected))); - $configData = new \Magento\Directory\Model\Country\Postcode\Config\Data($this->readerMock, $this->cacheMock); - + $this->cacheMock->expects($this->once()) + ->method('load') + ->willReturn(json_encode($expected)); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->willReturn($expected); + $configData = new \Magento\Directory\Model\Country\Postcode\Config\Data( + $this->readerMock, + $this->cacheMock, + 'country_postcodes', + $this->serializerMock + ); $this->assertEquals($expected, $configData->get()); } } diff --git a/app/code/Magento/DownloadableImportExport/Model/Import/Product/Type/Downloadable.php b/app/code/Magento/DownloadableImportExport/Model/Import/Product/Type/Downloadable.php index a641093f54540..7a447aa90eea8 100644 --- a/app/code/Magento/DownloadableImportExport/Model/Import/Product/Type/Downloadable.php +++ b/app/code/Magento/DownloadableImportExport/Model/Import/Product/Type/Downloadable.php @@ -7,7 +7,7 @@ */ namespace Magento\DownloadableImportExport\Model\Import\Product\Type; -use Magento\CatalogImportExport\Model\Import\Product; +use Magento\Framework\EntityManager\MetadataPool; use \Magento\Store\Model\Store; /** @@ -244,7 +244,7 @@ class Downloadable extends \Magento\CatalogImportExport\Model\Import\Product\Typ protected $downloadableHelper; /** - * Constructor + * Downloadable constructor * * @param \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory $attrSetColFac * @param \Magento\Catalog\Model\ResourceModel\Product\Attribute\CollectionFactory $prodAttrColFac @@ -252,7 +252,7 @@ class Downloadable extends \Magento\CatalogImportExport\Model\Import\Product\Typ * @param array $params * @param \Magento\DownloadableImportExport\Helper\Uploader $uploaderHelper * @param \Magento\DownloadableImportExport\Helper\Data $downloadableHelper - * @throws \Magento\Framework\Exception\LocalizedException + * @param MetadataPool $metadataPool */ public function __construct( \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory $attrSetColFac, @@ -260,12 +260,12 @@ public function __construct( \Magento\Framework\App\ResourceConnection $resource, array $params, \Magento\DownloadableImportExport\Helper\Uploader $uploaderHelper, - \Magento\DownloadableImportExport\Helper\Data $downloadableHelper + \Magento\DownloadableImportExport\Helper\Data $downloadableHelper, + MetadataPool $metadataPool = null ) { - parent::__construct($attrSetColFac, $prodAttrColFac, $resource, $params); + parent::__construct($attrSetColFac, $prodAttrColFac, $resource, $params, $metadataPool); $this->parameters = $this->_entityModel->getParameters(); $this->_resource = $resource; - $this->connection = $resource->getConnection('write'); $this->uploaderHelper = $uploaderHelper; $this->downloadableHelper = $downloadableHelper; } diff --git a/app/code/Magento/DownloadableImportExport/Test/Unit/Model/Import/Product/Type/DownloadableTest.php b/app/code/Magento/DownloadableImportExport/Test/Unit/Model/Import/Product/Type/DownloadableTest.php index d3cd979b31a91..c4799bcc42ae9 100644 --- a/app/code/Magento/DownloadableImportExport/Test/Unit/Model/Import/Product/Type/DownloadableTest.php +++ b/app/code/Magento/DownloadableImportExport/Test/Unit/Model/Import/Product/Type/DownloadableTest.php @@ -710,10 +710,6 @@ public function testSetUploaderDirFalse($newSku, $bunch, $allowImport) ->getMock(\Magento\Framework\EntityManager\MetadataPool::class, ['getLinkField'], [], '', false); $metadataPoolMock->expects($this->any())->method('getMetadata')->willReturnSelf(); - $this->prepareObjectManager([ - [\Magento\Framework\EntityManager\MetadataPool::class, $metadataPoolMock], - ]); - $this->downloadableModelMock = $this->objectManagerHelper->getObject( \Magento\DownloadableImportExport\Model\Import\Product\Type\Downloadable::class, [ @@ -722,7 +718,8 @@ public function testSetUploaderDirFalse($newSku, $bunch, $allowImport) 'resource' => $this->resourceMock, 'params' => $this->paramsArray, 'uploaderHelper' => $this->uploaderHelper, - 'downloadableHelper' => $this->downloadableHelper + 'downloadableHelper' => $this->downloadableHelper, + 'metadataPool' => $metadataPoolMock, ] ); $this->entityModelMock->expects($this->once())->method('getNewSku')->will($this->returnValue($newSku)); @@ -870,20 +867,4 @@ protected function setPropertyValue(&$object, $property, $value) $reflectionProperty->setValue($object, $value); return $object; } - - /** - * @param $map - */ - private function prepareObjectManager($map) - { - $objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); - $objectManagerMock->expects($this->any())->method('getInstance')->willReturnSelf(); - $objectManagerMock->expects($this->any()) - ->method('get') - ->will($this->returnValueMap($map)); - $reflectionClass = new \ReflectionClass(\Magento\Framework\App\ObjectManager::class); - $reflectionProperty = $reflectionClass->getProperty('_instance'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($objectManagerMock); - } } diff --git a/app/code/Magento/Eav/Model/Config.php b/app/code/Magento/Eav/Model/Config.php index 36be7733dcd75..0d0237a1f6732 100644 --- a/app/code/Magento/Eav/Model/Config.php +++ b/app/code/Magento/Eav/Model/Config.php @@ -6,6 +6,8 @@ namespace Magento\Eav\Model; use Magento\Eav\Model\Entity\Type; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\App\ObjectManager; /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -92,12 +94,18 @@ class Config */ protected $_universalFactory; + /** + * @var SerializerInterface + */ + private $serializer; + /** * @param \Magento\Framework\App\CacheInterface $cache * @param \Magento\Eav\Model\Entity\TypeFactory $entityTypeFactory * @param \Magento\Eav\Model\ResourceModel\Entity\Type\CollectionFactory $entityTypeCollectionFactory * @param \Magento\Framework\App\Cache\StateInterface $cacheState * @param \Magento\Framework\Validator\UniversalFactory $universalFactory + * @param SerializerInterface $serializer * @codeCoverageIgnore */ public function __construct( @@ -105,13 +113,15 @@ public function __construct( \Magento\Eav\Model\Entity\TypeFactory $entityTypeFactory, \Magento\Eav\Model\ResourceModel\Entity\Type\CollectionFactory $entityTypeCollectionFactory, \Magento\Framework\App\Cache\StateInterface $cacheState, - \Magento\Framework\Validator\UniversalFactory $universalFactory + \Magento\Framework\Validator\UniversalFactory $universalFactory, + SerializerInterface $serializer = null ) { $this->_cache = $cache; $this->_entityTypeFactory = $entityTypeFactory; $this->entityTypeCollectionFactory = $entityTypeCollectionFactory; $this->_cacheState = $cacheState; $this->_universalFactory = $universalFactory; + $this->serializer = $serializer ?: ObjectManager::getInstance()->get(SerializerInterface::class); } /** @@ -278,7 +288,7 @@ protected function _initEntityTypes() \Magento\Framework\Profiler::start('EAV: ' . __METHOD__, ['group' => 'EAV', 'method' => __METHOD__]); if ($this->isCacheEnabled() && ($cache = $this->_cache->load(self::ENTITIES_CACHE_ID))) { - $this->_entityTypeData = unserialize($cache); + $this->_entityTypeData = $this->serializer->unserialize($cache); foreach ($this->_entityTypeData as $typeCode => $data) { $typeId = $data['entity_type_id']; $this->_addEntityTypeReference($typeId, $typeCode); @@ -302,7 +312,7 @@ protected function _initEntityTypes() if ($this->isCacheEnabled()) { $this->_cache->save( - serialize($this->_entityTypeData), + $this->serializer->serialize($this->_entityTypeData), self::ENTITIES_CACHE_ID, [ \Magento\Eav\Model\Cache\Type::CACHE_TAG, @@ -372,7 +382,7 @@ protected function _initAttributes($entityType) } $cacheKey = self::ATTRIBUTES_CACHE_ID . $entityTypeCode; if ($this->isCacheEnabled() && ($attributes = $this->_cache->load($cacheKey))) { - $attributes = unserialize($attributes); + $attributes = $this->serializer->unserialize($attributes); if ($attributes) { foreach ($attributes as $attribute) { $this->_createAttribute($entityType, $attribute); @@ -402,7 +412,7 @@ protected function _initAttributes($entityType) } if ($this->isCacheEnabled()) { $this->_cache->save( - serialize($this->_attributeData[$entityTypeCode]), + $this->serializer->serialize($this->_attributeData[$entityTypeCode]), $cacheKey, [ \Magento\Eav\Model\Cache\Type::CACHE_TAG, @@ -487,7 +497,7 @@ public function getEntityAttributeCodes($entityType, $object = null) } if ($this->isCacheEnabled() && ($attributes = $this->_cache->load($cacheKey))) { - $this->_attributeCodes[$cacheKey] = unserialize($attributes); + $this->_attributeCodes[$cacheKey] = $this->serializer->unserialize($attributes); return $this->_attributeCodes[$cacheKey]; } @@ -514,7 +524,7 @@ public function getEntityAttributeCodes($entityType, $object = null) $this->_attributeCodes[$cacheKey] = $attributes; if ($this->isCacheEnabled()) { $this->_cache->save( - serialize($attributes), + $this->serializer->serialize($attributes), $cacheKey, [ \Magento\Eav\Model\Cache\Type::CACHE_TAG, diff --git a/app/code/Magento/Eav/Model/Entity/Attribute/Config.php b/app/code/Magento/Eav/Model/Entity/Attribute/Config.php index ae5c2f5e2339f..1bc5bba6d5e79 100644 --- a/app/code/Magento/Eav/Model/Entity/Attribute/Config.php +++ b/app/code/Magento/Eav/Model/Entity/Attribute/Config.php @@ -5,20 +5,28 @@ */ namespace Magento\Eav\Model\Entity\Attribute; +use Magento\Framework\Serialize\SerializerInterface; + +/** + * Provides EAV attributes configuration + */ class Config extends \Magento\Framework\Config\Data { /** - * @param \Magento\Eav\Model\Entity\Attribute\Config\Reader $reader + * Constructor + * + * @param Config\Reader $reader * @param \Magento\Framework\Config\CacheInterface $cache - * @param string $cacheId - * @codeCoverageIgnore + * @param string|null $cacheId + * @param SerializerInterface|null $serializer */ public function __construct( \Magento\Eav\Model\Entity\Attribute\Config\Reader $reader, \Magento\Framework\Config\CacheInterface $cache, - $cacheId = "eav_attributes" + $cacheId = 'eav_attributes', + SerializerInterface $serializer = null ) { - parent::__construct($reader, $cache, $cacheId); + parent::__construct($reader, $cache, $cacheId, $serializer); } /** diff --git a/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute/Set.php b/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute/Set.php index 4e6e45f5d2270..b3e7bf2bc3925 100644 --- a/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute/Set.php +++ b/app/code/Magento/Eav/Model/ResourceModel/Entity/Attribute/Set.php @@ -5,11 +5,8 @@ */ namespace Magento\Eav\Model\ResourceModel\Entity\Attribute; -/** - * Eav attribute set resource model - * - * @author Magento Core Team - */ +use Magento\Framework\Serialize\SerializerInterface; + class Set extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb { /** @@ -27,6 +24,11 @@ class Set extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb */ protected $eavConfig; + /** + * @var SerializerInterface + */ + private $serializer; + /** * @param \Magento\Framework\Model\ResourceModel\Db\Context $context * @param GroupFactory $attrGroupFactory @@ -152,7 +154,7 @@ public function getSetInfo(array $attributeIds, $setId = null) $cacheKey = self::ATTRIBUTES_CACHE_ID . $setId; if ($this->eavConfig->isCacheEnabled() && ($cache = $this->eavConfig->getCache()->load($cacheKey))) { - $setInfoData = unserialize($cache); + $setInfoData = $this->getSerializer()->unserialize($cache); } else { $attributeSetData = $this->fetchAttributeSetData($setId); @@ -168,7 +170,7 @@ public function getSetInfo(array $attributeIds, $setId = null) if ($this->eavConfig->isCacheEnabled()) { $this->eavConfig->getCache()->save( - serialize($setInfoData), + $this->getSerializer()->serialize($setInfoData), $cacheKey, [ \Magento\Eav\Model\Cache\Type::CACHE_TAG, @@ -233,4 +235,19 @@ protected function fetchAttributeSetData($setId = null) } return $connection->fetchAll($select, $bind); } + + /** + * Get serializer + * + * @return SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if (null === $this->serializer) { + $this->serializer = \Magento\Framework\App\ObjectManager::getInstance() + ->get(SerializerInterface::class); + } + return $this->serializer; + } } diff --git a/app/code/Magento/Eav/Plugin/Model/ResourceModel/Entity/Attribute.php b/app/code/Magento/Eav/Plugin/Model/ResourceModel/Entity/Attribute.php index c76449b1223ed..56bad8bf75e11 100644 --- a/app/code/Magento/Eav/Plugin/Model/ResourceModel/Entity/Attribute.php +++ b/app/code/Magento/Eav/Plugin/Model/ResourceModel/Entity/Attribute.php @@ -5,6 +5,13 @@ */ namespace Magento\Eav\Plugin\Model\ResourceModel\Entity; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\Cache\StateInterface; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Eav\Model\ResourceModel\Entity\Attribute as AttributeResource; +use Magento\Eav\Model\Cache\Type; +use Magento\Eav\Model\Entity\Attribute as EntityAttribute; + class Attribute { /** @@ -12,52 +19,74 @@ class Attribute */ const STORE_LABEL_ATTRIBUTE = 'EAV_STORE_LABEL_ATTRIBUTE'; - /** @var \Magento\Framework\App\CacheInterface */ - protected $cache; + /** + * @var CacheInterface + */ + private $cache; + + /** + * @var StateInterface + */ + private $cacheState; - /** @var bool|null */ - protected $isCacheEnabled = null; + /** + * @var SerializerInterface + */ + private $serializer; /** - * @param \Magento\Framework\App\CacheInterface $cache - * @param \Magento\Framework\App\Cache\StateInterface $cacheState + * @param CacheInterface $cache + * @param StateInterface $cacheState + * @param SerializerInterface $serializer * @codeCoverageIgnore */ public function __construct( - \Magento\Framework\App\CacheInterface $cache, - \Magento\Framework\App\Cache\StateInterface $cacheState + CacheInterface $cache, + StateInterface $cacheState, + SerializerInterface $serializer ) { $this->cache = $cache; - $this->isCacheEnabled = $cacheState->isEnabled(\Magento\Eav\Model\Cache\Type::TYPE_IDENTIFIER); + $this->serializer = $serializer; + $this->cacheState = $cacheState; } /** - * @param \Magento\Eav\Model\ResourceModel\Entity\Attribute $subject + * @param AttributeResource $subject * @param callable $proceed * @param int $attributeId * @return array * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function aroundGetStoreLabelsByAttributeId( - \Magento\Eav\Model\ResourceModel\Entity\Attribute $subject, + AttributeResource $subject, \Closure $proceed, $attributeId ) { $cacheId = self::STORE_LABEL_ATTRIBUTE . $attributeId; - if ($this->isCacheEnabled && ($storeLabels = $this->cache->load($cacheId))) { - return unserialize($storeLabels); + if ($this->isCacheEnabled() && ($storeLabels = $this->cache->load($cacheId))) { + return $this->serializer->unserialize($storeLabels); } $storeLabels = $proceed($attributeId); - if ($this->isCacheEnabled) { + if ($this->isCacheEnabled()) { $this->cache->save( - serialize($storeLabels), + $this->serializer->serialize($storeLabels), $cacheId, [ - \Magento\Eav\Model\Cache\Type::CACHE_TAG, - \Magento\Eav\Model\Entity\Attribute::CACHE_TAG + Type::CACHE_TAG, + EntityAttribute::CACHE_TAG ] ); } return $storeLabels; } + + /** + * Check if cache is enabled + * + * @return bool + */ + private function isCacheEnabled() + { + return $this->cacheState->isEnabled(Type::TYPE_IDENTIFIER); + } } diff --git a/app/code/Magento/Eav/Test/Unit/Model/ConfigTest.php b/app/code/Magento/Eav/Test/Unit/Model/ConfigTest.php index f5fad571f205c..ff1e186de604a 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/ConfigTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/ConfigTest.php @@ -3,11 +3,15 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ - namespace Magento\Eav\Test\Unit\Model; use Magento\Framework\DataObject; use Magento\Eav\Model\Config; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Eav\Model\Entity\Type; +use Magento\Eav\Model\Cache\Type as Cache; +use Magento\Eav\Model\Entity\Attribute; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection; class ConfigTest extends \PHPUnit_Framework_TestCase { @@ -34,19 +38,26 @@ class ConfigTest extends \PHPUnit_Framework_TestCase /** * @var \Magento\Framework\App\Cache\StateInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $stateMock; + protected $cacheStateMock; /** * @var \Magento\Framework\Validator\UniversalFactory|\PHPUnit_Framework_MockObject_MockObject */ protected $universalFactoryMock; + /** + * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $serializerMock; + + /** + * @var Type|\PHPUnit_Framework_MockObject_MockObject + */ + private $typeMock; + protected function setUp() { - $this->cacheMock = $this->getMockBuilder(\Magento\Framework\App\CacheInterface::class) - ->disableOriginalConstructor() - ->setMethods(['load', 'getFrontend', 'save', 'remove', 'clean']) - ->getMock(); + $this->cacheMock = $this->getMock(\Magento\Framework\App\CacheInterface::class); $this->typeFactoryMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\TypeFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() @@ -56,35 +67,44 @@ protected function setUp() ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); - $this->stateMock = $this->getMockBuilder(\Magento\Framework\App\Cache\StateInterface::class) - ->setMethods(['isEnabled', 'setEnabled', 'persist']) - ->disableOriginalConstructor() - ->getMock(); + $this->cacheStateMock = $this->getMock(\Magento\Framework\App\Cache\StateInterface::class); $this->universalFactoryMock = $this->getMockBuilder(\Magento\Framework\Validator\UniversalFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() ->getMock(); + $this->serializerMock = $this->getMock(SerializerInterface::class); + + $this->typeMock = $this->getMock(Type::class, [], [], '', false); + $this->config = new Config( $this->cacheMock, $this->typeFactoryMock, $this->collectionFactoryMock, - $this->stateMock, - $this->universalFactoryMock + $this->cacheStateMock, + $this->universalFactoryMock, + $this->serializerMock ); } /** * @param boolean $cacheEnabled * @param int $loadCalls - * @param string $cachedValue + * @param int $cachedValue + * @param int $unserializeCalls * @dataProvider getAttributeCacheDataProvider * @return void */ - public function testGetAttributeCache($cacheEnabled, $loadCalls, $cachedValue) + public function testGetAttributeCache($cacheEnabled, $loadCalls, $unserializeCalls, $cachedValue) { + $attributeData = [ + [ + 'attribute_code' => 'attribute_code_1', + 'attribute_id' => 1 + ] + ]; $attributeCollectionMock = $this->getMockBuilder( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection::class + Collection::class )->disableOriginalConstructor() ->setMethods(['getData', 'setEntityTypeFilter']) ->getMock(); @@ -96,29 +116,40 @@ public function testGetAttributeCache($cacheEnabled, $loadCalls, $cachedValue) ->expects($this->any()) ->method('getData') ->willReturn([]); - $entityAttributeMock = $this->getMockBuilder(\Magento\Eav\Model\Entity\Attribute::class) + $entityAttributeMock = $this->getMockBuilder(Attribute::class) ->setMethods(['setData']) ->disableOriginalConstructor() ->getMock(); $factoryCalls = [ - [\Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection::class, [], $attributeCollectionMock], - [\Magento\Eav\Model\Entity\Attribute::class, [], $entityAttributeMock], + [ + Collection::class, + [], + $attributeCollectionMock + ], + [ + Attribute::class, + [], + $entityAttributeMock + ], ]; - $this->stateMock + $this->cacheStateMock ->expects($this->atLeastOnce()) ->method('isEnabled') - ->with(\Magento\Eav\Model\Cache\Type::TYPE_IDENTIFIER) + ->with(Cache::TYPE_IDENTIFIER) ->willReturn($cacheEnabled); $this->cacheMock ->expects($this->exactly($loadCalls)) ->method('load') ->with(Config::ATTRIBUTES_CACHE_ID) ->willReturn($cachedValue); + $this->serializerMock + ->expects($this->exactly($unserializeCalls)) + ->method('unserialize') + ->with($cachedValue) + ->willReturn($attributeData); - $collectionStub = new DataObject([ - ['entity_type_code' => 'type_code_1', 'entity_type_id' => 1], - ]); + $collectionStub = new DataObject([$attributeData]); $this->collectionFactoryMock ->expects($this->any()) ->method('create') @@ -134,7 +165,7 @@ public function testGetAttributeCache($cacheEnabled, $loadCalls, $cachedValue) ->method('create') ->will($this->returnValueMap($factoryCalls)); - $entityType = $this->getMockBuilder(\Magento\Eav\Model\Entity\Type::class) + $entityType = $this->getMockBuilder(Type::class) ->setMethods(['getEntity', 'setData', 'getData']) ->disableOriginalConstructor() ->getMock(); @@ -151,38 +182,145 @@ public function getAttributeCacheDataProvider() 'cache-disabled' => [ false, 0, + 0, false, ], 'cache-miss' => [ true, 1, + 0, false, ], 'cached' => [ true, 1, - serialize( - [ - ['attribute_code' => 'attribute_code_1', 'attribute_id' => 1], - ] - ), + 1, + 'attribute serialzied data', ], ]; } public function testClear() { - $this->cacheMock - ->expects($this->once()) + $this->cacheMock->expects($this->once()) ->method('clean') ->with( $this->equalTo( [ - \Magento\Eav\Model\Cache\Type::CACHE_TAG, - \Magento\Eav\Model\Entity\Attribute::CACHE_TAG, + Cache::CACHE_TAG, + Attribute::CACHE_TAG, ] ) ); $this->config->clear(); } + + public function testGetEntityTypeInstanceOfTypePassed() + { + $this->assertEquals( + $this->typeMock, + $this->config->getEntityType($this->typeMock) + ); + } + + public function testGetEntityTypeCacheExists() + { + $entityTypeCode = 'catalog_product'; + $data = [ + $entityTypeCode => [ + 'entity_type_id' => 1 + ] + ]; + $serializedData = 'serialized data'; + $this->cacheStateMock->expects($this->once()) + ->method('isEnabled') + ->with(Cache::TYPE_IDENTIFIER) + ->willReturn(true); + $this->cacheMock->expects($this->once()) + ->method('load') + ->with(Config::ENTITIES_CACHE_ID) + ->willReturn($serializedData); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with($serializedData) + ->willReturn($data); + $this->typeMock->expects($this->exactly(2)) + ->method('getId') + ->willReturn($data[$entityTypeCode]['entity_type_id']); + $this->typeMock->expects($this->once()) + ->method('getEntityTypeCode') + ->willReturn($entityTypeCode); + $this->typeFactoryMock->expects($this->once()) + ->method('create') + ->with(['data' => $data[$entityTypeCode]]) + ->willReturn($this->typeMock); + $this->assertInstanceOf( + Type::class, + $this->config->getEntityType($entityTypeCode) + ); + } + + public function testGetEntityTypeCacheDoesNotExist() + { + $entityTypeCode = 'catalog_product'; + $collectionData = [ + [ + 'entity_type_id' => 1, + 'entity_type_code' => $entityTypeCode + ] + ]; + $data = [ + $entityTypeCode => [ + 'entity_type_id' => 1, + 'entity_type_code' => $entityTypeCode, + 'attribute_model' => Attribute::class + ] + ]; + $serializedData = 'serialized data'; + $this->cacheStateMock->expects($this->once()) + ->method('isEnabled') + ->with(Cache::TYPE_IDENTIFIER) + ->willReturn(true); + $this->cacheMock->expects($this->once()) + ->method('load') + ->with(Config::ENTITIES_CACHE_ID) + ->willReturn(false); + $this->serializerMock->expects($this->never()) + ->method('unserialize'); + $attributeCollectionMock = $this->getMock(Collection::class, [], [], '', false); + $this->collectionFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($attributeCollectionMock); + $attributeCollectionMock->expects($this->once()) + ->method('getData') + ->willReturn($collectionData); + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->with($data) + ->willReturn($serializedData); + $this->cacheMock->expects($this->once()) + ->method('save') + ->with( + $serializedData, + Config::ENTITIES_CACHE_ID, + [ + Cache::CACHE_TAG, + Attribute::CACHE_TAG + ] + ); + $this->typeMock->expects($this->exactly(2)) + ->method('getId') + ->willReturn($data[$entityTypeCode]['entity_type_id']); + $this->typeMock->expects($this->once()) + ->method('getEntityTypeCode') + ->willReturn($entityTypeCode); + $this->typeFactoryMock->expects($this->once()) + ->method('create') + ->with(['data' => $data[$entityTypeCode]]) + ->willReturn($this->typeMock); + $this->assertInstanceOf( + Type::class, + $this->config->getEntityType($entityTypeCode) + ); + } } diff --git a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/ConfigTest.php b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/ConfigTest.php index 78dbc6bed34c3..5ae74a16b27a9 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/ConfigTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/Entity/Attribute/ConfigTest.php @@ -32,7 +32,7 @@ class ConfigTest extends \PHPUnit_Framework_TestCase protected $_cacheId; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Eav\Model\Entity\Attribute|\PHPUnit_Framework_MockObject_MockObject */ protected $_attribute; @@ -54,20 +54,20 @@ protected function setUp() ); $this->_cacheMock = $this->getMock(\Magento\Framework\App\Cache\Type\Config::class, [], [], '', false); $this->_cacheId = 'eav_attributes'; - $this->_cacheMock->expects( - $this->once() - )->method( - 'load' - )->with( - $this->equalTo($this->_cacheId) - )->will( - $this->returnValue(serialize([])) - ); + $this->_cacheMock->expects($this->once()) + ->method('load') + ->with($this->_cacheId) + ->willReturn(''); + + $serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); + $serializerMock->method('unserialize') + ->willReturn([]); $this->_model = new \Magento\Eav\Model\Entity\Attribute\Config( $this->_readerMock, $this->_cacheMock, - $this->_cacheId + $this->_cacheId, + $serializerMock ); } diff --git a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/SetTest.php b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/SetTest.php index a380b14595eb2..e00a8ee97648c 100644 --- a/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/SetTest.php +++ b/app/code/Magento/Eav/Test/Unit/Model/ResourceModel/Entity/Attribute/SetTest.php @@ -1,14 +1,14 @@ resourceMock = $this->getMockBuilder(\Magento\Framework\App\ResourceConnection::class) ->disableOriginalConstructor() ->setMethods(['getConnection', 'getTableName']) @@ -81,31 +87,28 @@ protected function setUp() ->setMethods(['isCacheEnabled', 'getEntityType', 'getCache']) ->disableOriginalConstructor() ->getMock(); - $this->model = $this->getMock( + + $this->serializerMock = $this->getMock(SerializerInterface::class); + + $attributeGroupFactoryMock = $this->getMock( + \Magento\Eav\Model\ResourceModel\Entity\Attribute\GroupFactory::class, + [], + [], + '', + false + ); + + $this->model = $objectManager->getObject( \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set::class, [ - 'beginTransaction', - 'getMainTable', - 'getIdFieldName', - '_afterDelete', - 'commit', - 'rollBack', - '__wakeup' - ], - [ - $contextMock, - $this->getMock( - \Magento\Eav\Model\ResourceModel\Entity\Attribute\GroupFactory::class, - [], - [], - '', - false - ), - $this->eavConfigMock - ], - '', - true + 'context' => $contextMock, + 'attrGroupFactory' => $attributeGroupFactoryMock, + 'eavConfig' => $this->eavConfigMock + ] ); + + $objectManager->setBackwardCompatibleProperty($this->model, 'serializer', $this->serializerMock); + $this->typeMock = $this->getMock(\Magento\Eav\Model\Entity\Type::class, [], [], '', false); $this->objectMock = $this->getMock( \Magento\Framework\Model\AbstractModel::class, @@ -123,7 +126,6 @@ protected function setUp() '', false ); - } /** @@ -182,6 +184,22 @@ public function testBeforeDelete() */ public function testGetSetInfoCacheMiss() { + $serializedData = 'serialized data'; + $setElement = [ + 10000 => [ + 'group_id' => 10, + 'group_sort' => 100, + 'sort' => 1000 + ] + ]; + $setData = [ + 1 => $setElement, + 2 => [], + 3 => [] + ]; + $cached = [ + 1 => $setElement + ]; $cacheMock = $this->getMockBuilder(\Magento\Framework\App\CacheInterface::class) ->disableOriginalConstructor() ->setMethods(['load', 'save', 'getFrontend', 'remove', 'clean']) @@ -192,21 +210,15 @@ public function testGetSetInfoCacheMiss() ->method('load') ->with($cacheKey) ->willReturn(false); + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->with($cached) + ->willReturn($serializedData); $cacheMock ->expects($this->once()) ->method('save') ->with( - serialize( - [ - 1 => [ - 10000 => [ - 'group_id' => 10, - 'group_sort' => 100, - 'sort' => 1000 - ] - ] - ] - ), + $serializedData, $cacheKey, [\Magento\Eav\Model\Cache\Type::CACHE_TAG, \Magento\Eav\Model\Entity\Attribute::CACHE_TAG] ); @@ -242,17 +254,7 @@ public function testGetSetInfoCacheMiss() $this->resourceMock->expects($this->any())->method('getConnection')->willReturn($connectionMock); $this->resourceMock->expects($this->any())->method('getTableName')->willReturn('_TABLE_'); $this->assertEquals( - [ - 1 => [ - 10000 => [ - 'group_id' => 10, - 'group_sort' => 100, - 'sort' => 1000 - ] - ], - 2 => [], - 3 => [] - ], + $setData, $this->model->getSetInfo([1, 2, 3], 1) ); } @@ -262,42 +264,41 @@ public function testGetSetInfoCacheMiss() */ public function testGetSetInfoCacheHit() { - $cached = [ - 1 => [ - 10000 => [ - 'group_id' => 10, - 'group_sort' => 100, - 'sort' => 1000 - ] + $setElement = [ + 10000 => [ + 'group_id' => 10, + 'group_sort' => 100, + 'sort' => 1000 ] ]; - + $setData = [ + 1 => $setElement, + 2 => [], + 3 => [] + ]; + $cached = [ + 1 => $setElement + ]; + $serializedData = 'serialized data'; $this->resourceMock->expects($this->never())->method('getConnection'); $this->eavConfigMock->expects($this->any())->method('isCacheEnabled')->willReturn(true); $cacheMock = $this->getMockBuilder(\Magento\Framework\App\CacheInterface::class) ->disableOriginalConstructor() ->setMethods(['load', 'save', 'getFrontend', 'remove', 'clean']) ->getMock(); - $cacheMock - ->expects($this->once()) + $cacheMock->expects($this->once()) ->method('load') ->with(Set::ATTRIBUTES_CACHE_ID . 1) - ->willReturn(serialize($cached)); + ->willReturn($serializedData); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with($serializedData) + ->willReturn($cached); $this->eavConfigMock->expects($this->any())->method('getCache')->willReturn($cacheMock); $this->assertEquals( - [ - 1 => [ - 10000 => [ - 'group_id' => 10, - 'group_sort' => 100, - 'sort' => 1000 - ] - ], - 2 => [], - 3 => [] - ], + $setData, $this->model->getSetInfo([1, 2, 3], 1) ); } diff --git a/app/code/Magento/Eav/Test/Unit/Plugin/Model/ResourceModel/Entity/AttributeTest.php b/app/code/Magento/Eav/Test/Unit/Plugin/Model/ResourceModel/Entity/AttributeTest.php index 7d4561259cf88..3fa739d4096a8 100644 --- a/app/code/Magento/Eav/Test/Unit/Plugin/Model/ResourceModel/Entity/AttributeTest.php +++ b/app/code/Magento/Eav/Test/Unit/Plugin/Model/ResourceModel/Entity/AttributeTest.php @@ -3,111 +3,166 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ - -// @codingStandardsIgnoreFile - namespace Magento\Eav\Test\Unit\Plugin\Model\ResourceModel\Entity; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\App\CacheInterface; +use Magento\Framework\App\Cache\StateInterface; +use Magento\Eav\Model\ResourceModel\Entity\Attribute as AttributeResource; +use Magento\Eav\Plugin\Model\ResourceModel\Entity\Attribute as AttributeResourcePlugin; +use Magento\Eav\Model\Cache\Type; +use Magento\Eav\Model\Entity\Attribute; class AttributeTest extends \PHPUnit_Framework_TestCase { - /** @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $cache; + /** + * @var CacheInterface|\PHPUnit_Framework_MockObject_MockObject + */ + protected $cacheMock; - /** @var \Magento\Framework\App\Cache\StateInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $cacheState; + /** + * @var StateInterface|\PHPUnit_Framework_MockObject_MockObject + */ + protected $cacheStateMock; + + /** + * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $serializerMock; + + /** + * @var AttributeResource|\PHPUnit_Framework_MockObject_MockObject + */ + private $attributeResourceMock; - /** @var \Magento\Eav\Model\ResourceModel\Entity\Attribute|\PHPUnit_Framework_MockObject_MockObject */ - protected $subject; + /** + * @var AttributeResourcePlugin + */ + private $attributeResourcePlugin; protected function setUp() { - $this->cache = $this->getMock(\Magento\Framework\App\CacheInterface::class); - $this->cacheState = $this->getMock(\Magento\Framework\App\Cache\StateInterface::class); - $this->subject = $this->getMock(\Magento\Eav\Model\ResourceModel\Entity\Attribute::class, [], [], '', false); + $objectManager = new ObjectManager($this); + $this->cacheMock = $this->getMock(CacheInterface::class); + $this->cacheStateMock = $this->getMock(StateInterface::class); + $this->attributeResourceMock = $this->getMock(AttributeResource::class, [], [], '', false); + $this->serializerMock = $this->getMock(SerializerInterface::class); + $this->attributeResourcePlugin = $objectManager->getObject( + AttributeResourcePlugin::class, + [ + 'cache' => $this->cacheMock, + 'cacheState' => $this->cacheStateMock, + 'serializer' => $this->serializerMock + ] + ); } - public function testGetStoreLabelsByAttributeIdOnCacheDisabled() + public function testAroundGetStoreLabelsByAttributeIdCacheIsDisabled() { - $this->cache->expects($this->never())->method('load'); + $attributeId = 1; + $this->cacheMock->expects($this->never()) + ->method('load'); + $this->cacheStateMock->expects($this->exactly(2)) + ->method('isEnabled') + ->with(Type::TYPE_IDENTIFIER) + ->willReturn(false); - $this->assertEquals( - 'attributeId', - $this->getAttribute(false)->aroundGetStoreLabelsByAttributeId( - $this->subject, - $this->mockPluginProceed('attributeId'), - 'attributeId' - ) + $isProceedCalled = false; + // @SuppressWarnings(PHPMD.UnusedFormalParameter) + $proceed = function ($attributeId) use (&$isProceedCalled) { + $isProceedCalled = true; + }; + + $this->attributeResourcePlugin->aroundGetStoreLabelsByAttributeId( + $this->attributeResourceMock, + $proceed, + $attributeId ); + $this->assertTrue($isProceedCalled); } - public function testGetStoreLabelsByAttributeIdFromCache() + public function testAroundGetStoreLabelsByAttributeIdCacheExists() { $attributeId = 1; - $attributes = ['k' => 'v']; - $cacheId = \Magento\Eav\Plugin\Model\ResourceModel\Entity\Attribute::STORE_LABEL_ATTRIBUTE . $attributeId; - $this->cache->expects($this->any())->method('load')->with($cacheId)->willReturn(serialize($attributes)); + $attributes = ['foo' => 'bar']; + $serializedAttributes = 'serialized attributes'; + $cacheId = AttributeResourcePlugin::STORE_LABEL_ATTRIBUTE . $attributeId; + $this->cacheStateMock->expects($this->once()) + ->method('isEnabled') + ->with(Type::TYPE_IDENTIFIER) + ->willReturn(true); + $this->cacheMock->expects($this->once()) + ->method('load') + ->with($cacheId) + ->willReturn($serializedAttributes); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with($serializedAttributes) + ->willReturn($attributes); + + $isProceedCalled = false; + // @SuppressWarnings(PHPMD.UnusedFormalParameter) + $proceed = function ($attributeId) use (&$isProceedCalled) { + $isProceedCalled = true; + }; $this->assertEquals( $attributes, - $this->getAttribute(true)->aroundGetStoreLabelsByAttributeId( - $this->subject, - $this->mockPluginProceed(), + $this->attributeResourcePlugin->aroundGetStoreLabelsByAttributeId( + $this->attributeResourceMock, + $proceed, $attributeId ) ); + $this->assertFalse($isProceedCalled); } - public function testGetStoreLabelsByAttributeIdWithCacheSave() + public function testAroundGetStoreLabelsByAttributeIdCacheDoesNotExist() { $attributeId = 1; - $cacheId = \Magento\Eav\Plugin\Model\ResourceModel\Entity\Attribute::STORE_LABEL_ATTRIBUTE . $attributeId; - $this->cache->expects($this->any())->method('load')->with($cacheId)->willReturn(false); - $this->cache->expects($this->any())->method('save')->with( - serialize([$attributeId]), - $cacheId, - [ - \Magento\Eav\Model\Cache\Type::CACHE_TAG, - \Magento\Eav\Model\Entity\Attribute::CACHE_TAG - ] - ); + $attributes = ['foo' => 'bar']; + $serializedAttributes = 'serialized attributes'; + $cacheId = AttributeResourcePlugin::STORE_LABEL_ATTRIBUTE . $attributeId; + $this->cacheStateMock->expects($this->exactly(2)) + ->method('isEnabled') + ->with(Type::TYPE_IDENTIFIER) + ->willReturn(true); + $this->cacheMock->expects($this->once()) + ->method('load') + ->with($cacheId) + ->willReturn(false); + $this->serializerMock->expects($this->never()) + ->method('unserialize') + ->with($serializedAttributes) + ->willReturn($attributes); + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->with($attributes) + ->willReturn($serializedAttributes); + $this->cacheMock->expects($this->once()) + ->method('save') + ->with( + $serializedAttributes, + $cacheId, + [ + Type::CACHE_TAG, + Attribute::CACHE_TAG + ] + ); + + // @SuppressWarnings(PHPMD.UnusedFormalParameter) + $proceed = function ($attributeId) use ($attributes) { + return $attributes; + }; $this->assertEquals( - [$attributeId], - $this->getAttribute(true)->aroundGetStoreLabelsByAttributeId( - $this->subject, - $this->mockPluginProceed([$attributeId]), + $attributes, + $this->attributeResourcePlugin->aroundGetStoreLabelsByAttributeId( + $this->attributeResourceMock, + $proceed, $attributeId ) ); } - - /** - * @param bool $cacheEnabledFlag - * @return \Magento\Eav\Plugin\Model\ResourceModel\Entity\Attribute - */ - protected function getAttribute($cacheEnabledFlag) - { - $this->cacheState->expects($this->any())->method('isEnabled') - ->with(\Magento\Eav\Model\Cache\Type::TYPE_IDENTIFIER)->willReturn($cacheEnabledFlag); - return (new ObjectManager($this))->getObject( - \Magento\Eav\Plugin\Model\ResourceModel\Entity\Attribute::class, - [ - 'cache' => $this->cache, - 'cacheState' => $this->cacheState - ] - ); - } - - /** - * @param mixed $returnValue - * @return callable - */ - protected function mockPluginProceed($returnValue = null) - { - return function () use ($returnValue) { - return $returnValue; - }; - } } diff --git a/app/code/Magento/Email/Model/Template/Config/Data.php b/app/code/Magento/Email/Model/Template/Config/Data.php index c7f4054bf311e..1f6a4beb166e0 100644 --- a/app/code/Magento/Email/Model/Template/Config/Data.php +++ b/app/code/Magento/Email/Model/Template/Config/Data.php @@ -1,22 +1,31 @@ _readerMock = $this->getMock( + $this->readerMock = $this->getMock( \Magento\ImportExport\Model\Export\Config\Reader::class, [], [], '', false ); - $this->_configScopeMock = $this->getMock(\Magento\Framework\Config\CacheInterface::class); + $this->cacheMock = $this->getMock(\Magento\Framework\Config\CacheInterface::class); + $this->serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); } /** @@ -46,22 +52,23 @@ protected function setUp() */ public function testGetEntities($value, $expected) { - $this->_configScopeMock->expects( + $this->cacheMock->expects( $this->any() )->method( 'load' )->with( - $this->_cacheId + $this->cacheId )->will( $this->returnValue(false) ); - $this->_readerMock->expects($this->any())->method('read')->will($this->returnValue($value)); - $this->_model = new \Magento\ImportExport\Model\Export\Config( - $this->_readerMock, - $this->_configScopeMock, - $this->_cacheId + $this->readerMock->expects($this->any())->method('read')->will($this->returnValue($value)); + $this->model = new \Magento\ImportExport\Model\Export\Config( + $this->readerMock, + $this->cacheMock, + $this->cacheId, + $this->serializerMock ); - $this->assertEquals($expected, $this->_model->getEntities('entities')); + $this->assertEquals($expected, $this->model->getEntities('entities')); } public function getEntitiesDataProvider() @@ -80,22 +87,23 @@ public function getEntitiesDataProvider() */ public function testGetEntityTypes($configData, $entity, $expectedResult) { - $this->_configScopeMock->expects( + $this->cacheMock->expects( $this->any() )->method( 'load' )->with( - $this->_cacheId + $this->cacheId )->will( $this->returnValue(false) ); - $this->_readerMock->expects($this->any())->method('read')->will($this->returnValue($configData)); - $this->_model = new \Magento\ImportExport\Model\Export\Config( - $this->_readerMock, - $this->_configScopeMock, - $this->_cacheId + $this->readerMock->expects($this->any())->method('read')->will($this->returnValue($configData)); + $this->model = new \Magento\ImportExport\Model\Export\Config( + $this->readerMock, + $this->cacheMock, + $this->cacheId, + $this->serializerMock ); - $this->assertEquals($expectedResult, $this->_model->getEntityTypes($entity)); + $this->assertEquals($expectedResult, $this->model->getEntityTypes($entity)); } public function getEntityTypesDataProvider() @@ -133,22 +141,23 @@ public function getEntityTypesDataProvider() */ public function testGetFileFormats($value, $expected) { - $this->_configScopeMock->expects( + $this->cacheMock->expects( $this->any() )->method( 'load' )->with( - $this->_cacheId + $this->cacheId )->will( $this->returnValue(false) ); - $this->_readerMock->expects($this->any())->method('read')->will($this->returnValue($value)); - $this->_model = new \Magento\ImportExport\Model\Export\Config( - $this->_readerMock, - $this->_configScopeMock, - $this->_cacheId + $this->readerMock->expects($this->any())->method('read')->will($this->returnValue($value)); + $this->model = new \Magento\ImportExport\Model\Export\Config( + $this->readerMock, + $this->cacheMock, + $this->cacheId, + $this->serializerMock ); - $this->assertEquals($expected, $this->_model->getFileFormats('fileFormats')); + $this->assertEquals($expected, $this->model->getFileFormats('fileFormats')); } public function getFileFormatsDataProvider() diff --git a/app/code/Magento/ImportExport/Test/Unit/Model/Import/ConfigTest.php b/app/code/Magento/ImportExport/Test/Unit/Model/Import/ConfigTest.php index 1530c0b4a4d00..60cd1f50238a4 100644 --- a/app/code/Magento/ImportExport/Test/Unit/Model/Import/ConfigTest.php +++ b/app/code/Magento/ImportExport/Test/Unit/Model/Import/ConfigTest.php @@ -8,35 +8,41 @@ class ConfigTest extends \PHPUnit_Framework_TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\ImportExport\Model\Import\Config\Reader|\PHPUnit_Framework_MockObject_MockObject */ - protected $_readerMock; + protected $readerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Config\CacheInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $_configScopeMock; + protected $cacheMock; + + /** + * @var \Magento\Framework\Serialize\SerializerInterface + */ + private $serializerMock; /** * @var string */ - protected $_cacheId = 'some_id'; + protected $cacheId = 'some_id'; /** * @var \Magento\ImportExport\Model\Import\Config */ - protected $_model; + protected $model; protected function setUp() { - $this->_readerMock = $this->getMock( + $this->readerMock = $this->getMock( \Magento\ImportExport\Model\Import\Config\Reader::class, [], [], '', false ); - $this->_configScopeMock = $this->getMock(\Magento\Framework\Config\CacheInterface::class); + $this->cacheMock = $this->getMock(\Magento\Framework\Config\CacheInterface::class); + $this->serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); } /** @@ -46,22 +52,23 @@ protected function setUp() */ public function testGetEntities($value, $expected) { - $this->_configScopeMock->expects( + $this->cacheMock->expects( $this->any() )->method( 'load' )->with( - $this->_cacheId + $this->cacheId )->will( $this->returnValue(false) ); - $this->_readerMock->expects($this->any())->method('read')->will($this->returnValue($value)); - $this->_model = new \Magento\ImportExport\Model\Import\Config( - $this->_readerMock, - $this->_configScopeMock, - $this->_cacheId + $this->readerMock->expects($this->any())->method('read')->will($this->returnValue($value)); + $this->model = new \Magento\ImportExport\Model\Import\Config( + $this->readerMock, + $this->cacheMock, + $this->cacheId, + $this->serializerMock ); - $this->assertEquals($expected, $this->_model->getEntities('entities')); + $this->assertEquals($expected, $this->model->getEntities('entities')); } public function getEntitiesDataProvider() @@ -80,22 +87,23 @@ public function getEntitiesDataProvider() */ public function testGetEntityTypes($configData, $entity, $expectedResult) { - $this->_configScopeMock->expects( + $this->cacheMock->expects( $this->any() )->method( 'load' )->with( - $this->_cacheId + $this->cacheId )->will( $this->returnValue(false) ); - $this->_readerMock->expects($this->any())->method('read')->will($this->returnValue($configData)); - $this->_model = new \Magento\ImportExport\Model\Import\Config( - $this->_readerMock, - $this->_configScopeMock, - $this->_cacheId + $this->readerMock->expects($this->any())->method('read')->will($this->returnValue($configData)); + $this->model = new \Magento\ImportExport\Model\Import\Config( + $this->readerMock, + $this->cacheMock, + $this->cacheId, + $this->serializerMock ); - $this->assertEquals($expectedResult, $this->_model->getEntityTypes($entity)); + $this->assertEquals($expectedResult, $this->model->getEntityTypes($entity)); } public function getEntityTypesDataProvider() diff --git a/app/code/Magento/Indexer/Model/Config/Data.php b/app/code/Magento/Indexer/Model/Config/Data.php index 68a390a8c06b7..3cedaa51ef4bb 100644 --- a/app/code/Magento/Indexer/Model/Config/Data.php +++ b/app/code/Magento/Indexer/Model/Config/Data.php @@ -5,6 +5,12 @@ */ namespace Magento\Indexer\Model\Config; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\App\ObjectManager; + +/** + * Provides indexer configuration + */ class Data extends \Magento\Framework\Config\Data { /** @@ -13,22 +19,26 @@ class Data extends \Magento\Framework\Config\Data protected $stateCollection; /** + * Constructor + * * @param \Magento\Framework\Indexer\Config\Reader $reader * @param \Magento\Framework\Config\CacheInterface $cache * @param \Magento\Indexer\Model\ResourceModel\Indexer\State\Collection $stateCollection - * @param string $cacheId + * @param string|null $cacheId + * @param SerializerInterface|null $serializer */ public function __construct( \Magento\Framework\Indexer\Config\Reader $reader, \Magento\Framework\Config\CacheInterface $cache, \Magento\Indexer\Model\ResourceModel\Indexer\State\Collection $stateCollection, - $cacheId = 'indexer_config' + $cacheId = 'indexer_config', + SerializerInterface $serializer = null ) { $this->stateCollection = $stateCollection; $isCacheExists = $cache->test($cacheId); - parent::__construct($reader, $cache, $cacheId); + parent::__construct($reader, $cache, $cacheId, $serializer); if (!$isCacheExists) { $this->deleteNonexistentStates(); diff --git a/app/code/Magento/Indexer/Test/Unit/Model/Config/DataTest.php b/app/code/Magento/Indexer/Test/Unit/Model/Config/DataTest.php index 5e0f7c314cf31..e16c21b8f1125 100644 --- a/app/code/Magento/Indexer/Test/Unit/Model/Config/DataTest.php +++ b/app/code/Magento/Indexer/Test/Unit/Model/Config/DataTest.php @@ -37,6 +37,11 @@ class DataTest extends \PHPUnit_Framework_TestCase */ protected $indexers = ['indexer1' => [], 'indexer3' => []]; + /** + * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $serializerMock; + protected function setUp() { $this->reader = $this->getMock(\Magento\Framework\Indexer\Config\Reader::class, ['read'], [], '', false); @@ -56,20 +61,22 @@ protected function setUp() '', false ); + $this->serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); } public function testConstructorWithCache() { + $serializedData = 'serialized data'; $this->cache->expects($this->once())->method('test')->with($this->cacheId)->will($this->returnValue(true)); - $this->cache->expects( - $this->once() - )->method( - 'load' - )->with( - $this->cacheId - )->will( - $this->returnValue(serialize($this->indexers)) - ); + $this->cache->expects($this->once()) + ->method('load') + ->with($this->cacheId) + ->willReturn($serializedData); + + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with($serializedData) + ->willReturn($this->indexers); $this->stateCollection->expects($this->never())->method('getItems'); @@ -77,7 +84,8 @@ public function testConstructorWithCache() $this->reader, $this->cache, $this->stateCollection, - $this->cacheId + $this->cacheId, + $this->serializerMock ); } @@ -116,7 +124,8 @@ public function testConstructorWithoutCache() $this->reader, $this->cache, $this->stateCollection, - $this->cacheId + $this->cacheId, + $this->serializerMock ); } } diff --git a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/RepositoryTest.php b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/RepositoryTest.php index dae3d56aa04b0..c6e5241282cd0 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/RepositoryTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/Quote/Item/RepositoryTest.php @@ -12,6 +12,11 @@ */ class RepositoryTest extends \PHPUnit_Framework_TestCase { + /** + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + */ + private $objectManager; + /** * @var \Magento\Quote\Api\CartItemRepositoryInterface */ @@ -68,6 +73,7 @@ class RepositoryTest extends \PHPUnit_Framework_TestCase */ protected function setUp() { + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->quoteRepositoryMock = $this->getMock(\Magento\Quote\Api\CartRepositoryInterface::class); $this->productRepositoryMock = $this->getMock(\Magento\Catalog\Api\ProductRepositoryInterface::class); $this->itemDataFactoryMock = @@ -100,12 +106,6 @@ protected function setUp() '', false ); - $this->prepareObjectManager([ - [ - \Magento\Quote\Model\Quote\Item\CartItemOptionsProcessor::class, - $this->optionsProcessorMock - ] - ]); $this->repository = new \Magento\Quote\Model\Quote\Item\Repository( $this->quoteRepositoryMock, @@ -113,6 +113,11 @@ protected function setUp() $this->itemDataFactoryMock, ['custom_options' => $this->customOptionProcessor] ); + $this->objectManager->setBackwardCompatibleProperty( + $this->repository, + 'cartItemOptionsProcessor', + $this->optionsProcessorMock + ); } /** @@ -246,20 +251,4 @@ public function testDeleteById() $this->assertTrue($this->repository->deleteById($cartId, $itemId)); } - - /** - * @param array $map - */ - private function prepareObjectManager($map) - { - $objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); - $objectManagerMock->expects($this->any())->method('getInstance')->willReturnSelf(); - $objectManagerMock->expects($this->any()) - ->method('get') - ->will($this->returnValueMap($map)); - $reflectionClass = new \ReflectionClass(\Magento\Framework\App\ObjectManager::class); - $reflectionProperty = $reflectionClass->getProperty('_instance'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($objectManagerMock); - } } diff --git a/app/code/Magento/Quote/Test/Unit/Model/ShippingAddressManagementTest.php b/app/code/Magento/Quote/Test/Unit/Model/ShippingAddressManagementTest.php index abae7bae110e6..d8e65de847457 100644 --- a/app/code/Magento/Quote/Test/Unit/Model/ShippingAddressManagementTest.php +++ b/app/code/Magento/Quote/Test/Unit/Model/ShippingAddressManagementTest.php @@ -104,12 +104,6 @@ protected function setUp() '', false ); - $this->prepareObjectManager([ - [ - \Magento\Quote\Model\Quote\Validator\MinimumOrderAmount\ValidationMessage::class, - $this->amountErrorMessageMock - ] - ]); $this->service = $this->objectManager->getObject( \Magento\Quote\Model\ShippingAddressManagement::class, @@ -122,6 +116,11 @@ protected function setUp() 'addressRepository' => $this->addressRepository ] ); + $this->objectManager->setBackwardCompatibleProperty( + $this->service, + 'minimumAmountErrorMessage', + $this->amountErrorMessageMock + ); } /** @@ -375,20 +374,4 @@ public function testGetAddressOfQuoteWithVirtualProducts() $this->service->get('cartId'); } - - /** - * @param $map - */ - private function prepareObjectManager($map) - { - $objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); - $objectManagerMock->expects($this->any())->method('getInstance')->willReturnSelf(); - $objectManagerMock->expects($this->any()) - ->method('get') - ->will($this->returnValueMap($map)); - $reflectionClass = new \ReflectionClass(\Magento\Framework\App\ObjectManager::class); - $reflectionProperty = $reflectionClass->getProperty('_instance'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($objectManagerMock); - } } diff --git a/app/code/Magento/Review/Model/ResourceModel/Review/Product/Collection.php b/app/code/Magento/Review/Model/ResourceModel/Review/Product/Collection.php index f4945508fe722..f066bb53b51ac 100644 --- a/app/code/Magento/Review/Model/ResourceModel/Review/Product/Collection.php +++ b/app/code/Magento/Review/Model/ResourceModel/Review/Product/Collection.php @@ -7,6 +7,8 @@ use Magento\Eav\Model\Entity\Attribute\AbstractAttribute; use Magento\Framework\DB\Select; +use Magento\Framework\EntityManager\MetadataPool; +use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory; /** * Review Product Collection @@ -59,7 +61,8 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection protected $_voteFactory; /** - * Collection constructor. + * Collection constructor + * * @param \Magento\Framework\Data\Collection\EntityFactory $entityFactory * @param \Psr\Log\LoggerInterface $logger * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy @@ -81,7 +84,9 @@ class Collection extends \Magento\Catalog\Model\ResourceModel\Product\Collection * @param \Magento\Customer\Api\GroupManagementInterface $groupManagement * @param \Magento\Review\Model\RatingFactory $ratingFactory * @param \Magento\Review\Model\Rating\Option\VoteFactory $voteFactory - * @param mixed $connection + * @param \Magento\Framework\DB\Adapter\AdapterInterface|null $connection + * @param ProductLimitationFactory|null $productLimitationFactory + * @param MetadataPool|null $metadataPool * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ @@ -107,7 +112,9 @@ public function __construct( \Magento\Customer\Api\GroupManagementInterface $groupManagement, \Magento\Review\Model\RatingFactory $ratingFactory, \Magento\Review\Model\Rating\Option\VoteFactory $voteFactory, - \Magento\Framework\DB\Adapter\AdapterInterface $connection = null + \Magento\Framework\DB\Adapter\AdapterInterface $connection = null, + ProductLimitationFactory $productLimitationFactory = null, + MetadataPool $metadataPool = null ) { $this->_ratingFactory = $ratingFactory; $this->_voteFactory = $voteFactory; @@ -131,7 +138,9 @@ public function __construct( $customerSession, $dateTime, $groupManagement, - $connection + $connection, + $productLimitationFactory, + $metadataPool ); } diff --git a/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/Product/CollectionTest.php b/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/Product/CollectionTest.php index b1a1b9a69c7ff..8c51535a7f6ab 100644 --- a/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/Product/CollectionTest.php +++ b/app/code/Magento/Review/Test/Unit/Model/ResourceModel/Review/Product/CollectionTest.php @@ -5,11 +5,18 @@ */ namespace Magento\Review\Test\Unit\Model\ResourceModel\Review\Product; +use Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitationFactory; + /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class CollectionTest extends \PHPUnit_Framework_TestCase { + /** + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + */ + private $objectManager; + /** * @var \Magento\Review\Model\ResourceModel\Review\Product\Collection */ @@ -74,16 +81,23 @@ protected function setUp() false ); $fetchStrategy->expects($this->any())->method('fetchAll')->will($this->returnValue([])); - $this->model = (new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this)) - ->getObject( - \Magento\Review\Model\ResourceModel\Review\Product\Collection::class, - [ - 'universalFactory' => $universalFactory, - 'storeManager' => $storeManager, - 'eavConfig' => $eavConfig, - 'fetchStrategy' => $fetchStrategy - ] - ); + $productLimitationMock = $this->getMock( + \Magento\Catalog\Model\ResourceModel\Product\Collection\ProductLimitation::class + ); + $productLimitationFactoryMock = $this->getMock(ProductLimitationFactory::class, ['create']); + $productLimitationFactoryMock->method('create') + ->willReturn($productLimitationMock); + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->model = $this->objectManager->getObject( + \Magento\Review\Model\ResourceModel\Review\Product\Collection::class, + [ + 'universalFactory' => $universalFactory, + 'storeManager' => $storeManager, + 'eavConfig' => $eavConfig, + 'fetchStrategy' => $fetchStrategy, + 'productLimitationFactory' => $productLimitationFactoryMock + ] + ); } /** diff --git a/app/code/Magento/Rss/Model/Rss.php b/app/code/Magento/Rss/Model/Rss.php index 0f228cb9a21c2..af716613bd261 100644 --- a/app/code/Magento/Rss/Model/Rss.php +++ b/app/code/Magento/Rss/Model/Rss.php @@ -5,13 +5,10 @@ */ namespace Magento\Rss\Model; +use Magento\Framework\App\ObjectManager; use Magento\Framework\App\Rss\DataProviderInterface; +use Magento\Framework\Serialize\SerializerInterface; -/** - * Auth session model - * - * @author Magento Core Team - */ class Rss { /** @@ -25,11 +22,22 @@ class Rss protected $cache; /** + * @var SerializerInterface + */ + private $serializer; + + /** + * Rss constructor + * * @param \Magento\Framework\App\CacheInterface $cache + * @param SerializerInterface|null $serializer */ - public function __construct(\Magento\Framework\App\CacheInterface $cache) - { + public function __construct( + \Magento\Framework\App\CacheInterface $cache, + SerializerInterface $serializer = null + ) { $this->cache = $cache; + $this->serializer = $serializer ?: ObjectManager::getInstance()->get(SerializerInterface::class); } /** @@ -46,14 +54,14 @@ public function getFeeds() } if ($cache) { - return unserialize($cache); + return $this->serializer->unserialize($cache); } $data = $this->dataProvider->getRssData(); if ($this->dataProvider->getCacheKey() && $this->dataProvider->getCacheLifetime()) { $this->cache->save( - serialize($data), + $this->serializer->serialize($data), $this->dataProvider->getCacheKey(), ['rss'], $this->dataProvider->getCacheLifetime() diff --git a/app/code/Magento/Rss/Test/Unit/Model/RssTest.php b/app/code/Magento/Rss/Test/Unit/Model/RssTest.php index 7a12c4818e71a..0c5eb303935ff 100644 --- a/app/code/Magento/Rss/Test/Unit/Model/RssTest.php +++ b/app/code/Magento/Rss/Test/Unit/Model/RssTest.php @@ -6,6 +6,7 @@ namespace Magento\Rss\Test\Unit\Model; +use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; class RssTest extends \PHPUnit_Framework_TestCase @@ -40,17 +41,23 @@ class RssTest extends \PHPUnit_Framework_TestCase /** * @var \Magento\Framework\App\CacheInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $cacheInterface; + private $cacheMock; + + /** + * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $serializerMock; protected function setUp() { - $this->cacheInterface = $this->getMock(\Magento\Framework\App\CacheInterface::class); - + $this->cacheMock = $this->getMock(\Magento\Framework\App\CacheInterface::class); + $this->serializerMock = $this->getMock(SerializerInterface::class); $this->objectManagerHelper = new ObjectManagerHelper($this); $this->rss = $this->objectManagerHelper->getObject( \Magento\Rss\Model\Rss::class, [ - 'cache' => $this->cacheInterface + 'cache' => $this->cacheMock, + 'serializer' => $this->serializerMock ] ); } @@ -64,8 +71,18 @@ public function testGetFeeds() $this->rss->setDataProvider($dataProvider); - $this->cacheInterface->expects($this->once())->method('load')->will($this->returnValue(false)); - $this->cacheInterface->expects($this->once())->method('save')->will($this->returnValue(true)); + $this->cacheMock->expects($this->once()) + ->method('load') + ->with('cache_key') + ->will($this->returnValue(false)); + $this->cacheMock->expects($this->once()) + ->method('save') + ->with('serializedData') + ->will($this->returnValue(true)); + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->with($this->feedData) + ->willReturn('serializedData'); $this->assertEquals($this->feedData, $this->rss->getFeeds()); } @@ -79,9 +96,15 @@ public function testGetFeedsWithCache() $this->rss->setDataProvider($dataProvider); - $this->cacheInterface->expects($this->once())->method('load') - ->will($this->returnValue(serialize($this->feedData))); - $this->cacheInterface->expects($this->never())->method('save'); + $this->cacheMock->expects($this->once()) + ->method('load') + ->with('cache_key') + ->will($this->returnValue('serializedData')); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with('serializedData') + ->willReturn($this->feedData); + $this->cacheMock->expects($this->never())->method('save'); $this->assertEquals($this->feedData, $this->rss->getFeeds()); } diff --git a/app/code/Magento/Rule/Model/AbstractModel.php b/app/code/Magento/Rule/Model/AbstractModel.php index 45f0c092c4aec..73e3db2c8a358 100644 --- a/app/code/Magento/Rule/Model/AbstractModel.php +++ b/app/code/Magento/Rule/Model/AbstractModel.php @@ -3,9 +3,11 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ - namespace Magento\Rule\Model; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\ExtensionAttributesFactory; + /** * Abstract Rule entity data model * @SuppressWarnings(PHPMD.CouplingBetweenObjects) @@ -76,7 +78,7 @@ abstract public function getActionsInstance(); protected $_localeDate; /** - * AbstractModel constructor. + * AbstractModel constructor * * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry @@ -85,6 +87,8 @@ abstract public function getActionsInstance(); * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection * @param array $data + * @param ExtensionAttributesFactory|null $extensionFactory + * @param AttributeValueFactory|null $customAttributeFactory */ public function __construct( \Magento\Framework\Model\Context $context, @@ -93,15 +97,17 @@ public function __construct( \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [] + array $data = [], + ExtensionAttributesFactory $extensionFactory = null, + AttributeValueFactory $customAttributeFactory = null ) { $this->_formFactory = $formFactory; $this->_localeDate = $localeDate; parent::__construct( $context, $registry, - $this->getExtensionFactory(), - $this->getCustomAttributeFactory(), + $extensionFactory ?: $this->getExtensionFactory(), + $customAttributeFactory ?: $this->getCustomAttributeFactory(), $resource, $resourceCollection, $data diff --git a/app/code/Magento/Sales/Model/Config/Data.php b/app/code/Magento/Sales/Model/Config/Data.php index 6d3d3a2ac1234..b6a1b43012f9e 100644 --- a/app/code/Magento/Sales/Model/Config/Data.php +++ b/app/code/Magento/Sales/Model/Config/Data.php @@ -3,24 +3,29 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ +namespace Magento\Sales\Model\Config; + +use Magento\Framework\Serialize\SerializerInterface; /** - * Sales configuration data container + * Provides sales configuration */ -namespace Magento\Sales\Model\Config; - class Data extends \Magento\Framework\Config\Data { /** - * @param \Magento\Sales\Model\Config\Reader $reader + * Constructor + * + * @param Reader $reader * @param \Magento\Framework\Config\CacheInterface $cache - * @param string $cacheId + * @param string|null $cacheId + * @param SerializerInterface|null $serializer */ public function __construct( \Magento\Sales\Model\Config\Reader $reader, \Magento\Framework\Config\CacheInterface $cache, - $cacheId = 'sales_totals_config_cache' + $cacheId = 'sales_totals_config_cache', + SerializerInterface $serializer = null ) { - parent::__construct($reader, $cache, $cacheId); + parent::__construct($reader, $cache, $cacheId, $serializer); } } diff --git a/app/code/Magento/Sales/Test/Unit/Model/Config/DataTest.php b/app/code/Magento/Sales/Test/Unit/Model/Config/DataTest.php index 722fdb2b9495f..0c342ff115eaf 100644 --- a/app/code/Magento/Sales/Test/Unit/Model/Config/DataTest.php +++ b/app/code/Magento/Sales/Test/Unit/Model/Config/DataTest.php @@ -7,31 +7,56 @@ class DataTest extends \PHPUnit_Framework_TestCase { + /** + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + */ + private $objectManager; + /** * @var \PHPUnit_Framework_MockObject_MockObject */ - protected $_readerMock; + private $_readerMock; /** * @var \PHPUnit_Framework_MockObject_MockObject */ - protected $_cacheMock; + private $_cacheMock; + + /** + * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $serializerMock; protected function setUp() { + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->_readerMock = $this->getMockBuilder( \Magento\Sales\Model\Config\Reader::class )->disableOriginalConstructor()->getMock(); $this->_cacheMock = $this->getMockBuilder( \Magento\Framework\App\Cache\Type\Config::class )->disableOriginalConstructor()->getMock(); + $this->serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); } public function testGet() { $expected = ['someData' => ['someValue', 'someKey' => 'someValue']]; - $this->_cacheMock->expects($this->any())->method('load')->will($this->returnValue(serialize($expected))); - $configData = new \Magento\Sales\Model\Config\Data($this->_readerMock, $this->_cacheMock); + $this->_cacheMock->expects($this->once()) + ->method('load'); + + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->willReturn($expected); + + $configData = $this->objectManager->getObject( + \Magento\Sales\Model\Config\Data::class, + [ + 'reader' => $this->_readerMock, + 'cache' => $this->_cacheMock, + 'serializer' => $this->serializerMock, + ] + ); $this->assertEquals($expected, $configData->get()); } diff --git a/app/code/Magento/SalesRule/Model/ResourceModel/Rule.php b/app/code/Magento/SalesRule/Model/ResourceModel/Rule.php index 78cc3e1c39c27..0398508eccf3e 100644 --- a/app/code/Magento/SalesRule/Model/ResourceModel/Rule.php +++ b/app/code/Magento/SalesRule/Model/ResourceModel/Rule.php @@ -5,12 +5,11 @@ */ namespace Magento\SalesRule\Model\ResourceModel; +use Magento\Framework\App\ObjectManager; use \Magento\SalesRule\Model\Rule as SalesRule; use Magento\Framework\Model\AbstractModel; -use Magento\Framework\DB\Select; use Magento\Rule\Model\ResourceModel\AbstractResource; use Magento\Framework\EntityManager\EntityManager; -use Magento\SalesRule\Api\Data\RuleInterface; /** * Sales Rule resource model @@ -56,16 +55,21 @@ class Rule extends AbstractResource * @param \Magento\Framework\Stdlib\StringUtils $string * @param \Magento\SalesRule\Model\ResourceModel\Coupon $resourceCoupon * @param string $connectionName + * @param \Magento\Framework\DataObject|null $associatedEntityMapInstance */ public function __construct( \Magento\Framework\Model\ResourceModel\Db\Context $context, \Magento\Framework\Stdlib\StringUtils $string, \Magento\SalesRule\Model\ResourceModel\Coupon $resourceCoupon, - $connectionName = null + $connectionName = null, + \Magento\Framework\DataObject $associatedEntityMapInstance = null ) { $this->string = $string; $this->_resourceCoupon = $resourceCoupon; - $this->_associatedEntitiesMap = $this->getAssociatedEntitiesMap(); + $associatedEntitiesMapInstance = $associatedEntityMapInstance ?: ObjectManager::getInstance()->get( + \Magento\SalesRule\Model\ResourceModel\Rule\AssociatedEntityMap::class + ); + $this->_associatedEntitiesMap = $associatedEntitiesMapInstance->getData(); parent::__construct($context, $connectionName); } @@ -380,20 +384,6 @@ public function delete(AbstractModel $object) return $this; } - /** - * @return array - * @deprecated - */ - private function getAssociatedEntitiesMap() - { - if (!$this->_associatedEntitiesMap) { - $this->_associatedEntitiesMap = \Magento\Framework\App\ObjectManager::getInstance() - ->get(\Magento\SalesRule\Model\ResourceModel\Rule\AssociatedEntityMap::class) - ->getData(); - } - return $this->_associatedEntitiesMap; - } - /** * @return \Magento\Framework\EntityManager\EntityManager * @deprecated diff --git a/app/code/Magento/SalesRule/Model/Rule.php b/app/code/Magento/SalesRule/Model/Rule.php index 3253c040ac9f9..033c0ebd5be90 100644 --- a/app/code/Magento/SalesRule/Model/Rule.php +++ b/app/code/Magento/SalesRule/Model/Rule.php @@ -5,6 +5,8 @@ */ namespace Magento\SalesRule\Model; +use Magento\Framework\Api\AttributeValueFactory; +use Magento\Framework\Api\ExtensionAttributesFactory; use Magento\Quote\Model\Quote\Address; /** @@ -171,6 +173,8 @@ class Rule extends \Magento\Rule\Model\AbstractModel protected $_storeManager; /** + * Rule constructor + * * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry * @param \Magento\Framework\Data\FormFactory $formFactory @@ -184,6 +188,9 @@ class Rule extends \Magento\Rule\Model\AbstractModel * @param \Magento\Framework\Model\ResourceModel\AbstractResource|null $resource * @param \Magento\Framework\Data\Collection\AbstractDb|null $resourceCollection * @param array $data + * @param ExtensionAttributesFactory|null $extensionFactory + * @param AttributeValueFactory|null $customAttributeFactory + * * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -199,7 +206,9 @@ public function __construct( \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [] + array $data = [], + ExtensionAttributesFactory $extensionFactory = null, + AttributeValueFactory $customAttributeFactory = null ) { $this->_couponFactory = $couponFactory; $this->_codegenFactory = $codegenFactory; @@ -214,7 +223,9 @@ public function __construct( $localeDate, $resource, $resourceCollection, - $data + $data, + $extensionFactory, + $customAttributeFactory ); } diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/RuleTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/RuleTest.php index 5c60007543916..763e77f94f7a2 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/RuleTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/ResourceModel/RuleTest.php @@ -3,16 +3,18 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ - namespace Magento\SalesRule\Test\Unit\Model\ResourceModel; -use Magento\SalesRule\Api\Data\RuleInterface; - /** * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class RuleTest extends \PHPUnit_Framework_TestCase { + /** + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + */ + private $objectManager; + /** * @var \Magento\SalesRule\Model\ResourceModel\Rule */ @@ -60,7 +62,7 @@ class RuleTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->rule = $this->getMockBuilder(\Magento\SalesRule\Model\Rule::class) ->disableOriginalConstructor() ->getMock(); @@ -117,7 +119,13 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $associatedEntitiesMap = $this->getMock(\Magento\Framework\DataObject::class, [], [], '', false); + $associatedEntitiesMap = $this->getMock( + \Magento\Framework\DataObject::class, + ['getData'], + [], + '', + false + ); $associatedEntitiesMap->expects($this->once()) ->method('getData') ->willReturn( @@ -135,19 +143,13 @@ protected function setUp() ] ); - $this->prepareObjectManager([ - [ - \Magento\SalesRule\Model\ResourceModel\Rule\AssociatedEntityMap::class, - $associatedEntitiesMap - ], - ]); - - $this->model = $objectManager->getObject( + $this->model = $this->objectManager->getObject( \Magento\SalesRule\Model\ResourceModel\Rule::class, [ 'context' => $context, 'connectionName' => $connectionName, 'entityManager' => $this->entityManager, + 'associatedEntityMapInstance' => $associatedEntitiesMap ] ); } @@ -184,20 +186,4 @@ public function testDelete() ->with($this->rule); $this->assertEquals($this->model->delete($this->rule), $this->model); } - - /** - * @param $map - */ - private function prepareObjectManager($map) - { - $objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); - $objectManagerMock->expects($this->any())->method('getInstance')->willReturnSelf(); - $objectManagerMock->expects($this->any()) - ->method('get') - ->will($this->returnValueMap($map)); - $reflectionClass = new \ReflectionClass(\Magento\Framework\App\ObjectManager::class); - $reflectionProperty = $reflectionClass->getProperty('_instance'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($objectManagerMock); - } } diff --git a/app/code/Magento/SalesRule/Test/Unit/Model/RuleTest.php b/app/code/Magento/SalesRule/Test/Unit/Model/RuleTest.php index f3d16c188fdf9..48cd2ab7c4850 100644 --- a/app/code/Magento/SalesRule/Test/Unit/Model/RuleTest.php +++ b/app/code/Magento/SalesRule/Test/Unit/Model/RuleTest.php @@ -3,7 +3,6 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ - namespace Magento\SalesRule\Test\Unit\Model; class RuleTest extends \PHPUnit_Framework_TestCase @@ -57,17 +56,6 @@ protected function setUp() ->setMethods(['create']) ->getMock(); - $this->prepareObjectManager([ - [ - \Magento\Framework\Api\ExtensionAttributesFactory::class, - $this->getMock(\Magento\Framework\Api\ExtensionAttributesFactory::class, [], [], '', false) - ], - [ - \Magento\Framework\Api\AttributeValueFactory::class, - $this->getMock(\Magento\Framework\Api\AttributeValueFactory::class, [], [], '', false) - ], - ]); - $this->model = $objectManager->getObject( \Magento\SalesRule\Model\Rule::class, [ @@ -179,20 +167,4 @@ public function testGetActionsFieldSetId() $expectedResult = 'form_namerule_actions_fieldset_100'; $this->assertEquals($expectedResult, $this->model->getActionsFieldSetId($formName)); } - - /** - * @param $map - */ - private function prepareObjectManager($map) - { - $objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); - $objectManagerMock->expects($this->any())->method('getInstance')->willReturnSelf(); - $objectManagerMock->expects($this->any()) - ->method('get') - ->will($this->returnValueMap($map)); - $reflectionClass = new \ReflectionClass(\Magento\Framework\App\ObjectManager::class); - $reflectionProperty = $reflectionClass->getProperty('_instance'); - $reflectionProperty->setAccessible(true); - $reflectionProperty->setValue($objectManagerMock); - } } diff --git a/app/code/Magento/Search/Model/SearchEngine/Config/Data.php b/app/code/Magento/Search/Model/SearchEngine/Config/Data.php index 18a3b620eee18..d128a9d50025d 100644 --- a/app/code/Magento/Search/Model/SearchEngine/Config/Data.php +++ b/app/code/Magento/Search/Model/SearchEngine/Config/Data.php @@ -5,6 +5,11 @@ */ namespace Magento\Search\Model\SearchEngine\Config; +use Magento\Framework\Serialize\SerializerInterface; + +/** + * Provides search engine configuration + */ class Data extends \Magento\Framework\Config\Data { /** @@ -12,13 +17,15 @@ class Data extends \Magento\Framework\Config\Data * * @param \Magento\Framework\Search\SearchEngine\Config\Reader $reader * @param \Magento\Framework\Config\CacheInterface $cache - * @param string $cacheId + * @param string|null $cacheId + * @param SerializerInterface|null $serializer */ public function __construct( \Magento\Framework\Search\SearchEngine\Config\Reader $reader, \Magento\Framework\Config\CacheInterface $cache, - $cacheId = 'search_engine_config_cache' + $cacheId = 'search_engine_config_cache', + SerializerInterface $serializer = null ) { - parent::__construct($reader, $cache, $cacheId); + parent::__construct($reader, $cache, $cacheId, $serializer); } } diff --git a/app/code/Magento/Store/Model/StoreResolver.php b/app/code/Magento/Store/Model/StoreResolver.php index a19d75d9f47e0..cfb57849f25a8 100644 --- a/app/code/Magento/Store/Model/StoreResolver.php +++ b/app/code/Magento/Store/Model/StoreResolver.php @@ -5,8 +5,7 @@ */ namespace Magento\Store\Model; -use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Store\Api\StoreCookieManagerInterface; +use Magento\Framework\Serialize\SerializerInterface; class StoreResolver implements \Magento\Store\Api\StoreResolverInterface { @@ -21,7 +20,7 @@ class StoreResolver implements \Magento\Store\Api\StoreResolverInterface protected $storeRepository; /** - * @var StoreCookieManagerInterface + * @var \Magento\Store\Api\StoreCookieManagerInterface */ protected $storeCookieManager; @@ -31,7 +30,7 @@ class StoreResolver implements \Magento\Store\Api\StoreResolverInterface protected $cache; /** - * @var StoreResolver\ReaderList + * @var \Magento\Store\Model\StoreResolver\ReaderList */ protected $readerList; @@ -50,21 +49,26 @@ class StoreResolver implements \Magento\Store\Api\StoreResolverInterface */ protected $request; + /** + * @var \Magento\Framework\Serialize\SerializerInterface + */ + private $serializer; + /** * @param \Magento\Store\Api\StoreRepositoryInterface $storeRepository - * @param StoreCookieManagerInterface $storeCookieManager + * @param \Magento\Store\Api\StoreCookieManagerInterface $storeCookieManager * @param \Magento\Framework\App\RequestInterface $request * @param \Magento\Framework\Cache\FrontendInterface $cache - * @param StoreResolver\ReaderList $readerList + * @param \Magento\Store\Model\StoreResolver\ReaderList $readerList * @param string $runMode * @param null $scopeCode */ public function __construct( \Magento\Store\Api\StoreRepositoryInterface $storeRepository, - StoreCookieManagerInterface $storeCookieManager, + \Magento\Store\Api\StoreCookieManagerInterface $storeCookieManager, \Magento\Framework\App\RequestInterface $request, \Magento\Framework\Cache\FrontendInterface $cache, - StoreResolver\ReaderList $readerList, + \Magento\Store\Model\StoreResolver\ReaderList $readerList, $runMode = ScopeInterface::SCOPE_STORE, $scopeCode = null ) { @@ -94,7 +98,7 @@ public function getCurrentStoreId() if ($storeCode) { try { $store = $this->getRequestedStoreByCode($storeCode); - } catch (NoSuchEntityException $e) { + } catch (\Magento\Framework\Exception\NoSuchEntityException $e) { $store = $this->getDefaultStoreById($defaultStoreId); } @@ -117,10 +121,10 @@ protected function getStoresData() $cacheKey = 'resolved_stores_' . md5($this->runMode . $this->scopeCode); $cacheData = $this->cache->load($cacheKey); if ($cacheData) { - $storesData = unserialize($cacheData); + $storesData = $this->getSerializer()->unserialize($cacheData); } else { $storesData = $this->readStoresData(); - $this->cache->save(serialize($storesData), $cacheKey, [self::CACHE_TAG]); + $this->cache->save($this->getSerializer()->serialize($storesData), $cacheKey, [self::CACHE_TAG]); } return $storesData; } @@ -141,14 +145,14 @@ protected function readStoresData() * * @param string $storeCode * @return \Magento\Store\Api\Data\StoreInterface - * @throws NoSuchEntityException + * @throws \Magento\Framework\Exception\NoSuchEntityException */ protected function getRequestedStoreByCode($storeCode) { try { $store = $this->storeRepository->getActiveStoreByCode($storeCode); } catch (StoreIsInactiveException $e) { - throw new NoSuchEntityException(__('Requested store is inactive')); + throw new \Magento\Framework\Exception\NoSuchEntityException(__('Requested store is inactive')); } return $store; @@ -159,16 +163,31 @@ protected function getRequestedStoreByCode($storeCode) * * @param int $id * @return \Magento\Store\Api\Data\StoreInterface - * @throws NoSuchEntityException + * @throws \Magento\Framework\Exception\NoSuchEntityException */ protected function getDefaultStoreById($id) { try { $store = $this->storeRepository->getActiveStoreById($id); } catch (StoreIsInactiveException $e) { - throw new NoSuchEntityException(__('Default store is inactive')); + throw new \Magento\Framework\Exception\NoSuchEntityException(__('Default store is inactive')); } return $store; } + + /** + * Get serializer + * + * @return \Magento\Framework\Serialize\SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if ($this->serializer === null) { + $this->serializer = \Magento\Framework\App\ObjectManager::getInstance() + ->get(SerializerInterface::class); + } + return $this->serializer; + } } diff --git a/app/code/Magento/Theme/Model/Design.php b/app/code/Magento/Theme/Model/Design.php index 39527afc0250d..55941cfbcacb6 100644 --- a/app/code/Magento/Theme/Model/Design.php +++ b/app/code/Magento/Theme/Model/Design.php @@ -6,9 +6,11 @@ namespace Magento\Theme\Model; use Magento\Framework\App\DesignInterface; +use Magento\Framework\App\ObjectManager; use Magento\Framework\Model\AbstractModel; use Magento\Framework\Model\ResourceModel\AbstractResource; use Magento\Framework\DataObject\IdentityInterface; +use Magento\Framework\Serialize\SerializerInterface; /** * Design settings change model @@ -55,6 +57,11 @@ class Design extends AbstractModel implements IdentityInterface, DesignInterface */ protected $_dateTime; + /** + * @var SerializerInterface + */ + private $serializer; + /** * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry @@ -63,6 +70,7 @@ class Design extends AbstractModel implements IdentityInterface, DesignInterface * @param AbstractResource $resource * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection * @param array $data + * @param SerializerInterface $serializer */ public function __construct( \Magento\Framework\Model\Context $context, @@ -71,10 +79,12 @@ public function __construct( \Magento\Framework\Stdlib\DateTime $dateTime, AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, - array $data = [] + array $data = [], + SerializerInterface $serializer = null ) { $this->_localeDate = $localeDate; $this->_dateTime = $dateTime; + $this->serializer = $serializer ?: ObjectManager::getInstance()->get(SerializerInterface::class); parent::__construct($context, $registry, $resource, $resourceCollection, $data); } @@ -108,9 +118,9 @@ public function loadChange($storeId, $date = null) if (!$result) { $result = []; } - $this->_cacheManager->save(serialize($result), $changeCacheId, [self::CACHE_TAG], 86400); + $this->_cacheManager->save($this->serializer->serialize($result), $changeCacheId, [self::CACHE_TAG], 86400); } else { - $result = unserialize($result); + $result = $this->serializer->unserialize($result); } if ($result) { diff --git a/app/code/Magento/Theme/Test/Unit/Model/DesignTest.php b/app/code/Magento/Theme/Test/Unit/Model/DesignTest.php index dc11a4c46eda5..67f86575a8afd 100644 --- a/app/code/Magento/Theme/Test/Unit/Model/DesignTest.php +++ b/app/code/Magento/Theme/Test/Unit/Model/DesignTest.php @@ -9,6 +9,7 @@ */ namespace Magento\Theme\Test\Unit\Model; +use Magento\Framework\Serialize\SerializerInterface; use Magento\Theme\Model\Design; class DesignTest extends \PHPUnit_Framework_TestCase @@ -23,11 +24,6 @@ class DesignTest extends \PHPUnit_Framework_TestCase */ protected $cacheManager; - /** - * @var \Magento\Framework\Registry|\PHPUnit_Framework_MockObject_MockObject - */ - protected $registry; - /** * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface|\PHPUnit_Framework_MockObject_MockObject */ @@ -44,18 +40,15 @@ class DesignTest extends \PHPUnit_Framework_TestCase protected $resource; /** - * @var \Magento\Framework\Data\Collection\AbstractDb|\PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $resourceCollection; + private $serializerMock; protected function setUp() { $context = $this->getMockBuilder(\Magento\Framework\Model\Context::class) ->disableOriginalConstructor() ->getMock(); - $this->registry = $this->getMockBuilder( - \Magento\Framework\Registry::class - )->disableOriginalConstructor()->getMock(); $this->localeDate = $this->getMockBuilder( \Magento\Framework\Stdlib\DateTime\TimezoneInterface::class )->getMock(); @@ -65,25 +58,24 @@ protected function setUp() $this->resource = $this->getMockBuilder(\Magento\Theme\Model\ResourceModel\Design::class) ->disableOriginalConstructor() ->getMock(); - $this->resourceCollection = $this->getMockBuilder(\Magento\Theme\Model\ResourceModel\Design\Collection::class) - ->disableOriginalConstructor() - ->getMock(); $this->cacheManager = $this->getMockBuilder(\Magento\Framework\App\CacheInterface::class)->getMock(); $context->expects($this->any()) ->method('getCacheManager') ->willReturn($this->cacheManager); - /** - * @var $context \Magento\Framework\Model\Context - */ - $this->model = new Design( - $context, - $this->registry, - $this->localeDate, - $this->dateTime, - $this->resource, - $this->resourceCollection + $this->serializerMock = $this->getMock(SerializerInterface::class); + + $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->model = $objectManager->getObject( + Design::class, + [ + 'context' => $context, + 'localeDate' => $this->localeDate, + 'dateTime' => $this->dateTime, + 'resource' => $this->resource, + 'serializer' => $this->serializerMock, + ] ); } @@ -119,9 +111,12 @@ public function testLoadChange() ->method('loadChange') ->with($storeId, $date) ->willReturn(false); + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->willReturn('serializedData'); $this->cacheManager->expects($this->once()) ->method('save') - ->with(serialize([]), $cacheId, [Design::CACHE_TAG], 86400) + ->with('serializedData', $cacheId, [Design::CACHE_TAG], 86400) ->willReturnSelf(); $this->assertInstanceOf(get_class($this->model), $this->model->loadChange($storeId)); @@ -151,9 +146,16 @@ public function testLoadChangeFromCache() $this->cacheManager->expects($this->once()) ->method('load') ->with($cacheId) - ->willReturn(serialize(['test' => 'data'])); - - $this->assertInstanceOf(get_class($this->model), $this->model->loadChange($storeId)); + ->willReturn('serializedData'); + $data = ['test' => 'data']; + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with('serializedData') + ->willReturn($data); + + $change = $this->model->loadChange($storeId); + $this->assertInstanceOf(get_class($this->model), $change); + $this->assertEquals($data, $change->getData()); } /** diff --git a/app/code/Magento/Webapi/Test/Unit/Model/DataObjectProcessorTest.php b/app/code/Magento/Webapi/Test/Unit/Model/DataObjectProcessorTest.php index 4ab1609816332..0565832932a3f 100644 --- a/app/code/Magento/Webapi/Test/Unit/Model/DataObjectProcessorTest.php +++ b/app/code/Magento/Webapi/Test/Unit/Model/DataObjectProcessorTest.php @@ -6,6 +6,8 @@ namespace Magento\Webapi\Test\Unit\Model; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\Reflection\DataObjectProcessor; use Magento\Webapi\Model\Config as ModelConfig; class DataObjectProcessorTest extends \PHPUnit_Framework_TestCase @@ -30,6 +32,17 @@ protected function setup() 'typeProcessor' => $objectManager->getObject(\Magento\Framework\Reflection\TypeProcessor::class), ] ); + $serializerMock = $this->getMock(SerializerInterface::class); + $serializerMock->method('serialize') + ->willReturn('serializedData'); + $serializerMock->method('unserialize') + ->willReturn(['unserializedData']); + + $objectManager->setBackwardCompatibleProperty( + $methodsMapProcessor, + 'serializer', + $serializerMock + ); $this->dataObjectProcessor = $objectManager->getObject( \Magento\Framework\Reflection\DataObjectProcessor::class, [ diff --git a/dev/tests/integration/framework/Magento/TestFramework/Helper/CacheCleaner.php b/dev/tests/integration/framework/Magento/TestFramework/Helper/CacheCleaner.php new file mode 100644 index 0000000000000..5d7748f0b1fd9 --- /dev/null +++ b/dev/tests/integration/framework/Magento/TestFramework/Helper/CacheCleaner.php @@ -0,0 +1,50 @@ +get($cacheType)->getBackend()->clean(); + } + } + + /** + * Clean all cache + */ + public static function cleanAll() + { + $cachePool = self::getCachePool(); + foreach ($cachePool as $cacheType) { + $cacheType->getBackend()->clean(); + } + } + + /** + * Get cache pool + * + * @return Pool + */ + private static function getCachePool() + { + return Bootstrap::getObjectManager() + ->get(Pool::class); + } +} diff --git a/dev/tests/integration/framework/Magento/TestFramework/Interception/PluginList.php b/dev/tests/integration/framework/Magento/TestFramework/Interception/PluginList.php index 9e8901c91fd75..18cdc66cb3f2e 100644 --- a/dev/tests/integration/framework/Magento/TestFramework/Interception/PluginList.php +++ b/dev/tests/integration/framework/Magento/TestFramework/Interception/PluginList.php @@ -5,6 +5,11 @@ */ namespace Magento\TestFramework\Interception; +use Magento\Framework\Serialize\SerializerInterface; + +/** + * Provides plugin list configuration + */ class PluginList extends \Magento\Framework\Interception\PluginList\PluginList { /** @@ -13,6 +18,8 @@ class PluginList extends \Magento\Framework\Interception\PluginList\PluginList protected $_originScopeScheme = []; /** + * Constructor + * * @param \Magento\Framework\Config\ReaderInterface $reader * @param \Magento\Framework\Config\ScopeInterface $configScope * @param \Magento\Framework\Config\CacheInterface $cache @@ -22,8 +29,8 @@ class PluginList extends \Magento\Framework\Interception\PluginList\PluginList * @param \Magento\Framework\ObjectManagerInterface $objectManager * @param \Magento\Framework\ObjectManager\DefinitionInterface $classDefinitions * @param array $scopePriorityScheme - * @param string $cacheId - * + * @param string|null $cacheId + * @param SerializerInterface|null $serializer * @SuppressWarnings(PHPMD.ExcessiveParameterList) */ public function __construct( @@ -36,7 +43,8 @@ public function __construct( \Magento\Framework\ObjectManagerInterface $objectManager, \Magento\Framework\ObjectManager\DefinitionInterface $classDefinitions, array $scopePriorityScheme, - $cacheId = 'plugins' + $cacheId = 'plugins', + SerializerInterface $serializer = null ) { parent::__construct( $reader, @@ -48,7 +56,8 @@ public function __construct( $objectManager, $classDefinitions, $scopePriorityScheme, - $cacheId + $cacheId, + $serializer ); $this->_originScopeScheme = $this->_scopePriorityScheme; } diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/ConfigTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/ConfigTest.php new file mode 100644 index 0000000000000..178107e487e92 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/ConfigTest.php @@ -0,0 +1,61 @@ +objectManager = Bootstrap::getObjectManager(); + $this->config = $this->objectManager->get(Config::class); + } + + public function testGetEntityAttributeCodes() + { + $entityType = 'catalog_product'; + CacheCleaner::cleanAll(); + $this->assertEquals( + $this->config->getEntityAttributeCodes($entityType), + $this->config->getEntityAttributeCodes($entityType) + ); + } + + public function testGetAttribute() + { + $entityType = 'catalog_product'; + $attributeCode = 'color'; + CacheCleaner::cleanAll(); + $this->assertEquals( + $this->config->getAttribute($entityType, $attributeCode), + $this->config->getAttribute($entityType, $attributeCode) + ); + } + + public function testGetEntityType() + { + $entityType = 'catalog_product'; + CacheCleaner::cleanAll(); + $this->assertEquals( + $this->config->getEntityType($entityType), + $this->config->getEntityType($entityType) + ); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Source/CountryofmanufactureTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Source/CountryofmanufactureTest.php new file mode 100644 index 0000000000000..34fd3b678a086 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/Product/Attribute/Source/CountryofmanufactureTest.php @@ -0,0 +1,32 @@ +model = $objectManager->create( + \Magento\Catalog\Model\Product\Attribute\Source\Countryofmanufacture::class + ); + } + + public function testGetAllOptions() + { + CacheCleaner::cleanAll(); + $allOptions = $this->model->getAllOptions(); + $cachedAllOptions = $this->model->getAllOptions(); + $this->assertEquals($allOptions, $cachedAllOptions); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/CategoriesTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/CategoriesTest.php new file mode 100644 index 0000000000000..b01d1e6d38655 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/CategoriesTest.php @@ -0,0 +1,50 @@ +get(\Magento\Framework\Registry::class); + /** @var $store \Magento\Store\Model\Store */ + $store = $objectManager->create(\Magento\Store\Model\Store::class); + $store->load('admin'); + $registry->register('current_store', $store); + $this->object = $objectManager->create(Categories::class); + } + + public function testModifyMeta() + { + $inputMeta = include __DIR__ . '/_files/input_meta_for_categories.php'; + $expectedCategories = include __DIR__ . '/_files/expected_categories.php'; + CacheCleaner::cleanAll(); + $this->assertCategoriesInMeta($expectedCategories, $this->object->modifyMeta($inputMeta)); + // Verify cached data + $this->assertCategoriesInMeta($expectedCategories, $this->object->modifyMeta($inputMeta)); + } + + private function assertCategoriesInMeta(array $expectedCategories, array $meta) + { + $categoriesElement = $meta['product-details']['children']['container_category_ids']['children']['category_ids']; + $this->assertEquals($expectedCategories, $categoriesElement['arguments']['data']['config']['options']); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/_files/expected_categories.php b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/_files/expected_categories.php new file mode 100644 index 0000000000000..ed30676e16b07 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/_files/expected_categories.php @@ -0,0 +1,89 @@ + + [ + 'value' => '2', + 'is_active' => '1', + 'label' => 'Default Category', + 'optgroup' => + [ + 0 => + [ + 'value' => '3', + 'is_active' => '1', + 'label' => 'Category 1', + 'optgroup' => + [ + 0 => + [ + 'value' => '4', + 'is_active' => '1', + 'label' => 'Category 1.1', + 'optgroup' => + [ + 0 => + [ + 'value' => '5', + 'is_active' => '1', + 'label' => 'Category 1.1.1', + ], + ], + ], + 1 => + [ + 'value' => '13', + 'is_active' => '1', + 'label' => 'Category 1.2', + ], + ], + ], + 1 => + [ + 'value' => '6', + 'is_active' => '1', + 'label' => 'Category 2', + ], + 2 => + [ + 'value' => '7', + 'is_active' => '1', + 'label' => 'Movable', + ], + 3 => + [ + 'value' => '8', + 'is_active' => '0', + 'label' => 'Inactive', + ], + 4 => + [ + 'value' => '9', + 'is_active' => '1', + 'label' => 'Movable Position 1', + ], + 5 => + [ + 'value' => '10', + 'is_active' => '1', + 'label' => 'Movable Position 2', + ], + 6 => + [ + 'value' => '11', + 'is_active' => '1', + 'label' => 'Movable Position 3', + ], + 7 => + [ + 'value' => '12', + 'is_active' => '1', + 'label' => 'Category 12', + ], + ], + ], +]; diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/_files/input_meta_for_categories.php b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/_files/input_meta_for_categories.php new file mode 100644 index 0000000000000..f43e9c916fcd2 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Catalog/Ui/DataProvider/Product/Form/Modifier/_files/input_meta_for_categories.php @@ -0,0 +1,56 @@ + + [ + 'children' => + ['container_category_ids' => + [ + 'arguments' => + [ + 'data' => + [ + 'config' => + [ + 'formElement' => 'container', + 'componentType' => 'container', + 'breakLine' => false, + 'label' => 'Categories', + 'required' => '0', + 'sortOrder' => 70, + ], + ], + ], + 'children' => + [ + 'category_ids' => + [ + 'arguments' => + [ + 'data' => + [ + 'config' => + [ + 'dataType' => 'text', + 'formElement' => 'input', + 'visible' => '1', + 'required' => '0', + 'notice' => null, + 'default' => null, + 'label' => 'Categories', + 'code' => 'category_ids', + 'source' => 'product-details', + 'scopeLabel' => '[GLOBAL]', + 'globalScope' => true, + 'sortOrder' => 70, + 'componentType' => 'field', + ], + ], + ], + ], + ], + ]]]]; diff --git a/dev/tests/integration/testsuite/Magento/Directory/Block/DataTest.php b/dev/tests/integration/testsuite/Magento/Directory/Block/DataTest.php new file mode 100644 index 0000000000000..b0c08ed1792fc --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Directory/Block/DataTest.php @@ -0,0 +1,38 @@ +block = $objectManager->get(\Magento\Directory\Block\Data::class); + } + + public function testGetCountryHtmlSelect() + { + CacheCleaner::cleanAll(); + $result = $this->block->getCountryHtmlSelect(); + $resultTwo = $this->block->getCountryHtmlSelect(); + $this->assertEquals($result, $resultTwo); + } + + public function testGetRegionHtmlSelect() + { + CacheCleaner::cleanAll(); + $result = $this->block->getRegionHtmlSelect(); + $resultTwo = $this->block->getRegionHtmlSelect(); + $this->assertEquals($result, $resultTwo); + } +} diff --git a/dev/tests/integration/testsuite/Magento/DownloadableImportExport/Model/Import/Product/Type/DownloadableTest.php b/dev/tests/integration/testsuite/Magento/DownloadableImportExport/Model/Import/Product/Type/DownloadableTest.php index 8db369facf97f..d25e040688237 100644 --- a/dev/tests/integration/testsuite/Magento/DownloadableImportExport/Model/Import/Product/Type/DownloadableTest.php +++ b/dev/tests/integration/testsuite/Magento/DownloadableImportExport/Model/Import/Product/Type/DownloadableTest.php @@ -5,9 +5,7 @@ */ namespace Magento\DownloadableImportExport\Model\Import\Product\Type; -use Magento\Framework\App\Bootstrap; use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\ImportExport\Model\Import; /** * @magentoAppArea adminhtml diff --git a/dev/tests/integration/testsuite/Magento/Eav/Model/ConfigTest.php b/dev/tests/integration/testsuite/Magento/Eav/Model/ConfigTest.php new file mode 100644 index 0000000000000..4cb90c2c98c56 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Eav/Model/ConfigTest.php @@ -0,0 +1,40 @@ +objectManager = Bootstrap::getObjectManager(); + $this->config = $this->objectManager->get(Config::class); + } + + public function testGetEntityAttributeCodes() + { + $entityType = 'catalog_product'; + CacheCleaner::cleanAll(); + $this->assertEquals( + $this->config->getEntityAttributeCodes($entityType), + $this->config->getEntityAttributeCodes($entityType) + ); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Framework/App/Config/InitialTest.php b/dev/tests/integration/testsuite/Magento/Framework/App/Config/InitialTest.php new file mode 100644 index 0000000000000..a98704a130b3b --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Framework/App/Config/InitialTest.php @@ -0,0 +1,55 @@ +objectManager = Bootstrap::getObjectManager(); + } + + public function testGetMetadata() + { + CacheCleaner::cleanAll(); + $this->assertEquals( + $this->objectManager->create(Config::class)->getMetadata(), + $this->objectManager->create(Config::class)->getMetadata() + ); + } + + /** + * @param string $scope + * @dataProvider getDataDataProvider + */ + public function testGetData($scope) + { + CacheCleaner::cleanAll(); + $this->assertEquals( + $this->objectManager->create(Config::class)->getData($scope), + $this->objectManager->create(Config::class)->getData($scope) + ); + } + + public function getDataDataProvider() + { + return [ + ['default'], + ['stores|default'], + ['websites|default'] + ]; + } +} diff --git a/dev/tests/integration/testsuite/Magento/Framework/App/ObjectManager/ConfigLoaderTest.php b/dev/tests/integration/testsuite/Magento/Framework/App/ObjectManager/ConfigLoaderTest.php new file mode 100644 index 0000000000000..30e9c09e9b4c5 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Framework/App/ObjectManager/ConfigLoaderTest.php @@ -0,0 +1,33 @@ +object = $objectManager->create( + \Magento\Framework\App\ObjectManager\ConfigLoader::class + ); + } + + public function testLoad() + { + CacheCleaner::cleanAll(); + $data = $this->object->load('global'); + $this->assertNotEmpty($data); + $cachedData = $this->object->load('global'); + $this->assertEquals($data, $cachedData); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Framework/App/Route/ConfigTest.php b/dev/tests/integration/testsuite/Magento/Framework/App/Route/ConfigTest.php new file mode 100644 index 0000000000000..d0c4b562952ba --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Framework/App/Route/ConfigTest.php @@ -0,0 +1,45 @@ +objectManager = Bootstrap::getObjectManager(); + } + + /** + * @param string $route + * @param string $scope + * @dataProvider getRouteFrontNameDataProvider + */ + public function testGetRouteFrontName($route, $scope) + { + CacheCleaner::cleanAll(); + $this->assertEquals( + $this->objectManager->create(Config::class)->getRouteFrontName($route, $scope), + $this->objectManager->create(Config::class)->getRouteFrontName($route, $scope) + ); + } + + public function getRouteFrontNameDataProvider() + { + return [ + ['adminhtml', 'adminhtml'], + ['catalog', 'frontend'], + ]; + } +} diff --git a/dev/tests/integration/testsuite/Magento/Framework/Interception/AbstractPlugin.php b/dev/tests/integration/testsuite/Magento/Framework/Interception/AbstractPlugin.php index 5c0406ec372a5..43b962851c3bf 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/Interception/AbstractPlugin.php +++ b/dev/tests/integration/testsuite/Magento/Framework/Interception/AbstractPlugin.php @@ -71,6 +71,7 @@ public function setUpInterceptionConfig($pluginConfig) $definitions ); $interceptionDefinitions = new Definition\Runtime(); + $json = new \Magento\Framework\Serialize\Serializer\Json(); $sharedInstances = [ \Magento\Framework\Config\CacheInterface::class => $cache, \Magento\Framework\Config\ScopeInterface::class => $configScope, @@ -79,7 +80,8 @@ public function setUpInterceptionConfig($pluginConfig) \Magento\Framework\ObjectManager\ConfigInterface::class => $config, \Magento\Framework\Interception\ObjectManager\ConfigInterface::class => $config, \Magento\Framework\ObjectManager\DefinitionInterface::class => $definitions, - \Magento\Framework\Interception\DefinitionInterface::class => $interceptionDefinitions + \Magento\Framework\Interception\DefinitionInterface::class => $interceptionDefinitions, + \Magento\Framework\Serialize\SerializerInterface::class => $json, ]; $this->_objectManager = new \Magento\Framework\ObjectManager\ObjectManager( $factory, diff --git a/dev/tests/integration/testsuite/Magento/Framework/Reflection/MethodsMapTest.php b/dev/tests/integration/testsuite/Magento/Framework/Reflection/MethodsMapTest.php new file mode 100644 index 0000000000000..992b6a59382e7 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Framework/Reflection/MethodsMapTest.php @@ -0,0 +1,48 @@ +object = $objectManager->create( + \Magento\Framework\Reflection\MethodsMap::class + ); + } + + public function testGetMethodsMap() + { + CacheCleaner::cleanAll(); + $data = $this->object->getMethodsMap(\Magento\Framework\Reflection\MethodsMap::class); + $this->assertArrayHasKey('getMethodsMap', $data); + $cachedData = $this->object->getMethodsMap(\Magento\Framework\Reflection\MethodsMap::class); + $this->assertEquals($data, $cachedData); + } + + public function testGetMethodParams() + { + CacheCleaner::cleanAll(); + $data = $this->object->getMethodParams( + \Magento\Framework\Reflection\MethodsMap::class, + 'getMethodParams' + ); + $this->assertCount(2, $data); + $cachedData = $this->object->getMethodParams( + \Magento\Framework\Reflection\MethodsMap::class, + 'getMethodParams' + ); + $this->assertEquals($data, $cachedData); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Framework/TranslateTest.php b/dev/tests/integration/testsuite/Magento/Framework/TranslateTest.php index 0b3566a129b7f..93043a5deb12a 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/TranslateTest.php +++ b/dev/tests/integration/testsuite/Magento/Framework/TranslateTest.php @@ -6,6 +6,7 @@ namespace Magento\Framework; use Magento\TestFramework\Helper\Bootstrap; +use Magento\TestFramework\Helper\CacheCleaner; /** * @magentoAppIsolation enabled @@ -14,6 +15,9 @@ */ class TranslateTest extends \PHPUnit_Framework_TestCase { + /** @var \Magento\Framework\Translate */ + private $translate; + protected function setUp() { /** @var \Magento\Framework\View\FileSystem $viewFileSystem */ @@ -37,6 +41,7 @@ protected function setUp() $viewFileSystem->expects($this->any())->method('getDesignTheme')->will($this->returnValue($theme)); + /** @var \Magento\TestFramework\ObjectManager $objectManager */ $objectManager = Bootstrap::getObjectManager(); $objectManager->addSharedInstance($viewFileSystem, \Magento\Framework\View\FileSystem::class); @@ -72,19 +77,31 @@ protected function setUp() $objectManager->addSharedInstance($designModel, \Magento\Theme\Model\View\Design\Proxy::class); - $model = $objectManager->create(\Magento\Framework\Translate::class); - $objectManager->addSharedInstance($model, \Magento\Framework\Translate::class); + $this->translate = $objectManager->create(\Magento\Framework\Translate::class); + $objectManager->addSharedInstance($this->translate, \Magento\Framework\Translate::class); $objectManager->removeSharedInstance(\Magento\Framework\Phrase\Renderer\Composite::class); $objectManager->removeSharedInstance(\Magento\Framework\Phrase\Renderer\Translate::class); - \Magento\Framework\Phrase::setRenderer($objectManager->get(\Magento\Framework\Phrase\RendererInterface::class)); - $model->loadData(\Magento\Framework\App\Area::AREA_FRONTEND); + \Magento\Framework\Phrase::setRenderer( + $objectManager->get(\Magento\Framework\Phrase\RendererInterface::class) + ); + } + + public function testLoadData() + { + $data = $this->translate->loadData(null, true)->getData(); + CacheCleaner::cleanAll(); + $this->translate->loadData()->getData(); + $dataCached = $this->translate->loadData()->getData(); + $this->assertEquals($data, $dataCached); } /** + * @magentoCache all disabled * @dataProvider translateDataProvider */ public function testTranslate($inputText, $expectedTranslation) { + $this->translate->loadData(\Magento\Framework\App\Area::AREA_FRONTEND); $actualTranslation = new \Magento\Framework\Phrase($inputText); $this->assertEquals($expectedTranslation, $actualTranslation); } diff --git a/dev/tests/integration/testsuite/Magento/Framework/View/Element/UiComponent/Config/Provider/TemplateTest.php b/dev/tests/integration/testsuite/Magento/Framework/View/Element/UiComponent/Config/Provider/TemplateTest.php new file mode 100644 index 0000000000000..d2e5ab7215ff0 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Framework/View/Element/UiComponent/Config/Provider/TemplateTest.php @@ -0,0 +1,79 @@ +objectManager = Bootstrap::getObjectManager(); + $this->registerThemes(); + $this->objectManager->addSharedInstance( + $this->objectManager->create( + \Magento\Framework\App\Arguments\ValidationState::class, + ['appMode' => 'default'] + ), + \Magento\Framework\App\Arguments\ValidationState::class + ); + $this->model = $this->objectManager->create( + \Magento\Framework\View\Element\UiComponent\Config\Provider\Template::class + ); + } + + public function testGetTemplate() + { + $expected = file_get_contents(__DIR__ . '/../../../../_files/UiComponent/expected/config.xml'); + + \Magento\TestFramework\Helper\Bootstrap::getInstance()->loadArea('adminhtml'); + $this->objectManager->get(\Magento\Framework\View\DesignInterface::class) + ->setDesignTheme('FrameworkViewUiComponent/default'); + CacheCleaner::cleanAll(); + + $resultOne = $this->model->getTemplate('test.xml'); + $resultTwo = $this->model->getTemplate('test.xml'); + + $this->assertXmlStringEqualsXmlString($expected, $resultOne); + $this->assertXmlStringEqualsXmlString($expected, $resultTwo); + } + + /** + * Register themes in the fixture folder + */ + protected function registerThemes() + { + /** @var \Magento\Theme\Model\Theme\Registration $registration */ + $registration = $this->objectManager->get( + \Magento\Theme\Model\Theme\Registration::class + ); + $registration->register(); + } + + protected function tearDown() + { + $this->objectManager->removeSharedInstance( + \Magento\Framework\App\Arguments\ValidationState::class + ); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Framework/View/_files/UiComponent/expected/config.xml b/dev/tests/integration/testsuite/Magento/Framework/View/_files/UiComponent/expected/config.xml new file mode 100644 index 0000000000000..467afb2004cbe --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Framework/View/_files/UiComponent/expected/config.xml @@ -0,0 +1,17 @@ + + +
+ + + Magento\Catalog\Block\Adminhtml\Product\Edit\Button\CreateCategory + + + new_category_form.new_category_form_data_source + + +
diff --git a/dev/tests/integration/testsuite/Magento/Framework/View/_files/UiComponent/theme/Magento_Catalog/ui_component/test.xml b/dev/tests/integration/testsuite/Magento/Framework/View/_files/UiComponent/theme/Magento_Catalog/ui_component/test.xml new file mode 100644 index 0000000000000..e0bd296bfda2b --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Framework/View/_files/UiComponent/theme/Magento_Catalog/ui_component/test.xml @@ -0,0 +1,14 @@ + + +
+ + + new_category_form.new_category_form_data_source + + +
diff --git a/dev/tests/integration/testsuite/Magento/Framework/View/_files/UiComponent/theme/Magento_Customer/ui_component/test.xml b/dev/tests/integration/testsuite/Magento/Framework/View/_files/UiComponent/theme/Magento_Customer/ui_component/test.xml new file mode 100644 index 0000000000000..c1e0d46aee53e --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Framework/View/_files/UiComponent/theme/Magento_Customer/ui_component/test.xml @@ -0,0 +1,14 @@ + + +
+ + + Magento\Catalog\Block\Adminhtml\Product\Edit\Button\CreateCategory + + +
diff --git a/dev/tests/integration/testsuite/Magento/Framework/View/_files/UiComponent/theme/registration.php b/dev/tests/integration/testsuite/Magento/Framework/View/_files/UiComponent/theme/registration.php new file mode 100644 index 0000000000000..42145b38953bd --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Framework/View/_files/UiComponent/theme/registration.php @@ -0,0 +1,11 @@ + + + Test theme + diff --git a/dev/tests/integration/testsuite/Magento/Store/Model/StoreResolverTest.php b/dev/tests/integration/testsuite/Magento/Store/Model/StoreResolverTest.php new file mode 100644 index 0000000000000..b2aa803bc0105 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Store/Model/StoreResolverTest.php @@ -0,0 +1,37 @@ +objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); + $this->block = $this->objectManager->get(\Magento\Directory\Block\Data::class); + } + + public function testGetStoreData() + { + $methodGetStoresData = new \ReflectionMethod(\Magento\Store\Model\StoreResolver::class, 'getStoresData'); + $methodGetStoresData->setAccessible(true); + $methodReadStoresData = new \ReflectionMethod(\Magento\Store\Model\StoreResolver::class, 'readStoresData'); + $methodReadStoresData->setAccessible(true); + + $storeResolver = $this->objectManager->get(\Magento\Store\Model\StoreResolver::class); + + $storesDataRead = $methodReadStoresData->invoke($storeResolver); + CacheCleaner::cleanAll(); + $storesData = $methodGetStoresData->invoke($storeResolver); + $storesDataCached = $methodGetStoresData->invoke($storeResolver); + $this->assertEquals($storesDataRead, $storesData); + $this->assertEquals($storesDataRead, $storesDataCached); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Theme/Model/DesignTest.php b/dev/tests/integration/testsuite/Magento/Theme/Model/DesignTest.php index 6cd9746daca33..f450f1b3d0cbe 100644 --- a/dev/tests/integration/testsuite/Magento/Theme/Model/DesignTest.php +++ b/dev/tests/integration/testsuite/Magento/Theme/Model/DesignTest.php @@ -5,6 +5,9 @@ */ namespace Magento\Theme\Model; +use Magento\Backend\Block\Widget\Grid\Serializer; +use Magento\Framework\Serialize\SerializerInterface; + class DesignTest extends \PHPUnit_Framework_TestCase { /** @@ -121,7 +124,8 @@ public function testLoadChangeCache() )->load( $cacheId ); - $cachedDesign = unserialize($cachedDesign); + $serializer = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(SerializerInterface::class); + $cachedDesign = $serializer->unserialize($cachedDesign); $this->assertInternalType('array', $cachedDesign); $this->assertArrayHasKey('design', $cachedDesign); @@ -139,7 +143,8 @@ public function testLoadChangeCache() )->load( $cacheId ); - $cachedDesign = unserialize($cachedDesign); + + $cachedDesign = $serializer->unserialize($cachedDesign); $this->assertTrue(is_array($cachedDesign)); $this->assertEquals($cachedDesign['design'], $design->getDesign()); diff --git a/lib/internal/Magento/Framework/Api/ExtensionAttribute/Config.php b/lib/internal/Magento/Framework/Api/ExtensionAttribute/Config.php index 303e4a5792666..1dcfe02e56b3e 100644 --- a/lib/internal/Magento/Framework/Api/ExtensionAttribute/Config.php +++ b/lib/internal/Magento/Framework/Api/ExtensionAttribute/Config.php @@ -7,24 +7,32 @@ use Magento\Framework\Config\CacheInterface; use Magento\Framework\Api\ExtensionAttribute\Config\Reader; +use Magento\Framework\Serialize\SerializerInterface; /** * Extension attributes config */ class Config extends \Magento\Framework\Config\Data { + /** + * Cache identifier + */ const CACHE_ID = 'extension_attributes_config'; /** - * Initialize reader and cache. + * Constructor * * @param Reader $reader * @param CacheInterface $cache + * @param string $cacheId|null + * @param SerializerInterface|null $serializer */ public function __construct( Reader $reader, - CacheInterface $cache + CacheInterface $cache, + $cacheId = self::CACHE_ID, + SerializerInterface $serializer = null ) { - parent::__construct($reader, $cache, self::CACHE_ID); + parent::__construct($reader, $cache, $cacheId, $serializer); } } diff --git a/lib/internal/Magento/Framework/App/Cache/TypeList.php b/lib/internal/Magento/Framework/App/Cache/TypeList.php index 1fae9652810c8..38516b7174d6f 100644 --- a/lib/internal/Magento/Framework/App/Cache/TypeList.php +++ b/lib/internal/Magento/Framework/App/Cache/TypeList.php @@ -5,6 +5,9 @@ */ namespace Magento\Framework\App\Cache; +use Magento\Framework\App\ObjectManager; +use Magento\Framework\Serialize\SerializerInterface; + class TypeList implements TypeListInterface { const INVALIDATED_TYPES = 'core_cache_invalidate'; @@ -29,22 +32,30 @@ class TypeList implements TypeListInterface */ protected $_cache; + /** + * @var SerializerInterface + */ + private $serializer; + /** * @param \Magento\Framework\Cache\ConfigInterface $config * @param StateInterface $cacheState * @param InstanceFactory $factory * @param \Magento\Framework\App\CacheInterface $cache + * @param SerializerInterface $serializer */ public function __construct( \Magento\Framework\Cache\ConfigInterface $config, StateInterface $cacheState, InstanceFactory $factory, - \Magento\Framework\App\CacheInterface $cache + \Magento\Framework\App\CacheInterface $cache, + SerializerInterface $serializer = null ) { $this->_config = $config; $this->_factory = $factory; $this->_cacheState = $cacheState; $this->_cache = $cache; + $this->serializer = $serializer ?: ObjectManager::getInstance()->get(SerializerInterface::class); } /** @@ -72,7 +83,7 @@ protected function _getInvalidatedTypes() { $types = $this->_cache->load(self::INVALIDATED_TYPES); if ($types) { - $types = unserialize($types); + $types = $this->serializer->unserialize($types); } else { $types = []; } @@ -87,7 +98,7 @@ protected function _getInvalidatedTypes() */ protected function _saveInvalidatedTypes($types) { - $this->_cache->save(serialize($types), self::INVALIDATED_TYPES); + $this->_cache->save($this->serializer->serialize($types), self::INVALIDATED_TYPES); } /** diff --git a/lib/internal/Magento/Framework/App/Config/Initial.php b/lib/internal/Magento/Framework/App/Config/Initial.php index 0704fb8559396..5669041ee98d2 100644 --- a/lib/internal/Magento/Framework/App/Config/Initial.php +++ b/lib/internal/Magento/Framework/App/Config/Initial.php @@ -8,6 +8,7 @@ namespace Magento\Framework\App\Config; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\Serialize\SerializerInterface; class Initial { @@ -31,19 +32,30 @@ class Initial protected $_metadata = []; /** - * @param \Magento\Framework\App\Config\Initial\Reader $reader + * @var SerializerInterface + */ + private $serializer; + + /** + * Initial constructor + * + * @param Initial\Reader $reader * @param \Magento\Framework\App\Cache\Type\Config $cache + * @param SerializerInterface|null $serializer */ public function __construct( \Magento\Framework\App\Config\Initial\Reader $reader, - \Magento\Framework\App\Cache\Type\Config $cache + \Magento\Framework\App\Cache\Type\Config $cache, + SerializerInterface $serializer = null ) { + $this->serializer = $serializer ?: \Magento\Framework\App\ObjectManager::getInstance() + ->get(SerializerInterface::class); $data = $cache->load(self::CACHE_ID); if (!$data) { $data = $reader->read(); - $cache->save(serialize($data), self::CACHE_ID); + $cache->save($this->serializer->serialize($data), self::CACHE_ID); } else { - $data = unserialize($data); + $data = $this->serializer->unserialize($data); } $this->_data = $data['data']; $this->_metadata = $data['metadata']; diff --git a/lib/internal/Magento/Framework/App/ObjectManager/ConfigCache.php b/lib/internal/Magento/Framework/App/ObjectManager/ConfigCache.php index 7e8711d027bb7..4e685e3472ef8 100644 --- a/lib/internal/Magento/Framework/App/ObjectManager/ConfigCache.php +++ b/lib/internal/Magento/Framework/App/ObjectManager/ConfigCache.php @@ -7,6 +7,9 @@ */ namespace Magento\Framework\App\ObjectManager; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\Serialize\Serializer\Serialize; + class ConfigCache implements \Magento\Framework\ObjectManager\ConfigCacheInterface { /** @@ -21,6 +24,11 @@ class ConfigCache implements \Magento\Framework\ObjectManager\ConfigCacheInterfa */ protected $_prefix = 'diConfig'; + /** + * @var SerializerInterface + */ + private $serializer; + /** * @param \Magento\Framework\Cache\FrontendInterface $cacheFrontend */ @@ -37,7 +45,7 @@ public function __construct(\Magento\Framework\Cache\FrontendInterface $cacheFro */ public function get($key) { - return unserialize($this->_cacheFrontend->load($this->_prefix . $key)); + return $this->getSerializer()->unserialize($this->_cacheFrontend->load($this->_prefix . $key)); } /** @@ -49,6 +57,20 @@ public function get($key) */ public function save(array $config, $key) { - $this->_cacheFrontend->save(serialize($config), $this->_prefix . $key); + $this->_cacheFrontend->save($this->getSerializer()->serialize($config), $this->_prefix . $key); + } + + /** + * Get serializer + * + * @return SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if (null === $this->serializer) { + $this->serializer = \Magento\Framework\App\ObjectManager::getInstance()->get(Serialize::class); + } + return $this->serializer; } } diff --git a/lib/internal/Magento/Framework/App/ObjectManager/ConfigLoader.php b/lib/internal/Magento/Framework/App/ObjectManager/ConfigLoader.php index 2190ff6cdb37f..2770443b6d7e2 100644 --- a/lib/internal/Magento/Framework/App/ObjectManager/ConfigLoader.php +++ b/lib/internal/Magento/Framework/App/ObjectManager/ConfigLoader.php @@ -7,6 +7,8 @@ */ namespace Magento\Framework\App\ObjectManager; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\Serialize\Serializer\Serialize; use Magento\Framework\ObjectManager\ConfigLoaderInterface; class ConfigLoader implements ConfigLoaderInterface @@ -32,6 +34,11 @@ class ConfigLoader implements ConfigLoaderInterface */ protected $_cache; + /** + * @var SerializerInterface + */ + private $serializer; + /** * @param \Magento\Framework\Config\CacheInterface $cache * @param \Magento\Framework\ObjectManager\Config\Reader\DomFactory $readerFactory @@ -67,11 +74,25 @@ public function load($area) if (!$data) { $data = $this->_getReader()->read($area); - $this->_cache->save(serialize($data), $cacheId); + $this->_cache->save($this->getSerializer()->serialize($data), $cacheId); } else { - $data = unserialize($data); + $data = $this->getSerializer()->unserialize($data); } return $data; } + + /** + * Get serializer + * + * @return SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if (null === $this->serializer) { + $this->serializer = \Magento\Framework\App\ObjectManager::getInstance()->get(Serialize::class); + } + return $this->serializer; + } } diff --git a/lib/internal/Magento/Framework/App/ObjectManager/ConfigLoader/Compiled.php b/lib/internal/Magento/Framework/App/ObjectManager/ConfigLoader/Compiled.php index 844d3f038aefe..669c9f4121ac0 100644 --- a/lib/internal/Magento/Framework/App/ObjectManager/ConfigLoader/Compiled.php +++ b/lib/internal/Magento/Framework/App/ObjectManager/ConfigLoader/Compiled.php @@ -6,7 +6,10 @@ */ namespace Magento\Framework\App\ObjectManager\ConfigLoader; +use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\ObjectManager\ConfigLoaderInterface; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\Serialize\Serializer\Serialize; class Compiled implements ConfigLoaderInterface { @@ -17,6 +20,11 @@ class Compiled implements ConfigLoaderInterface */ private $configCache = []; + /** + * @var SerializerInterface + */ + private $serializer; + /** * {inheritdoc} */ @@ -25,18 +33,33 @@ public function load($area) if (isset($this->configCache[$area])) { return $this->configCache[$area]; } - $this->configCache[$area] = \unserialize(\file_get_contents(self::getFilePath($area))); + $this->configCache[$area] = $this->getSerializer()->unserialize(\file_get_contents(self::getFilePath($area))); return $this->configCache[$area]; } /** - * Returns path to cached configuration + * Returns path to compiled configuration * * @param string $area * @return string */ public static function getFilePath($area) { - return BP . '/var/di/' . $area . '.ser'; + $diPath = DirectoryList::getDefaultConfig()[DirectoryList::DI][DirectoryList::PATH]; + return BP . '/' . $diPath . '/' . $area . '.ser'; + } + + /** + * Get serializer + * + * @return SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if (null === $this->serializer) { + $this->serializer = new Serialize(); + } + return $this->serializer; } } diff --git a/lib/internal/Magento/Framework/App/ObjectManagerFactory.php b/lib/internal/Magento/Framework/App/ObjectManagerFactory.php index 3a007841532cc..530c7c43599df 100644 --- a/lib/internal/Magento/Framework/App/ObjectManagerFactory.php +++ b/lib/internal/Magento/Framework/App/ObjectManagerFactory.php @@ -1,7 +1,5 @@ get(), $arguments); $definitionFactory = new \Magento\Framework\ObjectManager\DefinitionFactory( $this->driverPool->getDriver(DriverPool::FILE), - $this->directoryList->getPath(DirectoryList::DI), - $this->directoryList->getPath(DirectoryList::GENERATION), - $deploymentConfig->get(self::CONFIG_PATH_DEFINITION_FORMAT, Serialized::MODE_NAME) + $this->directoryList->getPath(DirectoryList::GENERATION) ); - $definitions = $definitionFactory->createClassDefinition($deploymentConfig->get('definitions')); + $definitions = $definitionFactory->createClassDefinition(); $relations = $definitionFactory->createRelations(); /** @var EnvironmentFactory $envFactory */ $envFactory = new $this->envFactoryClassName($relations, $definitions); /** @var EnvironmentInterface $env */ - $env = $envFactory->createEnvironment(); + $env = $envFactory->createEnvironment(); /** @var ConfigInterface $diConfig */ $diConfig = $env->getDiConfig(); @@ -298,6 +287,8 @@ protected function _loadPrimaryConfig(DirectoryList $directoryList, $driverPool, * @param \Magento\Framework\ObjectManager\Config\Config $diConfig * @param \Magento\Framework\ObjectManager\DefinitionInterface $definitions * @return \Magento\Framework\Interception\PluginList\PluginList + * @deprecated + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ protected function _createPluginList( \Magento\Framework\ObjectManagerInterface $objectManager, @@ -312,8 +303,7 @@ protected function _createPluginList( 'relations' => $relations, 'definitions' => $definitionFactory->createPluginDefinition(), 'omConfig' => $diConfig, - 'classDefinitions' => $definitions instanceof - \Magento\Framework\ObjectManager\Definition\Compiled ? $definitions : null + 'classDefinitions' => null ] ); } diff --git a/lib/internal/Magento/Framework/App/ResourceConnection/Config.php b/lib/internal/Magento/Framework/App/ResourceConnection/Config.php index d9410bc9f7dd8..e967bb1b007b9 100644 --- a/lib/internal/Magento/Framework/App/ResourceConnection/Config.php +++ b/lib/internal/Magento/Framework/App/ResourceConnection/Config.php @@ -1,14 +1,16 @@ deploymentConfig = $deploymentConfig; } diff --git a/lib/internal/Magento/Framework/App/Route/Config.php b/lib/internal/Magento/Framework/App/Route/Config.php index 70968c84d77fc..60412e7fa888b 100644 --- a/lib/internal/Magento/Framework/App/Route/Config.php +++ b/lib/internal/Magento/Framework/App/Route/Config.php @@ -7,6 +7,8 @@ */ namespace Magento\Framework\App\Route; +use Magento\Framework\Serialize\SerializerInterface; + class Config implements ConfigInterface { /** @@ -39,6 +41,11 @@ class Config implements ConfigInterface */ protected $_routes; + /** + * @var SerializerInterface + */ + private $serializer; + /** * @param Config\Reader $reader * @param \Magento\Framework\Config\CacheInterface $cache @@ -73,7 +80,7 @@ protected function _getRoutes($scope = null) return $this->_routes[$scope]; } $cacheId = $scope . '::' . $this->_cacheId; - $cachedRoutes = unserialize($this->_cache->load($cacheId)); + $cachedRoutes = $this->getSerializer()->unserialize($this->_cache->load($cacheId)); if (is_array($cachedRoutes)) { $this->_routes[$scope] = $cachedRoutes; return $cachedRoutes; @@ -81,7 +88,8 @@ protected function _getRoutes($scope = null) $routers = $this->_reader->read($scope); $routes = $routers[$this->_areaList->getDefaultRouter($scope)]['routes']; - $this->_cache->save(serialize($routes), $cacheId); + $routesData = $this->getSerializer()->serialize($routes); + $this->_cache->save($routesData, $cacheId); $this->_routes[$scope] = $routes; return $routes; } @@ -133,4 +141,19 @@ public function getModulesByFrontName($frontName, $scope = null) return array_unique($modules); } + + /** + * Get serializer + * + * @return \Magento\Framework\Serialize\SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if ($this->serializer === null) { + $this->serializer = \Magento\Framework\App\ObjectManager::getInstance() + ->get(SerializerInterface::class); + } + return $this->serializer; + } } diff --git a/lib/internal/Magento/Framework/App/Router/ActionList.php b/lib/internal/Magento/Framework/App/Router/ActionList.php index 11ee22a5f375e..ec46154b2553a 100644 --- a/lib/internal/Magento/Framework/App/Router/ActionList.php +++ b/lib/internal/Magento/Framework/App/Router/ActionList.php @@ -6,6 +6,8 @@ */ namespace Magento\Framework\App\Router; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\Serialize\Serializer\Serialize; use Magento\Framework\Module\Dir\Reader as ModuleReader; class ActionList @@ -36,27 +38,42 @@ class ActionList ]; /** + * @var SerializerInterface + */ + private $serializer; + + /** + * @var string + */ + private $actionInterface; + + /** + * ActionList constructor + * * @param \Magento\Framework\Config\CacheInterface $cache * @param ModuleReader $moduleReader * @param string $actionInterface * @param string $cacheKey * @param array $reservedWords + * @param SerializerInterface|null $serializer */ public function __construct( \Magento\Framework\Config\CacheInterface $cache, ModuleReader $moduleReader, $actionInterface = \Magento\Framework\App\ActionInterface::class, $cacheKey = 'app_action_list', - $reservedWords = [] + $reservedWords = [], + SerializerInterface $serializer = null ) { $this->reservedWords = array_merge($reservedWords, $this->reservedWords); $this->actionInterface = $actionInterface; + $this->serializer = $serializer ?: \Magento\Framework\App\ObjectManager::getInstance()->get(Serialize::class); $data = $cache->load($cacheKey); if (!$data) { $this->actions = $moduleReader->getActionFiles(); - $cache->save(serialize($this->actions), $cacheKey); + $cache->save($this->serializer->serialize($this->actions), $cacheKey); } else { - $this->actions = unserialize($data); + $this->actions = $this->serializer->unserialize($data); } } diff --git a/lib/internal/Magento/Framework/App/Test/Unit/Cache/TypeListTest.php b/lib/internal/Magento/Framework/App/Test/Unit/Cache/TypeListTest.php index a6074f6c45740..d185219becefe 100644 --- a/lib/internal/Magento/Framework/App/Test/Unit/Cache/TypeListTest.php +++ b/lib/internal/Magento/Framework/App/Test/Unit/Cache/TypeListTest.php @@ -7,6 +7,7 @@ namespace Magento\Framework\App\Test\Unit\Cache; use \Magento\Framework\App\Cache\TypeList; +use Magento\Framework\Serialize\SerializerInterface; /** * Test class for \Magento\Framework\App\Cache\TypeList @@ -48,6 +49,11 @@ class TypeListTest extends \PHPUnit_Framework_TestCase */ const CACHE_TYPE = \Magento\Framework\Cache\FrontendInterface::class; + /** + * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $serializerMock; + protected function setUp() { $this->_typesArray = [ @@ -85,6 +91,7 @@ protected function setUp() '', false ); + $this->serializerMock = $this->getMock(SerializerInterface::class); $objectHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->_typeList = $objectHelper->getObject( @@ -93,7 +100,8 @@ protected function setUp() 'config' => $this->_config, 'cacheState' => $cacheState, 'factory' => $factory, - 'cache' => $this->_cache + 'cache' => $this->_cache, + 'serializer' => $this->serializerMock, ] ); } @@ -118,8 +126,12 @@ public function testGetInvalidated() { $expectation = [self::TYPE_KEY => $this->_getPreparedType()]; $this->_cache->expects($this->once())->method('load')->with(TypeList::INVALIDATED_TYPES)->will( - $this->returnValue(serialize($this->_typesArray)) + $this->returnValue('serializedData') ); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with('serializedData') + ->willReturn($this->_typesArray); $this->assertEquals($expectation, $this->_typeList->getInvalidated()); } @@ -132,8 +144,12 @@ public function testInvalidate() $expectedInvalidated = [ self::TYPE_KEY => 1, ]; + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->with($expectedInvalidated) + ->willReturn('serializedData'); $this->_cache->expects($this->once())->method('save')->with( - serialize($expectedInvalidated), + 'serializedData', TypeList::INVALIDATED_TYPES ); $this->_typeList->invalidate(self::TYPE_KEY); @@ -147,8 +163,12 @@ public function testInvalidateList() $expectedInvalidated = [ self::TYPE_KEY => 1, ]; + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->with($expectedInvalidated) + ->willReturn('serializedData'); $this->_cache->expects($this->once())->method('save')->with( - serialize($expectedInvalidated), + 'serializedData', TypeList::INVALIDATED_TYPES ); $this->_typeList->invalidate([self::TYPE_KEY]); @@ -156,15 +176,23 @@ public function testInvalidateList() public function testCleanType() { + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with('serializedData') + ->willReturn($this->_typesArray); $this->_cache->expects($this->once())->method('load')->with(TypeList::INVALIDATED_TYPES)->will( - $this->returnValue(serialize($this->_typesArray)) + $this->returnValue('serializedData') ); $this->_config->expects($this->once())->method('getType')->with(self::TYPE_KEY)->will( $this->returnValue(['instance' => self::CACHE_TYPE]) ); unset($this->_typesArray[self::TYPE_KEY]); + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->with($this->_typesArray) + ->willReturn('serializedData'); $this->_cache->expects($this->once())->method('save')->with( - serialize($this->_typesArray), + 'serializedData', TypeList::INVALIDATED_TYPES ); $this->_typeList->cleanType(self::TYPE_KEY); diff --git a/lib/internal/Magento/Framework/App/Test/Unit/Config/InitialTest.php b/lib/internal/Magento/Framework/App/Test/Unit/Config/InitialTest.php index ce85753bedab5..941a670b1b44c 100644 --- a/lib/internal/Magento/Framework/App/Test/Unit/Config/InitialTest.php +++ b/lib/internal/Magento/Framework/App/Test/Unit/Config/InitialTest.php @@ -7,59 +7,68 @@ class InitialTest extends \PHPUnit_Framework_TestCase { + /** + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + */ + private $objectManager; + /** * @var \Magento\Framework\App\Config\Initial */ - protected $_model; + private $config; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\Cache\Type\Config|\PHPUnit_Framework_MockObject_MockObject */ - protected $_initialReaderMock; + private $cacheMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var array */ - protected $_configCacheMock; + private $data = [ + 'data' => [ + 'default' => ['key' => 'default_value'], + 'stores' => ['default' => ['key' => 'store_value']], + 'websites' => ['default' => ['key' => 'website_value']], + ], + 'metadata' => ['metadata'], + ]; protected function setUp() { - $this->_initialReaderMock = - $this->getMock(\Magento\Framework\App\Config\Initial\Reader::class, [], [], '', false); - $this->_configCacheMock = - $this->getMock(\Magento\Framework\App\Cache\Type\Config::class, [], [], '', false); - $serializedData = serialize( + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->cacheMock = $this->getMock( + \Magento\Framework\App\Cache\Type\Config::class, + [], + [], + '', + false + ); + $this->cacheMock->expects($this->any()) + ->method('load') + ->with('initial_config') + ->willReturn(json_encode($this->data)); + $serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); + $serializerMock->method('unserialize') + ->willReturn($this->data); + + $this->config = $this->objectManager->getObject( + \Magento\Framework\App\Config\Initial::class, [ - 'data' => [ - 'default' => ['key' => 'default_value'], - 'stores' => ['default' => ['key' => 'store_value']], - 'websites' => ['default' => ['key' => 'website_value']], - ], - 'metadata' => ['metadata'], + 'cache' => $this->cacheMock, + 'serializer' => $serializerMock, ] ); - $this->_configCacheMock->expects( - $this->any() - )->method( - 'load' - )->with( - 'initial_config' - )->will( - $this->returnValue($serializedData) - ); - - $this->_model = new \Magento\Framework\App\Config\Initial($this->_initialReaderMock, $this->_configCacheMock); } /** - * @dataProvider getDataDataProvider - * * @param string $scope - * @param array $expectedResult + * @param array $expected + * @dataProvider getDataDataProvider */ - public function testGetData($scope, $expectedResult) + public function testGetData($scope, $expected) { - $this->assertEquals($expectedResult, $this->_model->getData($scope)); + $this->assertEquals($expected, $this->config->getData($scope)); } public function getDataDataProvider() @@ -73,7 +82,6 @@ public function getDataDataProvider() public function testGetMetadata() { - $expectedResult = ['metadata']; - $this->assertEquals($expectedResult, $this->_model->getMetadata()); + $this->assertEquals(['metadata'], $this->config->getMetadata()); } } diff --git a/lib/internal/Magento/Framework/App/Test/Unit/ObjectManager/ConfigCacheTest.php b/lib/internal/Magento/Framework/App/Test/Unit/ObjectManager/ConfigCacheTest.php index 336e958403f91..7f05857f7cc81 100644 --- a/lib/internal/Magento/Framework/App/Test/Unit/ObjectManager/ConfigCacheTest.php +++ b/lib/internal/Magento/Framework/App/Test/Unit/ObjectManager/ConfigCacheTest.php @@ -5,49 +5,86 @@ */ namespace Magento\Framework\App\Test\Unit\ObjectManager; +use Magento\Framework\Serialize\SerializerInterface; + class ConfigCacheTest extends \PHPUnit_Framework_TestCase { /** * @var \Magento\Framework\App\ObjectManager\ConfigCache */ - protected $_configCache; + private $configCache; + + /** + * @var \Magento\Framework\App\ObjectManager\ConfigCache|\PHPUnit_Framework_MockObject_MockObject + */ + private $cacheFrontendMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $_cacheFrontendMock; + private $serializerMock; protected function setUp() { - $this->_cacheFrontendMock = $this->getMock(\Magento\Framework\Cache\FrontendInterface::class); - $this->_configCache = new \Magento\Framework\App\ObjectManager\ConfigCache($this->_cacheFrontendMock); + $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->cacheFrontendMock = $this->getMock(\Magento\Framework\Cache\FrontendInterface::class); + $this->configCache = $objectManagerHelper->getObject( + \Magento\Framework\App\ObjectManager\ConfigCache::class, + ['cacheFrontend' => $this->cacheFrontendMock] + ); + + $this->serializerMock = $this->getMock(SerializerInterface::class); + $objectManagerHelper->setBackwardCompatibleProperty( + $this->configCache, + 'serializer', + $this->serializerMock + ); } protected function tearDown() { - unset($this->_configCache); + unset($this->configCache); } - public function testGet() + /** + * @dataProvider getDataProvider + */ + public function testGet($loadData, $expectedResult) { $key = 'key'; - $this->_cacheFrontendMock->expects( + $this->cacheFrontendMock->expects( $this->once() )->method( 'load' )->with( 'diConfig' . $key )->will( - $this->returnValue(false) + $this->returnValue($loadData) ); - $this->assertEquals(false, $this->_configCache->get($key)); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with($loadData) + ->willReturn($expectedResult); + $this->assertEquals($expectedResult, $this->configCache->get($key)); + } + + public function getDataProvider() + { + return [ + [false, false], + ['serialized data', ['some data']], + ]; } public function testSave() { $key = 'key'; $config = ['config']; - $this->_cacheFrontendMock->expects($this->once())->method('save')->with(serialize($config), 'diConfig' . $key); - $this->_configCache->save($config, $key); + $serializedData = 'serialized data'; + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->willReturn($serializedData); + $this->cacheFrontendMock->expects($this->once())->method('save')->with($serializedData, 'diConfig' . $key); + $this->configCache->save($config, $key); } } diff --git a/lib/internal/Magento/Framework/App/Test/Unit/ObjectManager/ConfigLoaderTest.php b/lib/internal/Magento/Framework/App/Test/Unit/ObjectManager/ConfigLoaderTest.php index 5a0b4ae96f26c..90dba092f054e 100644 --- a/lib/internal/Magento/Framework/App/Test/Unit/ObjectManager/ConfigLoaderTest.php +++ b/lib/internal/Magento/Framework/App/Test/Unit/ObjectManager/ConfigLoaderTest.php @@ -8,31 +8,38 @@ namespace Magento\Framework\App\Test\Unit\ObjectManager; +use Magento\Framework\Serialize\SerializerInterface; + class ConfigLoaderTest extends \PHPUnit_Framework_TestCase { /** * @var \Magento\Framework\App\ObjectManager\ConfigLoader */ - protected $_model; + private $object; + + /** + * @var \Magento\Framework\ObjectManager\Config\Reader\DomFactory|\PHPUnit_Framework_MockObject_MockObject + */ + private $readerFactoryMock; /** - * @var \Magento\Framework\ObjectManager\Config\Reader\DomFactory + * @var \Magento\Framework\ObjectManager\Config\Reader\Dom|\PHPUnit_Framework_MockObject_MockObject */ - protected $_readerFactoryMock; + private $readerMock; /** - * @var \Magento\Framework\ObjectManager\Config\Reader\Dom + * @var \Magento\Framework\App\Cache\Type\Config|\PHPUnit_Framework_MockObject_MockObject */ - protected $_readerMock; + private $cacheMock; /** - * @var \Magento\Framework\App\Cache\Type\Config + * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $_cacheMock; + private $serializerMock; protected function setUp() { - $this->_readerMock = $this->getMock( + $this->readerMock = $this->getMock( \Magento\Framework\ObjectManager\Config\Reader\Dom::class, [], [], @@ -40,7 +47,7 @@ protected function setUp() false ); - $this->_readerFactoryMock = $this->getMock( + $this->readerFactoryMock = $this->getMock( \Magento\Framework\ObjectManager\Config\Reader\DomFactory::class, ['create'], [], @@ -48,17 +55,29 @@ protected function setUp() false ); - $this->_readerFactoryMock->expects( + $this->readerFactoryMock->expects( $this->any() )->method( 'create' )->will( - $this->returnValue($this->_readerMock) + $this->returnValue($this->readerMock) ); - $this->_cacheMock = $this->getMock(\Magento\Framework\App\Cache\Type\Config::class, [], [], '', false); - $this->_model = new \Magento\Framework\App\ObjectManager\ConfigLoader( - $this->_cacheMock, $this->_readerFactoryMock + $this->cacheMock = $this->getMock(\Magento\Framework\App\Cache\Type\Config::class, [], [], '', false); + $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + + $this->object = $objectManagerHelper->getObject( + \Magento\Framework\App\ObjectManager\ConfigLoader::class, + [ + 'cache' => $this->cacheMock, + 'readerFactory' => $this->readerFactoryMock, + ] + ); + $this->serializerMock = $this->getMock(SerializerInterface::class); + $objectManagerHelper->setBackwardCompatibleProperty( + $this->object, + 'serializer', + $this->serializerMock ); } @@ -66,23 +85,28 @@ protected function setUp() * @param $area * @dataProvider loadDataProvider */ - public function testLoad($area) + public function testLoadNotCached($area) { $configData = ['some' => 'config', 'data' => 'value']; + $serializedData = 'serialized data'; - $this->_cacheMock->expects( - $this->once() - )->method( - 'load' - )->with( - $area . '::DiConfig' - )->will( - $this->returnValue(false) - ); + $this->cacheMock->expects($this->once()) + ->method('load') + ->with($area . '::DiConfig') + ->will($this->returnValue(false)); + + $this->cacheMock->expects($this->once()) + ->method('save') + ->with($serializedData); + $this->readerMock->expects($this->once())->method('read')->with($area)->will($this->returnValue($configData)); - $this->_readerMock->expects($this->once())->method('read')->with($area)->will($this->returnValue($configData)); + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->willReturn($serializedData); - $this->assertEquals($configData, $this->_model->load($area)); + $this->serializerMock->expects($this->never())->method('unserialize'); + + $this->assertEquals($configData, $this->object->load($area)); } /** @@ -98,4 +122,23 @@ public function loadDataProvider() 'any area files' => ['any'] ]; } + + public function testLoadCached() + { + $configData = ['some' => 'config', 'data' => 'value']; + $serializedData = 'serialized data'; + + $this->cacheMock->expects($this->once()) + ->method('load') + ->willReturn($serializedData); + $this->cacheMock->expects($this->never()) + ->method('save'); + $this->readerMock->expects($this->never())->method('read'); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with($serializedData) + ->willReturn($configData); + $this->serializerMock->expects($this->never())->method('serialize'); + $this->assertEquals($configData, $this->object->load('testArea')); + } } diff --git a/lib/internal/Magento/Framework/App/Test/Unit/ResourceConnection/ConfigTest.php b/lib/internal/Magento/Framework/App/Test/Unit/ResourceConnection/ConfigTest.php index dead64911174a..4b6944146e5ed 100644 --- a/lib/internal/Magento/Framework/App/Test/Unit/ResourceConnection/ConfigTest.php +++ b/lib/internal/Magento/Framework/App/Test/Unit/ResourceConnection/ConfigTest.php @@ -12,27 +12,32 @@ class ConfigTest extends \PHPUnit_Framework_TestCase /** * @var \Magento\Framework\App\ResourceConnection\Config */ - protected $_model; + private $config; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Config\ScopeInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $_scopeMock; + private $scopeMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\Config\CacheInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $_cacheMock; + private $cacheMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \Magento\Framework\App\ResourceConnection\Config\Reader|\PHPUnit_Framework_MockObject_MockObject */ - protected $_readerMock; + private $readerMock; + + /** + * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $serializerMock; /** * @var array */ - protected $_resourcesConfig; + private $resourcesConfig; /** * @var \Magento\Framework\App\DeploymentConfig|\PHPUnit_Framework_MockObject_MockObject @@ -41,13 +46,19 @@ class ConfigTest extends \PHPUnit_Framework_TestCase protected function setUp() { - $this->_scopeMock = $this->getMock(\Magento\Framework\Config\ScopeInterface::class); - $this->_cacheMock = $this->getMock(\Magento\Framework\Config\CacheInterface::class); - - $this->_readerMock = - $this->getMock(\Magento\Framework\App\ResourceConnection\Config\Reader::class, [], [], '', false); + $this->scopeMock = $this->getMock(\Magento\Framework\Config\ScopeInterface::class); + $this->cacheMock = $this->getMock(\Magento\Framework\Config\CacheInterface::class); + + $this->readerMock = $this->getMock( + \Magento\Framework\App\ResourceConnection\Config\Reader::class, + [], + [], + '', + false + ); + $this->serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); - $this->_resourcesConfig = [ + $this->resourcesConfig = [ 'mainResourceName' => ['name' => 'mainResourceName', 'extends' => 'anotherResourceName'], 'otherResourceName' => ['name' => 'otherResourceName', 'connection' => 'otherConnectionName'], 'anotherResourceName' => ['name' => 'anotherResourceName', 'connection' => 'anotherConnection'], @@ -55,28 +66,29 @@ protected function setUp() 'extendedResourceName' => ['name' => 'extendedResourceName', 'extends' => 'validResource'], ]; - $this->_cacheMock->expects( - $this->any() - )->method( - 'load' - )->will( - $this->returnValue(serialize($this->_resourcesConfig)) - ); + $serializedData = 'serialized data'; + $this->cacheMock->expects($this->any()) + ->method('load') + ->willReturn($serializedData); + $this->serializerMock->method('unserialize') + ->with($serializedData) + ->willReturn($this->resourcesConfig); $this->deploymentConfig = $this->getMock(\Magento\Framework\App\DeploymentConfig::class, [], [], '', false); - $this->_model = new \Magento\Framework\App\ResourceConnection\Config( - $this->_readerMock, - $this->_scopeMock, - $this->_cacheMock, + $this->config = new \Magento\Framework\App\ResourceConnection\Config( + $this->readerMock, + $this->scopeMock, + $this->cacheMock, $this->deploymentConfig, - 'cacheId' + 'cacheId', + $this->serializerMock ); } /** - * @dataProvider getConnectionNameDataProvider * @param string $resourceName * @param string $connectionName + * @dataProvider getConnectionNameDataProvider */ public function testGetConnectionName($resourceName, $connectionName) { @@ -86,7 +98,7 @@ public function testGetConnectionName($resourceName, $connectionName) ->willReturn([ 'validResource' => ['connection' => 'validConnectionName'], ]); - $this->assertEquals($connectionName, $this->_model->getConnectionName($resourceName)); + $this->assertEquals($connectionName, $this->config->getConnectionName($resourceName)); } /** @@ -94,20 +106,21 @@ public function testGetConnectionName($resourceName, $connectionName) */ public function testGetConnectionNameWithException() { - $deploymentConfig = $this->getMock(\Magento\Framework\App\DeploymentConfig::class, [], [], '', false); - $deploymentConfig->expects($this->once()) + $deploymentConfigMock = $this->getMock(\Magento\Framework\App\DeploymentConfig::class, [], [], '', false); + $deploymentConfigMock->expects($this->once()) ->method('getConfigData') ->with(ConfigOptionsListConstants::KEY_RESOURCE) ->willReturn(['validResource' => ['somekey' => 'validConnectionName']]); - $model = new \Magento\Framework\App\ResourceConnection\Config( - $this->_readerMock, - $this->_scopeMock, - $this->_cacheMock, - $deploymentConfig, - 'cacheId' + $config = new \Magento\Framework\App\ResourceConnection\Config( + $this->readerMock, + $this->scopeMock, + $this->cacheMock, + $deploymentConfigMock, + 'cacheId', + $this->serializerMock ); - $model->getConnectionName('default'); + $config->getConnectionName('default'); } /** diff --git a/lib/internal/Magento/Framework/App/Test/Unit/Route/ConfigTest.php b/lib/internal/Magento/Framework/App/Test/Unit/Route/ConfigTest.php index 949ed3f9953c9..fe6f8d05114c5 100644 --- a/lib/internal/Magento/Framework/App/Test/Unit/Route/ConfigTest.php +++ b/lib/internal/Magento/Framework/App/Test/Unit/Route/ConfigTest.php @@ -13,7 +13,7 @@ class ConfigTest extends \PHPUnit_Framework_TestCase protected $_config; /** - * @var Cache_Mock_Wrapper + * @var \Magento\Framework\App\Route\Config\Reader|\PHPUnit_Framework_MockObject_MockObject */ protected $_readerMock; @@ -32,88 +32,76 @@ class ConfigTest extends \PHPUnit_Framework_TestCase */ protected $_areaList; + /** + * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $serializerMock; + protected function setUp() { $this->_readerMock = $this->getMock(\Magento\Framework\App\Route\Config\Reader::class, [], [], '', false); $this->_cacheMock = $this->getMock(\Magento\Framework\Config\CacheInterface::class); $this->_configScopeMock = $this->getMock(\Magento\Framework\Config\ScopeInterface::class); $this->_areaList = $this->getMock(\Magento\Framework\App\AreaList::class, [], [], '', false); - $this->_configScopeMock->expects( - $this->any() - )->method( - 'getCurrentScope' - )->will( - $this->returnValue('areaCode') - ); - $this->_config = new \Magento\Framework\App\Route\Config( - $this->_readerMock, - $this->_cacheMock, - $this->_configScopeMock, - $this->_areaList + $this->_configScopeMock->expects($this->any()) + ->method('getCurrentScope') + ->willReturn('areaCode'); + $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->_config = $objectManager->getObject( + \Magento\Framework\App\Route\Config::class, + [ + 'reader' => $this->_readerMock, + 'cache' => $this->_cacheMock, + 'configScope' => $this->_configScopeMock, + 'areaList' => $this->_areaList + ] ); + $this->serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); + $objectManager->setBackwardCompatibleProperty($this->_config, 'serializer', $this->serializerMock); } public function testGetRouteFrontNameIfCacheIfRouterIdNotExist() { - $this->_cacheMock->expects( - $this->once() - )->method( - 'load' - )->with( - 'areaCode::RoutesConfig' - )->will( - $this->returnValue(serialize(['expected'])) - ); + $this->_cacheMock->expects($this->once()) + ->method('load') + ->with('areaCode::RoutesConfig') + ->willReturn('["expected"]'); $this->assertEquals('routerCode', $this->_config->getRouteFrontName('routerCode')); } public function testGetRouteByFrontName() { - $this->_cacheMock->expects( - $this->once() - )->method( - 'load' - )->with( - 'areaCode::RoutesConfig' - )->will( - $this->returnValue(serialize(['routerCode' => ['frontName' => 'routerName']])) - ); - - $this->assertEquals('routerCode', $this->_config->getRouteByFrontName('routerName')); - - // check internal caching in $this->_routes array + $data = ['routerCode' => ['frontName' => 'routerName']]; + $this->_cacheMock->expects($this->once()) + ->method('load') + ->with('areaCode::RoutesConfig') + ->willReturn('serializedData'); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with('serializedData') + ->willReturn($data); $this->assertEquals('routerCode', $this->_config->getRouteByFrontName('routerName')); } public function testGetRouteByFrontNameNoRoutes() { - $this->_cacheMock->expects( - $this->once() - )->method( - 'load' - )->with( - 'areaCode::RoutesConfig' - )->will( - $this->returnValue(serialize([])) - ); - - $this->assertFalse($this->_config->getRouteByFrontName('routerName')); - - // check caching in $this->_routes array + $this->_cacheMock->expects($this->once()) + ->method('load') + ->with('areaCode::RoutesConfig') + ->willReturn('serializedData'); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with('serializedData') + ->willReturn([]); $this->assertFalse($this->_config->getRouteByFrontName('routerName')); } public function testGetRouteByFrontNameNoCache() { - $this->_cacheMock->expects( - $this->once() - )->method( - 'load' - )->with( - 'scope::RoutesConfig' - )->will( - $this->returnValue(serialize(false)) - ); + $this->_cacheMock->expects($this->once()) + ->method('load') + ->with('scope::RoutesConfig') + ->willReturn('false'); $routes = [ 'routerCode' => [ @@ -127,6 +115,8 @@ public function testGetRouteByFrontNameNoCache() ], ]; + $serializedData = json_encode($routes); + $this->_readerMock->expects( $this->once() )->method( @@ -147,34 +137,29 @@ public function testGetRouteByFrontNameNoCache() $this->returnValue('default_router') ); - $this->_cacheMock->expects( - $this->once() - )->method( - 'save' - )->with( - serialize($routes), - 'scope::RoutesConfig' - ); + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->willReturn($serializedData); - $this->assertEquals('routerCode', $this->_config->getRouteByFrontName('routerName', 'scope')); + $this->_cacheMock->expects($this->once()) + ->method('save') + ->with($serializedData, 'scope::RoutesConfig'); - // check caching in $this->_routes array $this->assertEquals('routerCode', $this->_config->getRouteByFrontName('routerName', 'scope')); } public function testGetModulesByFrontName() { - $this->_cacheMock->expects( - $this->once() - )->method( - 'load' - )->with( - 'areaCode::RoutesConfig' - )->will( - $this->returnValue( - serialize(['routerCode' => ['frontName' => 'routerName', 'modules' => ['Module1']]]) - ) - ); + $data = ['routerCode' => ['frontName' => 'routerName', 'modules' => ['Module1']]]; + + $this->_cacheMock->expects($this->once()) + ->method('load') + ->with('areaCode::RoutesConfig') + ->willReturn('serializedData'); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with('serializedData') + ->willReturn($data); $this->assertEquals(['Module1'], $this->_config->getModulesByFrontName('routerName')); } } diff --git a/lib/internal/Magento/Framework/App/Test/Unit/Router/ActionListTest.php b/lib/internal/Magento/Framework/App/Test/Unit/Router/ActionListTest.php index c24c31e282c62..bef703e99a33e 100644 --- a/lib/internal/Magento/Framework/App/Test/Unit/Router/ActionListTest.php +++ b/lib/internal/Magento/Framework/App/Test/Unit/Router/ActionListTest.php @@ -1,7 +1,5 @@ objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->cacheMock = $this->getMockBuilder(\Magento\Framework\Config\CacheInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->moduleReaderMock = $this->getMockBuilder(\Magento\Framework\Module\Dir\Reader::class) - ->disableOriginalConstructor() - ->getMock(); + $this->cacheMock = $this->getMock( + \Magento\Framework\Config\CacheInterface::class, + [], + [], + '', + false + ); + $this->readerMock = $this->getMock( + \Magento\Framework\Module\Dir\Reader::class, + [], + [], + '', + false + ); + $this->serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); } - public function testConstructorCachedData() + public function testConstructActionsCached() { $this->cacheMock->expects($this->once()) ->method('load') - ->will($this->returnValue(serialize('data'))); + ->willReturn('"data"'); + $this->serializerMock->expects($this->once()) + ->method('unserialize'); $this->cacheMock->expects($this->never()) ->method('save'); - $this->moduleReaderMock->expects($this->never()) + $this->readerMock->expects($this->never()) ->method('getActionFiles'); - $this->actionList = $this->objectManager->getObject( - \Magento\Framework\App\Router\ActionList::class, - [ - 'cache' => $this->cacheMock, - 'moduleReader' => $this->moduleReaderMock, - ] - ); + $this->createActionListInstance(); } - public function testConstructorNoCachedData() + public function testConstructActionsNoCached() { $this->cacheMock->expects($this->once()) ->method('load') - ->will($this->returnValue(false)); + ->willReturn(false); + $this->serializerMock->expects($this->once()) + ->method('serialize'); $this->cacheMock->expects($this->once()) ->method('save'); - $this->moduleReaderMock->expects($this->once()) + $this->readerMock->expects($this->once()) ->method('getActionFiles') - ->will($this->returnValue('data')); - $this->actionList = $this->objectManager->getObject( - \Magento\Framework\App\Router\ActionList::class, - [ - 'cache' => $this->cacheMock, - 'moduleReader' => $this->moduleReaderMock, - ] - ); + ->willReturn('data') + ; + $this->createActionListInstance(); } /** @@ -88,22 +93,15 @@ public function testConstructorNoCachedData() */ public function testGet($module, $area, $namespace, $action, $data, $expected) { - $this->cacheMock->expects($this->once()) ->method('load') ->will($this->returnValue(false)); $this->cacheMock->expects($this->once()) ->method('save'); - $this->moduleReaderMock->expects($this->once()) + $this->readerMock->expects($this->once()) ->method('getActionFiles') - ->will($this->returnValue($data)); - $this->actionList = $this->objectManager->getObject( - \Magento\Framework\App\Router\ActionList::class, - [ - 'cache' => $this->cacheMock, - 'moduleReader' => $this->moduleReaderMock, - ] - ); + ->willReturn($data); + $this->createActionListInstance(); $this->assertEquals($expected, $this->actionList->get($module, $area, $namespace, $action)); } @@ -168,4 +166,16 @@ public function getDataProvider() ], ]; } + + private function createActionListInstance() + { + $this->actionList = $this->objectManager->getObject( + \Magento\Framework\App\Router\ActionList::class, + [ + 'cache' => $this->cacheMock, + 'moduleReader' => $this->readerMock, + 'serializer' => $this->serializerMock, + ] + ); + } } diff --git a/lib/internal/Magento/Framework/Cache/Config/Data.php b/lib/internal/Magento/Framework/Cache/Config/Data.php index a1f203d9aa7bb..5909fff105e2b 100644 --- a/lib/internal/Magento/Framework/Cache/Config/Data.php +++ b/lib/internal/Magento/Framework/Cache/Config/Data.php @@ -1,12 +1,15 @@ reader = $reader; $this->cache = $cache; $this->cacheId = $cacheId; + $this->serializer = $serializer ?: ObjectManager::getInstance()->get(SerializerInterface::class); $this->initData(); } /** * Initialise data for configuration + * * @return void */ protected function initData() @@ -89,10 +101,11 @@ protected function initData() $data = $this->cache->load($this->cacheId); if (false === $data) { $data = $this->reader->read(); - $this->cache->save(serialize($data), $this->cacheId, $this->cacheTags); + $this->cache->save($this->serializer->serialize($data), $this->cacheId, $this->cacheTags); } else { - $data = unserialize($data); + $data = $this->serializer->unserialize($data); } + $this->merge($data); } @@ -133,6 +146,7 @@ public function get($path = null, $default = null) /** * Clear cache data + * * @return void */ public function reset() diff --git a/lib/internal/Magento/Framework/Config/Data/Scoped.php b/lib/internal/Magento/Framework/Config/Data/Scoped.php index 36b265ac9e6f4..f9c151e867b89 100644 --- a/lib/internal/Magento/Framework/Config/Data/Scoped.php +++ b/lib/internal/Magento/Framework/Config/Data/Scoped.php @@ -5,6 +5,12 @@ */ namespace Magento\Framework\Config\Data; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\App\ObjectManager; + +/** + * Provides scoped configuration + */ class Scoped extends \Magento\Framework\Config\Data { /** @@ -49,6 +55,11 @@ class Scoped extends \Magento\Framework\Config\Data */ protected $_loadedScopes = []; + /** + * @var SerializerInterface + */ + private $serializer; + /** * Constructor * @@ -56,17 +67,20 @@ class Scoped extends \Magento\Framework\Config\Data * @param \Magento\Framework\Config\ScopeInterface $configScope * @param \Magento\Framework\Config\CacheInterface $cache * @param string $cacheId + * @param SerializerInterface|null $serializer */ public function __construct( \Magento\Framework\Config\ReaderInterface $reader, \Magento\Framework\Config\ScopeInterface $configScope, \Magento\Framework\Config\CacheInterface $cache, - $cacheId + $cacheId, + SerializerInterface $serializer = null ) { $this->_reader = $reader; $this->_configScope = $configScope; $this->_cache = $cache; $this->_cacheId = $cacheId; + $this->serializer = $serializer ?: ObjectManager::getInstance()->get(SerializerInterface::class); } /** @@ -98,11 +112,14 @@ protected function _loadScopedData() if (false == isset($this->_loadedScopes[$scopeCode])) { if ($scopeCode !== 'primary' && ($data = $this->_cache->load($scopeCode . '::' . $this->_cacheId)) ) { - $data = unserialize($data); + $data = $this->serializer->unserialize($data); } else { $data = $this->_reader->read($scopeCode); if ($scopeCode !== 'primary') { - $this->_cache->save(serialize($data), $scopeCode . '::' . $this->_cacheId); + $this->_cache->save( + $this->serializer->serialize($data), + $scopeCode . '::' . $this->_cacheId + ); } } $this->merge($data); diff --git a/lib/internal/Magento/Framework/Config/Test/Unit/Data/ScopedTest.php b/lib/internal/Magento/Framework/Config/Test/Unit/Data/ScopedTest.php index 496da72ceef9b..607977b99bb42 100644 --- a/lib/internal/Magento/Framework/Config/Test/Unit/Data/ScopedTest.php +++ b/lib/internal/Magento/Framework/Config/Test/Unit/Data/ScopedTest.php @@ -7,6 +7,11 @@ class ScopedTest extends \PHPUnit_Framework_TestCase { + /** + * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + */ + private $objectManager; + /** * @var \Magento\Framework\Config\Data\Scoped */ @@ -27,17 +32,28 @@ class ScopedTest extends \PHPUnit_Framework_TestCase */ protected $_cacheMock; + /** + * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $serializerMock; + protected function setUp() { + $this->objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->_readerMock = $this->getMock(\Magento\Framework\Config\ReaderInterface::class); $this->_configScopeMock = $this->getMock(\Magento\Framework\Config\ScopeInterface::class); $this->_cacheMock = $this->getMock(\Magento\Framework\Config\CacheInterface::class); + $this->serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); - $this->_model = new \Magento\Framework\Config\Data\Scoped( - $this->_readerMock, - $this->_configScopeMock, - $this->_cacheMock, - 'tag' + $this->_model = $this->objectManager->getObject( + \Magento\Framework\Config\Data\Scoped::class, + [ + 'reader' => $this->_readerMock, + 'configScope' => $this->_configScopeMock, + 'cache' => $this->_cacheMock, + 'cacheId' => 'tag', + 'serializer' => $this->serializerMock + ] ); } @@ -47,7 +63,7 @@ protected function setUp() * @param string $default * @dataProvider getConfigByPathDataProvider */ - public function testgetConfigByPath($path, $expectedValue, $default) + public function testGetConfigByPath($path, $expectedValue, $default) { $testData = [ 'key_1' => [ @@ -55,7 +71,12 @@ public function testgetConfigByPath($path, $expectedValue, $default) 'key_1.2' => ['some' => 'arrayValue'], ], ]; - $this->_cacheMock->expects($this->any())->method('load')->will($this->returnValue(serialize([]))); + $this->_cacheMock->expects($this->once()) + ->method('load') + ->willReturn(false); + $this->_readerMock->expects($this->once()) + ->method('read') + ->willReturn([]); $this->_model->merge($testData); $this->assertEquals($expectedValue, $this->_model->get($path, $default)); } @@ -77,6 +98,7 @@ public function getConfigByPathDataProvider() public function testGetScopeSwitchingWithNonCachedData() { $testValue = ['some' => 'testValue']; + $serializedData = 'serialized data'; /** change current area */ $this->_configScopeMock->expects( @@ -109,8 +131,15 @@ public function testGetScopeSwitchingWithNonCachedData() $this->returnValue($testValue) ); + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->with($testValue) + ->willReturn($serializedData); + /** test cache saving */ - $this->_cacheMock->expects($this->once())->method('save')->with(serialize($testValue), 'adminhtml::tag'); + $this->_cacheMock->expects($this->once()) + ->method('save') + ->with($serializedData, 'adminhtml::tag'); /** test config value existence */ $this->assertEquals('testValue', $this->_model->get('some')); @@ -122,6 +151,7 @@ public function testGetScopeSwitchingWithNonCachedData() public function testGetScopeSwitchingWithCachedData() { $testValue = ['some' => 'testValue']; + $serializedData = 'serialized data'; /** change current area */ $this->_configScopeMock->expects( @@ -132,16 +162,16 @@ public function testGetScopeSwitchingWithCachedData() $this->returnValue('adminhtml') ); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with($serializedData) + ->willReturn($testValue); + /** set cache data */ - $this->_cacheMock->expects( - $this->once() - )->method( - 'load' - )->with( - 'adminhtml::tag' - )->will( - $this->returnValue(serialize($testValue)) - ); + $this->_cacheMock->expects($this->once()) + ->method('load') + ->with('adminhtml::tag') + ->willReturn($serializedData); /** test preventing of getting data from reader */ $this->_readerMock->expects($this->never())->method('read'); diff --git a/lib/internal/Magento/Framework/Config/Test/Unit/DataTest.php b/lib/internal/Magento/Framework/Config/Test/Unit/DataTest.php index 5c58310e096bb..c37d2108191b4 100644 --- a/lib/internal/Magento/Framework/Config/Test/Unit/DataTest.php +++ b/lib/internal/Magento/Framework/Config/Test/Unit/DataTest.php @@ -10,33 +10,46 @@ class DataTest extends \PHPUnit_Framework_TestCase { - /** @var \Magento\Framework\Config\ReaderInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $reader; - /** @var \Magento\Framework\Config\CacheInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $cache; - /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ - protected $objectManagerHelper; + /** + * @var \Magento\Framework\Config\ReaderInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $readerMock; + + /** + * @var \Magento\Framework\Config\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $cacheMock; + + /** + * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $serializerMock; protected function setUp() { - $this->reader = $this->getMockBuilder(\Magento\Framework\Config\ReaderInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->cache = $this->getMockBuilder(\Magento\Framework\Config\CacheInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->readerMock = $this->getMock(\Magento\Framework\Config\ReaderInterface::class); + $this->cacheMock = $this->getMock(\Magento\Framework\Config\CacheInterface::class); + $this->serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); } - public function testGet() + public function testGetConfigNotCached() { $data = ['a' => 'b']; - $cacheid = 'test'; - $this->cache->expects($this->once())->method('load')->will($this->returnValue(false)); - $this->reader->expects($this->once())->method('read')->will($this->returnValue($data)); - + $cacheId = 'test'; + $this->cacheMock->expects($this->once()) + ->method('load') + ->willReturn(false); + $this->readerMock->expects($this->once()) + ->method('read') + ->willReturn($data); + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->with($data); $config = new \Magento\Framework\Config\Data( - $this->reader, $this->cache, $cacheid + $this->readerMock, + $this->cacheMock, + $cacheId, + $this->serializerMock ); $this->assertEquals($data, $config->get()); $this->assertEquals('b', $config->get('a')); @@ -44,18 +57,50 @@ public function testGet() $this->assertEquals(33, $config->get('a/b', 33)); } - public function testReset() + public function testGetConfigCached() { - $cacheid = 'test'; - $this->cache->expects($this->once())->method('load')->will($this->returnValue(serialize([]))); - $this->cache->expects($this->once())->method('remove')->with($cacheid); - + $data = ['a' => 'b']; + $serializedData = '{"a":"b"}'; + $cacheId = 'test'; + $this->cacheMock->expects($this->once()) + ->method('load') + ->willReturn($serializedData); + $this->readerMock->expects($this->never()) + ->method('read'); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with($serializedData) + ->willReturn($data); $config = new \Magento\Framework\Config\Data( - $this->reader, - $this->cache, - $cacheid + $this->readerMock, + $this->cacheMock, + $cacheId, + $this->serializerMock ); + $this->assertEquals($data, $config->get()); + $this->assertEquals('b', $config->get('a')); + } + public function testReset() + { + $serializedData = ''; + $cacheId = 'test'; + $this->cacheMock->expects($this->once()) + ->method('load') + ->willReturn($serializedData); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with($serializedData) + ->willReturn([]); + $this->cacheMock->expects($this->once()) + ->method('remove') + ->with($cacheId); + $config = new \Magento\Framework\Config\Data( + $this->readerMock, + $this->cacheMock, + $cacheId, + $this->serializerMock + ); $config->reset(); } } diff --git a/lib/internal/Magento/Framework/DataObject/Copy/Config/Data.php b/lib/internal/Magento/Framework/DataObject/Copy/Config/Data.php index 61802637750c6..5f2a1518d485a 100644 --- a/lib/internal/Magento/Framework/DataObject/Copy/Config/Data.php +++ b/lib/internal/Magento/Framework/DataObject/Copy/Config/Data.php @@ -1,12 +1,13 @@ _omConfig = $omConfig; $this->_relations = $relations; @@ -95,10 +107,11 @@ public function __construct( $this->_cacheId = $cacheId; $this->_reader = $reader; $this->_scopeList = $scopeList; - + $this->serializer = $serializer ?: \Magento\Framework\App\ObjectManager::getInstance() + ->get(Serialize::class); $intercepted = $this->_cache->load($this->_cacheId); if ($intercepted !== false) { - $this->_intercepted = unserialize($intercepted); + $this->_intercepted = $this->serializer->unserialize($intercepted); } else { $this->initialize($this->_classDefinitions->getClasses()); } @@ -129,7 +142,7 @@ public function initialize($classDefinitions = []) foreach ($classDefinitions as $class) { $this->hasPlugins($class); } - $this->_cache->save(serialize($this->_intercepted), $this->_cacheId); + $this->_cache->save($this->serializer->serialize($this->_intercepted), $this->_cacheId); } /** diff --git a/lib/internal/Magento/Framework/Interception/Definition/Compiled.php b/lib/internal/Magento/Framework/Interception/Definition/Compiled.php deleted file mode 100644 index 6fbe9c99dce86..0000000000000 --- a/lib/internal/Magento/Framework/Interception/Definition/Compiled.php +++ /dev/null @@ -1,39 +0,0 @@ -_definitions = $definitions; - } - - /** - * Retrieve list of methods - * - * @param string $type - * @return string[] - */ - public function getMethodList($type) - { - return $this->_definitions[$type]; - } -} diff --git a/lib/internal/Magento/Framework/Interception/PluginList/PluginList.php b/lib/internal/Magento/Framework/Interception/PluginList/PluginList.php index bae8f7c118c08..a84e23dc75548 100644 --- a/lib/internal/Magento/Framework/Interception/PluginList/PluginList.php +++ b/lib/internal/Magento/Framework/Interception/PluginList/PluginList.php @@ -1,7 +1,5 @@ serializer = $serializer ?: $objectManager->get(Serialize::class); + parent::__construct($reader, $configScope, $cache, $cacheId, $this->serializer); $this->_omConfig = $omConfig; $this->_relations = $relations; $this->_definitions = $definitions; @@ -275,7 +287,7 @@ protected function _loadScopedData() $cacheId = implode('|', $this->_scopePriorityScheme) . "|" . $this->_cacheId; $data = $this->_cache->load($cacheId); if ($data) { - list($this->_data, $this->_inherited, $this->_processed) = unserialize($data); + list($this->_data, $this->_inherited, $this->_processed) = $this->serializer->unserialize($data); foreach ($this->_scopePriorityScheme as $scopeCode) { $this->_loadedScopes[$scopeCode] = true; } @@ -307,7 +319,10 @@ protected function _loadScopedData() foreach ($this->getClassDefinitions() as $class) { $this->_inheritPlugins($class); } - $this->_cache->save(serialize([$this->_data, $this->_inherited, $this->_processed]), $cacheId); + $this->_cache->save( + $this->serializer->serialize([$this->_data, $this->_inherited, $this->_processed]), + $cacheId + ); } $this->_pluginInstances = []; } @@ -371,10 +386,10 @@ private function filterPlugins(array &$plugins) } /** - * Returns logger instance + * Get logger * - * @deprecated * @return \Psr\Log\LoggerInterface + * @deprecated */ private function getLogger() { diff --git a/lib/internal/Magento/Framework/Interception/Test/Unit/Config/ConfigTest.php b/lib/internal/Magento/Framework/Interception/Test/Unit/Config/ConfigTest.php index 992ed838b7c52..7d15d1029bda6 100644 --- a/lib/internal/Magento/Framework/Interception/Test/Unit/Config/ConfigTest.php +++ b/lib/internal/Magento/Framework/Interception/Test/Unit/Config/ConfigTest.php @@ -6,6 +6,8 @@ // @codingStandardsIgnoreFile namespace Magento\Framework\Interception\Test\Unit\Config; +use Magento\Framework\Serialize\SerializerInterface; + require_once __DIR__ . '/../Custom/Module/Model/Item.php'; require_once __DIR__ . '/../Custom/Module/Model/Item/Enhanced.php'; require_once __DIR__ . '/../Custom/Module/Model/ItemContainer.php'; @@ -22,32 +24,38 @@ class ConfigTest extends \PHPUnit_Framework_TestCase /** * @var \PHPUnit_Framework_MockObject_MockObject */ - protected $configScopeMock; + private $configScopeMock; /** * @var \PHPUnit_Framework_MockObject_MockObject */ - protected $readerMock; + private $readerMock; /** * @var \PHPUnit_Framework_MockObject_MockObject */ - protected $cacheMock; + private $cacheMock; /** * @var \PHPUnit_Framework_MockObject_MockObject */ - protected $omConfigMock; + private $omConfigMock; /** * @var \PHPUnit_Framework_MockObject_MockObject */ - protected $definitionMock; + private $definitionMock; /** * @var \PHPUnit_Framework_MockObject_MockObject */ - protected $relationsMock; + private $relationsMock; + + /** @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject */ + private $serializerMock; + + /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + private $objectManagerHelper; protected function setUp() { @@ -67,6 +75,8 @@ protected function setUp() $this->relationsMock = $this->getMockForAbstractClass( \Magento\Framework\ObjectManager\RelationsInterface::class ); + $this->serializerMock = $this->getMock(SerializerInterface::class); + $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); } /** @@ -131,14 +141,22 @@ public function testHasPluginsWhenDataIsNotCached($expectedResult, $type, $entit $this->relationsMock->expects($this->any())->method('has')->will($this->returnValue($expectedResult)); $this->relationsMock->expects($this->any())->method('getParents')->will($this->returnValue($entityParents)); - $model = new \Magento\Framework\Interception\Config\Config( - $this->readerMock, - $this->configScopeMock, - $this->cacheMock, - $this->relationsMock, - $this->omConfigMock, - $this->definitionMock, - 'interception' + $this->serializerMock->expects($this->once()) + ->method('serialize'); + + $this->serializerMock->expects($this->never())->method('unserialize'); + + $model = $this->objectManagerHelper->getObject( + \Magento\Framework\Interception\Config\Config::class, + [ + 'reader' => $this->readerMock, + 'scopeList' => $this->configScopeMock, + 'cache' => $this->cacheMock, + 'relations' => $this->relationsMock, + 'omConfig' => $this->omConfigMock, + 'classDefinitions' => $this->definitionMock, + 'serializer' => $this->serializerMock, + ] ); $this->assertEquals($expectedResult, $model->hasPlugins($type)); @@ -163,18 +181,32 @@ public function testHasPluginsWhenDataIsCached($expectedResult, $type) ]; $this->readerMock->expects($this->never())->method('read'); $this->cacheMock->expects($this->never())->method('save'); + $serializedValue = 'serializedData'; $this->cacheMock->expects($this->any()) ->method('load') ->with($cacheId) - ->will($this->returnValue(serialize($interceptionData))); - $model = new \Magento\Framework\Interception\Config\Config( - $this->readerMock, - $this->configScopeMock, - $this->cacheMock, - new \Magento\Framework\ObjectManager\Relations\Runtime(), - $this->omConfigMock, - $this->definitionMock, - $cacheId + ->will($this->returnValue($serializedValue)); + + $this->serializerMock->expects($this->never())->method('serialize'); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with($serializedValue) + ->willReturn($interceptionData); + + $model = $this->objectManagerHelper->getObject( + \Magento\Framework\Interception\Config\Config::class, + [ + 'reader' => $this->readerMock, + 'scopeList' => $this->configScopeMock, + 'cache' => $this->cacheMock, + 'relations' => $this->objectManagerHelper->getObject( + \Magento\Framework\ObjectManager\Relations\Runtime::class + ), + 'omConfig' => $this->omConfigMock, + 'classDefinitions' => $this->definitionMock, + 'cacheId' => $cacheId, + 'serializer' => $this->serializerMock, + ] ); $this->assertEquals($expectedResult, $model->hasPlugins($type)); diff --git a/lib/internal/Magento/Framework/Interception/Test/Unit/Definition/CompiledTest.php b/lib/internal/Magento/Framework/Interception/Test/Unit/Definition/CompiledTest.php deleted file mode 100644 index a64cd96b62966..0000000000000 --- a/lib/internal/Magento/Framework/Interception/Test/Unit/Definition/CompiledTest.php +++ /dev/null @@ -1,24 +0,0 @@ - 'definitions']; - - /** - * @covers \Magento\Framework\Interception\Definition\Compiled::getMethodList - * @covers \Magento\Framework\Interception\Definition\Compiled::__construct - */ - public function testGetMethodList() - { - $model = new \Magento\Framework\Interception\Definition\Compiled($this->_definitions); - $this->assertEquals('definitions', $model->getMethodList('type')); - } -} diff --git a/lib/internal/Magento/Framework/Interception/Test/Unit/PluginList/PluginListTest.php b/lib/internal/Magento/Framework/Interception/Test/Unit/PluginList/PluginListTest.php index ac1e510f28b22..11e8dabf6d924 100644 --- a/lib/internal/Magento/Framework/Interception/Test/Unit/PluginList/PluginListTest.php +++ b/lib/internal/Magento/Framework/Interception/Test/Unit/PluginList/PluginListTest.php @@ -5,6 +5,9 @@ */ namespace Magento\Framework\Interception\Test\Unit\PluginList; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\ObjectManagerInterface; + require_once __DIR__ . '/../Custom/Module/Model/Item.php'; require_once __DIR__ . '/../Custom/Module/Model/Item/Enhanced.php'; require_once __DIR__ . '/../Custom/Module/Model/ItemContainer.php'; @@ -23,22 +26,32 @@ class PluginListTest extends \PHPUnit_Framework_TestCase /** * @var \Magento\Framework\Interception\PluginList\PluginList */ - protected $_model; + private $object; + + /** + * @var \Magento\Framework\Config\ScopeInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $configScopeMock; + + /** + * @var \Magento\Framework\Config\CacheInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $cacheMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $_configScopeMock; + private $loggerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $_objectManagerMock; + private $serializerMock; /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var ObjectManagerInterface||\PHPUnit_Framework_MockObject_MockObject */ - protected $_cacheMock; + private $objectManagerMock; protected function setUp() { @@ -46,10 +59,10 @@ protected function setUp() $readerMock = $this->getMock(\Magento\Framework\ObjectManager\Config\Reader\Dom::class, [], [], '', false); $readerMock->expects($this->any())->method('read')->will($this->returnValueMap($readerMap)); - $this->_configScopeMock = $this->getMock(\Magento\Framework\Config\ScopeInterface::class); - $this->_cacheMock = $this->getMock(\Magento\Framework\Config\CacheInterface::class); + $this->configScopeMock = $this->getMock(\Magento\Framework\Config\ScopeInterface::class); + $this->cacheMock = $this->getMock(\Magento\Framework\Config\CacheInterface::class); // turn cache off - $this->_cacheMock->expects($this->any()) + $this->cacheMock->expects($this->any()) ->method('get') ->will($this->returnValue(false)); @@ -59,62 +72,76 @@ protected function setUp() $omConfigMock->expects($this->any())->method('getOriginalInstanceType')->will($this->returnArgument(0)); - $this->_objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); + $this->objectManagerMock = $this->getMock(ObjectManagerInterface::class); + $this->objectManagerMock->expects($this->any()) + ->method('get') + ->willReturnArgument(0); + $this->serializerMock = $this->getMock(SerializerInterface::class); $definitions = new \Magento\Framework\ObjectManager\Definition\Runtime(); - $this->_model = new \Magento\Framework\Interception\PluginList\PluginList( - $readerMock, - $this->_configScopeMock, - $this->_cacheMock, - new \Magento\Framework\ObjectManager\Relations\Runtime(), - $omConfigMock, - new \Magento\Framework\Interception\Definition\Runtime(), - $this->_objectManagerMock, - $definitions, - ['global'], - 'interception' + $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + $this->object = $objectManagerHelper->getObject( + \Magento\Framework\Interception\PluginList\PluginList::class, + [ + 'reader' => $readerMock, + 'configScope' => $this->configScopeMock, + 'cache' => $this->cacheMock, + 'relations' => new \Magento\Framework\ObjectManager\Relations\Runtime(), + 'omConfig' => $omConfigMock, + 'definitions' => new \Magento\Framework\Interception\Definition\Runtime(), + 'objectManager' => $this->objectManagerMock, + 'classDefinitions' => $definitions, + 'scopePriorityScheme' => ['global'], + 'cacheId' => 'interception', + 'serializer' => $this->serializerMock + ] + ); + + $this->loggerMock = $this->getMock(\Psr\Log\LoggerInterface::class); + $objectManagerHelper->setBackwardCompatibleProperty( + $this->object, + 'logger', + $this->loggerMock ); } public function testGetPlugin() { - $this->_objectManagerMock->expects($this->any())->method('get')->will($this->returnArgument(0)); - $this->_configScopeMock->expects($this->any())->method('getCurrentScope')->will($this->returnValue('backend')); - $this->_model->getNext(\Magento\Framework\Interception\Test\Unit\Custom\Module\Model\Item::class, 'getName'); - $this->_model->getNext( + $this->configScopeMock->expects($this->any())->method('getCurrentScope')->will($this->returnValue('backend')); + $this->object->getNext(\Magento\Framework\Interception\Test\Unit\Custom\Module\Model\Item::class, 'getName'); + $this->object->getNext( \Magento\Framework\Interception\Test\Unit\Custom\Module\Model\ItemContainer::class, 'getName' ); - $this->_model->getNext( + $this->object->getNext( \Magento\Framework\Interception\Test\Unit\Custom\Module\Model\StartingBackslash::class, 'getName' ); - $this->assertEquals( \Magento\Framework\Interception\Test\Unit\Custom\Module\Model\ItemPlugin\Simple::class, - $this->_model->getPlugin( + $this->object->getPlugin( \Magento\Framework\Interception\Test\Unit\Custom\Module\Model\Item::class, 'simple_plugin' ) ); $this->assertEquals( \Magento\Framework\Interception\Test\Unit\Custom\Module\Model\ItemPlugin\Advanced::class, - $this->_model->getPlugin( + $this->object->getPlugin( \Magento\Framework\Interception\Test\Unit\Custom\Module\Model\Item::class, 'advanced_plugin' ) ); $this->assertEquals( \Magento\Framework\Interception\Test\Unit\Custom\Module\Model\ItemContainerPlugin\Simple::class, - $this->_model->getPlugin( + $this->object->getPlugin( \Magento\Framework\Interception\Test\Unit\Custom\Module\Model\ItemContainer::class, 'simple_plugin' ) ); $this->assertEquals( \Magento\Framework\Interception\Test\Unit\Custom\Module\Model\StartingBackslash\Plugin::class, - $this->_model->getPlugin( + $this->object->getPlugin( \Magento\Framework\Interception\Test\Unit\Custom\Module\Model\StartingBackslash::class, 'simple_plugin' ) @@ -131,15 +158,14 @@ public function testGetPlugin() */ public function testGetPlugins($expectedResult, $type, $method, $scopeCode, $code = '__self') { - $this->_objectManagerMock->expects($this->any())->method('get')->will($this->returnArgument(0)); - $this->_configScopeMock->expects( + $this->configScopeMock->expects( $this->any() )->method( 'getCurrentScope' )->will( $this->returnValue($scopeCode) ); - $this->assertEquals($expectedResult, $this->_model->getNext($type, $method, $code)); + $this->assertEquals($expectedResult, $this->object->getNext($type, $method, $code)); } /** @@ -207,12 +233,26 @@ public function getPluginsDataProvider() */ public function testInheritPluginsWithNonExistingClass() { - $this->_objectManagerMock->expects($this->any())->method('get')->will($this->returnArgument(0)); - $this->_configScopeMock->expects($this->any()) + $this->configScopeMock->expects($this->any()) ->method('getCurrentScope') ->will($this->returnValue('frontend')); - $this->_model->getNext('SomeType', 'someMethod'); + $this->object->getNext('SomeType', 'someMethod'); + } + + public function testLoadScopedDataNotCached() + { + $this->configScopeMock->expects($this->exactly(3)) + ->method('getCurrentScope') + ->will($this->returnValue('scope')); + $this->serializerMock->expects($this->once()) + ->method('serialize'); + $this->serializerMock->expects($this->never()) + ->method('unserialize'); + $this->cacheMock->expects($this->once()) + ->method('save'); + + $this->assertEquals(null, $this->object->getNext('Type', 'method')); } /** @@ -221,19 +261,14 @@ public function testInheritPluginsWithNonExistingClass() */ public function testInheritPluginsWithNotExistingPlugin() { - $loggerMock = $this->getMock(\Psr\Log\LoggerInterface::class); - $this->_objectManagerMock->expects($this->once()) - ->method('get') - ->with(\Psr\Log\LoggerInterface::class) - ->willReturn($loggerMock); - $loggerMock->expects($this->once()) + $this->loggerMock->expects($this->once()) ->method('info') ->with("Reference to undeclared plugin with name 'simple_plugin'."); - $this->_configScopeMock->expects($this->any()) + $this->configScopeMock->expects($this->any()) ->method('getCurrentScope') ->will($this->returnValue('frontend')); - $this->assertNull($this->_model->getNext('typeWithoutInstance', 'someMethod')); + $this->assertNull($this->object->getNext('typeWithoutInstance', 'someMethod')); } /** @@ -242,19 +277,24 @@ public function testInheritPluginsWithNotExistingPlugin() */ public function testLoadScopedDataCached() { - $this->_objectManagerMock->expects($this->any())->method('get')->will($this->returnArgument(0)); - $this->_configScopeMock->expects($this->once()) + $this->configScopeMock->expects($this->once()) ->method('getCurrentScope') ->will($this->returnValue('scope')); $data = [['key'], ['key'], ['key']]; + $serializedData = 'serialized data'; - $this->_cacheMock->expects($this->once()) + $this->serializerMock->expects($this->never()) + ->method('serialize'); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->willReturn($data); + $this->cacheMock->expects($this->once()) ->method('load') ->with('global|scope|interception') - ->will($this->returnValue(serialize($data))); + ->willReturn($serializedData); - $this->assertEquals(null, $this->_model->getNext('Type', 'method')); + $this->assertEquals(null, $this->object->getNext('Type', 'method')); } /** @@ -263,23 +303,23 @@ public function testLoadScopedDataCached() */ public function testLoadScopeDataWithEmptyData() { - $this->_objectManagerMock->expects($this->any()) + $this->objectManagerMock->expects($this->any()) ->method('get') ->will($this->returnArgument(0)); - $this->_configScopeMock->expects($this->any()) + $this->configScopeMock->expects($this->any()) ->method('getCurrentScope') ->will($this->returnValue('emptyscope')); $this->assertEquals( [4 => ['simple_plugin']], - $this->_model->getNext( + $this->object->getNext( \Magento\Framework\Interception\Test\Unit\Custom\Module\Model\Item::class, 'getName' ) ); $this->assertEquals( \Magento\Framework\Interception\Test\Unit\Custom\Module\Model\ItemPlugin\Simple::class, - $this->_model->getPlugin( + $this->object->getPlugin( \Magento\Framework\Interception\Test\Unit\Custom\Module\Model\Item::class, 'simple_plugin' ) diff --git a/lib/internal/Magento/Framework/Mview/Config/Data.php b/lib/internal/Magento/Framework/Mview/Config/Data.php index d2e4ee91bea2d..fed3021a161ee 100644 --- a/lib/internal/Magento/Framework/Mview/Config/Data.php +++ b/lib/internal/Magento/Framework/Mview/Config/Data.php @@ -5,6 +5,11 @@ */ namespace Magento\Framework\Mview\Config; +use Magento\Framework\Serialize\SerializerInterface; + +/** + * Provides materialized view configuration + */ class Data extends \Magento\Framework\Config\Data { /** @@ -13,22 +18,26 @@ class Data extends \Magento\Framework\Config\Data protected $stateCollection; /** - * @param \Magento\Framework\Mview\Config\Reader $reader + * Constructor + * + * @param Reader $reader * @param \Magento\Framework\Config\CacheInterface $cache * @param \Magento\Framework\Mview\View\State\CollectionInterface $stateCollection - * @param string $cacheId + * @param string|null $cacheId + * @param SerializerInterface|null $serializer */ public function __construct( \Magento\Framework\Mview\Config\Reader $reader, \Magento\Framework\Config\CacheInterface $cache, \Magento\Framework\Mview\View\State\CollectionInterface $stateCollection, - $cacheId = 'mview_config' + $cacheId = 'mview_config', + SerializerInterface $serializer = null ) { $this->stateCollection = $stateCollection; $isCacheExists = $cache->test($cacheId); - parent::__construct($reader, $cache, $cacheId); + parent::__construct($reader, $cache, $cacheId, $serializer); if (!$isCacheExists) { $this->deleteNonexistentStates(); diff --git a/lib/internal/Magento/Framework/Mview/Test/Unit/Config/DataTest.php b/lib/internal/Magento/Framework/Mview/Test/Unit/Config/DataTest.php index 244b1b1e1382d..777c099d9b838 100644 --- a/lib/internal/Magento/Framework/Mview/Test/Unit/Config/DataTest.php +++ b/lib/internal/Magento/Framework/Mview/Test/Unit/Config/DataTest.php @@ -10,32 +10,37 @@ class DataTest extends \PHPUnit_Framework_TestCase /** * @var \Magento\Framework\Mview\Config\Data */ - protected $model; + private $config; /** * @var \Magento\Framework\Mview\Config\Reader|\PHPUnit_Framework_MockObject_MockObject */ - protected $reader; + private $reader; /** * @var \Magento\Framework\Config\CacheInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $cache; + private $cache; /** * @var \Magento\Framework\Mview\View\State\CollectionInterface|\PHPUnit_Framework_MockObject_MockObject */ - protected $stateCollection; + private $stateCollection; /** * @var string */ - protected $cacheId = 'mview_config'; + private $cacheId = 'mview_config'; /** * @var string */ - protected $views = ['view1' => [], 'view3' => []]; + private $views = ['view1' => [], 'view3' => []]; + + /** + * @var \Magento\Framework\Serialize\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $serializerMock; protected function setUp() { @@ -58,28 +63,29 @@ protected function setUp() true, ['getItems'] ); + + $this->serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); } public function testConstructorWithCache() { $this->cache->expects($this->once())->method('test')->with($this->cacheId)->will($this->returnValue(true)); - $this->cache->expects( - $this->once() - )->method( - 'load' - )->with( - $this->cacheId - )->will( - $this->returnValue(serialize($this->views)) - ); + $this->cache->expects($this->once()) + ->method('load') + ->with($this->cacheId); $this->stateCollection->expects($this->never())->method('getItems'); - $this->model = new \Magento\Framework\Mview\Config\Data( + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->willReturn($this->views); + + $this->config = new \Magento\Framework\Mview\Config\Data( $this->reader, $this->cache, $this->stateCollection, - $this->cacheId + $this->cacheId, + $this->serializerMock ); } @@ -114,11 +120,12 @@ public function testConstructorWithoutCache() $this->stateCollection->expects($this->once())->method('getItems')->will($this->returnValue($states)); - $this->model = new \Magento\Framework\Mview\Config\Data( + $this->config = new \Magento\Framework\Mview\Config\Data( $this->reader, $this->cache, $this->stateCollection, - $this->cacheId + $this->cacheId, + $this->serializerMock ); } } diff --git a/lib/internal/Magento/Framework/ObjectManager/Config/Compiled.php b/lib/internal/Magento/Framework/ObjectManager/Config/Compiled.php index 779e8cf0a0e5e..0260af34ef108 100644 --- a/lib/internal/Magento/Framework/ObjectManager/Config/Compiled.php +++ b/lib/internal/Magento/Framework/ObjectManager/Config/Compiled.php @@ -6,9 +6,14 @@ namespace Magento\Framework\ObjectManager\Config; use Magento\Framework\ObjectManager\ConfigInterface; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\Serialize\Serializer\Serialize; use Magento\Framework\ObjectManager\ConfigCacheInterface; use Magento\Framework\ObjectManager\RelationsInterface; +/** + * Provides object manager configuration when in compiled mode + */ class Compiled implements ConfigInterface { /** @@ -27,6 +32,13 @@ class Compiled implements ConfigInterface private $preferences; /** + * @var SerializerInterface + */ + private $serializer; + + /** + * Constructor + * * @param array $data */ public function __construct($data) @@ -72,7 +84,7 @@ public function getArguments($type) { if (isset($this->arguments[$type])) { if (is_string($this->arguments[$type])) { - $this->arguments[$type] = unserialize($this->arguments[$type]); + $this->arguments[$type] = $this->getSerializer()->unserialize($this->arguments[$type]); } return $this->arguments[$type]; } else { @@ -159,4 +171,19 @@ public function getPreferences() { return $this->preferences; } + + /** + * Get serializer + * + * @return SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if (null === $this->serializer) { + $this->serializer = \Magento\Framework\App\ObjectManager::getInstance() + ->get(Serialize::class); + } + return $this->serializer; + } } diff --git a/lib/internal/Magento/Framework/ObjectManager/Config/Config.php b/lib/internal/Magento/Framework/ObjectManager/Config/Config.php index 5dc02e6ba7d97..7ad196cdd34b4 100644 --- a/lib/internal/Magento/Framework/ObjectManager/Config/Config.php +++ b/lib/internal/Magento/Framework/ObjectManager/Config/Config.php @@ -5,6 +5,7 @@ */ namespace Magento\Framework\ObjectManager\Config; +use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\ObjectManager\ConfigCacheInterface; use Magento\Framework\ObjectManager\DefinitionInterface; use Magento\Framework\ObjectManager\RelationsInterface; @@ -74,6 +75,11 @@ class Config implements \Magento\Framework\ObjectManager\ConfigInterface */ protected $_mergedArguments; + /** + * @var \Magento\Framework\Serialize\SerializerInterface + */ + private $serializer; + /** * @param RelationsInterface $relations * @param DefinitionInterface $definitions @@ -267,10 +273,12 @@ public function extend(array $configuration) if ($this->_cache) { if (!$this->_currentCacheKey) { $this->_currentCacheKey = md5( - serialize([$this->_arguments, $this->_nonShared, $this->_preferences, $this->_virtualTypes]) + $this->getSerializer()->serialize( + [$this->_arguments, $this->_nonShared, $this->_preferences, $this->_virtualTypes] + ) ); } - $key = md5($this->_currentCacheKey . serialize($configuration)); + $key = md5($this->_currentCacheKey . $this->getSerializer()->serialize($configuration)); $cached = $this->_cache->get($key); if ($cached) { list( @@ -323,4 +331,19 @@ public function getPreferences() { return $this->_preferences; } + + /** + * Get serializer + * + * @return \Magento\Framework\Serialize\SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if ($this->serializer === null) { + $this->serializer = \Magento\Framework\App\ObjectManager::getInstance() + ->get(SerializerInterface::class); + } + return $this->serializer; + } } diff --git a/lib/internal/Magento/Framework/ObjectManager/Definition/Compiled.php b/lib/internal/Magento/Framework/ObjectManager/Definition/Compiled.php deleted file mode 100644 index 2cb3b21211f23..0000000000000 --- a/lib/internal/Magento/Framework/ObjectManager/Definition/Compiled.php +++ /dev/null @@ -1,85 +0,0 @@ -_signatures, $this->_definitions) = $definitions; - $this->reader = $reader ?: new \Magento\Framework\Code\Reader\ClassReader(); - } - - /** - * Unpack signature - * - * @param string $signature - * @return mixed - */ - abstract protected function _unpack($signature); - - /** - * Get list of method parameters - * - * Retrieve an ordered list of constructor parameters. - * Each value is an array with following entries: - * - * array( - * 0, // string: Parameter name - * 1, // string|null: Parameter type - * 2, // bool: whether this param is required - * 3, // mixed: default value - * ); - * - * @param string $className - * @return array|null - */ - public function getParameters($className) - { - // if the definition isn't found in the list gathered from the compiled file then using reflection to find it - if (!array_key_exists($className, $this->_definitions)) { - return $this->reader->getConstructor($className); - } - - $definition = $this->_definitions[$className]; - if ($definition !== null) { - if (is_string($this->_signatures[$definition])) { - $this->_signatures[$definition] = $this->_unpack($this->_signatures[$definition]); - } - return $this->_signatures[$definition]; - } - return null; - } - - /** - * Retrieve list of all classes covered with definitions - * - * @return array - */ - public function getClasses() - { - return array_keys($this->_definitions); - } -} diff --git a/lib/internal/Magento/Framework/ObjectManager/Definition/Compiled/Binary.php b/lib/internal/Magento/Framework/ObjectManager/Definition/Compiled/Binary.php deleted file mode 100644 index bba816e072e6b..0000000000000 --- a/lib/internal/Magento/Framework/ObjectManager/Definition/Compiled/Binary.php +++ /dev/null @@ -1,27 +0,0 @@ - \Magento\Framework\ObjectManager\Definition\Compiled\Binary::class, - Serialized::MODE_NAME => \Magento\Framework\ObjectManager\Definition\Compiled\Serialized::class, - ]; - /** * @var \Magento\Framework\Code\Generator */ @@ -74,39 +38,26 @@ class DefinitionFactory /** * @param DriverInterface $filesystemDriver - * @param string $definitionDir * @param string $generationDir - * @param string $definitionFormat */ - public function __construct(DriverInterface $filesystemDriver, $definitionDir, $generationDir, $definitionFormat) - { + public function __construct( + DriverInterface $filesystemDriver, + $generationDir + ) { $this->_filesystemDriver = $filesystemDriver; - $this->_definitionDir = $definitionDir; $this->_generationDir = $generationDir; - $this->_definitionFormat = $definitionFormat; } /** * Create class definitions * - * @param mixed $definitions - * @return Runtime + * @return DefinitionInterface */ - public function createClassDefinition($definitions = false) + public function createClassDefinition() { - if ($definitions) { - if (is_string($definitions)) { - $definitions = $this->_unpack($definitions); - } - $definitionModel = self::$definitionClasses[$this->_definitionFormat]; - $result = new $definitionModel($definitions); - } else { - $autoloader = new \Magento\Framework\Code\Generator\Autoloader($this->getCodeGenerator()); - spl_autoload_register([$autoloader, 'load']); - - $result = new Runtime(); - } - return $result; + $autoloader = new Autoloader($this->getCodeGenerator()); + spl_autoload_register([$autoloader, 'load']); + return new Runtime(); } /** @@ -116,14 +67,7 @@ public function createClassDefinition($definitions = false) */ public function createPluginDefinition() { - $path = $this->_definitionDir . '/plugins.ser'; - if ($this->_filesystemDriver->isReadable($path)) { - return new \Magento\Framework\Interception\Definition\Compiled( - $this->_unpack($this->_filesystemDriver->fileGetContents($path)) - ); - } else { - return new \Magento\Framework\Interception\Definition\Runtime(); - } + return new \Magento\Framework\Interception\Definition\Runtime(); } /** @@ -133,36 +77,7 @@ public function createPluginDefinition() */ public function createRelations() { - $path = $this->_definitionDir . '/' . 'relations.ser'; - if ($this->_filesystemDriver->isReadable($path)) { - return new \Magento\Framework\ObjectManager\Relations\Compiled( - $this->_unpack($this->_filesystemDriver->fileGetContents($path)) - ); - } else { - return new \Magento\Framework\ObjectManager\Relations\Runtime(); - } - } - - /** - * Gets supported definition formats - * - * @return array - */ - public static function getSupportedFormats() - { - return array_keys(self::$definitionClasses); - } - - /** - * Un-compress definitions - * - * @param string $definitions - * @return mixed - */ - protected function _unpack($definitions) - { - $extractor = $this->_definitionFormat == Binary::MODE_NAME ? 'igbinary_unserialize' : 'unserialize'; - return $extractor($definitions); + return new \Magento\Framework\ObjectManager\Relations\Runtime(); } /** diff --git a/lib/internal/Magento/Framework/ObjectManager/Relations/Compiled.php b/lib/internal/Magento/Framework/ObjectManager/Relations/Compiled.php deleted file mode 100644 index 71455dbf9acd4..0000000000000 --- a/lib/internal/Magento/Framework/ObjectManager/Relations/Compiled.php +++ /dev/null @@ -1,55 +0,0 @@ -_relations = $relations; - } - - /** - * Check whether requested type is available for read - * - * @param string $type - * @return bool - */ - public function has($type) - { - return isset($this->_relations[$type]); - } - - /** - * Retrieve parents for class - * - * @param string $type - * @return array - */ - public function getParents($type) - { - return $this->_relations[$type]; - } -} diff --git a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Config/CompiledTest.php b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Config/CompiledTest.php index 1fcf3176540db..489dc9d814e11 100644 --- a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Config/CompiledTest.php +++ b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Config/CompiledTest.php @@ -5,87 +5,93 @@ */ namespace Magento\Framework\ObjectManager\Test\Unit\Config; -use Magento\Framework\ObjectManager\Config\Compiled as CompiledConfig; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Magento\Framework\ObjectManager\Config\Compiled; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManager; +use Magento\Framework\Serialize\SerializerInterface; class CompiledTest extends \PHPUnit_Framework_TestCase { /** - * @var ObjectManagerHelper + * @var ObjectManager */ - private $objectManagerHelper; - - protected function setUp() - { - $this->objectManagerHelper = new ObjectManagerHelper($this); - } + private $objectManager; /** - * @param array $initialData - * @param array $configuration - * @param array $expectedArguments - * @param array $expectedVirtualTypes - * @param array $expectedPreferences - * - * @dataProvider extendDataProvider + * @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject */ - public function testExtend( - array $initialData, - array $configuration, - array $expectedArguments, - array $expectedVirtualTypes, - array $expectedPreferences - ) { - /** @var CompiledConfig $compiledConfig */ - $compiledConfig = $this->objectManagerHelper->getObject(CompiledConfig::class, ['data' => $initialData]); - $compiledConfig->extend($configuration); + private $serializerMock; - foreach ($expectedArguments as $type => $arguments) { - $this->assertEquals($arguments, $compiledConfig->getArguments($type)); - } - - $this->assertEquals($expectedVirtualTypes, $compiledConfig->getVirtualTypes()); - $this->assertEquals($expectedPreferences, $compiledConfig->getPreferences()); + protected function setUp() + { + $this->objectManager = new ObjectManager($this); + $this->serializerMock = $this->getMock(SerializerInterface::class); } - /** - * @return array - */ - public function extendDataProvider() + public function testExtend() { - return [ - [ - 'initialData' => [ - 'arguments' => [ - 'type1' => serialize(['argument1_1' => 'argumentValue1_1', 'argument1_2' => 'argumentValue1_2']) - ], - 'instanceTypes' => [ - 'instanceType1' => 'instanceTypeValue1', 'instanceType2' => 'instanceTypeValue2' - ], - 'preferences' => ['preference1' => 'preferenceValue1', 'preference2' => 'preferenceValue2'] - ], - 'configuration' => [ - 'arguments' => [ - 'type1' => serialize(['argument1_1' => 'newArgumentValue1_1']), - 'type2' => serialize(['argument2_1' => 'newArgumentValue2_1']) - ], - 'instanceTypes' => [ - 'instanceType2' => 'newInstanceTypeValue2', 'instanceType3' => 'newInstanceTypeValue3' - ], - 'preferences' => ['preference1' => 'newPreferenceValue1'] - ], - 'expectedArguments' => [ - 'type1' => ['argument1_1' => 'newArgumentValue1_1'], - 'type2' => ['argument2_1' => 'newArgumentValue2_1'] - ], - 'expectedVirtualTypes' => [ - 'instanceType1' => 'instanceTypeValue1', 'instanceType2' => 'newInstanceTypeValue2', - 'instanceType3' => 'newInstanceTypeValue3' - ], - 'expectedPreferences' => [ - 'preference1' => 'newPreferenceValue1', 'preference2' => 'preferenceValue2' - ] + $initialData = [ + 'arguments' => [ + 'type1' => 'initial serialized configuration for type1' + ], + 'instanceTypes' => [ + 'instanceType1' => 'instanceTypeValue1', + 'instanceType2' => 'instanceTypeValue2' + ], + 'preferences' => [ + 'preference1' => 'preferenceValue1', + 'preference2' => 'preferenceValue2' + ] + ]; + $configuration = [ + 'arguments' => [ + 'type1' => 'serialized configuration for type1', + 'type2' => 'serialized configuration for type2' + ], + 'instanceTypes' => [ + 'instanceType2' => 'newInstanceTypeValue2', + 'instanceType3' => 'newInstanceTypeValue3' + ], + 'preferences' => [ + 'preference1' => 'newPreferenceValue1' ] ]; + $expectedArguments = [ + 'type1' => [ + 'argument1_1' => 'newArgumentValue1_1' + ], + 'type2' => [ + 'argument2_1' => 'newArgumentValue2_1' + ] + ]; + $expectedVirtualTypes = [ + 'instanceType1' => 'instanceTypeValue1', + 'instanceType2' => 'newInstanceTypeValue2', + 'instanceType3' => 'newInstanceTypeValue3' + ]; + $expectedPreferences = [ + 'preference1' => 'newPreferenceValue1', + 'preference2' => 'preferenceValue2' + ]; + $this->serializerMock->expects($this->at(0)) + ->method('unserialize') + ->with($configuration['arguments']['type1']) + ->willReturn($expectedArguments['type1']); + $this->serializerMock->expects($this->at(1)) + ->method('unserialize') + ->with($configuration['arguments']['type2']) + ->willReturn($expectedArguments['type2']); + $compiled = $this->objectManager->getObject( + Compiled::class, + [ + 'data' => $initialData, + 'serializer' => $this->serializerMock + ] + ); + $compiled->extend($configuration); + foreach ($expectedArguments as $type => $arguments) { + $this->assertEquals($arguments, $compiled->getArguments($type)); + } + $this->assertEquals($expectedVirtualTypes, $compiled->getVirtualTypes()); + $this->assertEquals($expectedPreferences, $compiled->getPreferences()); } } diff --git a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Config/ConfigTest.php b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Config/ConfigTest.php index 844d5fa94a627..4cc51652fdb74 100644 --- a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Config/ConfigTest.php +++ b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Config/ConfigTest.php @@ -5,10 +5,19 @@ */ namespace Magento\Framework\ObjectManager\Test\Unit\Config; +use Magento\Framework\Serialize\SerializerInterface; use \Magento\Framework\ObjectManager\Config\Config; class ConfigTest extends \PHPUnit_Framework_TestCase { + /** @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ + private $objectManagerHelper; + + protected function setUp() + { + $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + } + public function testGetArgumentsEmpty() { $config = new Config(); @@ -42,6 +51,14 @@ public function testExtendWithCacheMock() $cache->expects($this->once())->method('get')->will($this->returnValue(false)); $config = new Config(null, $definitions); + $serializerMock = $this->getMock(SerializerInterface::class); + $serializerMock->expects($this->exactly(2)) + ->method('serialize'); + $this->objectManagerHelper->setBackwardCompatibleProperty( + $config, + 'serializer', + $serializerMock + ); $config->setCache($cache); $this->_assertFooTypeArguments($config); diff --git a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Definition/Compiled/BinaryTest.php b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Definition/Compiled/BinaryTest.php deleted file mode 100644 index 80cf73a44e7ac..0000000000000 --- a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Definition/Compiled/BinaryTest.php +++ /dev/null @@ -1,21 +0,0 @@ -markTestSkipped('This test requires igbinary PHP extension'); - } - $checkString = 'packed code'; - $signatures = ['wonderfulClass' => igbinary_serialize($checkString)]; - $definitions = ['wonderful' => 'wonderfulClass']; - $model = new \Magento\Framework\ObjectManager\Definition\Compiled\Binary([$signatures, $definitions]); - $this->assertEquals($checkString, $model->getParameters('wonderful')); - } -} diff --git a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Definition/Compiled/SerializedTest.php b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Definition/Compiled/SerializedTest.php deleted file mode 100644 index 9454377c3b720..0000000000000 --- a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Definition/Compiled/SerializedTest.php +++ /dev/null @@ -1,35 +0,0 @@ - null]; - $model = new \Magento\Framework\ObjectManager\Definition\Compiled\Serialized([$signatures, $definitions]); - $this->assertEquals(null, $model->getParameters('wonderful')); - } - - public function testGetParametersWithSignatureObject() - { - $wonderfulSignature = new \stdClass(); - $signatures = ['wonderfulClass' => $wonderfulSignature]; - $definitions = ['wonderful' => 'wonderfulClass']; - $model = new \Magento\Framework\ObjectManager\Definition\Compiled\Serialized([$signatures, $definitions]); - $this->assertEquals($wonderfulSignature, $model->getParameters('wonderful')); - } - - public function testGetParametersWithUnpacking() - { - $checkString = 'code to pack'; - $signatures = ['wonderfulClass' => serialize($checkString)]; - $definitions = ['wonderful' => 'wonderfulClass']; - $model = new \Magento\Framework\ObjectManager\Definition\Compiled\Serialized([$signatures, $definitions]); - $this->assertEquals($checkString, $model->getParameters('wonderful')); - } -} diff --git a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Definition/CompiledStub.php b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Definition/CompiledStub.php deleted file mode 100644 index 16b8436a0c41a..0000000000000 --- a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Definition/CompiledStub.php +++ /dev/null @@ -1,25 +0,0 @@ -getMock( - \Magento\Framework\Code\Reader\ClassReader::class, - ['getConstructor'], - [], - '', - false - ); - $readerMock->expects($this->once()) - ->method('getConstructor') - ->with($className) - ->willReturn($undefinedDefinitionSignature); - $model = $objectManager->getObject( - \Magento\Framework\ObjectManager\Test\Unit\Definition\CompiledStub::class, - [ - 'definitions' => [[], []], - 'reader' => $readerMock - ] - ); - $this->assertEquals($undefinedDefinitionSignature, $model->getParameters($className)); - } -} diff --git a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/DefinitionFactoryTest.php b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/DefinitionFactoryTest.php index 468e01ce80aba..8c587cec4351c 100644 --- a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/DefinitionFactoryTest.php +++ b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/DefinitionFactoryTest.php @@ -3,119 +3,56 @@ * Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details. */ - namespace Magento\Framework\ObjectManager\Test\Unit; -use Magento\Framework\ObjectManager\Definition\Compiled\Serialized; +use Magento\Framework\Filesystem\Driver\File; +use Magento\Framework\ObjectManager\DefinitionFactory; +use Magento\Framework\ObjectManager\DefinitionInterface; +use Magento\Framework\Interception\DefinitionInterface as InterceptionDefinitionInterface; +use Magento\Framework\ObjectManager\RelationsInterface; class DefinitionFactoryTest extends \PHPUnit_Framework_TestCase { /** - * @var \Magento\Framework\Filesystem\DriverInterface | \PHPUnit_Framework_MockObject_MockObject - */ - protected $filesystemDriverMock; - - /** - * @var \Magento\Framework\ObjectManager\DefinitionFactory + * @var File|\PHPUnit_Framework_MockObject_MockObject */ - protected $model; + private $filesystemDriverMock; /** - * @var string + * @var DefinitionFactory */ - protected $sampleContent; + private $definitionFactory; protected function setUp() { - $this->sampleContent = serialize([1, 2, 3]); - $this->filesystemDriverMock = $this->getMock( - \Magento\Framework\Filesystem\Driver\File::class, - [], - [], - '', - false - ); - $this->model = new \Magento\Framework\ObjectManager\DefinitionFactory( + $this->filesystemDriverMock = $this->getMock(File::class); + $this->definitionFactory = new DefinitionFactory( $this->filesystemDriverMock, - 'DefinitionDir', - 'GenerationDir', - Serialized::MODE_NAME + 'generation dir' ); } - public function testCreateClassDefinitionFromString() + public function testCreateClassDefinition() { $this->assertInstanceOf( - \Magento\Framework\ObjectManager\Definition\Compiled\Serialized::class, - $this->model->createClassDefinition($this->sampleContent) + DefinitionInterface::class, + $this->definitionFactory->createClassDefinition() ); } - /** - * @param string $path - * @param string $callMethod - * @param string $expectedClass - * @dataProvider createPluginsAndRelationsReadableDataProvider - */ - public function testCreatePluginsAndRelationsReadable($path, $callMethod, $expectedClass) - { - $this->filesystemDriverMock->expects($this->once())->method('isReadable') - ->with($path) - ->will($this->returnValue(true)); - $this->filesystemDriverMock->expects($this->once())->method('fileGetContents') - ->with($path) - ->will($this->returnValue($this->sampleContent)); - $this->assertInstanceOf($expectedClass, $this->model->$callMethod()); - } - - public function createPluginsAndRelationsReadableDataProvider() - { - return [ - 'relations' => [ - 'DefinitionDir/relations.ser', - 'createRelations', \Magento\Framework\ObjectManager\Relations\Compiled::class, - ], - 'plugins' => [ - 'DefinitionDir/plugins.ser', - 'createPluginDefinition', \Magento\Framework\Interception\Definition\Compiled::class, - ], - ]; - } - - /** - * @param string $path - * @param string $callMethod - * @param string $expectedClass - * @dataProvider createPluginsAndRelationsNotReadableDataProvider - */ - public function testCreatePluginsAndRelationsNotReadable($path, $callMethod, $expectedClass) + public function testCreatePluginDefinition() { - $this->filesystemDriverMock->expects($this->once())->method('isReadable') - ->with($path) - ->will($this->returnValue(false)); - $this->assertInstanceOf($expectedClass, $this->model->$callMethod()); - } - - public function createPluginsAndRelationsNotReadableDataProvider() - { - return [ - 'relations' => [ - 'DefinitionDir/relations.ser', - 'createRelations', \Magento\Framework\ObjectManager\Relations\Runtime::class, - ], - 'plugins' => [ - 'DefinitionDir/plugins.ser', - 'createPluginDefinition', \Magento\Framework\Interception\Definition\Runtime::class, - ], - ]; + $this->assertInstanceOf( + InterceptionDefinitionInterface::class, + $this->definitionFactory->createPluginDefinition() + ); } - public function testGetSupportedFormats() + public function testCreateRelations() { - $actual = \Magento\Framework\ObjectManager\DefinitionFactory::getSupportedFormats(); - $this->assertInternalType('array', $actual); - foreach ($actual as $className) { - $this->assertInternalType('string', $className); - } + $this->assertInstanceOf( + RelationsInterface::class, + $this->definitionFactory->createRelations() + ); } } diff --git a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Relations/CompiledTest.php b/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Relations/CompiledTest.php deleted file mode 100644 index 336a798df100e..0000000000000 --- a/lib/internal/Magento/Framework/ObjectManager/Test/Unit/Relations/CompiledTest.php +++ /dev/null @@ -1,27 +0,0 @@ - 'yes']; - - $model = new \Magento\Framework\ObjectManager\Relations\Compiled($relations); - $this->assertEquals(true, $model->has('amazing')); - $this->assertEquals(false, $model->has('fuzzy')); - } - - public function testGetParents() - { - $relations = ['amazing' => 'parents']; - - $model = new \Magento\Framework\ObjectManager\Relations\Compiled($relations); - $this->assertEquals('parents', $model->getParents('amazing')); - } -} diff --git a/lib/internal/Magento/Framework/Reflection/MethodsMap.php b/lib/internal/Magento/Framework/Reflection/MethodsMap.php index f7f402ae4b8a0..c7a9183a78ee5 100644 --- a/lib/internal/Magento/Framework/Reflection/MethodsMap.php +++ b/lib/internal/Magento/Framework/Reflection/MethodsMap.php @@ -6,6 +6,7 @@ namespace Magento\Framework\Reflection; +use Magento\Framework\Serialize\SerializerInterface; use Zend\Code\Reflection\ClassReflection; use Zend\Code\Reflection\MethodReflection; use Zend\Code\Reflection\ParameterReflection; @@ -45,6 +46,11 @@ class MethodsMap */ private $fieldNamer; + /** + * @var \Magento\Framework\Serialize\SerializerInterface + */ + private $serializer; + /** * @param \Magento\Framework\Cache\FrontendInterface $cache * @param TypeProcessor $typeProcessor @@ -95,11 +101,11 @@ public function getMethodsMap($interfaceName) if (!isset($this->serviceInterfaceMethodsMap[$key])) { $methodMap = $this->cache->load($key); if ($methodMap) { - $this->serviceInterfaceMethodsMap[$key] = unserialize($methodMap); + $this->serviceInterfaceMethodsMap[$key] = $this->getSerializer()->unserialize($methodMap); } else { $methodMap = $this->getMethodMapViaReflection($interfaceName); $this->serviceInterfaceMethodsMap[$key] = $methodMap; - $this->cache->save(serialize($this->serviceInterfaceMethodsMap[$key]), $key); + $this->cache->save($this->getSerializer()->serialize($this->serviceInterfaceMethodsMap[$key]), $key); } } return $this->serviceInterfaceMethodsMap[$key]; @@ -117,7 +123,7 @@ public function getMethodParams($serviceClassName, $serviceMethodName) $cacheId = self::SERVICE_METHOD_PARAMS_CACHE_PREFIX . hash('md5', $serviceClassName . $serviceMethodName); $params = $this->cache->load($cacheId); if ($params !== false) { - return unserialize($params); + return $this->getSerializer()->unserialize($params); } $serviceClass = new ClassReflection($serviceClassName); /** @var MethodReflection $serviceMethod */ @@ -133,7 +139,7 @@ public function getMethodParams($serviceClassName, $serviceMethodName) self::METHOD_META_DEFAULT_VALUE => $isDefaultValueAvailable ? $paramReflection->getDefaultValue() : null ]; } - $this->cache->save(serialize($params), $cacheId, [ReflectionCache::CACHE_TAG]); + $this->cache->save($this->getSerializer()->serialize($params), $cacheId, [ReflectionCache::CACHE_TAG]); return $params; } @@ -217,4 +223,19 @@ public function isMethodReturnValueRequired($type, $methodName) $methods = $this->getMethodsMap($type); return $methods[$methodName]['isRequired']; } + + /** + * Get serializer + * + * @return \Magento\Framework\Serialize\SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if ($this->serializer === null) { + $this->serializer = \Magento\Framework\App\ObjectManager::getInstance() + ->get(SerializerInterface::class); + } + return $this->serializer; + } } diff --git a/lib/internal/Magento/Framework/Reflection/Test/Unit/MethodsMapTest.php b/lib/internal/Magento/Framework/Reflection/Test/Unit/MethodsMapTest.php index 6f4dc37b8faff..67a372c4d33ca 100644 --- a/lib/internal/Magento/Framework/Reflection/Test/Unit/MethodsMapTest.php +++ b/lib/internal/Magento/Framework/Reflection/Test/Unit/MethodsMapTest.php @@ -6,9 +6,9 @@ namespace Magento\Framework\Reflection\Test\Unit; +use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\Reflection\MethodsMap; use Magento\Framework\Reflection\TypeProcessor; -use Magento\Framework\Reflection\FieldNamer; /** * MethodsMap test @@ -18,7 +18,10 @@ class MethodsMapTest extends \PHPUnit_Framework_TestCase /** * @var MethodsMap */ - private $model; + private $object; + + /** @var SerializerInterface|\PHPUnit_Framework_MockObject_MockObject */ + private $serializerMock; /** * Set up helper. @@ -39,7 +42,7 @@ protected function setUp() ->getMockForAbstractClass(); $fieldNamerMock = $this->getMockBuilder(\Magento\Framework\Reflection\FieldNamer::class) ->getMockForAbstractClass(); - $this->model = $objectManager->getObject( + $this->object = $objectManager->getObject( \Magento\Framework\Reflection\MethodsMap::class, [ 'cache' => $cacheMock, @@ -48,27 +51,33 @@ protected function setUp() 'fieldNamer' => $fieldNamerMock, ] ); + $this->serializerMock = $this->getMock(SerializerInterface::class); + $objectManager->setBackwardCompatibleProperty( + $this->object, + 'serializer', + $this->serializerMock + ); } public function testGetMethodReturnType() { $this->assertEquals( 'string', - $this->model->getMethodReturnType( + $this->object->getMethodReturnType( \Magento\Framework\Reflection\FieldNamer::class, 'getFieldNameForMethodName' ) ); $this->assertEquals( 'mixed', - $this->model->getMethodReturnType( + $this->object->getMethodReturnType( \Magento\Framework\Reflection\TypeCaster::class, 'castValueToType' ) ); $this->assertEquals( 'array', - $this->model->getMethodReturnType( + $this->object->getMethodReturnType( \Magento\Framework\Reflection\MethodsMap::class, 'getMethodsMap' ) @@ -77,42 +86,46 @@ public function testGetMethodReturnType() public function testGetMethodsMap() { - $methodsMap = $this->model->getMethodsMap(\Magento\Framework\Reflection\MethodsMap::class); - $this->assertEquals( - [ - 'getMethodReturnType' => [ - 'type' => 'string', - 'isRequired' => true, - 'description' => null, - 'parameterCount' => 2, - ], - 'getMethodsMap' => [ - 'type' => 'array', - 'isRequired' => true, - 'description' => "
 Service methods' reflection data stored in cache as 'methodName' => "
-                        . "'returnType' ex. [ 'create' => '\Magento\Customer\Api\Data\Customer', 'validatePassword' "
-                        . "=> 'boolean' ] 
", - 'parameterCount' => 1, - ], - 'getMethodParams' => [ - 'type' => 'array', - 'isRequired' => true, - 'description' => null, - 'parameterCount' => 2 - ], - 'isMethodValidForDataField' => [ - 'type' => 'bool', - 'isRequired' => true, - 'description' => null, - 'parameterCount' => 2, - ], - 'isMethodReturnValueRequired' => [ - 'type' => 'bool', - 'isRequired' => true, - 'description' => null, - 'parameterCount' => 2, - ], + $data = [ + 'getMethodReturnType' => [ + 'type' => 'string', + 'isRequired' => true, + 'description' => null, + 'parameterCount' => 2, + ], + 'getMethodsMap' => [ + 'type' => 'array', + 'isRequired' => true, + 'description' => "
 Service methods' reflection data stored in cache as 'methodName' => "
+                    . "'returnType' ex. [ 'create' => '\Magento\Customer\Api\Data\Customer', 'validatePassword' "
+                    . "=> 'boolean' ] 
", + 'parameterCount' => 1, ], + 'getMethodParams' => [ + 'type' => 'array', + 'isRequired' => true, + 'description' => null, + 'parameterCount' => 2 + ], + 'isMethodValidForDataField' => [ + 'type' => 'bool', + 'isRequired' => true, + 'description' => null, + 'parameterCount' => 2, + ], + 'isMethodReturnValueRequired' => [ + 'type' => 'bool', + 'isRequired' => true, + 'description' => null, + 'parameterCount' => 2, + ], + ]; + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->with($data); + $methodsMap = $this->object->getMethodsMap(\Magento\Framework\Reflection\MethodsMap::class); + $this->assertEquals( + $data, $methodsMap ); } @@ -125,7 +138,7 @@ public function testGetMethodsMap() */ public function testIsMethodValidForDataField($type, $methodName, $expectedResult) { - $this->assertEquals($this->model->isMethodValidForDataField($type, $methodName), $expectedResult); + $this->assertEquals($this->object->isMethodValidForDataField($type, $methodName), $expectedResult); } /** @@ -157,7 +170,7 @@ public function isMethodValidForDataFieldProvider() */ public function testIsMethodReturnValueRequired($type, $methodName, $expectedResult) { - $this->assertEquals($this->model->isMethodValidForDataField($type, $methodName), $expectedResult); + $this->assertEquals($this->object->isMethodValidForDataField($type, $methodName), $expectedResult); } /** diff --git a/lib/internal/Magento/Framework/Search/Request/Config.php b/lib/internal/Magento/Framework/Search/Request/Config.php index b348f214dd4c2..80a963af39b41 100644 --- a/lib/internal/Magento/Framework/Search/Request/Config.php +++ b/lib/internal/Magento/Framework/Search/Request/Config.php @@ -5,21 +5,32 @@ */ namespace Magento\Framework\Search\Request; +use Magento\Framework\Serialize\SerializerInterface; + +/** + * Provides search request configuration + */ class Config extends \Magento\Framework\Config\Data { - /** Cache ID for Search Request*/ + /** + * Cache identifier + */ const CACHE_ID = 'request_declaration'; /** + * Constructor + * * @param \Magento\Framework\Search\Request\Config\FilesystemReader $reader * @param \Magento\Framework\Config\CacheInterface $cache - * @param string $cacheId + * @param string|null $cacheId + * @param SerializerInterface|null $serializer */ public function __construct( \Magento\Framework\Search\Request\Config\FilesystemReader $reader, \Magento\Framework\Config\CacheInterface $cache, - $cacheId = self::CACHE_ID + $cacheId = self::CACHE_ID, + SerializerInterface $serializer = null ) { - parent::__construct($reader, $cache, $cacheId); + parent::__construct($reader, $cache, $cacheId, $serializer); } } diff --git a/lib/internal/Magento/Framework/Test/Unit/TranslateTest.php b/lib/internal/Magento/Framework/Test/Unit/TranslateTest.php index 8d1692dd9cdc1..a8199768a365f 100644 --- a/lib/internal/Magento/Framework/Test/Unit/TranslateTest.php +++ b/lib/internal/Magento/Framework/Test/Unit/TranslateTest.php @@ -5,6 +5,7 @@ */ namespace Magento\Framework\Test\Unit; +use Magento\Framework\Serialize\SerializerInterface; use \Magento\Framework\Translate; /** @@ -59,6 +60,7 @@ class TranslateTest extends \PHPUnit_Framework_TestCase protected function setUp() { + $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); $this->viewDesign = $this->getMock(\Magento\Framework\View\DesignInterface::class, [], [], '', false); $this->cache = $this->getMock(\Magento\Framework\Cache\FrontendInterface::class, [], [], '', false); $this->viewFileSystem = $this->getMock(\Magento\Framework\View\FileSystem::class, [], [], '', false); @@ -104,6 +106,21 @@ protected function setUp() $this->csvParser, $this->packDictionary ); + + $serializerMock = $this->getMock(SerializerInterface::class); + $serializerMock->method('serialize') + ->willReturnCallback(function ($data) { + return json_encode($data); + }); + $serializerMock->method('unserialize') + ->willReturnCallback(function ($string) { + return json_decode($string, true); + }); + $objectManager->setBackwardCompatibleProperty( + $this->translate, + 'serializer', + $serializerMock + ); } /** @@ -119,7 +136,7 @@ public function testLoadData($area, $forceReload, $cachedData) $this->cache->expects($this->exactly($forceReload ? 0 : 1)) ->method('load') - ->will($this->returnValue(serialize($cachedData))); + ->will($this->returnValue(json_encode($cachedData))); if (!$forceReload && $cachedData !== false) { $this->translate->loadData($area, $forceReload); @@ -222,7 +239,7 @@ public function testGetData($data, $result) { $this->cache->expects($this->once()) ->method('load') - ->will($this->returnValue(serialize($data))); + ->will($this->returnValue(json_encode($data))); $this->expectsSetConfig('themeId'); $this->translate->loadData('frontend'); $this->assertEquals($result, $this->translate->getData()); diff --git a/lib/internal/Magento/Framework/Translate.php b/lib/internal/Magento/Framework/Translate.php index 36f693270f42f..c5571ab0b8edb 100644 --- a/lib/internal/Magento/Framework/Translate.php +++ b/lib/internal/Magento/Framework/Translate.php @@ -108,6 +108,11 @@ class Translate implements \Magento\Framework\TranslateInterface */ protected $packDictionary; + /** + * @var \Magento\Framework\Serialize\SerializerInterface + */ + private $serializer; + /** * @param \Magento\Framework\View\DesignInterface $viewDesign * @param \Magento\Framework\Cache\FrontendInterface $cache @@ -474,7 +479,7 @@ protected function _loadCache() { $data = $this->_cache->load($this->getCacheId()); if ($data) { - $data = unserialize($data); + $data = $this->getSerializer()->unserialize($data); } return $data; } @@ -486,7 +491,22 @@ protected function _loadCache() */ protected function _saveCache() { - $this->_cache->save(serialize($this->getData()), $this->getCacheId(true), [], false); + $this->_cache->save($this->getSerializer()->serialize($this->getData()), $this->getCacheId(true), [], false); return $this; } + + /** + * Get serializer + * + * @return \Magento\Framework\Serialize\SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if ($this->serializer === null) { + $this->serializer = \Magento\Framework\App\ObjectManager::getInstance() + ->get(Serialize\SerializerInterface::class); + } + return $this->serializer; + } } diff --git a/lib/internal/Magento/Framework/Unserialize/README.md b/lib/internal/Magento/Framework/Unserialize/README.md index 971bd6980abb1..2dbf7436aa60f 100644 --- a/lib/internal/Magento/Framework/Unserialize/README.md +++ b/lib/internal/Magento/Framework/Unserialize/README.md @@ -1,2 +1 @@ -Library provides custom unserialize method. Method checks if serialized string contains serialized object and do not -unserialize it. If string doesn't contain serialized object, method calls native PHP function unserialize. \ No newline at end of file +This library is deprecated, please use Magento\Framework\Serialize\SerializerInterface instead. \ No newline at end of file diff --git a/lib/internal/Magento/Framework/Unserialize/Unserialize.php b/lib/internal/Magento/Framework/Unserialize/Unserialize.php index 9d4785915a6dd..cfd3e81ca6b09 100644 --- a/lib/internal/Magento/Framework/Unserialize/Unserialize.php +++ b/lib/internal/Magento/Framework/Unserialize/Unserialize.php @@ -6,6 +6,9 @@ namespace Magento\Framework\Unserialize; +/** + * @deprecated + */ class Unserialize { /** diff --git a/lib/internal/Magento/Framework/Validator/Factory.php b/lib/internal/Magento/Framework/Validator/Factory.php index d2e3837d13138..76633f48dfe0b 100644 --- a/lib/internal/Magento/Framework/Validator/Factory.php +++ b/lib/internal/Magento/Framework/Validator/Factory.php @@ -1,20 +1,20 @@ _configFiles = $this->cache->load(self::CACHE_KEY); if (!$this->_configFiles) { $this->_configFiles = $this->moduleReader->getConfigurationFiles('validation.xml'); - $this->cache->save(serialize($this->_configFiles), self::CACHE_KEY); + $this->cache->save($this->getSerializer()->serialize($this->_configFiles->toArray()), self::CACHE_KEY); } else { - $this->_configFiles = unserialize($this->_configFiles); + $filesArray = $this->getSerializer()->unserialize($this->_configFiles); + $this->_configFiles = $this->getFileIteratorFactory()->create(array_keys($filesArray)); } } } @@ -109,7 +120,7 @@ public function getValidatorConfig() { $this->_initializeConfigList(); $this->_initializeDefaultTranslator(); - return $this->_objectManager->create( + return $this->_objectManager->create( \Magento\Framework\Validator\Config::class, ['configFiles' => $this->_configFiles]); } @@ -140,4 +151,33 @@ public function createValidator($entityName, $groupName, array $builderConfig = $this->_initializeDefaultTranslator(); return $this->getValidatorConfig()->createValidator($entityName, $groupName, $builderConfig); } + + /** + * Get serializer + * + * @return \Magento\Framework\Serialize\SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if ($this->serializer === null) { + $this->serializer = $this->_objectManager->get(\Magento\Framework\Serialize\SerializerInterface::class); + } + return $this->serializer; + } + + /** + * Get file iterator factory + * + * @return \Magento\Framework\Config\FileIteratorFactory + * @deprecated + */ + private function getFileIteratorFactory() + { + if ($this->fileIteratorFactory === null) { + $this->fileIteratorFactory = $this->_objectManager + ->get(\Magento\Framework\Config\FileIteratorFactory::class); + } + return $this->fileIteratorFactory; + } } diff --git a/lib/internal/Magento/Framework/Validator/Test/Unit/FactoryTest.php b/lib/internal/Magento/Framework/Validator/Test/Unit/FactoryTest.php index bb829010795e8..4c4ef93bc15be 100644 --- a/lib/internal/Magento/Framework/Validator/Test/Unit/FactoryTest.php +++ b/lib/internal/Magento/Framework/Validator/Test/Unit/FactoryTest.php @@ -1,98 +1,139 @@ _defaultTranslator = \Magento\Framework\Validator\AbstractValidator::getDefaultTranslator(); - $this->_objectManager = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); - $this->_validatorConfig = $this->getMockBuilder( - \Magento\Framework\Validator\Config::class - )->setMethods( - ['createValidatorBuilder', 'createValidator'] - )->disableOriginalConstructor()->getMock(); - - $this->_objectManager->expects( - $this->at(0) - )->method( - 'create' - )->with( - \Magento\Framework\Translate\Adapter::class - )->will( - $this->returnValue(new \Magento\Framework\Translate\Adapter()) - ); + $this->defaultTranslator = \Magento\Framework\Validator\AbstractValidator::getDefaultTranslator(); - $this->_objectManager->expects( - $this->at(1) - )->method( - 'create' - )->with( + $this->objectManagerMock = $this->getMock(\Magento\Framework\ObjectManagerInterface::class); + $this->validatorConfigMock = $this->getMock( \Magento\Framework\Validator\Config::class, - ['configFiles' => ['/tmp/moduleOne/etc/validation.xml']] - )->will( - $this->returnValue($this->_validatorConfig) + ['createValidatorBuilder', 'createValidator'], + [], + '', + false ); - - // Config mock - $this->_config = $this->getMockBuilder( - \Magento\Framework\Module\Dir\Reader::class - )->setMethods( - ['getConfigurationFiles'] - )->disableOriginalConstructor()->getMock(); - $this->_config->expects( - $this->once() - )->method( - 'getConfigurationFiles' - )->with( - 'validation.xml' - )->will( - $this->returnValue(['/tmp/moduleOne/etc/validation.xml']) + $translateAdapterMock = $this->getMock(\Magento\Framework\Translate\Adapter::class, [], [], '', false); + $this->objectManagerMock->expects($this->at(0)) + ->method('create') + ->with(\Magento\Framework\Translate\Adapter::class) + ->willReturn($translateAdapterMock); + $this->fileIteratorMock = $this->getMock( + \Magento\Framework\Config\FileIterator::class, + [], + [], + '', + false + ); + $this->objectManagerMock->expects($this->at(1)) + ->method('create') + ->with( + \Magento\Framework\Validator\Config::class, + ['configFiles' => $this->fileIteratorMock] + ) + ->willReturn($this->validatorConfigMock); + $this->readerMock = $this->getMock( + \Magento\Framework\Module\Dir\Reader::class, + ['getConfigurationFiles'], + [], + '', + false ); + $this->cacheMock = $this->getMock(\Magento\Framework\Cache\FrontendInterface::class); - // Translate adapter mock - $this->_translateAdapter = $this->getMockBuilder( - \Magento\Framework\TranslateInterface::class - )->disableOriginalConstructor()->getMock(); + $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); + + $this->factory = $objectManager->getObject( + \Magento\Framework\Validator\Factory::class, + [ + 'objectManager' => $this->objectManagerMock, + 'moduleReader' => $this->readerMock, + 'cache' => $this->cacheMock + ] + ); - $this->cache = $this->getMockBuilder(\Magento\Framework\Cache\FrontendInterface::class) - ->getMockForAbstractClass(); + $this->serializerMock = $this->getMock(\Magento\Framework\Serialize\SerializerInterface::class); + $this->fileIteratorFactoryMock = $this->getMock( + \Magento\Framework\Config\FileIteratorFactory::class, + [], + [], + '', + false + ); + $objectManager->setBackwardCompatibleProperty( + $this->factory, + 'serializer', + $this->serializerMock + ); + $objectManager->setBackwardCompatibleProperty( + $this->factory, + 'fileIteratorFactory', + $this->fileIteratorFactoryMock + ); } /** @@ -100,87 +141,103 @@ protected function setUp() */ protected function tearDown() { - \Magento\Framework\Validator\AbstractValidator::setDefaultTranslator($this->_defaultTranslator); - unset($this->_defaultTranslator); + \Magento\Framework\Validator\AbstractValidator::setDefaultTranslator($this->defaultTranslator); + unset($this->defaultTranslator); } - /** - * Test getValidatorConfig created correct validator config. Check that validator translator was initialized. - */ public function testGetValidatorConfig() { - $factory = new \Magento\Framework\Validator\Factory( - $this->_objectManager, - $this->_config, - $this->cache - ); - $actualConfig = $factory->getValidatorConfig(); + $this->readerMock->method('getConfigurationFiles') + ->with('validation.xml') + ->willReturn($this->fileIteratorMock); + $this->fileIteratorMock->method('toArray') + ->willReturn($this->data); + $actualConfig = $this->factory->getValidatorConfig(); $this->assertInstanceOf( \Magento\Framework\Validator\Config::class, $actualConfig, 'Object of incorrect type was created' ); - - // Check that validator translator was correctly instantiated - $validatorTranslator = \Magento\Framework\Validator\AbstractValidator::getDefaultTranslator(); $this->assertInstanceOf( \Magento\Framework\Translate\Adapter::class, - $validatorTranslator, + \Magento\Framework\Validator\AbstractValidator::getDefaultTranslator(), 'Default validator translate adapter was not set correctly' ); } - /** - * Test createValidatorBuilder call - */ + public function testGetValidatorConfigCacheNotExist() + { + $this->cacheMock->expects($this->once()) + ->method('load') + ->willReturn(false); + $this->readerMock->expects($this->once()) + ->method('getConfigurationFiles') + ->willReturn($this->fileIteratorMock); + $this->fileIteratorMock->method('toArray') + ->willReturn($this->data); + $this->cacheMock->expects($this->once()) + ->method('save') + ->with($this->jsonString); + $this->serializerMock->expects($this->once()) + ->method('serialize') + ->with($this->data) + ->willReturn($this->jsonString); + $this->factory->getValidatorConfig(); + $this->factory->getValidatorConfig(); + } + + public function testGetValidatorConfigCacheExist() + { + $this->cacheMock->expects($this->once()) + ->method('load') + ->willReturn($this->jsonString); + $this->readerMock->expects($this->never()) + ->method('getConfigurationFiles'); + $this->cacheMock->expects($this->never()) + ->method('save'); + $this->serializerMock->expects($this->once()) + ->method('unserialize') + ->with($this->jsonString) + ->willReturn($this->data); + $this->fileIteratorFactoryMock->method('create') + ->willReturn($this->fileIteratorMock); + $this->factory->getValidatorConfig(); + $this->factory->getValidatorConfig(); + } + public function testCreateValidatorBuilder() { - $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - $this->_validatorConfig->expects( - $this->once() - )->method( - 'createValidatorBuilder' - )->with( - 'test', - 'class', - [] - )->will( - $this->returnValue( - $objectManager->getObject(\Magento\Framework\Validator\Builder::class, ['constraints' => []]) - ) - ); - $factory = new \Magento\Framework\Validator\Factory( - $this->_objectManager, - $this->_config, - $this->cache - ); + $this->readerMock->method('getConfigurationFiles') + ->with('validation.xml') + ->willReturn($this->fileIteratorMock); + $this->fileIteratorMock->method('toArray') + ->willReturn($this->data); + $builderMock = $this->getMock(\Magento\Framework\Validator\Builder::class, [], [], '', false); + $this->validatorConfigMock->expects($this->once()) + ->method('createValidatorBuilder') + ->with('test', 'class', []) + ->willReturn($builderMock); $this->assertInstanceOf( \Magento\Framework\Validator\Builder::class, - $factory->createValidatorBuilder('test', 'class', []) + $this->factory->createValidatorBuilder('test', 'class', []) ); } - /** - * Test createValidatorBuilder call - */ public function testCreateValidator() { - $this->_validatorConfig->expects( - $this->once() - )->method( - 'createValidator' - )->with( - 'test', - 'class', - [] - )->will( - $this->returnValue(new \Magento\Framework\Validator()) - ); - $factory = new \Magento\Framework\Validator\Factory( - $this->_objectManager, - $this->_config, - $this->cache + $this->readerMock->method('getConfigurationFiles') + ->with('validation.xml') + ->willReturn($this->fileIteratorMock); + $this->fileIteratorMock->method('toArray') + ->willReturn($this->data); + $validatorMock = $this->getMock(\Magento\Framework\Validator::class, [], [], '', false); + $this->validatorConfigMock->expects($this->once()) + ->method('createValidator') + ->with('test', 'class', []) + ->willReturn($validatorMock); + $this->assertInstanceOf( + \Magento\Framework\Validator::class, + $this->factory->createValidator('test', 'class', []) ); - $this->assertInstanceOf(\Magento\Framework\Validator::class, $factory->createValidator('test', 'class', [])); } } diff --git a/lib/internal/Magento/Framework/View/Element/UiComponent/Config/Provider/Component/Definition.php b/lib/internal/Magento/Framework/View/Element/UiComponent/Config/Provider/Component/Definition.php index 1980da578c248..3778839894adb 100644 --- a/lib/internal/Magento/Framework/View/Element/UiComponent/Config/Provider/Component/Definition.php +++ b/lib/internal/Magento/Framework/View/Element/UiComponent/Config/Provider/Component/Definition.php @@ -39,6 +39,11 @@ class Definition */ protected $componentData; + /** + * @var \Magento\Framework\Serialize\SerializerInterface + */ + private $serializer; + /** * Constructor * @@ -56,9 +61,9 @@ public function __construct( $cachedData = $this->cache->load(static::CACHE_ID); if ($cachedData === false) { $data = $uiReader->read(); - $this->cache->save(serialize($data), static::CACHE_ID); + $this->cache->save($this->getSerializer()->serialize($data), static::CACHE_ID); } else { - $data = unserialize($cachedData); + $data = $this->getSerializer()->unserialize($cachedData); } $this->prepareComponentData($data); } @@ -109,4 +114,19 @@ protected function prepareComponentData(array $componentsData) $this->setComponentData($name, reset($data)); } } + + /** + * Get serializer + * + * @return \Magento\Framework\Serialize\SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if ($this->serializer === null) { + $this->serializer = \Magento\Framework\App\ObjectManager::getInstance() + ->get(\Magento\Framework\Serialize\SerializerInterface::class); + } + return $this->serializer; + } } diff --git a/lib/internal/Magento/Framework/View/Element/UiComponent/Config/Provider/Template.php b/lib/internal/Magento/Framework/View/Element/UiComponent/Config/Provider/Template.php index 79d185b2b26a7..f740a2e403bb8 100644 --- a/lib/internal/Magento/Framework/View/Element/UiComponent/Config/Provider/Template.php +++ b/lib/internal/Magento/Framework/View/Element/UiComponent/Config/Provider/Template.php @@ -5,9 +5,6 @@ */ namespace Magento\Framework\View\Element\UiComponent\Config\Provider; -use Magento\Framework\Config\CacheInterface; -use Magento\Framework\View\Element\UiComponent\Config\ReaderFactory; -use Magento\Framework\View\Element\UiComponent\Config\DomMergerInterface; use Magento\Framework\View\Element\UiComponent\Config\FileCollector\AggregatedFileCollector; use Magento\Framework\View\Element\UiComponent\Config\FileCollector\AggregatedFileCollectorFactory; @@ -32,19 +29,19 @@ class Template protected $aggregatedFileCollector; /** - * @var DomMergerInterface + * @var \Magento\Framework\View\Element\UiComponent\Config\DomMergerInterface */ protected $domMerger; /** - * @var CacheInterface + * @var \Magento\Framework\Config\CacheInterface */ protected $cache; /** * Factory for UI config reader * - * @var ReaderFactory + * @var \Magento\Framework\View\Element\UiComponent\Config\ReaderFactory */ protected $readerFactory; @@ -58,20 +55,25 @@ class Template */ protected $cachedTemplates = []; + /** + * @var \Magento\Framework\Serialize\SerializerInterface + */ + private $serializer; + /** * Constructor * * @param AggregatedFileCollector $aggregatedFileCollector - * @param DomMergerInterface $domMerger - * @param CacheInterface $cache - * @param ReaderFactory $readerFactory + * @param \Magento\Framework\View\Element\UiComponent\Config\DomMergerInterface $domMerger + * @param \Magento\Framework\Config\CacheInterface $cache + * @param \Magento\Framework\View\Element\UiComponent\Config\ReaderFactory $readerFactory * @param AggregatedFileCollectorFactory $aggregatedFileCollectorFactory */ public function __construct( AggregatedFileCollector $aggregatedFileCollector, - DomMergerInterface $domMerger, - CacheInterface $cache, - ReaderFactory $readerFactory, + \Magento\Framework\View\Element\UiComponent\Config\DomMergerInterface $domMerger, + \Magento\Framework\Config\CacheInterface $cache, + \Magento\Framework\View\Element\UiComponent\Config\ReaderFactory $readerFactory, AggregatedFileCollectorFactory $aggregatedFileCollectorFactory ) { $this->aggregatedFileCollector = $aggregatedFileCollector; @@ -81,7 +83,9 @@ public function __construct( $this->aggregatedFileCollectorFactory = $aggregatedFileCollectorFactory; $cachedTemplates = $this->cache->load(static::CACHE_ID); - $this->cachedTemplates = $cachedTemplates === false ? [] : unserialize($cachedTemplates); + $this->cachedTemplates = $cachedTemplates === false ? [] : $this->getSerializer()->unserialize( + $cachedTemplates + ); } /** @@ -104,8 +108,23 @@ public function getTemplate($template) 'domMerger' => $this->domMerger ] )->getContent(); - $this->cache->save(serialize($this->cachedTemplates), static::CACHE_ID); + $this->cache->save($this->getSerializer()->serialize($this->cachedTemplates), static::CACHE_ID); return $this->cachedTemplates[$hash]; } + + /** + * Get serializer + * + * @return \Magento\Framework\Serialize\SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if ($this->serializer === null) { + $this->serializer = \Magento\Framework\App\ObjectManager::getInstance() + ->get(\Magento\Framework\Serialize\SerializerInterface::class); + } + return $this->serializer; + } } diff --git a/lib/internal/Magento/Framework/Webapi/Test/Unit/ServiceInputProcessorTest.php b/lib/internal/Magento/Framework/Webapi/Test/Unit/ServiceInputProcessorTest.php index 0ebb6d9be4f3d..658755d38a4e8 100644 --- a/lib/internal/Magento/Framework/Webapi/Test/Unit/ServiceInputProcessorTest.php +++ b/lib/internal/Magento/Framework/Webapi/Test/Unit/ServiceInputProcessorTest.php @@ -8,6 +8,7 @@ namespace Magento\Framework\Webapi\Test\Unit; +use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\Webapi\ServiceInputProcessor; use Magento\Framework\Webapi\Test\Unit\ServiceInputProcessor\WebapiBuilderFactory; use Magento\Framework\Webapi\Test\Unit\ServiceInputProcessor\AssociativeArray; @@ -97,6 +98,16 @@ function () use ($objectManager) { 'fieldNamer' => $this->fieldNamer ] ); + $serializerMock = $this->getMock(SerializerInterface::class); + $serializerMock->method('serialize') + ->willReturn('serializedData'); + $serializerMock->method('unserialize') + ->willReturn('unserializedData'); + $objectManager->setBackwardCompatibleProperty( + $this->methodsMap, + 'serializer', + $serializerMock + ); $this->serviceInputProcessor = $objectManager->getObject( \Magento\Framework\Webapi\ServiceInputProcessor::class, @@ -111,10 +122,11 @@ function () use ($objectManager) { /** @var \Magento\Framework\Reflection\NameFinder $nameFinder */ $nameFinder = $objectManager->getObject(\Magento\Framework\Reflection\NameFinder::class); - $serviceInputProcessorReflection = new \ReflectionClass(get_class($this->serviceInputProcessor)); - $typeResolverReflection = $serviceInputProcessorReflection->getProperty('nameFinder'); - $typeResolverReflection->setAccessible(true); - $typeResolverReflection->setValue($this->serviceInputProcessor, $nameFinder); + $objectManager->setBackwardCompatibleProperty( + $this->serviceInputProcessor, + 'nameFinder', + $nameFinder + ); } public function testSimpleProperties() diff --git a/setup/src/Magento/Setup/Console/Command/DiCompileMultiTenantCommand.php b/setup/src/Magento/Setup/Console/Command/DiCompileMultiTenantCommand.php deleted file mode 100644 index ac6a43189d7ab..0000000000000 --- a/setup/src/Magento/Setup/Console/Command/DiCompileMultiTenantCommand.php +++ /dev/null @@ -1,493 +0,0 @@ -objectManager = $objectManagerProvider->get(); - $this->directoryList = $directoryList; - $this->componentRegistrar = $componentRegistrar; - parent::__construct(); - } - - /** - * {@inheritdoc} - */ - protected function configure() - { - $options = [ - new InputOption( - self::INPUT_KEY_SERIALIZER, - null, - InputOption::VALUE_REQUIRED, - 'Serializer function that should be used (' . self::SERIALIZER_VALUE_SERIALIZE . '|' - . self::SERIALIZER_VALUE_IGBINARY . ') default: ' . self::SERIALIZER_VALUE_SERIALIZE - ), - new InputOption( - self::INPUT_KEY_EXTRA_CLASSES_FILE, - null, - InputOption::VALUE_REQUIRED, - 'Path to file with extra proxies and factories to generate' - ), - new InputOption( - self::INPUT_KEY_GENERATION, - null, - InputOption::VALUE_REQUIRED, - 'Absolute path to generated classes, /var/generation by default' - ), - new InputOption( - self::INPUT_KEY_DI, - null, - InputOption::VALUE_REQUIRED, - 'Absolute path to DI definitions directory, /var/di by default' - ), - new InputOption( - self::INPUT_KEY_EXCLUDE_PATTERN, - null, - InputOption::VALUE_REQUIRED, - 'Allows to exclude Paths from compilation (default is #[\\\\/]m1[\\\\/]#i)' - ), - ]; - $this->setName(self::NAME) - ->setDescription( - 'Generates all non-existing proxies and factories, and pre-compile class definitions, ' - . 'inheritance information and plugin definitions' - ) - ->setDefinition($options); - parent::configure(); - } - - /** - * Get module directories exclude patterns - * - * @return array - */ - private function getModuleExcludePatterns() - { - $modulesExcludePatterns = []; - foreach ($this->componentRegistrar->getPaths(ComponentRegistrar::MODULE) as $modulePath) { - $modulesExcludePatterns[] = "#^" . $modulePath . "/Test#"; - } - return $modulesExcludePatterns; - } - - /** - * Get library directories exclude patterns - * - * @return array - */ - private function getLibraryExcludePatterns() - { - $libraryExcludePatterns = []; - foreach ($this->componentRegistrar->getPaths(ComponentRegistrar::LIBRARY) as $libraryPath) { - $libraryExcludePatterns[] = "#^" . $libraryPath . "/([\\w]+/)?Test#"; - } - return $libraryExcludePatterns; - } - - /** - * {@inheritdoc} - */ - protected function execute(InputInterface $input, OutputInterface $output) - { - $errors = $this->validate($input); - if ($errors) { - $output->writeln($errors); - return; - } - - $generationDir = $input->getOption(self::INPUT_KEY_GENERATION) ? $input->getOption(self::INPUT_KEY_GENERATION) - : $this->directoryList->getPath(DirectoryList::GENERATION); - $modulesExcludePatterns = $this->getModuleExcludePatterns(); - $testExcludePatterns = [ - "#^" . $this->directoryList->getPath(DirectoryList::SETUP) . "/[\\w]+/[\\w]+/Test#", - "#^" . $this->directoryList->getRoot() . "/dev/tools/Magento/Tools/[\\w]+/Test#" - ]; - $librariesExcludePatterns = $this->getLibraryExcludePatterns(); - $testExcludePatterns = array_merge($testExcludePatterns, $modulesExcludePatterns, $librariesExcludePatterns); - $fileExcludePatterns = $input->getOption('exclude-pattern') ? - [$input->getOption(self::INPUT_KEY_EXCLUDE_PATTERN)] : ['#[\\\\/]M1[\\\\/]#i']; - $fileExcludePatterns = array_merge($fileExcludePatterns, $testExcludePatterns); - /** @var Writer\Console logWriter Writer model for success messages */ - $logWriter = new Writer\Console($output); - $this->log = new Log($logWriter, $logWriter); - AutoloaderRegistry::getAutoloader()->addPsr4('Magento\\', $generationDir . '/Magento/'); - // 1 Code generation - $this->generateCode($generationDir, $fileExcludePatterns, $input); - // 2. Compilation - $this->compileCode($generationDir, $fileExcludePatterns, $input); - //Reporter - $this->log->report(); - if (!$this->log->hasError()) { - $output->writeln( - 'On *nix systems, verify the Magento application has permissions to modify files ' - . 'created by the compiler in the "var" directory. For instance, if you run the Magento application ' - . 'using Apache, the owner of the files in the "var" directory should be the Apache user (example ' - . 'command: "chown -R www-data:www-data /var" where MAGENTO_ROOT is the Magento ' - . 'root directory).' - ); - } - } - - /** - * Generate Code - * - * @param string $generationDir - * @param array $fileExcludePatterns - * @param InputInterface $input - * @return void - * @SuppressWarnings(PHPMD.CyclomaticComplexity) - * @SuppressWarnings(PHPMD.NPathComplexity) - */ - public function generateCode($generationDir, $fileExcludePatterns, $input) - { - // 1.1 Code scan - $filePatterns = ['php' => '/.*\.php$/', 'di' => '/\/etc\/([a-zA-Z_]*\/di|di)\.xml$/']; - $directoryScanner = new Scanner\DirectoryScanner(); - foreach ($this->componentRegistrar->getPaths(ComponentRegistrar::MODULE) as $codeScanDir) { - $this->files = array_merge_recursive( - $this->files, - $directoryScanner->scan($codeScanDir, $filePatterns, $fileExcludePatterns) - ); - } - $this->files['di'][] = $this->directoryList->getPath( - \Magento\Framework\App\Filesystem\DirectoryList::CONFIG - ) . '/di.xml'; - $this->files['additional'] = [$input->getOption(self::INPUT_KEY_EXTRA_CLASSES_FILE)]; - $repositoryScanner = new Scanner\RepositoryScanner(); - $repositories = $repositoryScanner->collectEntities($this->files['di']); - $scanner = new Scanner\CompositeScanner(); - $scanner->addChild(new Scanner\PhpScanner($this->log), 'php'); - $scanner->addChild(new Scanner\XmlScanner($this->log), 'di'); - $scanner->addChild(new Scanner\ArrayScanner(), 'additional'); - $this->entities = $scanner->collectEntities($this->files); - $interceptorScanner = new Scanner\XmlInterceptorScanner(); - $this->entities['interceptors'] = $interceptorScanner->collectEntities($this->files['di']); - // 1.2 Generation of Factory and Additional Classes - $generatorIo = $this->objectManager->create( - \Magento\Framework\Code\Generator\Io::class, - ['generationDirectory' => $generationDir] - ); - $this->generator = $this->objectManager->create( - \Magento\Framework\Code\Generator::class, - ['ioObject' => $generatorIo] - ); - /** Initialize object manager for code generation based on configs */ - $this->generator->setObjectManager($this->objectManager); - $generatorAutoloader = new \Magento\Framework\Code\Generator\Autoloader($this->generator); - spl_autoload_register([$generatorAutoloader, 'load']); - - foreach ($repositories as $entityName) { - switch ($this->generator->generateClass($entityName)) { - case CodeGenerator::GENERATION_SUCCESS: - $this->log->add(Log::GENERATION_SUCCESS, $entityName); - break; - case CodeGenerator::GENERATION_ERROR: - $this->log->add(Log::GENERATION_ERROR, $entityName); - break; - case CodeGenerator::GENERATION_SKIP: - default: - //no log - break; - } - } - foreach (['php', 'additional'] as $type) { - sort($this->entities[$type]); - foreach ($this->entities[$type] as $entityName) { - switch ($this->generator->generateClass($entityName)) { - case CodeGenerator::GENERATION_SUCCESS: - $this->log->add(Log::GENERATION_SUCCESS, $entityName); - break; - case CodeGenerator::GENERATION_ERROR: - $this->log->add(Log::GENERATION_ERROR, $entityName); - break; - case CodeGenerator::GENERATION_SKIP: - default: - //no log - break; - } - } - } - } - - /** - * Compile Code - * - * @param string $generationDir - * @param array $fileExcludePatterns - * @param InputInterface $input - * @return void - * @SuppressWarnings(PHPMD.CyclomaticComplexity) - * @SuppressWarnings(PHPMD.NPathComplexity) - */ - private function compileCode($generationDir, $fileExcludePatterns, $input) - { - $diDir = $input->getOption(self::INPUT_KEY_DI) ? $input->getOption(self::INPUT_KEY_DI) : - $this->directoryList->getPath(DirectoryList::DI); - $relationsFile = $diDir . '/relations.ser'; - $pluginDefFile = $diDir . '/plugins.ser'; - $compilationDirs = [ - $this->directoryList->getPath(DirectoryList::SETUP) . '/Magento/Setup/Module', - $this->directoryList->getRoot() . '/dev/tools/Magento/Tools', - ]; - $compilationDirs = array_merge( - $compilationDirs, - $this->componentRegistrar->getPaths(ComponentRegistrar::MODULE), - $this->componentRegistrar->getPaths(ComponentRegistrar::LIBRARY) - ); - $serializer = $input->getOption(self::INPUT_KEY_SERIALIZER) == Igbinary::NAME ? new Igbinary() : new Standard(); - // 2.1 Code scan - $validator = new \Magento\Framework\Code\Validator(); - $validator->add(new \Magento\Framework\Code\Validator\ConstructorIntegrity()); - $validator->add(new \Magento\Framework\Code\Validator\ContextAggregation()); - $classesScanner = new \Magento\Setup\Module\Di\Code\Reader\ClassesScanner(); - $classesScanner->addExcludePatterns($fileExcludePatterns); - $directoryInstancesNamesList = new \Magento\Setup\Module\Di\Code\Reader\Decorator\Directory( - $this->log, - new \Magento\Framework\Code\Reader\ClassReader(), - $classesScanner, - $validator, - $generationDir - ); - foreach ($compilationDirs as $path) { - if (is_readable($path)) { - $directoryInstancesNamesList->getList($path); - } - } - $inheritanceScanner = new Scanner\InheritanceInterceptorScanner( - new \Magento\Framework\ObjectManager\InterceptableValidator() - ); - $this->entities['interceptors'] = $inheritanceScanner->collectEntities( - get_declared_classes(), - $this->entities['interceptors'] - ); - // 2.1.1 Generation of Proxy and Interceptor Classes - foreach (['interceptors', 'di'] as $type) { - foreach ($this->entities[$type] as $entityName) { - switch ($this->generator->generateClass($entityName)) { - case CodeGenerator::GENERATION_SUCCESS: - $this->log->add(Log::GENERATION_SUCCESS, $entityName); - break; - case CodeGenerator::GENERATION_ERROR: - $this->log->add(Log::GENERATION_ERROR, $entityName); - break; - case CodeGenerator::GENERATION_SKIP: - default: - //no log - break; - } - } - } - //2.1.2 Compile relations for Proxy/Interceptor classes - $directoryInstancesNamesList->getList($generationDir); - $relations = $directoryInstancesNamesList->getRelations(); - // 2.2 Compression - $relationsFileDir = dirname($relationsFile); - if (!file_exists($relationsFileDir)) { - mkdir($relationsFileDir, 0777, true); - } - $relations = array_filter($relations); - file_put_contents($relationsFile, $serializer->serialize($relations)); - // 3. Plugin Definition Compilation - $pluginScanner = new Scanner\CompositeScanner(); - $pluginScanner->addChild(new Scanner\PluginScanner(), 'di'); - $pluginDefinitions = []; - $pluginList = $pluginScanner->collectEntities($this->files); - $pluginDefinitionList = new \Magento\Framework\Interception\Definition\Runtime(); - foreach ($pluginList as $type => $entityList) { - foreach ($entityList as $entity) { - $pluginDefinitions[ltrim($entity, '\\')] = $pluginDefinitionList->getMethodList($entity); - } - } - $outputContent = $serializer->serialize($pluginDefinitions); - $pluginDefFileDir = dirname($pluginDefFile); - if (!file_exists($pluginDefFileDir)) { - mkdir($pluginDefFileDir, 0777, true); - } - file_put_contents($pluginDefFile, $outputContent); - } - - /** - * Check if all option values provided by the user are valid - * - * @param InputInterface $input - * @return string[] - * @SuppressWarnings(PHPMD.CyclomaticComplexity) - */ - private function validate(InputInterface $input) - { - $errors = []; - $options = $input->getOptions(); - foreach ($options as $key => $value) { - if (!$value) { - continue; - } - switch ($key) { - case self::INPUT_KEY_SERIALIZER: - if (($value !== self::SERIALIZER_VALUE_SERIALIZE) && ($value !== self::SERIALIZER_VALUE_IGBINARY)) { - $errors[] = 'Invalid value for command option \'' . self::INPUT_KEY_SERIALIZER - . '\'. Possible values (' . self::SERIALIZER_VALUE_SERIALIZE . '|' - . self::SERIALIZER_VALUE_IGBINARY . ').'; - } - break; - case self::INPUT_KEY_EXTRA_CLASSES_FILE: - if (!file_exists($value)) { - $errors[] = 'Path does not exist for the value of command option \'' - . self::INPUT_KEY_EXTRA_CLASSES_FILE . '\'.'; - } - break; - case self::INPUT_KEY_GENERATION: - $errorMsg = $this->validateOutputPath($value, self::INPUT_KEY_GENERATION); - if ($errorMsg !== '') { - $errors[] = $errorMsg; - } - break; - case self::INPUT_KEY_DI: - $errorMsg = $this->validateOutputPath($value, self::INPUT_KEY_DI); - if ($errorMsg !== '') { - $errors[] = $errorMsg; - } - break; - case self::INPUT_KEY_EXCLUDE_PATTERN: - if (@preg_match($value, null) === false) { - $errors[] = 'Invalid pattern for command option \'' . self::INPUT_KEY_EXCLUDE_PATTERN - . '\'.'; - } - break; - } - } - return $errors; - } - - /** - * Validate output path based on type - * - * @param string $value - * @param string $type - * @return string - */ - private function validateOutputPath($value, $type) - { - $errorMsg = ''; - if (!file_exists($value)) { - $errorMsg = 'Path does not exist for the value of command option \'' . $type . '\'.'; - } - if (file_exists($value) && !is_writeable($value)) { - $errorMsg .= 'Non-writable directory is provided by the value of command option \'' - . $type . '\'.'; - - } - return $errorMsg; - } -} diff --git a/setup/src/Magento/Setup/Model/ConfigGenerator.php b/setup/src/Magento/Setup/Model/ConfigGenerator.php index 140f5a739889c..ce86ce4dd471f 100644 --- a/setup/src/Magento/Setup/Model/ConfigGenerator.php +++ b/setup/src/Magento/Setup/Model/ConfigGenerator.php @@ -116,19 +116,12 @@ public function createSessionConfig(array $data) * * @param array $data * @return ConfigData + * @deprecated + * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function createDefinitionsConfig(array $data) { - $configData = new ConfigData(ConfigFilePool::APP_ENV); - - if (!empty($data[ConfigOptionsListConstants::INPUT_KEY_DEFINITION_FORMAT])) { - $configData->set( - ObjectManagerFactory::CONFIG_PATH_DEFINITION_FORMAT, - $data[ConfigOptionsListConstants::INPUT_KEY_DEFINITION_FORMAT] - ); - } - - return $configData; + return null; } /** diff --git a/setup/src/Magento/Setup/Model/ConfigOptionsList.php b/setup/src/Magento/Setup/Model/ConfigOptionsList.php index 4e8374aabb4e6..0c1419a73cb8e 100644 --- a/setup/src/Magento/Setup/Model/ConfigOptionsList.php +++ b/setup/src/Magento/Setup/Model/ConfigOptionsList.php @@ -72,13 +72,6 @@ public function getOptions() 'Session save handler', ConfigOptionsListConstants::SESSION_SAVE_FILES ), - new SelectConfigOption( - ConfigOptionsListConstants::INPUT_KEY_DEFINITION_FORMAT, - SelectConfigOption::FRONTEND_WIZARD_SELECT, - DefinitionFactory::getSupportedFormats(), - ObjectManagerFactory::CONFIG_PATH_DEFINITION_FORMAT, - 'Type of definitions used by Object Manager' - ), new TextConfigOption( ConfigOptionsListConstants::INPUT_KEY_DB_HOST, TextConfigOption::FRONTEND_WIZARD_TEXT, diff --git a/setup/src/Magento/Setup/Module/Di/Code/Generator/PluginList.php b/setup/src/Magento/Setup/Module/Di/Code/Generator/PluginList.php index 703cbced8e33a..851bfa8c36313 100644 --- a/setup/src/Magento/Setup/Module/Di/Code/Generator/PluginList.php +++ b/setup/src/Magento/Setup/Module/Di/Code/Generator/PluginList.php @@ -1,14 +1,15 @@ initialize(); - $serialized = serialize($config); - file_put_contents($this->directoryList->getPath(DirectoryList::DI) . '/' . $key . '.ser', $serialized); + file_put_contents( + $this->directoryList->getPath(DirectoryList::DI) . '/' . $key . '.ser', + $this->getSerializer()->serialize($config) + ); } /** @@ -54,4 +62,19 @@ private function initialize() mkdir($this->directoryList->getPath(DirectoryList::DI)); } } + + /** + * Get serializer + * + * @return SerializerInterface + * @deprecated + */ + private function getSerializer() + { + if (null === $this->serializer) { + $this->serializer = \Magento\Framework\App\ObjectManager::getInstance() + ->get(Serialize::class); + } + return $this->serializer; + } } diff --git a/setup/src/Magento/Setup/Test/Unit/Model/ConfigOptionsListTest.php b/setup/src/Magento/Setup/Test/Unit/Model/ConfigOptionsListTest.php index 1e37d351d8f03..eaab4d28d7620 100644 --- a/setup/src/Magento/Setup/Test/Unit/Model/ConfigOptionsListTest.php +++ b/setup/src/Magento/Setup/Test/Unit/Model/ConfigOptionsListTest.php @@ -48,32 +48,30 @@ public function testGetOptions() $this->assertSame('Encryption key', $options[0]->getDescription()); $this->assertInstanceOf(\Magento\Framework\Setup\Option\SelectConfigOption::class, $options[1]); $this->assertSame('Session save handler', $options[1]->getDescription()); - $this->assertInstanceOf(\Magento\Framework\Setup\Option\SelectConfigOption::class, $options[2]); - $this->assertSame('Type of definitions used by Object Manager', $options[2]->getDescription()); + $this->assertInstanceOf(\Magento\Framework\Setup\Option\TextConfigOption::class, $options[2]); + $this->assertSame('Database server host', $options[2]->getDescription()); $this->assertInstanceOf(\Magento\Framework\Setup\Option\TextConfigOption::class, $options[3]); - $this->assertSame('Database server host', $options[3]->getDescription()); + $this->assertSame('Database name', $options[3]->getDescription()); $this->assertInstanceOf(\Magento\Framework\Setup\Option\TextConfigOption::class, $options[4]); - $this->assertSame('Database name', $options[4]->getDescription()); + $this->assertSame('Database server username', $options[4]->getDescription()); $this->assertInstanceOf(\Magento\Framework\Setup\Option\TextConfigOption::class, $options[5]); - $this->assertSame('Database server username', $options[5]->getDescription()); + $this->assertSame('Database server engine', $options[5]->getDescription()); $this->assertInstanceOf(\Magento\Framework\Setup\Option\TextConfigOption::class, $options[6]); - $this->assertSame('Database server engine', $options[6]->getDescription()); + $this->assertSame('Database server password', $options[6]->getDescription()); $this->assertInstanceOf(\Magento\Framework\Setup\Option\TextConfigOption::class, $options[7]); - $this->assertSame('Database server password', $options[7]->getDescription()); + $this->assertSame('Database table prefix', $options[7]->getDescription()); $this->assertInstanceOf(\Magento\Framework\Setup\Option\TextConfigOption::class, $options[8]); - $this->assertSame('Database table prefix', $options[8]->getDescription()); + $this->assertSame('Database type', $options[8]->getDescription()); $this->assertInstanceOf(\Magento\Framework\Setup\Option\TextConfigOption::class, $options[9]); - $this->assertSame('Database type', $options[9]->getDescription()); - $this->assertInstanceOf(\Magento\Framework\Setup\Option\TextConfigOption::class, $options[10]); - $this->assertSame('Database initial set of commands', $options[10]->getDescription()); - $this->assertInstanceOf(\Magento\Framework\Setup\Option\FlagConfigOption::class, $options[11]); + $this->assertSame('Database initial set of commands', $options[9]->getDescription()); + $this->assertInstanceOf(\Magento\Framework\Setup\Option\FlagConfigOption::class, $options[10]); $this->assertSame( 'If specified, then db connection validation will be skipped', - $options[11]->getDescription() + $options[10]->getDescription() ); - $this->assertInstanceOf(\Magento\Framework\Setup\Option\TextConfigOption::class, $options[12]); - $this->assertSame('http Cache hosts', $options[12]->getDescription()); - $this->assertEquals(13, count($options)); + $this->assertInstanceOf(\Magento\Framework\Setup\Option\TextConfigOption::class, $options[11]); + $this->assertSame('http Cache hosts', $options[11]->getDescription()); + $this->assertEquals(12, count($options)); } public function testCreateOptions() diff --git a/setup/src/Magento/Setup/Test/Unit/Module/ConfigGeneratorTest.php b/setup/src/Magento/Setup/Test/Unit/Module/ConfigGeneratorTest.php index caca5509d1e14..238bf7ea3db9f 100644 --- a/setup/src/Magento/Setup/Test/Unit/Module/ConfigGeneratorTest.php +++ b/setup/src/Magento/Setup/Test/Unit/Module/ConfigGeneratorTest.php @@ -66,14 +66,6 @@ public function testCreateSessionConfigWithoutInput() $this->assertEquals([], $returnValue->getData()); } - public function testCreateDefinitionsConfig() - { - $testData = [ConfigOptionsListConstants::INPUT_KEY_DEFINITION_FORMAT => 'test-format']; - $returnValue = $this->configGeneratorObject->createDefinitionsConfig($testData); - $this->assertEquals(ConfigFilePool::APP_ENV, $returnValue->getFileKey()); - $this->assertEquals(['definition' => ['format' => 'test-format']], $returnValue->getData()); - } - public function testCreateDbConfig() { $testData = [