From 7be97ea71632ea0f065469a9cf2eb36be1c463bd Mon Sep 17 00:00:00 2001 From: Max Lesechko Date: Wed, 22 Mar 2017 10:41:33 +0200 Subject: [PATCH 01/44] MAGETWO-66484: Analytics Module does not support tables with prefixes --- .../ReportXml/DB/Assembler/FromAssembler.php | 23 +++-- .../ReportXml/DB/Assembler/JoinAssembler.php | 18 +++- .../DB/Assembler/FromAssemblerTest.php | 96 ++++++++++++++----- .../DB/Assembler/JoinAssemblerTest.php | 56 +++++++---- 4 files changed, 144 insertions(+), 49 deletions(-) diff --git a/app/code/Magento/Analytics/ReportXml/DB/Assembler/FromAssembler.php b/app/code/Magento/Analytics/ReportXml/DB/Assembler/FromAssembler.php index 2ae835bb3344f..7dfbd7edeb754 100644 --- a/app/code/Magento/Analytics/ReportXml/DB/Assembler/FromAssembler.php +++ b/app/code/Magento/Analytics/ReportXml/DB/Assembler/FromAssembler.php @@ -9,10 +9,9 @@ use Magento\Analytics\ReportXml\DB\ColumnsResolver; use Magento\Analytics\ReportXml\DB\SelectBuilder; use Magento\Analytics\ReportXml\DB\NameResolver; +use Magento\Framework\App\ResourceConnection; /** - * Class FromAssembler - * * Assembles FROM condition */ class FromAssembler implements AssemblerInterface @@ -28,17 +27,23 @@ class FromAssembler implements AssemblerInterface private $columnsResolver; /** - * FromAssembler constructor. - * + * @var ResourceConnection + */ + private $resourceConnection; + + /** * @param NameResolver $nameResolver * @param ColumnsResolver $columnsResolver + * @param ResourceConnection $resourceConnection */ public function __construct( NameResolver $nameResolver, - ColumnsResolver $columnsResolver + ColumnsResolver $columnsResolver, + ResourceConnection $resourceConnection ) { $this->nameResolver = $nameResolver; $this->columnsResolver = $columnsResolver; + $this->resourceConnection = $resourceConnection; } /** @@ -52,8 +57,12 @@ public function assemble(SelectBuilder $selectBuilder, $queryConfig) { $selectBuilder->setFrom( [ - $this->nameResolver->getAlias($queryConfig['source']) - => $this->nameResolver->getName($queryConfig['source']) + $this->nameResolver->getAlias($queryConfig['source']) => + $this->resourceConnection + ->getTableName( + $this->nameResolver->getName($queryConfig['source']), + $selectBuilder->getConnectionName() + ), ] ); $columns = $this->columnsResolver->getColumns($selectBuilder, $queryConfig['source']); diff --git a/app/code/Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php b/app/code/Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php index a457b8bd126a1..39b48f12a3a6b 100644 --- a/app/code/Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php +++ b/app/code/Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php @@ -10,6 +10,7 @@ use Magento\Analytics\ReportXml\DB\SelectBuilder; use Magento\Analytics\ReportXml\DB\ConditionResolver; use Magento\Analytics\ReportXml\DB\ColumnsResolver; +use Magento\Framework\App\ResourceConnection; /** * Class JoinAssembler @@ -34,8 +35,11 @@ class JoinAssembler implements AssemblerInterface private $columnsResolver; /** - * JoinAssembler constructor. - * + * @var ResourceConnection + */ + private $resourceConnection; + + /** * @param ConditionResolver $conditionResolver * @param ColumnsResolver $columnsResolver * @param NameResolver $nameResolver @@ -43,11 +47,13 @@ class JoinAssembler implements AssemblerInterface public function __construct( ConditionResolver $conditionResolver, ColumnsResolver $columnsResolver, - NameResolver $nameResolver + NameResolver $nameResolver, + ResourceConnection $resourceConnection ) { $this->conditionResolver = $conditionResolver; $this->nameResolver = $nameResolver; $this->columnsResolver = $columnsResolver; + $this->resourceConnection = $resourceConnection; } /** @@ -73,7 +79,11 @@ public function assemble(SelectBuilder $selectBuilder, $queryConfig) $joins[$joinAlias] = [ 'link-type' => isset($join['link-type']) ? $join['link-type'] : 'left', 'table' => [ - $joinAlias => $this->nameResolver->getName($join) + $joinAlias => $this->resourceConnection + ->getTableName( + $this->nameResolver->getName($join), + $selectBuilder->getConnectionName() + ), ], 'condition' => $this->conditionResolver->getFilter( $selectBuilder, diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FromAssemblerTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FromAssemblerTest.php index e5e847648039d..bc361a112b9d2 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FromAssemblerTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FromAssemblerTest.php @@ -5,6 +5,8 @@ */ namespace Magento\Analytics\Test\Unit\ReportXml\DB\Assembler; +use Magento\Framework\App\ResourceConnection; + /** * A unit test for testing of the 'from' assembler. */ @@ -35,6 +37,11 @@ class FromAssemblerTest extends \PHPUnit_Framework_TestCase */ private $columnsResolverMock; + /** + * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + */ + private $resourceConnection; + /** * @return void */ @@ -61,6 +68,10 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); + $this->resourceConnection = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); + $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); @@ -68,45 +79,49 @@ protected function setUp() \Magento\Analytics\ReportXml\DB\Assembler\FromAssembler::class, [ 'nameResolver' => $this->nameResolverMock, - 'columnsResolver' => $this->columnsResolverMock + 'columnsResolver' => $this->columnsResolverMock, + 'resourceConnection' => $this->resourceConnection, ] ); } /** + * @dataProvider assembleDataProvider + * @param array $queryConfig + * @param string $tableName * @return void */ - public function testAssemble() + public function testAssemble(array $queryConfig, $tableName) { - $queryConfigMock = [ - 'source' => [ - 'name' => 'sales_order', - 'alias' => 'sales', - 'attribute' => [ - [ - 'name' => 'entity_id' - ] - ] - ] - ]; - $this->nameResolverMock->expects($this->any()) ->method('getAlias') - ->with($queryConfigMock['source']) - ->willReturn($queryConfigMock['source']['alias']); + ->with($queryConfig['source']) + ->willReturn($queryConfig['source']['alias']); - $this->nameResolverMock->expects($this->any()) + $this->nameResolverMock->expects($this->once()) ->method('getName') - ->with($queryConfigMock['source']) - ->willReturn($queryConfigMock['source']['name']); + ->with($queryConfig['source']) + ->willReturn($queryConfig['source']['name']); + + $this->selectBuilderMock + ->expects($this->once()) + ->method('getConnectionName') + ->with() + ->willReturn(ResourceConnection::DEFAULT_CONNECTION); + + $this->resourceConnection + ->expects($this->once()) + ->method('getTableName') + ->with($queryConfig['source']['name'], ResourceConnection::DEFAULT_CONNECTION) + ->willReturn($tableName); $this->selectBuilderMock->expects($this->once()) ->method('setFrom') - ->with([$queryConfigMock['source']['alias'] => $queryConfigMock['source']['name']]); + ->with([$queryConfig['source']['alias'] => $tableName]); $this->columnsResolverMock->expects($this->once()) ->method('getColumns') - ->with($this->selectBuilderMock, $queryConfigMock['source']) + ->with($this->selectBuilderMock, $queryConfig['source']) ->willReturn(['entity_id' => 'sales.entity_id']); $this->selectBuilderMock->expects($this->once()) @@ -115,7 +130,44 @@ public function testAssemble() $this->assertEquals( $this->selectBuilderMock, - $this->subject->assemble($this->selectBuilderMock, $queryConfigMock) + $this->subject->assemble($this->selectBuilderMock, $queryConfig) ); } + + /** + * @return array + */ + public function assembleDataProvider() + { + return [ + 'Tables without prefixes' => [ + [ + 'source' => [ + 'name' => 'sales_order', + 'alias' => 'sales', + 'attribute' => [ + [ + 'name' => 'entity_id' + ] + ], + ], + ], + 'sales_order', + ], + 'Tables with prefixes' => [ + [ + 'source' => [ + 'name' => 'sales_order', + 'alias' => 'sales', + 'attribute' => [ + [ + 'name' => 'entity_id' + ] + ], + ], + ], + 'pref_sales_order', + ] + ]; + } } diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php index f32f9dc3fa152..2d698fae35dee 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php @@ -5,6 +5,8 @@ */ namespace Magento\Analytics\Test\Unit\ReportXml\DB\Assembler; +use Magento\Framework\App\ResourceConnection; + /** * A unit test for testing of the 'join' assembler. */ @@ -40,6 +42,11 @@ class JoinAssemblerTest extends \PHPUnit_Framework_TestCase */ private $conditionResolverMock; + /** + * @var ResourceConnection|\PHPUnit_Framework_MockObject_MockObject + */ + private $resourceConnection; + /** * @return void */ @@ -78,6 +85,10 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); + $this->resourceConnection = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); + $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); @@ -86,7 +97,8 @@ protected function setUp() [ 'conditionResolver' => $this->conditionResolverMock, 'nameResolver' => $this->nameResolverMock, - 'columnsResolver' => $this->columnsResolverMock + 'columnsResolver' => $this->columnsResolverMock, + 'resourceConnection' => $this->resourceConnection, ] ); } @@ -118,24 +130,15 @@ public function testAssembleEmpty() /** * @param array $queryConfigMock - * - * @dataProvider assembleNotEmptyDataProvider + * @param array $joinsMock + * @param array $tablesMapping * @return void + * @dataProvider assembleNotEmptyDataProvider */ - public function testAssembleNotEmpty(array $queryConfigMock) + public function testAssembleNotEmpty(array $queryConfigMock, array $joinsMock, array $tablesMapping) { $filtersMock = []; - $joinsMock = [ - 'billing' => [ - 'link-type' => 'left', - 'table' => [ - 'billing' => 'sales_order_address' - ], - 'condition' => '(billing.parent_id = `sales`.`entity_id`)' - ] - ]; - $this->nameResolverMock->expects($this->at(0)) ->method('getAlias') ->with($queryConfigMock['source']) @@ -144,11 +147,22 @@ public function testAssembleNotEmpty(array $queryConfigMock) ->method('getAlias') ->with($queryConfigMock['source']['link-source'][0]) ->willReturn($queryConfigMock['source']['link-source'][0]['alias']); - $this->nameResolverMock->expects($this->any()) + $this->nameResolverMock->expects($this->once()) ->method('getName') ->with($queryConfigMock['source']['link-source'][0]) ->willReturn($queryConfigMock['source']['link-source'][0]['name']); + $this->selectBuilderMock + ->expects($this->once()) + ->method('getConnectionName') + ->with() + ->willReturn(ResourceConnection::DEFAULT_CONNECTION); + + $this->resourceConnection + ->expects($this->any()) + ->method('getTableName') + ->willReturnOnConsecutiveCalls(...array_values($tablesMapping)); + $this->conditionResolverMock->expects($this->at(0)) ->method('getFilter') ->with( @@ -254,7 +268,17 @@ public function assembleNotEmptyDataProvider() ] ] ] - ] + ], + [ + 'billing' => [ + 'link-type' => 'left', + 'table' => [ + 'billing' => 'pref_sales_order_address' + ], + 'condition' => '(billing.parent_id = `sales`.`entity_id`)' + ] + ], + ['sales_order_address' => 'pref_sales_order_address'] ] ]; } From f9d990fc65c6cfb5cbea4cf119031ad3b878e6d6 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Wed, 22 Mar 2017 15:23:37 +0200 Subject: [PATCH 02/44] MAGETWO-66528: Add response handler Identify and reduce code duplication --- .../Model/Connector/Http/Client/Curl.php | 73 ++++++++++----- .../Model/Connector/Http/ClientInterface.php | 6 +- .../Connector/Http/ConverterInterface.php | 31 +++++++ .../Model/Connector/Http/JsonConverter.php | 55 ++++++++++++ .../Connector/NotifyDataChangedCommand.php | 39 +++----- .../Analytics/Model/Connector/OTPRequest.php | 90 ++++++++----------- .../Model/Connector/SignUpRequest.php | 82 ++++++----------- .../Model/Connector/UpdateCommand.php | 67 +++++++------- app/code/Magento/Analytics/etc/di.xml | 11 +++ 9 files changed, 263 insertions(+), 191 deletions(-) create mode 100644 app/code/Magento/Analytics/Model/Connector/Http/ConverterInterface.php create mode 100644 app/code/Magento/Analytics/Model/Connector/Http/JsonConverter.php diff --git a/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php b/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php index 388132ea73144..395e59bce616b 100644 --- a/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php +++ b/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php @@ -5,6 +5,7 @@ */ namespace Magento\Analytics\Model\Connector\Http\Client; +use Magento\Analytics\Model\Connector\Http\ConverterInterface; use Psr\Log\LoggerInterface; use Magento\Framework\HTTP\Adapter\CurlFactory; use Magento\Analytics\Model\Connector\Http\ResponseFactory; @@ -16,11 +17,6 @@ */ class Curl implements \Magento\Analytics\Model\Connector\Http\ClientInterface { - /** - * @var LoggerInterface - */ - private $logger; - /** * @var CurlFactory */ @@ -31,46 +27,83 @@ class Curl implements \Magento\Analytics\Model\Connector\Http\ClientInterface */ private $responseFactory; + /** + * @var ConverterInterface + */ + private $converter; + + /** + * @var LoggerInterface + */ + private $logger; + /** * @param CurlFactory $curlFactory * @param ResponseFactory $responseFactory + * @param ConverterInterface $converter * @param LoggerInterface $logger */ public function __construct( CurlFactory $curlFactory, ResponseFactory $responseFactory, + ConverterInterface $converter, LoggerInterface $logger ) { $this->curlFactory = $curlFactory; $this->responseFactory = $responseFactory; + $this->converter = $converter; $this->logger = $logger; } /** * {@inheritdoc} */ - public function request($method, $url, $body = '', array $headers = [], $version = '1.1') + public function request($method, $url, array $body = [], array $headers = [], $version = '1.1') { - $curl = $this->curlFactory->create(); + $response = false; + + try { + $curl = $this->curlFactory->create(); + $headers = $this->applyContentTypeHeaderFromConverter($headers); - $curl->write($method, $url, $version, $headers, $body); + $curl->write($method, $url, $version, $headers, $this->converter->toBody($body)); - $result = $curl->read(); + $result = $curl->read(); - if ($curl->getErrno()) { - $this->logger->critical( - new \Exception( - sprintf( - 'MBI service CURL connection error #%s: %s', - $curl->getErrno(), - $curl->getError() + if ($curl->getErrno()) { + $this->logger->critical( + new \Exception( + sprintf( + 'MBI service CURL connection error #%s: %s', + $curl->getErrno(), + $curl->getError() + ) ) - ) - ); + ); + + return false; + } + + $response = $this->responseFactory->create($result); + } catch (\Exception $e) { + $this->logger->critical($e); + } - return false; + return $response; + } + + /** + * @param array $headers + * + * @return array + */ + private function applyContentTypeHeaderFromConverter(array $headers) + { + $contentTypeHeaderKey = array_search('Content-Type', $headers); + if ($contentTypeHeaderKey === false) { + $headers[] = $this->converter->getContentTypeHeader(); } - return $this->responseFactory->create($result); + return $headers; } } diff --git a/app/code/Magento/Analytics/Model/Connector/Http/ClientInterface.php b/app/code/Magento/Analytics/Model/Connector/Http/ClientInterface.php index 37eb6865544a0..28f60833a0d0c 100644 --- a/app/code/Magento/Analytics/Model/Connector/Http/ClientInterface.php +++ b/app/code/Magento/Analytics/Model/Connector/Http/ClientInterface.php @@ -19,11 +19,11 @@ interface ClientInterface * * @param string $method * @param string $url - * @param string $body + * @param array $body * @param array $headers * @param string $version * - * @return \Zend_Http_Response|bool + * @return \Zend_Http_Response|false */ - public function request($method, $url, $body = '', array $headers = [], $version = '1.1'); + public function request($method, $url, array $body = [], array $headers = [], $version = '1.1'); } diff --git a/app/code/Magento/Analytics/Model/Connector/Http/ConverterInterface.php b/app/code/Magento/Analytics/Model/Connector/Http/ConverterInterface.php new file mode 100644 index 0000000000000..d478eb99f166c --- /dev/null +++ b/app/code/Magento/Analytics/Model/Connector/Http/ConverterInterface.php @@ -0,0 +1,31 @@ +contentTypeHeader = $contentTypeHeader; + } + + /** + * @param string $body + * + * @return array + */ + public function fromBody($body) + { + return json_decode($body, 1); + } + + /** + * @param array $data + * + * @return string + */ + public function toBody(array $data) + { + return json_encode($data); + } + + /** + * @return string + */ + public function getContentTypeHeader() + { + return $this->contentTypeHeader; + } +} diff --git a/app/code/Magento/Analytics/Model/Connector/NotifyDataChangedCommand.php b/app/code/Magento/Analytics/Model/Connector/NotifyDataChangedCommand.php index ccdbf2da898c5..1f20dbb329392 100644 --- a/app/code/Magento/Analytics/Model/Connector/NotifyDataChangedCommand.php +++ b/app/code/Magento/Analytics/Model/Connector/NotifyDataChangedCommand.php @@ -67,35 +67,18 @@ public function __construct( public function execute() { $result = false; - try { - if ($this->analyticsToken->isTokenExist()) { - $this->httpClient->request( - ZendClient::POST, - $this->config->getConfigDataValue($this->notifyDataChangedUrlPath), - $this->getRequestJson(), - ['Content-Type: application/json'] - ); - $result = true; - } - } catch (\Exception $e) { - $this->logger->critical($e); + if ($this->analyticsToken->isTokenExist()) { + $result = (bool)$this->httpClient->request( + ZendClient::POST, + $this->config->getConfigDataValue($this->notifyDataChangedUrlPath), + [ + "access-token" => $this->analyticsToken->getToken(), + "url" => $this->config->getConfigDataValue( + Store::XML_PATH_SECURE_BASE_URL + ), + ] + ); } return $result; } - - /** - * Prepares request data in JSON format. - * @return string - */ - private function getRequestJson() - { - return json_encode( - [ - "access-token" => $this->analyticsToken->getToken(), - "url" => $this->config->getConfigDataValue( - Store::XML_PATH_SECURE_BASE_URL - ), - ] - ); - } } diff --git a/app/code/Magento/Analytics/Model/Connector/OTPRequest.php b/app/code/Magento/Analytics/Model/Connector/OTPRequest.php index 7f76db05d8dce..b4076514d3d4d 100644 --- a/app/code/Magento/Analytics/Model/Connector/OTPRequest.php +++ b/app/code/Magento/Analytics/Model/Connector/OTPRequest.php @@ -6,6 +6,7 @@ namespace Magento\Analytics\Model\Connector; use Magento\Analytics\Model\AnalyticsToken; +use Magento\Analytics\Model\Connector\Http\ConverterInterface; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\HTTP\ZendClient; use Magento\Store\Model\Store; @@ -34,6 +35,11 @@ class OTPRequest */ private $httpClient; + /** + * @var ConverterInterface + */ + private $converter; + /** * @var LoggerInterface */ @@ -55,17 +61,20 @@ class OTPRequest /** * @param AnalyticsToken $analyticsToken * @param Http\ClientInterface $httpClient + * @param ConverterInterface $converter * @param ScopeConfigInterface $config * @param LoggerInterface $logger */ public function __construct( AnalyticsToken $analyticsToken, Http\ClientInterface $httpClient, + ConverterInterface $converter, ScopeConfigInterface $config, LoggerInterface $logger ) { $this->analyticsToken = $analyticsToken; $this->httpClient = $httpClient; + $this->converter = $converter; $this->config = $config; $this->logger = $logger; } @@ -79,70 +88,49 @@ public function __construct( */ public function call() { - $otp = false; + $result = false; if ($this->analyticsToken->isTokenExist()) { - try { - $response = $this->httpClient->request( - ZendClient::POST, - $this->config->getValue($this->otpUrlConfigPath), - $this->getRequestJson(), - ['Content-Type: application/json'] - ); - - if ($response) { - $otp = $this->extractOtp($response); - - if (!$otp) { - $this->logger->warning( - sprintf( - 'Obtaining of an OTP from the MBI service has been failed: %s', - !empty($response->getBody()) ? $response->getBody() : 'Response body is empty.' - ) - ); - } - } - } catch (\Exception $e) { - $this->logger->critical($e); - } + $response = $this->httpClient->request( + ZendClient::POST, + $this->config->getValue($this->otpUrlConfigPath), + [ + "access-token" => $this->analyticsToken->getToken(), + "url" => $this->config->getValue(Store::XML_PATH_SECURE_BASE_URL), + ] + ); + + $result = $this->parseResult($response); } - return $otp; + return $result; } /** - * Prepares request data in JSON format. + * @param \Zend_Http_Response $response * - * @return string + * @return false|string */ - private function getRequestJson() + private function parseResult($response) { - return json_encode( - [ - "access-token" => $this->analyticsToken->getToken(), - "url" => $this->config->getValue(Store::XML_PATH_SECURE_BASE_URL), - ] - ); - } + $result = false; - /** - * Extracts an OTP from the response. - * - * Returns the OTP or FALSE if the OTP is not found. - * - * @param HttpResponse $response - * @return string|false - */ - private function extractOtp(HttpResponse $response) - { - $otp = false; - - if ($response->getStatus() === 201) { - $body = json_decode($response->getBody(), 1); + if ($response) { + if ($response->getStatus() === 201) { + $body = $this->converter->fromBody($response->getBody()); + $result = !empty($body['otp']) ? $body['otp'] : false; + } - $otp = !empty($body['otp']) ? $body['otp'] : false; + if (!$result) { + $this->logger->warning( + sprintf( + 'Obtaining of an OTP from the MBI service has been failed: %s', + !empty($response->getBody()) ? $response->getBody() : 'Response body is empty.' + ) + ); + } } - return $otp; + return $result; } } diff --git a/app/code/Magento/Analytics/Model/Connector/SignUpRequest.php b/app/code/Magento/Analytics/Model/Connector/SignUpRequest.php index 74bfa84d0ef62..273a7e5c86db3 100644 --- a/app/code/Magento/Analytics/Model/Connector/SignUpRequest.php +++ b/app/code/Magento/Analytics/Model/Connector/SignUpRequest.php @@ -54,14 +54,18 @@ public function __construct( } /** - * Prepares request data in JSON format. + * Performs a 'signUp' call to MBI service. + * + * Returns MBI access token or FALSE in case of failure. * * @param string $integrationToken - * @return string + * @return string|false */ - private function getRequestJson($integrationToken) + public function call($integrationToken) { - return json_encode( + $response = $this->httpClient->request( + ZendClient::POST, + $this->config->getConfigDataValue($this->signUpUrlPath), [ "token" => $integrationToken, "url" => $this->config->getConfigDataValue( @@ -69,67 +73,37 @@ private function getRequestJson($integrationToken) ) ] ); - } - - /** - * Extracts an MBI access token from the response. - * - * Returns the token or FALSE if the token is not found. - * - * @param HttpResponse $response - * @return string|false - */ - private function extractAccessToken(HttpResponse $response) - { - $token = false; - - if ($response->getStatus() === 201) { - $body = json_decode($response->getBody(), 1); - if (isset($body['access-token']) && !empty($body['access-token'])) { - $token = $body['access-token']; - } - } - - return $token; + return $this->parseResult($response); } /** - * Performs a 'signUp' call to MBI service. + * @param \Zend_Http_Response $response * - * Returns MBI access token or FALSE in case of failure. - * - * @param string $integrationToken - * @return string|false + * @return false|string */ - public function call($integrationToken) + private function parseResult($response) { - $token = false; - - try { - $response = $this->httpClient->request( - ZendClient::POST, - $this->config->getConfigDataValue($this->signUpUrlPath), - $this->getRequestJson($integrationToken), - ['Content-Type: application/json'] - ); + $result = false; + if ($response) { + if ($response->getStatus() === 201) { + $body = json_decode($response->getBody(), 1); - if ($response) { - $token = $this->extractAccessToken($response); - - if (!$token) { - $this->logger->warning( - sprintf( - 'Subscription for MBI service has been failed. An error occurred during token exchange: %s', - !empty($response->getBody()) ? $response->getBody() : 'Response body is empty.' - ) - ); + if (isset($body['access-token']) && !empty($body['access-token'])) { + $result = $body['access-token']; } } - } catch (\Exception $e) { - $this->logger->critical($e); + + if (!$result) { + $this->logger->warning( + sprintf( + 'Subscription for MBI service has been failed. An error occurred during token exchange: %s', + !empty($response->getBody()) ? $response->getBody() : 'Response body is empty.' + ) + ); + } } - return $token; + return $result; } } diff --git a/app/code/Magento/Analytics/Model/Connector/UpdateCommand.php b/app/code/Magento/Analytics/Model/Connector/UpdateCommand.php index ba9e779122f55..4d80e94b59dee 100644 --- a/app/code/Magento/Analytics/Model/Connector/UpdateCommand.php +++ b/app/code/Magento/Analytics/Model/Connector/UpdateCommand.php @@ -77,48 +77,45 @@ public function __construct( public function execute() { $result = false; - try { - if ($this->analyticsToken->isTokenExist()) { - $response = $this->httpClient->request( - ZendClient::PUT, - $this->config->getConfigDataValue($this->updateUrlPath), - $this->getRequestJson(), - ['Content-Type: application/json'] - ); - - if ($response) { - $result = $response->getStatus() === 201; - if (!$result) { - $this->logger->warning( - sprintf( - 'Update of the subscription for MBI service has been failed: %s', - !empty($response->getBody()) ? $response->getBody() : 'Response body is empty.' - ) - ); - } - } - } - } catch (\Exception $e) { - $this->logger->critical($e); + if ($this->analyticsToken->isTokenExist()) { + $response = $this->httpClient->request( + ZendClient::PUT, + $this->config->getConfigDataValue($this->updateUrlPath), + [ + "url" => $this->flagManager->getFlagData(BaseUrlConfigPlugin::OLD_BASE_URL_FLAG_CODE), + "new-url" => $this->config->getConfigDataValue( + Store::XML_PATH_SECURE_BASE_URL + ), + "access-token" => $this->analyticsToken->getToken(), + ] + ); + $result = $this->parseResult($response); } return $result; } /** - * Prepares request data in JSON format. - * @return string + * @param \Zend_Http_Response $response + * + * @return bool */ - private function getRequestJson() + private function parseResult($response) { - return json_encode( - [ - "url" => $this->flagManager->getFlagData(BaseUrlConfigPlugin::OLD_BASE_URL_FLAG_CODE), - "new-url" => $this->config->getConfigDataValue( - Store::XML_PATH_SECURE_BASE_URL - ), - "access-token" => $this->analyticsToken->getToken(), - ] - ); + $result = false; + + if ($response) { + $result = $response->getStatus() === 201; + if (!$result) { + $this->logger->warning( + sprintf( + 'Update of the subscription for MBI service has been failed: %s', + !empty($response->getBody()) ? $response->getBody() : 'Response body is empty.' + ) + ); + } + } + + return $result; } } diff --git a/app/code/Magento/Analytics/etc/di.xml b/app/code/Magento/Analytics/etc/di.xml index de282e4ba73a1..89293089ce8e1 100644 --- a/app/code/Magento/Analytics/etc/di.xml +++ b/app/code/Magento/Analytics/etc/di.xml @@ -13,6 +13,7 @@ + @@ -147,4 +148,14 @@ + + + Content-Type: application/json + + + + + Magento\Analytics\Model\Connector\Http\JsonConverter + + From 3819c105bd1251e7123b1d5c1b003e531b5c918f Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Wed, 22 Mar 2017 15:37:43 +0200 Subject: [PATCH 03/44] MAGETWO-66528: Add response handler Remove redundant class SignUp Request. --- .../Model/Connector/SignUpCommand.php | 81 +++++++++++-- .../Model/Connector/SignUpRequest.php | 109 ------------------ 2 files changed, 72 insertions(+), 118 deletions(-) delete mode 100644 app/code/Magento/Analytics/Model/Connector/SignUpRequest.php diff --git a/app/code/Magento/Analytics/Model/Connector/SignUpCommand.php b/app/code/Magento/Analytics/Model/Connector/SignUpCommand.php index f9fd78420be46..9bb2c6dbd7bfd 100644 --- a/app/code/Magento/Analytics/Model/Connector/SignUpCommand.php +++ b/app/code/Magento/Analytics/Model/Connector/SignUpCommand.php @@ -7,6 +7,8 @@ use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\IntegrationManager; +use Magento\Config\Model\Config; +use Psr\Log\LoggerInterface; /** * Class SignUpCommand @@ -15,6 +17,11 @@ */ class SignUpCommand implements CommandInterface { + /** + * @var string + */ + private $signUpUrlPath = 'analytics/url/signup'; + /** * @var AnalyticsToken */ @@ -26,9 +33,19 @@ class SignUpCommand implements CommandInterface private $integrationManager; /** - * @var SignUpRequest + * @var Config + */ + private $config; + + /** + * @var Http\ClientInterface */ - private $signUpRequest; + private $httpClient; + + /** + * @var LoggerInterface + */ + private $logger; /** * SignUpCommand constructor. @@ -38,13 +55,17 @@ class SignUpCommand implements CommandInterface * @param IntegrationManager $integrationManager */ public function __construct( - SignUpRequest $signUpRequest, AnalyticsToken $analyticsToken, - IntegrationManager $integrationManager + IntegrationManager $integrationManager, + Config $config, + Http\ClientInterface $httpClient, + LoggerInterface $logger ) { $this->analyticsToken = $analyticsToken; $this->integrationManager = $integrationManager; - $this->signUpRequest = $signUpRequest; + $this->config = $config; + $this->httpClient = $httpClient; + $this->logger = $logger; } /** @@ -61,14 +82,56 @@ public function __construct( */ public function execute() { + $result = false; $integrationToken = $this->integrationManager->generateToken(); if ($integrationToken) { $this->integrationManager->activateIntegration(); - $responseToken = $this->signUpRequest->call($integrationToken->getToken()); - if ($responseToken) { - $this->analyticsToken->storeToken($responseToken); + $response = $this->httpClient->request( + ZendClient::POST, + $this->config->getConfigDataValue($this->signUpUrlPath), + [ + "token" => $integrationToken->getToken(), + "url" => $this->config->getConfigDataValue( + Store::XML_PATH_SECURE_BASE_URL + ) + ] + ); + + $result = $this->parseResult($response); + if ($result) { + $this->analyticsToken->storeToken($result); + } + } + return $result; + } + + /** + * @param \Zend_Http_Response $response + * + * @return false|string + */ + private function parseResult($response) + { + $result = false; + if ($response) { + if ($response->getStatus() === 201) { + $body = json_decode($response->getBody(), 1); + + if (isset($body['access-token']) && !empty($body['access-token'])) { + $result = $body['access-token']; + } + } + + if (!$result) { + $this->logger->warning( + sprintf( + 'Subscription for MBI service has been failed. An error occurred during token exchange: %s', + !empty($response->getBody()) ? $response->getBody() : 'Response body is empty.' + ) + ); } } - return ((bool)$integrationToken && isset($responseToken) && (bool)$responseToken); + + return $result; } } diff --git a/app/code/Magento/Analytics/Model/Connector/SignUpRequest.php b/app/code/Magento/Analytics/Model/Connector/SignUpRequest.php deleted file mode 100644 index 273a7e5c86db3..0000000000000 --- a/app/code/Magento/Analytics/Model/Connector/SignUpRequest.php +++ /dev/null @@ -1,109 +0,0 @@ -config = $config; - $this->httpClient = $httpClient; - $this->logger = $logger; - } - - /** - * Performs a 'signUp' call to MBI service. - * - * Returns MBI access token or FALSE in case of failure. - * - * @param string $integrationToken - * @return string|false - */ - public function call($integrationToken) - { - $response = $this->httpClient->request( - ZendClient::POST, - $this->config->getConfigDataValue($this->signUpUrlPath), - [ - "token" => $integrationToken, - "url" => $this->config->getConfigDataValue( - Store::XML_PATH_SECURE_BASE_URL - ) - ] - ); - - return $this->parseResult($response); - } - - /** - * @param \Zend_Http_Response $response - * - * @return false|string - */ - private function parseResult($response) - { - $result = false; - if ($response) { - if ($response->getStatus() === 201) { - $body = json_decode($response->getBody(), 1); - - if (isset($body['access-token']) && !empty($body['access-token'])) { - $result = $body['access-token']; - } - } - - if (!$result) { - $this->logger->warning( - sprintf( - 'Subscription for MBI service has been failed. An error occurred during token exchange: %s', - !empty($response->getBody()) ? $response->getBody() : 'Response body is empty.' - ) - ); - } - } - - return $result; - } -} From 30bdc30ec928411d9cca6ba461557a1f0eefa2f3 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Thu, 23 Mar 2017 13:31:37 +0200 Subject: [PATCH 04/44] MAGETWO-66528: Add response handler Add handlers. --- .../Model/Connector/CommandInterface.php | 3 +- .../Model/Connector/Http/Client/Curl.php | 2 +- .../Http/ResponseHandlerInterface.php | 18 ++++++ .../Model/Connector/Http/ResponseResolver.php | 50 +++++++++++++++ .../Connector/NotifyDataChangedCommand.php | 6 +- .../Analytics/Model/Connector/OTPRequest.php | 31 +++------- .../Model/Connector/ResponseHandler/OTP.php | 24 +++++++ .../Connector/ResponseHandler/SignUp.php | 62 +++++++++++++++++++ .../Connector/ResponseHandler/Update.php | 24 +++++++ .../Model/Connector/SignUpCommand.php | 43 +++++-------- .../Model/Connector/UpdateCommand.php | 30 ++++----- app/code/Magento/Analytics/etc/di.xml | 35 ++++++++++- 12 files changed, 255 insertions(+), 73 deletions(-) create mode 100644 app/code/Magento/Analytics/Model/Connector/Http/ResponseHandlerInterface.php create mode 100644 app/code/Magento/Analytics/Model/Connector/Http/ResponseResolver.php create mode 100644 app/code/Magento/Analytics/Model/Connector/ResponseHandler/OTP.php create mode 100644 app/code/Magento/Analytics/Model/Connector/ResponseHandler/SignUp.php create mode 100644 app/code/Magento/Analytics/Model/Connector/ResponseHandler/Update.php diff --git a/app/code/Magento/Analytics/Model/Connector/CommandInterface.php b/app/code/Magento/Analytics/Model/Connector/CommandInterface.php index 8ac1a5fce4371..843fdf05dde93 100644 --- a/app/code/Magento/Analytics/Model/Connector/CommandInterface.php +++ b/app/code/Magento/Analytics/Model/Connector/CommandInterface.php @@ -14,7 +14,8 @@ interface CommandInterface /** * Execute call to external service * Information about destination and arguments appears from config - * @return void + * + * @return bool */ public function execute(); } diff --git a/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php b/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php index 395e59bce616b..7b6c2806baf9d 100644 --- a/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php +++ b/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php @@ -60,7 +60,7 @@ public function __construct( */ public function request($method, $url, array $body = [], array $headers = [], $version = '1.1') { - $response = false; + $response = new \Zend_Http_Response(0, []); try { $curl = $this->curlFactory->create(); diff --git a/app/code/Magento/Analytics/Model/Connector/Http/ResponseHandlerInterface.php b/app/code/Magento/Analytics/Model/Connector/Http/ResponseHandlerInterface.php new file mode 100644 index 0000000000000..d4d5ab30938a6 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Connector/Http/ResponseHandlerInterface.php @@ -0,0 +1,18 @@ +converter = $converter; + $this->responseHandlers = $responseHandlers; + } + + /** + * @param \Zend_Http_Response $response + * + * @return bool|string + */ + public function getResult(\Zend_Http_Response $response) + { + $result = false; + $responseBody = $this->converter->fromBody($response->getBody()); + if (array_key_exists($response->getStatus(), $this->responseHandlers)) { + $result = $this->responseHandlers[$response->getStatus()]->handle($responseBody); + } + + return $result; + } +} diff --git a/app/code/Magento/Analytics/Model/Connector/NotifyDataChangedCommand.php b/app/code/Magento/Analytics/Model/Connector/NotifyDataChangedCommand.php index 1f20dbb329392..f8ead49de1e6b 100644 --- a/app/code/Magento/Analytics/Model/Connector/NotifyDataChangedCommand.php +++ b/app/code/Magento/Analytics/Model/Connector/NotifyDataChangedCommand.php @@ -62,13 +62,13 @@ public function __construct( /** * Notify MBI about that data collection was finished + * * @return bool */ public function execute() { - $result = false; if ($this->analyticsToken->isTokenExist()) { - $result = (bool)$this->httpClient->request( + $this->httpClient->request( ZendClient::POST, $this->config->getConfigDataValue($this->notifyDataChangedUrlPath), [ @@ -79,6 +79,6 @@ public function execute() ] ); } - return $result; + return true; } } diff --git a/app/code/Magento/Analytics/Model/Connector/OTPRequest.php b/app/code/Magento/Analytics/Model/Connector/OTPRequest.php index b4076514d3d4d..7d8b96ba7fda0 100644 --- a/app/code/Magento/Analytics/Model/Connector/OTPRequest.php +++ b/app/code/Magento/Analytics/Model/Connector/OTPRequest.php @@ -7,6 +7,7 @@ use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\Connector\Http\ConverterInterface; +use Magento\Analytics\Model\Connector\Http\ResponseResolver; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\HTTP\ZendClient; use Magento\Store\Model\Store; @@ -50,6 +51,11 @@ class OTPRequest */ private $config; + /** + * @var ResponseResolver + */ + private $responseResolver; + /** * Path to the configuration value which contains * an URL that provides an OTP. @@ -63,6 +69,7 @@ class OTPRequest * @param Http\ClientInterface $httpClient * @param ConverterInterface $converter * @param ScopeConfigInterface $config + * @param ResponseResolver $responseResolver * @param LoggerInterface $logger */ public function __construct( @@ -70,12 +77,14 @@ public function __construct( Http\ClientInterface $httpClient, ConverterInterface $converter, ScopeConfigInterface $config, + ResponseResolver $responseResolver, LoggerInterface $logger ) { $this->analyticsToken = $analyticsToken; $this->httpClient = $httpClient; $this->converter = $converter; $this->config = $config; + $this->responseResolver = $responseResolver; $this->logger = $logger; } @@ -100,27 +109,7 @@ public function call() ] ); - $result = $this->parseResult($response); - } - - return $result; - } - - /** - * @param \Zend_Http_Response $response - * - * @return false|string - */ - private function parseResult($response) - { - $result = false; - - if ($response) { - if ($response->getStatus() === 201) { - $body = $this->converter->fromBody($response->getBody()); - $result = !empty($body['otp']) ? $body['otp'] : false; - } - + $result = $this->responseResolver->getResult($response); if (!$result) { $this->logger->warning( sprintf( diff --git a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/OTP.php b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/OTP.php new file mode 100644 index 0000000000000..711960d76c565 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/OTP.php @@ -0,0 +1,24 @@ +analyticsToken = $analyticsToken; + $this->logger = $logger; + $this->converter = $converter; + } + + /** + * @inheritdoc + */ + public function handleResponse(array $body) + { + if (isset($body['access-token']) && !empty($body['access-token'])) { + $this->analyticsToken->storeToken($body['access-token']); + return $body['access-token']; + } + + return false; + } +} diff --git a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/Update.php b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/Update.php new file mode 100644 index 0000000000000..7af60c8168f54 --- /dev/null +++ b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/Update.php @@ -0,0 +1,24 @@ +analyticsToken = $analyticsToken; $this->integrationManager = $integrationManager; $this->config = $config; $this->httpClient = $httpClient; $this->logger = $logger; + $this->responseResolver = $responseResolver; } /** @@ -97,31 +110,7 @@ public function execute() ] ); - $result = $this->parseResult($response); - if ($result) { - $this->analyticsToken->storeToken($result); - } - } - return $result; - } - - /** - * @param \Zend_Http_Response $response - * - * @return false|string - */ - private function parseResult($response) - { - $result = false; - if ($response) { - if ($response->getStatus() === 201) { - $body = json_decode($response->getBody(), 1); - - if (isset($body['access-token']) && !empty($body['access-token'])) { - $result = $body['access-token']; - } - } - + $result = $this->responseResolver->getResult($response); if (!$result) { $this->logger->warning( sprintf( diff --git a/app/code/Magento/Analytics/Model/Connector/UpdateCommand.php b/app/code/Magento/Analytics/Model/Connector/UpdateCommand.php index 4d80e94b59dee..76eac177a92a4 100644 --- a/app/code/Magento/Analytics/Model/Connector/UpdateCommand.php +++ b/app/code/Magento/Analytics/Model/Connector/UpdateCommand.php @@ -6,6 +6,7 @@ namespace Magento\Analytics\Model\Connector; use Magento\Analytics\Model\AnalyticsToken; +use Magento\Analytics\Model\Connector\Http\ResponseResolver; use Magento\Analytics\Model\FlagManager; use Magento\Framework\HTTP\ZendClient; use Magento\Config\Model\Config; @@ -49,29 +50,38 @@ class UpdateCommand implements CommandInterface */ private $flagManager; + /** + * @var ResponseResolver + */ + private $responseResolver; + /** * @param AnalyticsToken $analyticsToken * @param Http\ClientInterface $httpClient * @param Config $config * @param LoggerInterface $logger * @param FlagManager $flagManager + * @param ResponseResolver $responseResolver */ public function __construct( AnalyticsToken $analyticsToken, Http\ClientInterface $httpClient, Config $config, LoggerInterface $logger, - FlagManager $flagManager + FlagManager $flagManager, + ResponseResolver $responseResolver ) { $this->analyticsToken = $analyticsToken; $this->httpClient = $httpClient; $this->config = $config; $this->logger = $logger; $this->flagManager = $flagManager; + $this->responseResolver = $responseResolver; } /** * Executes update request to MBI api in case store url was changed + * * @return bool */ public function execute() @@ -89,23 +99,7 @@ public function execute() "access-token" => $this->analyticsToken->getToken(), ] ); - $result = $this->parseResult($response); - } - - return $result; - } - - /** - * @param \Zend_Http_Response $response - * - * @return bool - */ - private function parseResult($response) - { - $result = false; - - if ($response) { - $result = $response->getStatus() === 201; + $result = $this->responseResolver->getResult($response); if (!$result) { $this->logger->warning( sprintf( diff --git a/app/code/Magento/Analytics/etc/di.xml b/app/code/Magento/Analytics/etc/di.xml index 89293089ce8e1..1699a543c4516 100644 --- a/app/code/Magento/Analytics/etc/di.xml +++ b/app/code/Magento/Analytics/etc/di.xml @@ -153,9 +153,40 @@ Content-Type: application/json - + - Magento\Analytics\Model\Connector\Http\JsonConverter + + \Magento\Analytics\Model\Connector\ResponseHandler\SignUp + + + + + + + Magento\Analytics\Model\Connector\ResponseHandler\Update + + + + + + + Magento\Analytics\Model\Connector\ResponseHandler\OTP + + + + + + SignUpResponseResolver + + + + + UpdateResponseResolver + + + + + UpdateResponseResolver From b4a80477c6f6f8096b3f6aa8628716254bf2409a Mon Sep 17 00:00:00 2001 From: Max Lesechko Date: Thu, 23 Mar 2017 14:29:35 +0200 Subject: [PATCH 05/44] MAGETWO-66484: Analytics Module does not support tables with prefixes --- .../Analytics/ReportXml/DB/Assembler/FromAssembler.php | 5 +---- .../Analytics/ReportXml/DB/Assembler/JoinAssembler.php | 5 +---- .../Unit/ReportXml/DB/Assembler/FromAssemblerTest.php | 8 +------- .../Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php | 6 ------ 4 files changed, 3 insertions(+), 21 deletions(-) diff --git a/app/code/Magento/Analytics/ReportXml/DB/Assembler/FromAssembler.php b/app/code/Magento/Analytics/ReportXml/DB/Assembler/FromAssembler.php index 7dfbd7edeb754..b861042aace61 100644 --- a/app/code/Magento/Analytics/ReportXml/DB/Assembler/FromAssembler.php +++ b/app/code/Magento/Analytics/ReportXml/DB/Assembler/FromAssembler.php @@ -59,10 +59,7 @@ public function assemble(SelectBuilder $selectBuilder, $queryConfig) [ $this->nameResolver->getAlias($queryConfig['source']) => $this->resourceConnection - ->getTableName( - $this->nameResolver->getName($queryConfig['source']), - $selectBuilder->getConnectionName() - ), + ->getTableName($this->nameResolver->getName($queryConfig['source'])), ] ); $columns = $this->columnsResolver->getColumns($selectBuilder, $queryConfig['source']); diff --git a/app/code/Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php b/app/code/Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php index 39b48f12a3a6b..a900f9d4df17e 100644 --- a/app/code/Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php +++ b/app/code/Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php @@ -80,10 +80,7 @@ public function assemble(SelectBuilder $selectBuilder, $queryConfig) 'link-type' => isset($join['link-type']) ? $join['link-type'] : 'left', 'table' => [ $joinAlias => $this->resourceConnection - ->getTableName( - $this->nameResolver->getName($join), - $selectBuilder->getConnectionName() - ), + ->getTableName($this->nameResolver->getName($join)), ], 'condition' => $this->conditionResolver->getFilter( $selectBuilder, diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FromAssemblerTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FromAssemblerTest.php index bc361a112b9d2..7f6c628068d86 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FromAssemblerTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/FromAssemblerTest.php @@ -103,16 +103,10 @@ public function testAssemble(array $queryConfig, $tableName) ->with($queryConfig['source']) ->willReturn($queryConfig['source']['name']); - $this->selectBuilderMock - ->expects($this->once()) - ->method('getConnectionName') - ->with() - ->willReturn(ResourceConnection::DEFAULT_CONNECTION); - $this->resourceConnection ->expects($this->once()) ->method('getTableName') - ->with($queryConfig['source']['name'], ResourceConnection::DEFAULT_CONNECTION) + ->with($queryConfig['source']['name']) ->willReturn($tableName); $this->selectBuilderMock->expects($this->once()) diff --git a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php index 2d698fae35dee..84db785ef5ec7 100644 --- a/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php +++ b/app/code/Magento/Analytics/Test/Unit/ReportXml/DB/Assembler/JoinAssemblerTest.php @@ -152,12 +152,6 @@ public function testAssembleNotEmpty(array $queryConfigMock, array $joinsMock, a ->with($queryConfigMock['source']['link-source'][0]) ->willReturn($queryConfigMock['source']['link-source'][0]['name']); - $this->selectBuilderMock - ->expects($this->once()) - ->method('getConnectionName') - ->with() - ->willReturn(ResourceConnection::DEFAULT_CONNECTION); - $this->resourceConnection ->expects($this->any()) ->method('getTableName') From 9c305911727ddd99db83636acf78c6da946b504a Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Thu, 23 Mar 2017 15:23:56 +0200 Subject: [PATCH 06/44] MAGETWO-66528: Add response handler Add re-signup call. --- .../Connector/ResponseHandler/ReSignUp.php | 47 +++++++++++++++++++ app/code/Magento/Analytics/etc/di.xml | 2 + 2 files changed, 49 insertions(+) create mode 100644 app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php diff --git a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php new file mode 100644 index 0000000000000..d22a7e42cbb5e --- /dev/null +++ b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php @@ -0,0 +1,47 @@ +analyticsToken = $analyticsToken; + $this->subscription = $subscription; + } + + /** + * @param array $responseBody + * + * @return bool|string + */ + public function handleResponse(array $responseBody) + { + $this->analyticsToken->storeToken(null); + $this->subscription->retry(); + return false; + } +} diff --git a/app/code/Magento/Analytics/etc/di.xml b/app/code/Magento/Analytics/etc/di.xml index 1699a543c4516..0f25c1e986f4e 100644 --- a/app/code/Magento/Analytics/etc/di.xml +++ b/app/code/Magento/Analytics/etc/di.xml @@ -164,6 +164,7 @@ Magento\Analytics\Model\Connector\ResponseHandler\Update + Magento\Analytics\Model\Connector\ResponseHandler\ReSignUp @@ -171,6 +172,7 @@ Magento\Analytics\Model\Connector\ResponseHandler\OTP + Magento\Analytics\Model\Connector\ResponseHandler\ReSignUp From 68e737ad954b451c68b0c799dddbf1ae9ebaca8c Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Sun, 26 Mar 2017 00:29:32 +0200 Subject: [PATCH 07/44] MAGETWO-66528: Add response handler Fix up tests. --- .../Model/Connector/Http/Client/Curl.php | 2 +- .../Connector/Http/ConverterInterface.php | 2 +- .../Model/Connector/Http/JsonConverter.php | 2 +- .../Http/ResponseHandlerInterface.php | 2 +- .../Model/Connector/Http/ResponseResolver.php | 2 - .../Analytics/Model/Connector/OTPRequest.php | 10 - .../Model/Connector/ResponseHandler/OTP.php | 2 +- .../Connector/ResponseHandler/ReSignUp.php | 3 +- .../Connector/ResponseHandler/SignUp.php | 13 +- .../Connector/ResponseHandler/Update.php | 2 +- .../Model/Connector/SignUpCommand.php | 6 +- .../Analytics/Model/IntegrationManager.php | 2 +- .../Model/Connector/Http/Client/CurlTest.php | 54 +++-- .../NotifyDataChangedCommandTest.php | 19 +- .../Unit/Model/Connector/OTPRequestTest.php | 190 ++++----------- .../Model/Connector/SignUpCommandTest.php | 121 +++++++--- .../Model/Connector/SignUpRequestTest.php | 226 ------------------ .../Model/Connector/UpdateCommandTest.php | 34 +-- 18 files changed, 205 insertions(+), 487 deletions(-) delete mode 100644 app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpRequestTest.php diff --git a/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php b/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php index 7b6c2806baf9d..038fc6382d805 100644 --- a/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php +++ b/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php @@ -99,7 +99,7 @@ public function request($method, $url, array $body = [], array $headers = [], $v */ private function applyContentTypeHeaderFromConverter(array $headers) { - $contentTypeHeaderKey = array_search('Content-Type', $headers); + $contentTypeHeaderKey = array_search($this->converter->getContentTypeHeader(), $headers); if ($contentTypeHeaderKey === false) { $headers[] = $this->converter->getContentTypeHeader(); } diff --git a/app/code/Magento/Analytics/Model/Connector/Http/ConverterInterface.php b/app/code/Magento/Analytics/Model/Connector/Http/ConverterInterface.php index d478eb99f166c..3a3ae66e0fb17 100644 --- a/app/code/Magento/Analytics/Model/Connector/Http/ConverterInterface.php +++ b/app/code/Magento/Analytics/Model/Connector/Http/ConverterInterface.php @@ -6,7 +6,7 @@ namespace Magento\Analytics\Model\Connector\Http; /** - * Interface ConverterInterface + * Represents converter interface for http request and response body. */ interface ConverterInterface { diff --git a/app/code/Magento/Analytics/Model/Connector/Http/JsonConverter.php b/app/code/Magento/Analytics/Model/Connector/Http/JsonConverter.php index 5d78823d09dc9..0793daf5e86fe 100644 --- a/app/code/Magento/Analytics/Model/Connector/Http/JsonConverter.php +++ b/app/code/Magento/Analytics/Model/Connector/Http/JsonConverter.php @@ -6,7 +6,7 @@ namespace Magento\Analytics\Model\Connector\Http; /** - * Class JsonConverter + * Represents JSON converter for http request and response body. */ class JsonConverter implements ConverterInterface { diff --git a/app/code/Magento/Analytics/Model/Connector/Http/ResponseHandlerInterface.php b/app/code/Magento/Analytics/Model/Connector/Http/ResponseHandlerInterface.php index d4d5ab30938a6..505f9041b4655 100644 --- a/app/code/Magento/Analytics/Model/Connector/Http/ResponseHandlerInterface.php +++ b/app/code/Magento/Analytics/Model/Connector/Http/ResponseHandlerInterface.php @@ -6,7 +6,7 @@ namespace Magento\Analytics\Model\Connector\Http; /** - * Interface ResponseHandlerInterface + * Represents an interface for response handler which process response body. */ interface ResponseHandlerInterface { diff --git a/app/code/Magento/Analytics/Model/Connector/Http/ResponseResolver.php b/app/code/Magento/Analytics/Model/Connector/Http/ResponseResolver.php index 0d611fca168b1..b554bafb35f0e 100644 --- a/app/code/Magento/Analytics/Model/Connector/Http/ResponseResolver.php +++ b/app/code/Magento/Analytics/Model/Connector/Http/ResponseResolver.php @@ -21,8 +21,6 @@ class ResponseResolver private $responseHandlers; /** - * ResponseResolver constructor. - * * @param ConverterInterface $converter * @param ResponseHandlerInterface[] $responseHandlers */ diff --git a/app/code/Magento/Analytics/Model/Connector/OTPRequest.php b/app/code/Magento/Analytics/Model/Connector/OTPRequest.php index 7d8b96ba7fda0..0ed1ff0b10aea 100644 --- a/app/code/Magento/Analytics/Model/Connector/OTPRequest.php +++ b/app/code/Magento/Analytics/Model/Connector/OTPRequest.php @@ -6,13 +6,11 @@ namespace Magento\Analytics\Model\Connector; use Magento\Analytics\Model\AnalyticsToken; -use Magento\Analytics\Model\Connector\Http\ConverterInterface; use Magento\Analytics\Model\Connector\Http\ResponseResolver; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\HTTP\ZendClient; use Magento\Store\Model\Store; use Psr\Log\LoggerInterface; -use Zend_Http_Response as HttpResponse; /** * Representation of an 'OTP' request. @@ -36,11 +34,6 @@ class OTPRequest */ private $httpClient; - /** - * @var ConverterInterface - */ - private $converter; - /** * @var LoggerInterface */ @@ -67,7 +60,6 @@ class OTPRequest /** * @param AnalyticsToken $analyticsToken * @param Http\ClientInterface $httpClient - * @param ConverterInterface $converter * @param ScopeConfigInterface $config * @param ResponseResolver $responseResolver * @param LoggerInterface $logger @@ -75,14 +67,12 @@ class OTPRequest public function __construct( AnalyticsToken $analyticsToken, Http\ClientInterface $httpClient, - ConverterInterface $converter, ScopeConfigInterface $config, ResponseResolver $responseResolver, LoggerInterface $logger ) { $this->analyticsToken = $analyticsToken; $this->httpClient = $httpClient; - $this->converter = $converter; $this->config = $config; $this->responseResolver = $responseResolver; $this->logger = $logger; diff --git a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/OTP.php b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/OTP.php index 711960d76c565..5e21919e5ed19 100644 --- a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/OTP.php +++ b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/OTP.php @@ -8,7 +8,7 @@ use Magento\Analytics\Model\Connector\Http\ResponseHandlerInterface; /** - * Class OTP + * Fetches OTP from body. */ class OTP implements ResponseHandlerInterface { diff --git a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php index d22a7e42cbb5e..b50dc14cf056b 100644 --- a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php +++ b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php @@ -10,7 +10,7 @@ use Magento\Analytics\Model\Subscription; /** - * Class ReSignUp + * Removes stored token and triggers subscription process. */ class ReSignUp implements ResponseHandlerInterface { @@ -18,6 +18,7 @@ class ReSignUp implements ResponseHandlerInterface * @var AnalyticsToken */ private $analyticsToken; + /** * @var Subscription */ diff --git a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/SignUp.php b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/SignUp.php index 4757d3c84577c..ff6e341407740 100644 --- a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/SignUp.php +++ b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/SignUp.php @@ -8,10 +8,9 @@ use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\Connector\Http\ConverterInterface; use Magento\Analytics\Model\Connector\Http\ResponseHandlerInterface; -use Psr\Log\LoggerInterface; /** - * Class StoreTokenHandler + * Stores access token to MBI that received in body. */ class SignUp implements ResponseHandlerInterface { @@ -20,30 +19,20 @@ class SignUp implements ResponseHandlerInterface */ private $analyticsToken; - /** - * @var LoggerInterface - */ - private $logger; - /** * @var ConverterInterface */ private $converter; /** - * SignUpResponseHandler constructor. - * * @param AnalyticsToken $analyticsToken - * @param LoggerInterface $logger * @param ConverterInterface $converter */ public function __construct( AnalyticsToken $analyticsToken, - LoggerInterface $logger, ConverterInterface $converter ) { $this->analyticsToken = $analyticsToken; - $this->logger = $logger; $this->converter = $converter; } diff --git a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/Update.php b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/Update.php index 7af60c8168f54..65517c84f04b7 100644 --- a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/Update.php +++ b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/Update.php @@ -8,7 +8,7 @@ use Magento\Analytics\Model\Connector\Http\ResponseHandlerInterface; /** - * Class Update + * Return positive answer that request was finished successfully. */ class Update implements ResponseHandlerInterface { diff --git a/app/code/Magento/Analytics/Model/Connector/SignUpCommand.php b/app/code/Magento/Analytics/Model/Connector/SignUpCommand.php index 7be77276f2429..659e1153fb306 100644 --- a/app/code/Magento/Analytics/Model/Connector/SignUpCommand.php +++ b/app/code/Magento/Analytics/Model/Connector/SignUpCommand.php @@ -10,6 +10,8 @@ use Magento\Analytics\Model\IntegrationManager; use Magento\Config\Model\Config; use Psr\Log\LoggerInterface; +use Magento\Framework\HTTP\ZendClient; +use Magento\Store\Model\Store; /** * Class SignUpCommand @@ -62,8 +64,6 @@ class SignUpCommand implements CommandInterface * @param Http\ClientInterface $httpClient * @param LoggerInterface $logger * @param ResponseResolver $responseResolver - * - * @internal param SignUpRequest $signUpRequest */ public function __construct( AnalyticsToken $analyticsToken, @@ -103,7 +103,7 @@ public function execute() ZendClient::POST, $this->config->getConfigDataValue($this->signUpUrlPath), [ - "token" => $integrationToken->getToken(), + "token" => $integrationToken->getData('token'), "url" => $this->config->getConfigDataValue( Store::XML_PATH_SECURE_BASE_URL ) diff --git a/app/code/Magento/Analytics/Model/IntegrationManager.php b/app/code/Magento/Analytics/Model/IntegrationManager.php index bf625f03dc69a..c3bec14ab0b6b 100644 --- a/app/code/Magento/Analytics/Model/IntegrationManager.php +++ b/app/code/Magento/Analytics/Model/IntegrationManager.php @@ -76,7 +76,7 @@ public function activateIntegration() /** * This method execute Generate Token command and enable integration * - * @return bool|string + * @return bool|\Magento\Integration\Model\Oauth\Token */ public function generateToken() { diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/Client/CurlTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/Client/CurlTest.php index 20f7e80bf0287..14602a918481b 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/Client/CurlTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/Client/CurlTest.php @@ -5,6 +5,7 @@ */ namespace Magento\Analytics\Test\Unit\Model\Connector\Http\Client; +use Magento\Analytics\Model\Connector\Http\ConverterInterface; use Magento\Framework\HTTP\Adapter\CurlFactory; /** @@ -27,11 +28,6 @@ class CurlTest extends \PHPUnit_Framework_TestCase */ private $loggerMock; - /** - * @var \Zend_Http_Response|\PHPUnit_Framework_MockObject_MockObject - */ - private $responseMock; - /** * @var CurlFactory|\PHPUnit_Framework_MockObject_MockObject */ @@ -42,6 +38,11 @@ class CurlTest extends \PHPUnit_Framework_TestCase */ private $responseFactoryMock; + /** + * @var ConverterInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $converterMock; + /** * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager */ @@ -63,13 +64,6 @@ protected function setUp() ) ->disableOriginalConstructor() ->getMock(); - - $this->responseMock = $this->getMockBuilder( - \Zend_Http_Response::class - ) - ->disableOriginalConstructor() - ->getMock(); - $this->curlFactoryMock = $this->getMockBuilder(CurlFactory::class) ->setMethods(['create']) ->disableOriginalConstructor() @@ -83,6 +77,7 @@ protected function setUp() ) ->disableOriginalConstructor() ->getMock(); + $this->converterMock = $this->createJsonConverter(); $this->objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); @@ -92,7 +87,8 @@ protected function setUp() [ 'curlFactory' => $this->curlFactoryMock, 'responseFactory' => $this->responseFactoryMock, - 'logger' => $this->loggerMock + 'converter' => $this->converterMock, + 'logger' => $this->loggerMock, ] ); } @@ -108,7 +104,7 @@ public function getTestData() [ 'data' => [ 'version' => '1.1', - 'body'=> '{"name": "value"}', + 'body'=> ['name' => 'value'], 'url' => 'http://www.mystore.com', 'headers' => ['Content-Type: application/json'], 'method' => \Magento\Framework\HTTP\ZendClient::POST, @@ -124,7 +120,7 @@ public function getTestData() public function testRequestSuccess(array $data) { $responseString = 'This is response.'; - + $response = new \Zend_Http_Response(201, [], $responseString); $this->curlMock->expects($this->once()) ->method('write') ->with( @@ -132,7 +128,7 @@ public function testRequestSuccess(array $data) $data['url'], $data['version'], $data['headers'], - $data['version'] + json_encode($data['body']) ); $this->curlMock->expects($this->once()) ->method('read') @@ -144,14 +140,14 @@ public function testRequestSuccess(array $data) $this->responseFactoryMock->expects($this->any()) ->method('create') ->with($responseString) - ->willReturn($this->responseMock); + ->willReturn($response); $this->assertEquals( - $this->responseMock, + $response, $this->subject->request( $data['method'], $data['url'], - $data['version'], + $data['body'], $data['headers'], $data['version'] ) @@ -171,7 +167,7 @@ public function testRequestError(array $data) $data['url'], $data['version'], $data['headers'], - $data['version'] + json_encode($data['body']) ); $this->curlMock->expects($this->once()) ->method('read'); @@ -194,10 +190,26 @@ public function testRequestError(array $data) $this->subject->request( $data['method'], $data['url'], - $data['version'], + $data['body'], $data['headers'], $data['version'] ) ); } + + /** + * @return \PHPUnit_Framework_MockObject_MockObject + */ + private function createJsonConverter() + { + $converterMock = $this->getMockBuilder(ConverterInterface::class) + ->getMockForAbstractClass(); + $converterMock->expects($this->any())->method('toBody')->willReturnCallback(function ($value) { + return json_encode($value); + }); + $converterMock->expects($this->any()) + ->method('getContentTypeHeader') + ->willReturn('Content-Type: application/json'); + return $converterMock; + } } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/NotifyDataChangedCommandTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/NotifyDataChangedCommandTest.php index 87551ec52b26e..42f3d64af6d9d 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/NotifyDataChangedCommandTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/NotifyDataChangedCommandTest.php @@ -39,11 +39,6 @@ class NotifyDataChangedCommandTest extends \PHPUnit_Framework_TestCase */ private $loggerMock; - /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject - */ - private $responseMock; - protected function setUp() { $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) @@ -62,10 +57,6 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->responseMock = $this->getMockBuilder(\Zend_Http_Response::class) - ->disableOriginalConstructor() - ->getMock(); - $this->notifyDataChangedCommand = new NotifyDataChangedCommand( $this->analyticsTokenMock, $this->httpClientMock, @@ -78,7 +69,6 @@ public function testExecuteSuccess() { $configVal = "Config val"; $token = "Secret token!"; - $requestJson = sprintf('{"access-token":"%s","url":"%s"}', $token, $configVal); $this->analyticsTokenMock->expects($this->once()) ->method('isTokenExist') ->willReturn(true); @@ -93,9 +83,8 @@ public function testExecuteSuccess() ->with( ZendClient::POST, $configVal, - $requestJson, - ['Content-Type: application/json'] - )->willReturn($this->responseMock); + ['access-token' => $token, 'url' => $configVal] + )->willReturn(new \Zend_Http_Response(201, [])); $this->assertTrue($this->notifyDataChangedCommand->execute()); } @@ -104,6 +93,8 @@ public function testExecuteWithoutToken() $this->analyticsTokenMock->expects($this->once()) ->method('isTokenExist') ->willReturn(false); - $this->assertFalse($this->notifyDataChangedCommand->execute()); + $this->httpClientMock->expects($this->never()) + ->method('request'); + $this->assertTrue($this->notifyDataChangedCommand->execute()); } } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/OTPRequestTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/OTPRequestTest.php index f8faef12adc77..2644e23e47e0f 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/OTPRequestTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/OTPRequestTest.php @@ -5,92 +5,79 @@ */ namespace Magento\Analytics\Test\Unit\Model\Connector; +use Magento\Analytics\Model\AnalyticsToken; +use Magento\Analytics\Model\Connector\Http\ClientInterface; +use Magento\Analytics\Model\Connector\Http\ResponseResolver; +use Magento\Analytics\Model\Connector\OTPRequest; +use Magento\Framework\App\Config\ScopeConfigInterface; +use Psr\Log\LoggerInterface; + /** * A unit test for testing of the representation of a 'OTP' request. */ class OTPRequestTest extends \PHPUnit_Framework_TestCase { /** - * @var \Magento\Analytics\Model\Connector\OTPRequest + * @var OTPRequest */ private $subject; /** - * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject */ private $loggerMock; /** - * @var \Magento\Framework\App\Config\ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ private $configMock; /** - * @var \Zend_Http_Response|\PHPUnit_Framework_MockObject_MockObject - */ - private $responseMock; - - /** - * @var \Magento\Analytics\Model\Connector\Http\ClientInterface|\PHPUnit_Framework_MockObject_MockObject + * @var ClientInterface|\PHPUnit_Framework_MockObject_MockObject */ private $httpClientMock; /** - * @var \Magento\Analytics\Model\AnalyticsToken|\PHPUnit_Framework_MockObject_MockObject + * @var AnalyticsToken|\PHPUnit_Framework_MockObject_MockObject */ private $analyticsTokenMock; /** - * @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager + * @var ResponseResolver|\PHPUnit_Framework_MockObject_MockObject */ - private $objectManagerHelper; + private $responseResolverMock; /** * @return void */ public function setUp() { - $this->loggerMock = $this->getMockBuilder( - \Psr\Log\LoggerInterface::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->configMock = $this->getMockBuilder( - \Magento\Framework\App\Config\ScopeConfigInterface::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->responseMock = $this->getMockBuilder( - \Zend_Http_Response::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->httpClientMock = $this->getMockBuilder( - \Magento\Analytics\Model\Connector\Http\ClientInterface::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->analyticsTokenMock = $this->getMockBuilder( - \Magento\Analytics\Model\AnalyticsToken::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->objectManagerHelper = - new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - - $this->subject = $this->objectManagerHelper->getObject( - \Magento\Analytics\Model\Connector\OTPRequest::class, - [ - 'analyticsToken' => $this->analyticsTokenMock, - 'config' => $this->configMock, - 'httpClient' => $this->httpClientMock, - 'logger' => $this->loggerMock - ] + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->httpClientMock = $this->getMockBuilder(ClientInterface::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->responseResolverMock = $this->getMockBuilder(ResponseResolver::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->subject = new OTPRequest( + $this->analyticsTokenMock, + $this->httpClientMock, + $this->configMock, + $this->responseResolverMock, + $this->loggerMock ); } @@ -105,9 +92,8 @@ private function getTestData() 'otp' => 'thisisotp', 'url' => 'http://www.mystore.com', 'access-token' => 'thisisaccesstoken', - 'headers' => ['Content-Type: application/json'], 'method' => \Magento\Framework\HTTP\ZendClient::POST, - 'body'=> '{"access-token":"thisisaccesstoken","url":"http:\/\/www.mystore.com"}', + 'body'=> ['access-token' => 'thisisaccesstoken','url' => 'http://www.mystore.com'], ]; } @@ -134,17 +120,12 @@ public function testCallSuccess() ->with( $data['method'], $data['url'], - $data['body'], - $data['headers'] + $data['body'] ) - ->willReturn($this->responseMock); - - $this->responseMock->expects($this->any()) - ->method('getStatus') - ->willReturn(201); - $this->responseMock->expects($this->any()) - ->method('getBody') - ->willReturn('{"otp": "' . $data['otp'] . '"}'); + ->willReturn(new \Zend_Http_Response(201, [])); + $this->responseResolverMock->expects($this->once()) + ->method('getResult') + ->willReturn($data['otp']); $this->assertEquals( $data['otp'], @@ -167,37 +148,6 @@ public function testCallNoAccessToken() $this->assertFalse($this->subject->call()); } - /** - * @return void - */ - public function testCallTransportFailure() - { - $data = $this->getTestData(); - - $this->analyticsTokenMock->expects($this->once()) - ->method('isTokenExist') - ->willReturn(true); - $this->analyticsTokenMock->expects($this->once()) - ->method('getToken') - ->willReturn($data['access-token']); - - $this->configMock->expects($this->any()) - ->method('getValue') - ->willReturn($data['url']); - - $this->httpClientMock->expects($this->once()) - ->method('request') - ->with( - $data['method'], - $data['url'], - $data['body'], - $data['headers'] - ) - ->willReturn(false); - - $this->assertFalse($this->subject->call()); - } - /** * @return void */ @@ -221,55 +171,17 @@ public function testCallNoOtp() ->with( $data['method'], $data['url'], - $data['body'], - $data['headers'] + $data['body'] ) - ->willReturn($this->responseMock); + ->willReturn(new \Zend_Http_Response(0, [])); - $this->responseMock->expects($this->any()) - ->method('getStatus') - ->willReturn(409); + $this->responseResolverMock->expects($this->once()) + ->method('getResult') + ->willReturn(false); $this->loggerMock->expects($this->once()) ->method('warning'); $this->assertFalse($this->subject->call()); } - - /** - * @return void - */ - public function testCallException() - { - $data = $this->getTestData(); - - $exception = new \Exception('Test Exception'); - - $this->analyticsTokenMock->expects($this->once()) - ->method('isTokenExist') - ->willReturn(true); - $this->analyticsTokenMock->expects($this->once()) - ->method('getToken') - ->willReturn($data['access-token']); - - $this->configMock->expects($this->any()) - ->method('getValue') - ->willReturn($data['url']); - - $this->httpClientMock->expects($this->once()) - ->method('request') - ->with( - $data['method'], - $data['url'], - $data['body'], - $data['headers'] - ) - ->willThrowException($exception); - - $this->loggerMock->expects($this->once()) - ->method('critical') - ->with($exception); - - $this->assertFalse($this->subject->call()); - } } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpCommandTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpCommandTest.php index 42d7ea0824ad5..038d53aa6ce1b 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpCommandTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpCommandTest.php @@ -5,12 +5,14 @@ */ namespace Magento\Analytics\Test\Unit\Model\Connector; +use Magento\Analytics\Model\Connector\Http\ClientInterface; +use Magento\Analytics\Model\Connector\Http\ResponseResolver; use Magento\Analytics\Model\Connector\SignUpCommand; -use Magento\Analytics\Model\Connector\SignUpRequest; use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\IntegrationManager; +use Magento\Config\Model\Config; use Magento\Integration\Model\Oauth\Token as IntegrationToken; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; +use Psr\Log\LoggerInterface; /** * Class SignUpCommandTest @@ -38,9 +40,24 @@ class SignUpCommandTest extends \PHPUnit_Framework_TestCase private $integrationToken; /** - * @var SignUpRequest|\PHPUnit_Framework_MockObject_MockObject + * @var Config|\PHPUnit_Framework_MockObject_MockObject */ - private $signUpRequestMock; + private $configMock; + + /** + * @var ClientInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $httpClientMock; + + /** + * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + */ + private $loggerMock; + + /** + * @var ResponseResolver|\PHPUnit_Framework_MockObject_MockObject + */ + private $responseResolverMock; protected function setUp() { @@ -52,22 +69,27 @@ protected function setUp() ->getMock(); $this->integrationToken = $this->getMockBuilder(IntegrationToken::class) ->disableOriginalConstructor() - ->setMethods(['getToken']) ->getMock(); - $this->integrationToken->expects($this->any()) - ->method('getToken') - ->willReturn('IntegrationToken'); - $this->signUpRequestMock = $this->getMockBuilder(SignUpRequest::class) + $this->configMock = $this->getMockBuilder(Config::class) + ->disableOriginalConstructor() + ->getMock(); + $this->httpClientMock = $this->getMockBuilder(ClientInterface::class) + ->disableOriginalConstructor() + ->getMock(); + $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() ->getMock(); - $objectManagerHelper = new ObjectManagerHelper($this); - $this->signUpCommand = $objectManagerHelper->getObject( - SignUpCommand::class, - [ - 'analyticsToken' => $this->analyticsTokenMock, - 'integrationManager' => $this->integrationManagerMock, - 'signUpRequest' => $this->signUpRequestMock - ] + $this->responseResolverMock = $this->getMockBuilder(ResponseResolver::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->signUpCommand = new SignUpCommand( + $this->analyticsTokenMock, + $this->integrationManagerMock, + $this->configMock, + $this->httpClientMock, + $this->loggerMock, + $this->responseResolverMock ); } @@ -79,13 +101,27 @@ public function testExecuteSuccess() $this->integrationManagerMock->expects($this->once()) ->method('activateIntegration') ->willReturn(true); - $this->signUpRequestMock->expects($this->once()) - ->method('call') - ->with('IntegrationToken') - ->willReturn('MAToken'); - $this->analyticsTokenMock->expects($this->once()) - ->method('storeToken') - ->with('MAToken') + $data = $this->getTestData(); + + $this->configMock->expects($this->any()) + ->method('getConfigDataValue') + ->willReturn($data['url']); + $this->integrationToken->expects($this->once()) + ->method('getData') + ->with('token') + ->willReturn($data['integration-token']); + $httpResponse = new \Zend_Http_Response(201, [], '{"access-token": "' . $data['access-token'] . '"}'); + $this->httpClientMock->expects($this->once()) + ->method('request') + ->with( + $data['method'], + $data['url'], + $data['body'] + ) + ->willReturn($httpResponse); + $this->responseResolverMock->expects($this->once()) + ->method('getResult') + ->with($httpResponse) ->willReturn(true); $this->assertTrue($this->signUpCommand->execute()); } @@ -96,14 +132,7 @@ public function testExecuteFailureCannotGenerateToken() ->method('generateToken') ->willReturn(false); $this->integrationManagerMock->expects($this->never()) - ->method('activateIntegration') - ->willReturn(true); - $this->signUpRequestMock->expects($this->never()) - ->method('call') - ->willReturn('MAToken'); - $this->analyticsTokenMock->expects($this->never()) - ->method('storeToken') - ->willReturn(true); + ->method('activateIntegration'); $this->assertFalse($this->signUpCommand->execute()); } @@ -115,12 +144,30 @@ public function testExecuteFailureResponseIsEmpty() $this->integrationManagerMock->expects($this->once()) ->method('activateIntegration') ->willReturn(true); - $this->signUpRequestMock->expects($this->once()) - ->method('call') - ->with('IntegrationToken') + $httpResponse = new \Zend_Http_Response(0, []); + $this->httpClientMock->expects($this->once()) + ->method('request') + ->willReturn($httpResponse); + $this->responseResolverMock->expects($this->once()) + ->method('getResult') ->willReturn(false); - $this->analyticsTokenMock->expects($this->never()) - ->method('storeToken'); $this->assertFalse($this->signUpCommand->execute()); } + + /** + * Returns test parameters for request. + * + * @return array + */ + private function getTestData() + { + return [ + 'url' => 'http://www.mystore.com', + 'access-token' => 'thisisaccesstoken', + 'integration-token' => 'thisisintegrationtoken', + 'headers' => ['Content-Type: application/json'], + 'method' => \Magento\Framework\HTTP\ZendClient::POST, + 'body'=> ['token' => 'thisisintegrationtoken','url' => 'http://www.mystore.com'], + ]; + } } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpRequestTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpRequestTest.php deleted file mode 100644 index 98ea13e092fa6..0000000000000 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpRequestTest.php +++ /dev/null @@ -1,226 +0,0 @@ -loggerMock = $this->getMockBuilder( - \Psr\Log\LoggerInterface::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->configMock = $this->getMockBuilder( - \Magento\Config\Model\Config::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->responseMock = $this->getMockBuilder( - \Zend_Http_Response::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->httpClientMock = $this->getMockBuilder( - \Magento\Analytics\Model\Connector\Http\ClientInterface::class - ) - ->disableOriginalConstructor() - ->getMock(); - - $this->objectManagerHelper = - new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this); - - $this->subject = $this->objectManagerHelper->getObject( - \Magento\Analytics\Model\Connector\SignUpRequest::class, - [ - 'config' => $this->configMock, - 'httpClient' => $this->httpClientMock, - 'logger' => $this->loggerMock - ] - ); - } - - /** - * Returns test parameters for request. - * - * @return array - */ - private function getTestData() - { - return [ - 'url' => 'http://www.mystore.com', - 'access-token' => 'thisisaccesstoken', - 'integration-token' => 'thisisintegrationtoken', - 'headers' => ['Content-Type: application/json'], - 'method' => \Magento\Framework\HTTP\ZendClient::POST, - 'body'=> '{"token":"thisisintegrationtoken","url":"http:\/\/www.mystore.com"}', - ]; - } - - /** - * @return void - */ - public function testCallSuccess() - { - $data = $this->getTestData(); - - $this->configMock->expects($this->any()) - ->method('getConfigDataValue') - ->willReturn($data['url']); - - $this->httpClientMock->expects($this->once()) - ->method('request') - ->with( - $data['method'], - $data['url'], - $data['body'], - $data['headers'] - ) - ->willReturn($this->responseMock); - - $this->responseMock->expects($this->any()) - ->method('getStatus') - ->willReturn(201); - $this->responseMock->expects($this->any()) - ->method('getBody') - ->willReturn('{"access-token": "' . $data['access-token'] . '"}'); - - $this->assertEquals( - $data['access-token'], - $this->subject->call($data['integration-token']) - ); - } - - /** - * @return void - */ - public function testCallTransportFailure() - { - $data = $this->getTestData(); - - $this->configMock->expects($this->any()) - ->method('getConfigDataValue') - ->willReturn($data['url']); - - $this->httpClientMock->expects($this->once()) - ->method('request') - ->with( - $data['method'], - $data['url'], - $data['body'], - $data['headers'] - ) - ->willReturn(false); - - $this->assertFalse( - $this->subject->call($data['integration-token']) - ); - } - - /** - * @return void - */ - public function testCallNoAccessToken() - { - $data = $this->getTestData(); - - $this->configMock->expects($this->any()) - ->method('getConfigDataValue') - ->willReturn($data['url']); - - $this->httpClientMock->expects($this->once()) - ->method('request') - ->with( - $data['method'], - $data['url'], - $data['body'], - $data['headers'] - ) - ->willReturn($this->responseMock); - - $this->responseMock->expects($this->any()) - ->method('getStatus') - ->willReturn(409); - - $this->loggerMock->expects($this->once()) - ->method('warning'); - - $this->assertFalse( - $this->subject->call($data['integration-token']) - ); - } - - /** - * @return void - */ - public function testCallException() - { - $data = $this->getTestData(); - - $exception = new \Exception('Test Exception'); - - $this->configMock->expects($this->any()) - ->method('getConfigDataValue') - ->willReturn($data['url']); - - $this->httpClientMock->expects($this->once()) - ->method('request') - ->with( - $data['method'], - $data['url'], - $data['body'], - $data['headers'] - ) - ->willThrowException($exception); - - $this->loggerMock->expects($this->once()) - ->method('critical') - ->with($exception); - - $this->assertFalse( - $this->subject->call($data['integration-token']) - ); - } -} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/UpdateCommandTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/UpdateCommandTest.php index f16944d2f3417..afc7f50906ebd 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/UpdateCommandTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/UpdateCommandTest.php @@ -6,6 +6,7 @@ namespace Magento\Analytics\Test\Unit\Model\Connector; use Magento\Analytics\Model\AnalyticsToken; +use Magento\Analytics\Model\Connector\Http\ResponseResolver; use Magento\Analytics\Model\FlagManager; use Magento\Framework\HTTP\ZendClient; use Magento\Config\Model\Config; @@ -45,14 +46,14 @@ class UpdateCommandTest extends \PHPUnit_Framework_TestCase private $loggerMock; /** - * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject + * @var FlagManager|\PHPUnit_Framework_MockObject_MockObject */ - private $responseMock; + private $flagManagerMock; /** - * @var FlagManager|\PHPUnit_Framework_MockObject_MockObject + * @var ResponseResolver|\PHPUnit_Framework_MockObject_MockObject */ - private $flagManagerMock; + private $responseResolverMock; protected function setUp() { @@ -76,16 +77,17 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->responseMock = $this->getMockBuilder(\Zend_Http_Response::class) + $this->responseResolverMock = $this->getMockBuilder(ResponseResolver::class) ->disableOriginalConstructor() ->getMock(); - + $this->updateCommand = new UpdateCommand( $this->analyticsTokenMock, $this->httpClientMock, $this->configMock, $this->loggerMock, - $this->flagManagerMock + $this->flagManagerMock, + $this->responseResolverMock ); } @@ -94,7 +96,6 @@ public function testExecuteSuccess() $url = "old.localhost.com"; $configVal = "Config val"; $token = "Secret token!"; - $requestJson = sprintf('{"url":"%s","new-url":"%s","access-token":"%s"}', $url, $configVal, $token); $this->analyticsTokenMock->expects($this->once()) ->method('isTokenExist') ->willReturn(true); @@ -117,13 +118,16 @@ public function testExecuteSuccess() ->with( ZendClient::PUT, $configVal, - $requestJson, - ['Content-Type: application/json'] - )->willReturn($this->responseMock); - - $this->responseMock->expects($this->once()) - ->method('getStatus') - ->willReturn(201); + [ + 'url' => $url, + 'new-url' => $configVal, + 'access-token' => $token + ] + )->willReturn(new \Zend_Http_Response(200, [])); + + $this->responseResolverMock->expects($this->once()) + ->method('getResult') + ->willReturn(true); $this->assertTrue($this->updateCommand->execute()); } From 3d96bdaa9918a7647f6fd1264a396705591c6cca Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Sun, 26 Mar 2017 20:18:55 +0300 Subject: [PATCH 08/44] MAGETWO-66528: Add response handler Add new unit tests. --- .../Model/Connector/Http/ResponseResolver.php | 2 +- .../Connector/Http/JsonConverterTest.php | 36 ++++++++++++++++ .../Connector/Http/ResponseResolverTest.php | 42 +++++++++++++++++++ .../Connector/ResponseHandler/OTPTest.php | 22 ++++++++++ .../ResponseHandler/ReSignUpTest.php | 31 ++++++++++++++ .../Connector/ResponseHandler/SignUpTest.php | 30 +++++++++++++ .../Connector/ResponseHandler/UpdateTest.php | 20 +++++++++ 7 files changed, 182 insertions(+), 1 deletion(-) create mode 100644 app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/JsonConverterTest.php create mode 100644 app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/ResponseResolverTest.php create mode 100644 app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/OTPTest.php create mode 100644 app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php create mode 100644 app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php create mode 100644 app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/UpdateTest.php diff --git a/app/code/Magento/Analytics/Model/Connector/Http/ResponseResolver.php b/app/code/Magento/Analytics/Model/Connector/Http/ResponseResolver.php index b554bafb35f0e..411de34d4ded5 100644 --- a/app/code/Magento/Analytics/Model/Connector/Http/ResponseResolver.php +++ b/app/code/Magento/Analytics/Model/Connector/Http/ResponseResolver.php @@ -40,7 +40,7 @@ public function getResult(\Zend_Http_Response $response) $result = false; $responseBody = $this->converter->fromBody($response->getBody()); if (array_key_exists($response->getStatus(), $this->responseHandlers)) { - $result = $this->responseHandlers[$response->getStatus()]->handle($responseBody); + $result = $this->responseHandlers[$response->getStatus()]->handleResponse($responseBody); } return $result; diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/JsonConverterTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/JsonConverterTest.php new file mode 100644 index 0000000000000..d23ea2e3b98fa --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/JsonConverterTest.php @@ -0,0 +1,36 @@ +jsonApplicationHeader); + $this->assertEquals($this->jsonApplicationHeader, $converter->getContentTypeHeader()); + } + + public function testConvertBody() + { + $body = '{"token": "secret-token"}'; + $converter = new JsonConverter($this->jsonApplicationHeader); + $this->assertEquals(json_decode($body, 1), $converter->fromBody($body)); + } + + public function testConvertData() + { + $data = ["token" => "secret-token"]; + $converter = new JsonConverter($this->jsonApplicationHeader); + $this->assertEquals(json_encode($data), $converter->toBody($data)); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/ResponseResolverTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/ResponseResolverTest.php new file mode 100644 index 0000000000000..d2e35b9d5803b --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/ResponseResolverTest.php @@ -0,0 +1,42 @@ + 'testValue']; + $response = new \Zend_Http_Response(201, [], json_encode($expectedBody)); + $responseHandlerMock = $this->getMockBuilder(ResponseHandlerInterface::class) + ->getMockForAbstractClass(); + $responseHandlerMock->expects($this->once()) + ->method('handleResponse') + ->with($expectedBody) + ->willReturn(true); + $notFoundResponseHandlerMock = $this->getMockBuilder(ResponseHandlerInterface::class) + ->getMockForAbstractClass(); + $notFoundResponseHandlerMock->expects($this->never()) + ->method('handleResponse') + ->with($expectedBody) + ->willReturn(false); + $responseResolver = new ResponseResolver( + new JsonConverter('Content-Type: application/json'), + [ + 201 => $responseHandlerMock, + 404 => $notFoundResponseHandlerMock, + ] + ); + $this->assertTrue($responseResolver->getResult($response)); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/OTPTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/OTPTest.php new file mode 100644 index 0000000000000..aeffacc128d0f --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/OTPTest.php @@ -0,0 +1,22 @@ +assertFalse($OTPHandler->handleResponse([])); + $expectedOtp = 123; + $this->assertEquals($expectedOtp, $OTPHandler->handleResponse(['otp' => $expectedOtp])); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php new file mode 100644 index 0000000000000..7dc1ba9750712 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php @@ -0,0 +1,31 @@ +getMockBuilder(AnalyticsToken::class) + ->disableOriginalConstructor() + ->getMock(); + $analyticsToken->expects($this->once()) + ->method('storeToken') + ->with(null); + $subscription = $this->getMockBuilder(Subscription::class) + ->disableOriginalConstructor() + ->getMock(); + $reSignUpHandler = new ReSignUp($analyticsToken, $subscription); + $this->assertFalse($reSignUpHandler->handleResponse([])); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php new file mode 100644 index 0000000000000..eeb482356ac42 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php @@ -0,0 +1,30 @@ +getMockBuilder(AnalyticsToken::class) + ->disableOriginalConstructor() + ->getMock(); + $analyticsToken->expects($this->once()) + ->method('storeToken') + ->with($accessToken); + $signUpHandler = new SignUp($analyticsToken, new JsonConverter('Content-Type: application/json')); + $this->assertFalse($signUpHandler->handleResponse([])); + $this->assertEquals($accessToken, $signUpHandler->handleResponse(['access-token' => $accessToken])); + } +} diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/UpdateTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/UpdateTest.php new file mode 100644 index 0000000000000..c06a687b90431 --- /dev/null +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/UpdateTest.php @@ -0,0 +1,20 @@ +assertTrue($updateHandler->handleResponse([])); + } +} From b8d57121d9c08b4384c27035cd14218fbcd8c7f8 Mon Sep 17 00:00:00 2001 From: Max Lesechko Date: Mon, 27 Mar 2017 16:38:51 +0300 Subject: [PATCH 09/44] MAGETWO-66783: Expand data provided in Analytics reports --- app/code/Magento/SalesAnalytics/etc/reports.xml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/code/Magento/SalesAnalytics/etc/reports.xml b/app/code/Magento/SalesAnalytics/etc/reports.xml index 1d94a878a7b78..530d284491546 100644 --- a/app/code/Magento/SalesAnalytics/etc/reports.xml +++ b/app/code/Magento/SalesAnalytics/etc/reports.xml @@ -24,6 +24,8 @@ + + From 8dae2866fcbeb32f745ccef4153775768ca9354f Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Mon, 27 Mar 2017 18:07:52 +0300 Subject: [PATCH 10/44] MAGETWO-66798: Create integration test Create integration for analytics resubscribe handler. --- .../Http/ReSignUpResponseResolverTest.php | 135 ++++++++++++++++++ .../_files/create_failed_subscription.php | 29 ++++ 2 files changed, 164 insertions(+) create mode 100644 dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php create mode 100644 dev/tests/integration/testsuite/Magento/Analytics/_files/create_failed_subscription.php diff --git a/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php b/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php new file mode 100644 index 0000000000000..960de8e649948 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php @@ -0,0 +1,135 @@ +otpResponseResolver = Bootstrap::getObjectManager()->get( + 'OtpResponseResolver' + ); + $this->updateResponseResolver = Bootstrap::getObjectManager()->get( + 'UpdateResponseResolver' + ); + $this->converter = Bootstrap::getObjectManager()->get(ConverterInterface::class); + } + + /** + * @magentoDataFixture Magento/Analytics/_files/create_failed_subscription.php + */ + public function testReSignUpOnOtp() + { + $body = $this->converter->toBody(['test' => '42']); + $retryResponse = new \Zend_Http_Response(401, [$this->converter->getContentTypeHeader()], $body); + $this->otpResponseResolver->getResult($retryResponse); + $this->assertCronWasSet(); + } + + /** + * @magentoDataFixture Magento/Analytics/_files/create_failed_subscription.php + */ + public function testReSignOnOtpWasNotCalled() + { + $body = $this->converter->toBody(['test' => '42']); + $successResponse = new \Zend_Http_Response(201, [$this->converter->getContentTypeHeader()], $body); + $this->otpResponseResolver->getResult($successResponse); + $this->assertCronWasNotSet(); + } + + /** + * @magentoDataFixture Magento/Analytics/_files/create_failed_subscription.php + */ + public function testReSignUpOnUpdateWasCalled() + { + $body = $this->converter->toBody(['test' => '42']); + $retryResponse = new \Zend_Http_Response(401, [$this->converter->getContentTypeHeader()], $body); + $this->updateResponseResolver->getResult($retryResponse); + $this->assertCronWasSet(); + } + + /** + * @magentoDataFixture Magento/Analytics/_files/create_failed_subscription.php + */ + public function testReSignUpOnUpdateWasnotCalled() + { + $body = $this->converter->toBody(['test' => '42']); + $successResponse = new \Zend_Http_Response(201, [$this->converter->getContentTypeHeader()], $body); + $this->updateResponseResolver->getResult($successResponse); + $this->assertCronWasNotSet(); + } + + /** + * @return string|null + */ + private function getSubscribeSchedule() + { + $objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); + /** + * @var $scopeConfig ScopeConfigInterface + */ + $scopeConfig = $objectManager->get(ScopeConfigInterface::class); + return $scopeConfig->getValue(SubscriptionHandler::CRON_STRING_PATH); + } + + /** + * @return int|null + */ + private function getAttemptFlag() + { + $objectManager = Bootstrap::getObjectManager(); + /** + * @var $flagManager FlagManager + */ + $flagManager = $objectManager->get(FlagManager::class); + + return $flagManager->getFlagData(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE); + } + + /** + * @return void + */ + private function assertCronWasSet() + { + $this->assertEquals('0 * * * *', $this->getSubscribeSchedule()); + $this->assertGreaterThan(1, $this->getAttemptFlag()); + } + + /** + * @return void + */ + private function assertCronWasNotSet() + { + $this->assertNull($this->getSubscribeSchedule()); + $this->assertNull($this->getAttemptFlag()); + } +} diff --git a/dev/tests/integration/testsuite/Magento/Analytics/_files/create_failed_subscription.php b/dev/tests/integration/testsuite/Magento/Analytics/_files/create_failed_subscription.php new file mode 100644 index 0000000000000..76bf0c7120abc --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Analytics/_files/create_failed_subscription.php @@ -0,0 +1,29 @@ +get(\Magento\Framework\App\Config\Storage\WriterInterface::class); + +$configWriter->delete(SubscriptionHandler::CRON_STRING_PATH); +$configWriter->save('default/analytics/subscription/enabled', 1); + +/** + * @var $analyticsToken \Magento\Analytics\Model\AnalyticsToken + */ +$analyticsToken = $objectManager->get(\Magento\Analytics\Model\AnalyticsToken::class); +$analyticsToken->storeToken(null); + +/** + * @var $flagManager \Magento\Analytics\Model\FlagManager + */ +$flagManager = $objectManager->get(\Magento\Analytics\Model\FlagManager::class); + +$flagManager->deleteFlag(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE); From a4a8fc25cf2d29b8855552610fffa30807f8e6e8 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Mon, 27 Mar 2017 18:50:10 +0300 Subject: [PATCH 11/44] MAGETWO-66528: Add response handler Fix review comments. --- app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php | 2 +- .../Magento/Analytics/Model/Connector/Http/JsonConverter.php | 2 -- .../Magento/Analytics/Model/Connector/Http/ResponseResolver.php | 2 +- 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php b/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php index 038fc6382d805..222719fd23606 100644 --- a/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php +++ b/app/code/Magento/Analytics/Model/Connector/Http/Client/Curl.php @@ -81,7 +81,7 @@ public function request($method, $url, array $body = [], array $headers = [], $v ) ); - return false; + return $response; } $response = $this->responseFactory->create($result); diff --git a/app/code/Magento/Analytics/Model/Connector/Http/JsonConverter.php b/app/code/Magento/Analytics/Model/Connector/Http/JsonConverter.php index 0793daf5e86fe..e2d6fd35b1e2e 100644 --- a/app/code/Magento/Analytics/Model/Connector/Http/JsonConverter.php +++ b/app/code/Magento/Analytics/Model/Connector/Http/JsonConverter.php @@ -16,8 +16,6 @@ class JsonConverter implements ConverterInterface private $contentTypeHeader; /** - * JsonConverter constructor. - * * @param string $contentTypeHeader */ public function __construct($contentTypeHeader) diff --git a/app/code/Magento/Analytics/Model/Connector/Http/ResponseResolver.php b/app/code/Magento/Analytics/Model/Connector/Http/ResponseResolver.php index 411de34d4ded5..7979c09458741 100644 --- a/app/code/Magento/Analytics/Model/Connector/Http/ResponseResolver.php +++ b/app/code/Magento/Analytics/Model/Connector/Http/ResponseResolver.php @@ -24,7 +24,7 @@ class ResponseResolver * @param ConverterInterface $converter * @param ResponseHandlerInterface[] $responseHandlers */ - public function __construct(ConverterInterface $converter, $responseHandlers = []) + public function __construct(ConverterInterface $converter, array $responseHandlers = []) { $this->converter = $converter; $this->responseHandlers = $responseHandlers; From 24f00d1702f206a01cf334ed25fe5b4c14a11549 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Mon, 27 Mar 2017 18:52:29 +0300 Subject: [PATCH 12/44] MAGETWO-66528: Add response handler Fix review comments. --- .../Magento/Analytics/Model/Connector/Http/ClientInterface.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/Analytics/Model/Connector/Http/ClientInterface.php b/app/code/Magento/Analytics/Model/Connector/Http/ClientInterface.php index 28f60833a0d0c..022416e7a369b 100644 --- a/app/code/Magento/Analytics/Model/Connector/Http/ClientInterface.php +++ b/app/code/Magento/Analytics/Model/Connector/Http/ClientInterface.php @@ -23,7 +23,7 @@ interface ClientInterface * @param array $headers * @param string $version * - * @return \Zend_Http_Response|false + * @return \Zend_Http_Response */ public function request($method, $url, array $body = [], array $headers = [], $version = '1.1'); } From 1ea838ce05ab5e98c218d633a8098fb2b0c60d73 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Tue, 28 Mar 2017 12:02:54 +0300 Subject: [PATCH 13/44] MAGETWO-66528: Add response handler Fix review comments. --- .../Model/Connector/Http/JsonConverter.php | 17 ++++--------- .../Connector/ResponseHandler/ReSignUp.php | 25 +++++++++++++------ .../Model/Connector/Http/Client/CurlTest.php | 9 ++++--- .../Connector/Http/JsonConverterTest.php | 10 +++----- .../Connector/Http/ResponseResolverTest.php | 7 ++---- .../ResponseHandler/ReSignUpTest.php | 7 +++++- .../Connector/ResponseHandler/SignUpTest.php | 2 +- .../Model/Connector/SignUpCommandTest.php | 9 ++++--- app/code/Magento/Analytics/etc/di.xml | 9 ++----- 9 files changed, 49 insertions(+), 46 deletions(-) diff --git a/app/code/Magento/Analytics/Model/Connector/Http/JsonConverter.php b/app/code/Magento/Analytics/Model/Connector/Http/JsonConverter.php index e2d6fd35b1e2e..594469074264a 100644 --- a/app/code/Magento/Analytics/Model/Connector/Http/JsonConverter.php +++ b/app/code/Magento/Analytics/Model/Connector/Http/JsonConverter.php @@ -11,17 +11,9 @@ class JsonConverter implements ConverterInterface { /** - * @var string + * Content-Type HTTP header for json. */ - private $contentTypeHeader; - - /** - * @param string $contentTypeHeader - */ - public function __construct($contentTypeHeader) - { - $this->contentTypeHeader = $contentTypeHeader; - } + const CONTENT_TYPE_HEADER = 'Content-Type: application/json'; /** * @param string $body @@ -30,7 +22,8 @@ public function __construct($contentTypeHeader) */ public function fromBody($body) { - return json_decode($body, 1); + $decodedBody = json_decode($body, 1); + return $decodedBody === null ? [$body] : $decodedBody; } /** @@ -48,6 +41,6 @@ public function toBody(array $data) */ public function getContentTypeHeader() { - return $this->contentTypeHeader; + return self::CONTENT_TYPE_HEADER; } } diff --git a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php index b50dc14cf056b..b34b2b7a7c9a1 100644 --- a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php +++ b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php @@ -8,6 +8,7 @@ use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\Connector\Http\ResponseHandlerInterface; use Magento\Analytics\Model\Subscription; +use Magento\Analytics\Model\SubscriptionStatusProvider; /** * Removes stored token and triggers subscription process. @@ -24,25 +25,35 @@ class ReSignUp implements ResponseHandlerInterface */ private $subscription; + /** + * @var SubscriptionStatusProvider + */ + private $subscriptionStatusProvider; + /** * @param AnalyticsToken $analyticsToken * @param Subscription $subscription + * @param SubscriptionStatusProvider $subscriptionStatusProvider */ - public function __construct(AnalyticsToken $analyticsToken, Subscription $subscription) - { + public function __construct( + AnalyticsToken $analyticsToken, + Subscription $subscription, + SubscriptionStatusProvider $subscriptionStatusProvider + ) { $this->analyticsToken = $analyticsToken; $this->subscription = $subscription; + $this->subscriptionStatusProvider = $subscriptionStatusProvider; } /** - * @param array $responseBody - * - * @return bool|string + * @inheritdoc */ public function handleResponse(array $responseBody) { - $this->analyticsToken->storeToken(null); - $this->subscription->retry(); + if ($this->subscriptionStatusProvider->getStatus() === SubscriptionStatusProvider::ENABLED) { + $this->analyticsToken->storeToken(null); + $this->subscription->retry(); + } return false; } } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/Client/CurlTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/Client/CurlTest.php index 14602a918481b..8904aa14476c2 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/Client/CurlTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/Client/CurlTest.php @@ -6,6 +6,7 @@ namespace Magento\Analytics\Test\Unit\Model\Connector\Http\Client; use Magento\Analytics\Model\Connector\Http\ConverterInterface; +use Magento\Analytics\Model\Connector\Http\JsonConverter; use Magento\Framework\HTTP\Adapter\CurlFactory; /** @@ -106,7 +107,7 @@ public function getTestData() 'version' => '1.1', 'body'=> ['name' => 'value'], 'url' => 'http://www.mystore.com', - 'headers' => ['Content-Type: application/json'], + 'headers' => [JsonConverter::CONTENT_TYPE_HEADER], 'method' => \Magento\Framework\HTTP\ZendClient::POST, ] ] @@ -160,6 +161,7 @@ public function testRequestSuccess(array $data) */ public function testRequestError(array $data) { + $response = new \Zend_Http_Response(0, []); $this->curlMock->expects($this->once()) ->method('write') ->with( @@ -186,7 +188,8 @@ public function testRequestError(array $data) ) ); - $this->assertFalse( + $this->assertEquals( + $response, $this->subject->request( $data['method'], $data['url'], @@ -209,7 +212,7 @@ private function createJsonConverter() }); $converterMock->expects($this->any()) ->method('getContentTypeHeader') - ->willReturn('Content-Type: application/json'); + ->willReturn(JsonConverter::CONTENT_TYPE_HEADER); return $converterMock; } } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/JsonConverterTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/JsonConverterTest.php index d23ea2e3b98fa..37de4f8089f89 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/JsonConverterTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/JsonConverterTest.php @@ -12,25 +12,23 @@ */ class JsonConverterTest extends \PHPUnit_Framework_TestCase { - private $jsonApplicationHeader = 'Content-Type: application/json'; - public function testConverterContainsHeader() { - $converter = new JsonConverter($this->jsonApplicationHeader); - $this->assertEquals($this->jsonApplicationHeader, $converter->getContentTypeHeader()); + $converter = new JsonConverter(); + $this->assertEquals(JsonConverter::CONTENT_TYPE_HEADER, $converter->getContentTypeHeader()); } public function testConvertBody() { $body = '{"token": "secret-token"}'; - $converter = new JsonConverter($this->jsonApplicationHeader); + $converter = new JsonConverter(); $this->assertEquals(json_decode($body, 1), $converter->fromBody($body)); } public function testConvertData() { $data = ["token" => "secret-token"]; - $converter = new JsonConverter($this->jsonApplicationHeader); + $converter = new JsonConverter(); $this->assertEquals(json_encode($data), $converter->toBody($data)); } } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/ResponseResolverTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/ResponseResolverTest.php index d2e35b9d5803b..243767e3b0140 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/ResponseResolverTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/Http/ResponseResolverTest.php @@ -26,12 +26,9 @@ public function testGetResultHandleResponseSuccess() ->willReturn(true); $notFoundResponseHandlerMock = $this->getMockBuilder(ResponseHandlerInterface::class) ->getMockForAbstractClass(); - $notFoundResponseHandlerMock->expects($this->never()) - ->method('handleResponse') - ->with($expectedBody) - ->willReturn(false); + $notFoundResponseHandlerMock->expects($this->never())->method('handleResponse'); $responseResolver = new ResponseResolver( - new JsonConverter('Content-Type: application/json'), + new JsonConverter(), [ 201 => $responseHandlerMock, 404 => $notFoundResponseHandlerMock, diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php index 7dc1ba9750712..b65d565a798f1 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php @@ -8,6 +8,7 @@ use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\Connector\ResponseHandler\ReSignUp; use Magento\Analytics\Model\Subscription; +use Magento\Analytics\Model\SubscriptionStatusProvider; /** * Class ReSignUpTest @@ -25,7 +26,11 @@ public function testHandleResult() $subscription = $this->getMockBuilder(Subscription::class) ->disableOriginalConstructor() ->getMock(); - $reSignUpHandler = new ReSignUp($analyticsToken, $subscription); + $subscriptionStatusProvider = $this->getMockBuilder(SubscriptionStatusProvider::class) + ->disableOriginalConstructor() + ->getMock(); + $subscriptionStatusProvider->method('getStatus')->willReturn(SubscriptionStatusProvider::ENABLED); + $reSignUpHandler = new ReSignUp($analyticsToken, $subscription, $subscriptionStatusProvider); $this->assertFalse($reSignUpHandler->handleResponse([])); } } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php index eeb482356ac42..f006693c668ac 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php @@ -23,7 +23,7 @@ public function testHandleResult() $analyticsToken->expects($this->once()) ->method('storeToken') ->with($accessToken); - $signUpHandler = new SignUp($analyticsToken, new JsonConverter('Content-Type: application/json')); + $signUpHandler = new SignUp($analyticsToken, new JsonConverter()); $this->assertFalse($signUpHandler->handleResponse([])); $this->assertEquals($accessToken, $signUpHandler->handleResponse(['access-token' => $accessToken])); } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpCommandTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpCommandTest.php index 038d53aa6ce1b..12484942e041e 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpCommandTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpCommandTest.php @@ -6,6 +6,7 @@ namespace Magento\Analytics\Test\Unit\Model\Connector; use Magento\Analytics\Model\Connector\Http\ClientInterface; +use Magento\Analytics\Model\Connector\Http\JsonConverter; use Magento\Analytics\Model\Connector\Http\ResponseResolver; use Magento\Analytics\Model\Connector\SignUpCommand; use Magento\Analytics\Model\AnalyticsToken; @@ -106,7 +107,7 @@ public function testExecuteSuccess() $this->configMock->expects($this->any()) ->method('getConfigDataValue') ->willReturn($data['url']); - $this->integrationToken->expects($this->once()) + $this->integrationToken->expects($this->any()) ->method('getData') ->with('token') ->willReturn($data['integration-token']); @@ -119,7 +120,7 @@ public function testExecuteSuccess() $data['body'] ) ->willReturn($httpResponse); - $this->responseResolverMock->expects($this->once()) + $this->responseResolverMock->expects($this->any()) ->method('getResult') ->with($httpResponse) ->willReturn(true); @@ -148,7 +149,7 @@ public function testExecuteFailureResponseIsEmpty() $this->httpClientMock->expects($this->once()) ->method('request') ->willReturn($httpResponse); - $this->responseResolverMock->expects($this->once()) + $this->responseResolverMock->expects($this->any()) ->method('getResult') ->willReturn(false); $this->assertFalse($this->signUpCommand->execute()); @@ -165,7 +166,7 @@ private function getTestData() 'url' => 'http://www.mystore.com', 'access-token' => 'thisisaccesstoken', 'integration-token' => 'thisisintegrationtoken', - 'headers' => ['Content-Type: application/json'], + 'headers' => [JsonConverter::CONTENT_TYPE_HEADER], 'method' => \Magento\Framework\HTTP\ZendClient::POST, 'body'=> ['token' => 'thisisintegrationtoken','url' => 'http://www.mystore.com'], ]; diff --git a/app/code/Magento/Analytics/etc/di.xml b/app/code/Magento/Analytics/etc/di.xml index 0f25c1e986f4e..65614c3580356 100644 --- a/app/code/Magento/Analytics/etc/di.xml +++ b/app/code/Magento/Analytics/etc/di.xml @@ -148,11 +148,6 @@ - - - Content-Type: application/json - - @@ -186,9 +181,9 @@ UpdateResponseResolver - + - UpdateResponseResolver + OtpResponseResolver From 694d438b103deaf71d22cb89573efe7597e91861 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Tue, 28 Mar 2017 15:19:43 +0300 Subject: [PATCH 14/44] MAGETWO-66798: Create integration test Fix review comments. --- .../Http/ReSignUpResponseResolverTest.php | 8 ++--- ...abled_subscription_with_invalid_token.php} | 2 +- ...bscription_with_invalid_token_rollback.php | 29 +++++++++++++++++++ 3 files changed, 34 insertions(+), 5 deletions(-) rename dev/tests/integration/testsuite/Magento/Analytics/_files/{create_failed_subscription.php => enabled_subscription_with_invalid_token.php} (96%) create mode 100644 dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php diff --git a/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php b/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php index 960de8e649948..492d45606880c 100644 --- a/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php +++ b/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php @@ -45,7 +45,7 @@ protected function setUp() } /** - * @magentoDataFixture Magento/Analytics/_files/create_failed_subscription.php + * @magentoDataFixture Magento/Analytics/_files/enabled_subscription_with_invalid_token.php */ public function testReSignUpOnOtp() { @@ -56,7 +56,7 @@ public function testReSignUpOnOtp() } /** - * @magentoDataFixture Magento/Analytics/_files/create_failed_subscription.php + * @magentoDataFixture Magento/Analytics/_files/enabled_subscription_with_invalid_token.php */ public function testReSignOnOtpWasNotCalled() { @@ -67,7 +67,7 @@ public function testReSignOnOtpWasNotCalled() } /** - * @magentoDataFixture Magento/Analytics/_files/create_failed_subscription.php + * @magentoDataFixture Magento/Analytics/_files/enabled_subscription_with_invalid_token.php */ public function testReSignUpOnUpdateWasCalled() { @@ -78,7 +78,7 @@ public function testReSignUpOnUpdateWasCalled() } /** - * @magentoDataFixture Magento/Analytics/_files/create_failed_subscription.php + * @magentoDataFixture Magento/Analytics/_files/enabled_subscription_with_invalid_token.php */ public function testReSignUpOnUpdateWasnotCalled() { diff --git a/dev/tests/integration/testsuite/Magento/Analytics/_files/create_failed_subscription.php b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token.php similarity index 96% rename from dev/tests/integration/testsuite/Magento/Analytics/_files/create_failed_subscription.php rename to dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token.php index 76bf0c7120abc..28f543d79c457 100644 --- a/dev/tests/integration/testsuite/Magento/Analytics/_files/create_failed_subscription.php +++ b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token.php @@ -19,7 +19,7 @@ * @var $analyticsToken \Magento\Analytics\Model\AnalyticsToken */ $analyticsToken = $objectManager->get(\Magento\Analytics\Model\AnalyticsToken::class); -$analyticsToken->storeToken(null); +$analyticsToken->storeToken('42'); /** * @var $flagManager \Magento\Analytics\Model\FlagManager diff --git a/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php new file mode 100644 index 0000000000000..6c631b97a6597 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php @@ -0,0 +1,29 @@ +get(\Magento\Framework\App\Config\Storage\WriterInterface::class); + +$configWriter->delete(SubscriptionHandler::CRON_STRING_PATH); +$configWriter->save('default/analytics/subscription/enabled', 0); + +/** + * @var $analyticsToken \Magento\Analytics\Model\AnalyticsToken + */ +$analyticsToken = $objectManager->get(\Magento\Analytics\Model\AnalyticsToken::class); +$analyticsToken->storeToken(null); + +/** + * @var $flagManager \Magento\Analytics\Model\FlagManager + */ +$flagManager = $objectManager->get(\Magento\Analytics\Model\FlagManager::class); + +$flagManager->deleteFlag(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE); From efad7beffb2c2a7bc9421e336f0331887617d9d6 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Tue, 28 Mar 2017 15:52:13 +0300 Subject: [PATCH 15/44] MAGETWO-66798: Create integration test Replace systemConfig to scopeConfig. --- .../Model/SubscriptionStatusProvider.php | 14 ++++----- .../Model/SubscriptionStatusProviderTest.php | 29 +++++++++---------- 2 files changed, 21 insertions(+), 22 deletions(-) diff --git a/app/code/Magento/Analytics/Model/SubscriptionStatusProvider.php b/app/code/Magento/Analytics/Model/SubscriptionStatusProvider.php index 9f4de800907ca..47440da94aa02 100644 --- a/app/code/Magento/Analytics/Model/SubscriptionStatusProvider.php +++ b/app/code/Magento/Analytics/Model/SubscriptionStatusProvider.php @@ -6,7 +6,7 @@ namespace Magento\Analytics\Model; use Magento\Analytics\Model\Config\Backend\Enabled\SubscriptionHandler; -use Magento\Config\App\Config\Type\System; +use Magento\Framework\App\Config\ScopeConfigInterface; /** * Provider of subscription status. @@ -34,9 +34,9 @@ class SubscriptionStatusProvider const DISABLED = "Disabled"; /** - * @var System + * @var ScopeConfigInterface */ - private $systemConfig; + private $scopeConfig; /** * @var AnalyticsToken @@ -49,16 +49,16 @@ class SubscriptionStatusProvider private $flagManager; /** - * @param System $systemConfig + * @param ScopeConfigInterface $scopeConfig * @param AnalyticsToken $analyticsToken * @param FlagManager $flagManager */ public function __construct( - System $systemConfig, + ScopeConfigInterface $scopeConfig, AnalyticsToken $analyticsToken, FlagManager $flagManager ) { - $this->systemConfig = $systemConfig; + $this->scopeConfig = $scopeConfig; $this->analyticsToken = $analyticsToken; $this->flagManager = $flagManager; } @@ -76,7 +76,7 @@ public function __construct( */ public function getStatus() { - $isSubscriptionEnabledInConfig = $this->systemConfig->get('default/analytics/subscription/enabled'); + $isSubscriptionEnabledInConfig = $this->scopeConfig->getValue('default/analytics/subscription/enabled'); if ($isSubscriptionEnabledInConfig) { return $this->getStatusForEnabledSubscription(); } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php index b81b776d25760..3ca906fb76657 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php @@ -9,7 +9,7 @@ use Magento\Analytics\Model\Config\Backend\Enabled\SubscriptionHandler; use Magento\Analytics\Model\FlagManager; use Magento\Analytics\Model\SubscriptionStatusProvider; -use Magento\Config\App\Config\Type\System; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; /** @@ -18,9 +18,9 @@ class SubscriptionStatusProviderTest extends \PHPUnit_Framework_TestCase { /** - * @var System|\PHPUnit_Framework_MockObject_MockObject + * @var ScopeConfigInterface|\PHPUnit_Framework_MockObject_MockObject */ - private $systemConfigMock; + private $scopeConfigMock; /** * @var AnalyticsToken|\PHPUnit_Framework_MockObject_MockObject @@ -47,9 +47,8 @@ class SubscriptionStatusProviderTest extends \PHPUnit_Framework_TestCase */ protected function setUp() { - $this->systemConfigMock = $this->getMockBuilder(System::class) - ->disableOriginalConstructor() - ->getMock(); + $this->scopeConfigMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->getMockForAbstractClass(); $this->analyticsTokenMock = $this->getMockBuilder(AnalyticsToken::class) ->disableOriginalConstructor() @@ -64,7 +63,7 @@ protected function setUp() $this->statusProvider = $this->objectManagerHelper->getObject( SubscriptionStatusProvider::class, [ - 'systemConfig' => $this->systemConfigMock, + 'scopeConfig' => $this->scopeConfigMock, 'analyticsToken' => $this->analyticsTokenMock, 'flagManager' => $this->flagManagerMock, ] @@ -76,8 +75,8 @@ public function testGetStatusShouldBeFailed() $this->analyticsTokenMock->expects($this->once()) ->method('isTokenExist') ->willReturn(false); - $this->systemConfigMock->expects($this->once()) - ->method('get') + $this->scopeConfigMock->expects($this->once()) + ->method('getValue') ->with('default/analytics/subscription/enabled') ->willReturn(true); @@ -90,8 +89,8 @@ public function testGetStatusShouldBePending() $this->analyticsTokenMock->expects($this->once()) ->method('isTokenExist') ->willReturn(false); - $this->systemConfigMock->expects($this->once()) - ->method('get') + $this->scopeConfigMock->expects($this->once()) + ->method('getValue') ->with('default/analytics/subscription/enabled') ->willReturn(true); @@ -104,8 +103,8 @@ public function testGetStatusShouldBeEnabled() $this->analyticsTokenMock->expects($this->once()) ->method('isTokenExist') ->willReturn(true); - $this->systemConfigMock->expects($this->once()) - ->method('get') + $this->scopeConfigMock->expects($this->once()) + ->method('getValue') ->with('default/analytics/subscription/enabled') ->willReturn(true); $this->assertEquals(SubscriptionStatusProvider::ENABLED, $this->statusProvider->getStatus()); @@ -113,8 +112,8 @@ public function testGetStatusShouldBeEnabled() public function testGetStatusShouldBeDisabled() { - $this->systemConfigMock->expects($this->once()) - ->method('get') + $this->scopeConfigMock->expects($this->once()) + ->method('getValue') ->with('default/analytics/subscription/enabled') ->willReturn(false); $this->assertEquals(SubscriptionStatusProvider::DISABLED, $this->statusProvider->getStatus()); From f7b7b12d887f3a1efbce1f6b6efc7b7b30f65dd2 Mon Sep 17 00:00:00 2001 From: Max Lesechko Date: Tue, 28 Mar 2017 15:59:05 +0300 Subject: [PATCH 16/44] MAGETWO-66537: Update modules version --- app/code/Magento/Analytics/etc/module.xml | 2 +- app/code/Magento/CatalogAnalytics/etc/module.xml | 2 +- app/code/Magento/CustomerAnalytics/etc/module.xml | 2 +- app/code/Magento/QuoteAnalytics/etc/module.xml | 2 +- app/code/Magento/ReviewAnalytics/etc/module.xml | 2 +- app/code/Magento/SalesAnalytics/etc/module.xml | 2 +- app/code/Magento/WishlistAnalytics/etc/module.xml | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/app/code/Magento/Analytics/etc/module.xml b/app/code/Magento/Analytics/etc/module.xml index 958d43cd6ee53..23e94e82e95ab 100644 --- a/app/code/Magento/Analytics/etc/module.xml +++ b/app/code/Magento/Analytics/etc/module.xml @@ -6,7 +6,7 @@ */ --> - + diff --git a/app/code/Magento/CatalogAnalytics/etc/module.xml b/app/code/Magento/CatalogAnalytics/etc/module.xml index a940e6ef72b2d..1f6f291b43499 100644 --- a/app/code/Magento/CatalogAnalytics/etc/module.xml +++ b/app/code/Magento/CatalogAnalytics/etc/module.xml @@ -6,7 +6,7 @@ */ --> - + diff --git a/app/code/Magento/CustomerAnalytics/etc/module.xml b/app/code/Magento/CustomerAnalytics/etc/module.xml index 9e11a44a026f1..261e0dca9904b 100644 --- a/app/code/Magento/CustomerAnalytics/etc/module.xml +++ b/app/code/Magento/CustomerAnalytics/etc/module.xml @@ -6,7 +6,7 @@ */ --> - + diff --git a/app/code/Magento/QuoteAnalytics/etc/module.xml b/app/code/Magento/QuoteAnalytics/etc/module.xml index 5809a3eedf220..40b979d023613 100644 --- a/app/code/Magento/QuoteAnalytics/etc/module.xml +++ b/app/code/Magento/QuoteAnalytics/etc/module.xml @@ -6,7 +6,7 @@ */ --> - + diff --git a/app/code/Magento/ReviewAnalytics/etc/module.xml b/app/code/Magento/ReviewAnalytics/etc/module.xml index b09dc5d401492..19055e031c608 100644 --- a/app/code/Magento/ReviewAnalytics/etc/module.xml +++ b/app/code/Magento/ReviewAnalytics/etc/module.xml @@ -6,7 +6,7 @@ */ --> - + diff --git a/app/code/Magento/SalesAnalytics/etc/module.xml b/app/code/Magento/SalesAnalytics/etc/module.xml index 3f390d5297b1b..f260b9bba8acb 100644 --- a/app/code/Magento/SalesAnalytics/etc/module.xml +++ b/app/code/Magento/SalesAnalytics/etc/module.xml @@ -6,7 +6,7 @@ */ --> - + diff --git a/app/code/Magento/WishlistAnalytics/etc/module.xml b/app/code/Magento/WishlistAnalytics/etc/module.xml index 9edbeabec5c85..15e0c2ef187f3 100644 --- a/app/code/Magento/WishlistAnalytics/etc/module.xml +++ b/app/code/Magento/WishlistAnalytics/etc/module.xml @@ -6,7 +6,7 @@ */ --> - + From 6d22d9aae422d04ed71c44dd8ea254fb3e19d5b1 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Tue, 28 Mar 2017 18:56:57 +0300 Subject: [PATCH 17/44] MAGETWO-66798: Create integration test Replace systemConfig to scopeConfig. --- .../Analytics/Model/SubscriptionStatusProvider.php | 2 +- .../Test/Unit/Model/SubscriptionStatusProviderTest.php | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/app/code/Magento/Analytics/Model/SubscriptionStatusProvider.php b/app/code/Magento/Analytics/Model/SubscriptionStatusProvider.php index 47440da94aa02..799ed7f97db7f 100644 --- a/app/code/Magento/Analytics/Model/SubscriptionStatusProvider.php +++ b/app/code/Magento/Analytics/Model/SubscriptionStatusProvider.php @@ -76,7 +76,7 @@ public function __construct( */ public function getStatus() { - $isSubscriptionEnabledInConfig = $this->scopeConfig->getValue('default/analytics/subscription/enabled'); + $isSubscriptionEnabledInConfig = $this->scopeConfig->getValue('analytics/subscription/enabled'); if ($isSubscriptionEnabledInConfig) { return $this->getStatusForEnabledSubscription(); } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php index 3ca906fb76657..3d0d190750ffa 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php @@ -77,7 +77,7 @@ public function testGetStatusShouldBeFailed() ->willReturn(false); $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with('default/analytics/subscription/enabled') + ->with('analytics/subscription/enabled') ->willReturn(true); $this->expectFlagCounterReturn(null); @@ -91,7 +91,7 @@ public function testGetStatusShouldBePending() ->willReturn(false); $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with('default/analytics/subscription/enabled') + ->with('analytics/subscription/enabled') ->willReturn(true); $this->expectFlagCounterReturn(45); @@ -105,7 +105,7 @@ public function testGetStatusShouldBeEnabled() ->willReturn(true); $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with('default/analytics/subscription/enabled') + ->with('analytics/subscription/enabled') ->willReturn(true); $this->assertEquals(SubscriptionStatusProvider::ENABLED, $this->statusProvider->getStatus()); } @@ -114,7 +114,7 @@ public function testGetStatusShouldBeDisabled() { $this->scopeConfigMock->expects($this->once()) ->method('getValue') - ->with('default/analytics/subscription/enabled') + ->with('analytics/subscription/enabled') ->willReturn(false); $this->assertEquals(SubscriptionStatusProvider::DISABLED, $this->statusProvider->getStatus()); } From 8dbde00cd05984197ae2b9448559b79c46cf8f15 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Tue, 28 Mar 2017 19:12:21 +0300 Subject: [PATCH 18/44] MAGETWO-66528: Add response handler Small refactoring. --- .../Adminhtml/Subscription/Activate.php | 32 ++- .../Adminhtml/Subscription/Retry.php | 14 +- .../Model/Config/Backend/Enabled.php | 10 + .../Backend/Enabled/SubscriptionHandler.php | 12 +- .../Connector/ResponseHandler/ReSignUp.php | 14 +- .../Magento/Analytics/Model/Subscription.php | 144 ---------- .../Adminhtml/Subscription/ActivateTest.php | 43 ++- .../Adminhtml/Subscription/RetryTest.php | 15 +- .../ResponseHandler/ReSignUpTest.php | 6 +- .../Test/Unit/Model/SubscriptionTest.php | 257 ------------------ app/code/Magento/Analytics/etc/di.xml | 2 +- 11 files changed, 110 insertions(+), 439 deletions(-) delete mode 100644 app/code/Magento/Analytics/Model/Subscription.php delete mode 100644 app/code/Magento/Analytics/Test/Unit/Model/SubscriptionTest.php diff --git a/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php b/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php index bf14c909810e2..e4fa96ccdb9b7 100644 --- a/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php +++ b/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php @@ -6,13 +6,17 @@ namespace Magento\Analytics\Controller\Adminhtml\Subscription; +use Magento\Analytics\Model\Config\Backend\Enabled; use Magento\Analytics\Model\NotificationTime; use Magento\Analytics\Model\Subscription; use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; +use Magento\Config\Model\PreparedValueFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Controller\Result\Json; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Psr\Log\LoggerInterface; /** @@ -46,6 +50,16 @@ class Activate extends Action */ private $subscriptionApprovedField = 'analytics_subscription_checkbox'; + /** + * @var AbstractDb + */ + private $configValueResource; + + /** + * @var PreparedValueFactory + */ + private $preparedValueFactory; + /** * Activate constructor. * @@ -53,16 +67,22 @@ class Activate extends Action * @param Subscription $subscription * @param LoggerInterface $logger * @param NotificationTime $notificationTime + * @param AbstractDb $configValueResource + * @param PreparedValueFactory $preparedValueFactory */ public function __construct( Context $context, Subscription $subscription, LoggerInterface $logger, - NotificationTime $notificationTime + NotificationTime $notificationTime, + AbstractDb $configValueResource, + PreparedValueFactory $preparedValueFactory ) { $this->subscription = $subscription; $this->logger = $logger; $this->notificationTime = $notificationTime; + $this->configValueResource = $configValueResource; + $this->preparedValueFactory = $preparedValueFactory; parent::__construct($context); } @@ -85,7 +105,15 @@ public function execute() { try { if ($this->getRequest()->getParam($this->subscriptionApprovedField)) { - $this->subscription->enable(); + $configValue = $this->preparedValueFactory->create( + Enabled::XML_ENABLED_CONFIG_STRUCTURE_PATH, + Enabled::YES_VALUE, + ScopeConfigInterface::SCOPE_TYPE_DEFAULT, + null + ); + + $this->configValueResource + ->save($configValue); } else { $this->notificationTime->unsetLastTimeNotificationValue(); } diff --git a/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Retry.php b/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Retry.php index c1a880d8a6821..5903679d9edb9 100644 --- a/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Retry.php +++ b/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Retry.php @@ -6,7 +6,7 @@ namespace Magento\Analytics\Controller\Adminhtml\Subscription; -use Magento\Analytics\Model\Subscription; +use Magento\Analytics\Model\Config\Backend\Enabled\SubscriptionHandler; use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; use Magento\Framework\Controller\Result\Redirect; @@ -21,19 +21,19 @@ class Retry extends Action /** * Resource for managing subscription to Magento Analytics. * - * @var Subscription + * @var SubscriptionHandler */ - private $subscription; + private $subscriptionHandler; /** * @param Context $context - * @param Subscription $subscription + * @param SubscriptionHandler $subscriptionHandler */ public function __construct( Context $context, - Subscription $subscription + SubscriptionHandler $subscriptionHandler ) { - $this->subscription = $subscription; + $this->subscriptionHandler = $subscriptionHandler; parent::__construct($context); } @@ -58,7 +58,7 @@ public function execute() $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); try { $resultRedirect->setPath('adminhtml'); - $this->subscription->retry(); + $this->subscriptionHandler->processEnabled(); } catch (LocalizedException $e) { $this->getMessageManager()->addExceptionMessage($e, $e->getMessage()); } catch (\Exception $e) { diff --git a/app/code/Magento/Analytics/Model/Config/Backend/Enabled.php b/app/code/Magento/Analytics/Model/Config/Backend/Enabled.php index 8bba39bbad9c7..d563758f1b747 100644 --- a/app/code/Magento/Analytics/Model/Config/Backend/Enabled.php +++ b/app/code/Magento/Analytics/Model/Config/Backend/Enabled.php @@ -20,6 +20,16 @@ */ class Enabled extends Value { + /** + * Path to field subscription enabled into config structure. + */ + const XML_ENABLED_CONFIG_STRUCTURE_PATH = 'analytics/general/enabled'; + + /** + * Value which equal Yes for Yesno dropdown. + */ + const YES_VALUE = 1; + /** * Service for processing of activation/deactivation MBI subscription. * diff --git a/app/code/Magento/Analytics/Model/Config/Backend/Enabled/SubscriptionHandler.php b/app/code/Magento/Analytics/Model/Config/Backend/Enabled/SubscriptionHandler.php index 62d84960d035a..589408d9ae5b4 100644 --- a/app/code/Magento/Analytics/Model/Config/Backend/Enabled/SubscriptionHandler.php +++ b/app/code/Magento/Analytics/Model/Config/Backend/Enabled/SubscriptionHandler.php @@ -9,6 +9,7 @@ use Magento\Analytics\Model\FlagManager; use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\NotificationTime; +use Magento\Framework\App\Config\ReinitableConfigInterface; use Magento\Framework\App\Config\Storage\WriterInterface; /** @@ -61,22 +62,30 @@ class SubscriptionHandler */ private $notificationTime; + /** + * @var ReinitableConfigInterface + */ + private $reinitableConfig; + /** * @param WriterInterface $configWriter * @param FlagManager $flagManager * @param AnalyticsToken $analyticsToken * @param NotificationTime $notificationTime + * @param ReinitableConfigInterface $reinitableConfig */ public function __construct( WriterInterface $configWriter, FlagManager $flagManager, AnalyticsToken $analyticsToken, - NotificationTime $notificationTime + NotificationTime $notificationTime, + ReinitableConfigInterface $reinitableConfig ) { $this->configWriter = $configWriter; $this->flagManager = $flagManager; $this->analyticsToken = $analyticsToken; $this->notificationTime = $notificationTime; + $this->reinitableConfig = $reinitableConfig; } /** @@ -92,6 +101,7 @@ public function processEnabled() $this->setCronSchedule(); $this->setAttemptsFlag(); $this->notificationTime->unsetLastTimeNotificationValue(); + $this->reinitableConfig->reinit(); } return true; diff --git a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php index b34b2b7a7c9a1..4e132abe61977 100644 --- a/app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php +++ b/app/code/Magento/Analytics/Model/Connector/ResponseHandler/ReSignUp.php @@ -6,8 +6,8 @@ namespace Magento\Analytics\Model\Connector\ResponseHandler; use Magento\Analytics\Model\AnalyticsToken; +use Magento\Analytics\Model\Config\Backend\Enabled\SubscriptionHandler; use Magento\Analytics\Model\Connector\Http\ResponseHandlerInterface; -use Magento\Analytics\Model\Subscription; use Magento\Analytics\Model\SubscriptionStatusProvider; /** @@ -21,9 +21,9 @@ class ReSignUp implements ResponseHandlerInterface private $analyticsToken; /** - * @var Subscription + * @var SubscriptionHandler */ - private $subscription; + private $subscriptionHandler; /** * @var SubscriptionStatusProvider @@ -32,16 +32,16 @@ class ReSignUp implements ResponseHandlerInterface /** * @param AnalyticsToken $analyticsToken - * @param Subscription $subscription + * @param SubscriptionHandler $subscriptionHandler * @param SubscriptionStatusProvider $subscriptionStatusProvider */ public function __construct( AnalyticsToken $analyticsToken, - Subscription $subscription, + SubscriptionHandler $subscriptionHandler, SubscriptionStatusProvider $subscriptionStatusProvider ) { $this->analyticsToken = $analyticsToken; - $this->subscription = $subscription; + $this->subscriptionHandler = $subscriptionHandler; $this->subscriptionStatusProvider = $subscriptionStatusProvider; } @@ -52,7 +52,7 @@ public function handleResponse(array $responseBody) { if ($this->subscriptionStatusProvider->getStatus() === SubscriptionStatusProvider::ENABLED) { $this->analyticsToken->storeToken(null); - $this->subscription->retry(); + $this->subscriptionHandler->processEnabled(); } return false; } diff --git a/app/code/Magento/Analytics/Model/Subscription.php b/app/code/Magento/Analytics/Model/Subscription.php deleted file mode 100644 index 02d9a71bdefb9..0000000000000 --- a/app/code/Magento/Analytics/Model/Subscription.php +++ /dev/null @@ -1,144 +0,0 @@ -configValueFactory = $configValueFactory; - $this->configStructure = $configStructure; - $this->configValueResource = $configValueResource; - $this->reinitableConfig = $reinitableConfig; - $this->subscriptionHandler = $subscriptionHandler; - $this->statusProvider = $statusProvider; - } - - /** - * Set subscription enabled config value. - * - * @return boolean - */ - public function enable() - { - /** @var Field $field */ - $field = $this->configStructure->getElement($this->enabledConfigStructurePath); - /** @var Value $configValue */ - $configValue = $field->hasBackendModel() - ? $field->getBackendModel() - : $this->configValueFactory->create(); - $configPath = $field->getConfigPath() ?: $this->enabledConfigStructurePath; - - $this->configValueResource - ->load($configValue, $configPath, 'path'); - - $configValue->setValue($this->yesValueDropdown); - $configValue->setPath($configPath); - - $this->configValueResource - ->save($configValue); - - $this->reinitableConfig->reinit(); - - return true; - } - - /** - * Retry process of subscription that was unsuccessful. - * - * @return bool - */ - public function retry() - { - if ($this->statusProvider->getStatus() === SubscriptionStatusProvider::FAILED) { - $this->subscriptionHandler->processEnabled(); - $this->reinitableConfig->reinit(); - } - - return true; - } -} diff --git a/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/ActivateTest.php b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/ActivateTest.php index a1cf41ace802c..12eb7dbce7b6f 100644 --- a/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/ActivateTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/ActivateTest.php @@ -8,11 +8,12 @@ use Magento\Analytics\Controller\Adminhtml\Subscription\Activate; use Magento\Analytics\Model\NotificationTime; -use Magento\Analytics\Model\Subscription; +use Magento\Config\Model\PreparedValueFactory; use Magento\Framework\App\RequestInterface; use Magento\Framework\Controller\Result\Json; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Model\ResourceModel\Db\AbstractDb; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; use Psr\Log\LoggerInterface; @@ -32,9 +33,14 @@ class ActivateTest extends \PHPUnit_Framework_TestCase private $resultJsonMock; /** - * @var Subscription|\PHPUnit_Framework_MockObject_MockObject + * @var PreparedValueFactory|\PHPUnit_Framework_MockObject_MockObject */ - private $subscriptionModelMock; + private $preparedValueFactoryMock; + + /** + * @var AbstractDb|\PHPUnit_Framework_MockObject_MockObject + */ + private $configValueResourceMock; /** * @var LoggerInterface|\PHPUnit_Framework_MockObject_MockObject @@ -79,7 +85,11 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->subscriptionModelMock = $this->getMockBuilder(Subscription::class) + $this->preparedValueFactoryMock = $this->getMockBuilder(PreparedValueFactory::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->configValueResourceMock = $this->getMockBuilder(AbstractDb::class) ->disableOriginalConstructor() ->getMock(); @@ -101,7 +111,8 @@ protected function setUp() Activate::class, [ 'resultFactory' => $this->resultFactoryMock, - 'subscription' => $this->subscriptionModelMock, + 'preparedValueFactory' => $this->preparedValueFactoryMock, + 'configValueResource' => $this->configValueResourceMock, 'logger' => $this->loggerMock, 'notificationTime' => $this->notificationTimeMock, '_request' => $this->requestMock, @@ -130,10 +141,12 @@ public function testExecute($isSubscriptionEnabled) ->willReturn($isSubscriptionEnabled); if ($isSubscriptionEnabled) { - $this->subscriptionModelMock + $configValue = $this->createConfigValueMock(); + $this->preparedValueFactoryMock ->expects($this->once()) - ->method('enable') - ->willReturn(true); + ->method('create') + ->willReturn($configValue); + $this->configValueResourceMock->expects($this->once())->method('save')->with($configValue); } else { $this->notificationTimeMock ->expects($this->once()) @@ -168,9 +181,9 @@ public function testExecuteWithException(\Exception $exception) ->with($this->subscriptionApprovedField) ->willReturn(true); - $this->subscriptionModelMock + $this->preparedValueFactoryMock ->expects($this->once()) - ->method('enable') + ->method('create') ->willThrowException($exception); $this->loggerMock ->expects($this->once()) @@ -205,6 +218,16 @@ public function testExecuteWithException(\Exception $exception) ); } + /** + * @return \PHPUnit_Framework_MockObject_MockObject + */ + private function createConfigValueMock() + { + return $this->getMockBuilder(\Magento\Framework\Model\AbstractModel::class) + ->disableOriginalConstructor() + ->getMock(); + } + /** * @return array */ diff --git a/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/RetryTest.php b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/RetryTest.php index 835fe4e1f5894..e7c6f0769644f 100644 --- a/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/RetryTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/RetryTest.php @@ -7,6 +7,7 @@ namespace Magento\Analytics\Test\Unit\Controller\Adminhtml\Subscription; use Magento\Analytics\Controller\Adminhtml\Subscription\Retry; +use Magento\Analytics\Model\Config\Backend\Enabled\SubscriptionHandler; use Magento\Analytics\Model\Subscription; use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\Controller\ResultFactory; @@ -33,7 +34,7 @@ class RetryTest extends \PHPUnit_Framework_TestCase /** * @var Subscription|\PHPUnit_Framework_MockObject_MockObject */ - private $subscriptionMock; + private $subscriptionHandlerMock; /** * @var ManagerInterface|\PHPUnit_Framework_MockObject_MockObject @@ -63,7 +64,7 @@ protected function setUp() ->disableOriginalConstructor() ->getMock(); - $this->subscriptionMock = $this->getMockBuilder(Subscription::class) + $this->subscriptionHandlerMock = $this->getMockBuilder(SubscriptionHandler::class) ->disableOriginalConstructor() ->getMock(); @@ -77,7 +78,7 @@ protected function setUp() Retry::class, [ 'resultFactory' => $this->resultFactoryMock, - 'subscription' => $this->subscriptionMock, + 'subscriptionHandler' => $this->subscriptionHandlerMock, 'messageManager' => $this->messageManagerMock, ] ); @@ -98,9 +99,9 @@ public function testExecute() ->method('setPath') ->with('adminhtml') ->willReturnSelf(); - $this->subscriptionMock + $this->subscriptionHandlerMock ->expects($this->once()) - ->method('retry') + ->method('processEnabled') ->with() ->willReturn(true); $this->assertSame( @@ -127,9 +128,9 @@ public function testExecuteWithException(\Exception $exception, Phrase $message) ->method('setPath') ->with('adminhtml') ->willReturnSelf(); - $this->subscriptionMock + $this->subscriptionHandlerMock ->expects($this->once()) - ->method('retry') + ->method('processEnabled') ->with() ->willThrowException($exception); $this->messageManagerMock diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php index b65d565a798f1..bb4d53307a026 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php @@ -6,8 +6,8 @@ namespace Magento\Analytics\Test\Unit\Model\Connector\ResponseHandler; use Magento\Analytics\Model\AnalyticsToken; +use Magento\Analytics\Model\Config\Backend\Enabled\SubscriptionHandler; use Magento\Analytics\Model\Connector\ResponseHandler\ReSignUp; -use Magento\Analytics\Model\Subscription; use Magento\Analytics\Model\SubscriptionStatusProvider; /** @@ -23,14 +23,14 @@ public function testHandleResult() $analyticsToken->expects($this->once()) ->method('storeToken') ->with(null); - $subscription = $this->getMockBuilder(Subscription::class) + $subscriptionHandler = $this->getMockBuilder(SubscriptionHandler::class) ->disableOriginalConstructor() ->getMock(); $subscriptionStatusProvider = $this->getMockBuilder(SubscriptionStatusProvider::class) ->disableOriginalConstructor() ->getMock(); $subscriptionStatusProvider->method('getStatus')->willReturn(SubscriptionStatusProvider::ENABLED); - $reSignUpHandler = new ReSignUp($analyticsToken, $subscription, $subscriptionStatusProvider); + $reSignUpHandler = new ReSignUp($analyticsToken, $subscriptionHandler, $subscriptionStatusProvider); $this->assertFalse($reSignUpHandler->handleResponse([])); } } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionTest.php b/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionTest.php deleted file mode 100644 index 0c08cfd70cbf3..0000000000000 --- a/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionTest.php +++ /dev/null @@ -1,257 +0,0 @@ -configValueFactoryMock = $this->getMockBuilder(ValueFactory::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->configValueMock = $this->getMockBuilder(Value::class) - ->disableOriginalConstructor() - ->setMethods(['setValue', 'setPath']) - ->getMock(); - - $this->configStructureMock = $this->getMockBuilder(SearchInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->configValueResourceMock = $this->getMockBuilder(AbstractDb::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->elementFieldMock = $this->getMockBuilder(Field::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->reinitableConfigMock = $this->getMockBuilder(ReinitableConfigInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->subscriptionHandlerMock = $this->getMockBuilder(SubscriptionHandler::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->statusProviderMock = $this->getMockBuilder(SubscriptionStatusProvider::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->objectManagerHelper = new ObjectManagerHelper($this); - - $this->subscriptionModel = $this->objectManagerHelper->getObject( - SubscriptionModel::class, - [ - 'configValueFactory' => $this->configValueFactoryMock, - 'configStructure' => $this->configStructureMock, - 'configValueResource' => $this->configValueResourceMock, - 'reinitableConfig' => $this->reinitableConfigMock, - 'enabledConfigStructurePath' => $this->enableConfigStructurePath, - 'yesValueDropdown' => $this->yesValueDropdown, - 'subscriptionHandler' => $this->subscriptionHandlerMock, - 'statusProvider' => $this->statusProviderMock, - ] - ); - } - - /** - * @dataProvider enabledDataProvider - * - * @param boolean $backendModel - * @param string $configPath - * - * @return void - */ - public function testEnabled($backendModel, $configPath) - { - $this->configStructureMock - ->expects($this->once()) - ->method('getElement') - ->with($this->enableConfigStructurePath) - ->willReturn($this->elementFieldMock); - $this->elementFieldMock - ->expects($this->once()) - ->method('hasBackendModel') - ->willReturn($backendModel); - if ($backendModel) { - $this->elementFieldMock - ->expects($this->once()) - ->method('getBackendModel') - ->willReturn($this->configValueMock); - } else { - $this->configValueFactoryMock - ->expects($this->once()) - ->method('create') - ->willReturn($this->configValueMock); - } - $this->elementFieldMock - ->expects($this->once()) - ->method('getConfigPath') - ->willReturn($configPath); - $configPath = $configPath ?: $this->enableConfigStructurePath; - $this->configValueResourceMock - ->expects($this->once()) - ->method('load') - ->with($this->configValueMock, $configPath, 'path') - ->willReturnSelf(); - $this->configValueMock - ->expects($this->once()) - ->method('setValue') - ->with(1) - ->willReturnSelf(); - $this->configValueMock - ->expects($this->once()) - ->method('setPath') - ->with($configPath) - ->willReturnSelf(); - $this->configValueResourceMock - ->expects($this->once()) - ->method('save') - ->with($this->configValueMock) - ->willReturnSelf(); - $this->reinitableConfigMock - ->expects($this->once()) - ->method('reinit') - ->willReturnSelf(); - $this->assertTrue($this->subscriptionModel->enable()); - } - - /** - * @return array - */ - public function enabledDataProvider() - { - return [ - 'TestWithBackendModelWithoutConfigPath' => [true, null], - 'TestWithBackendModelWithConfigPath' => [true, $this->configPath], - 'TestWithoutBackendModelWithoutConfigPath' => [false, null], - 'TestWithoutBackendModelWithConfigPath' => [false, $this->configPath], - ]; - } - - /** - * @dataProvider retryDataProvider - * @param string $status - * @param \PHPUnit_Framework_MockObject_Matcher_InvokedCount $invokedCount - * @return void - */ - public function testRetry($status, \PHPUnit_Framework_MockObject_Matcher_InvokedCount $invokedCount) - { - $this->statusProviderMock - ->expects($this->once()) - ->method('getStatus') - ->with() - ->willReturn($status); - $this->subscriptionHandlerMock - ->expects(clone $invokedCount) - ->method('processEnabled') - ->with() - ->willReturn(true); - $this->reinitableConfigMock - ->expects(clone $invokedCount) - ->method('reinit') - ->with() - ->willReturnSelf(); - $this->assertTrue($this->subscriptionModel->retry()); - } - - /** - * @return array - */ - public function retryDataProvider() - { - return [ - 'Status Pending' => [SubscriptionStatusProvider::PENDING, $this->never()], - 'Status Failed' => [SubscriptionStatusProvider::FAILED, $this->once()], - 'Status Disabled' => [SubscriptionStatusProvider::DISABLED, $this->never()], - ]; - } -} diff --git a/app/code/Magento/Analytics/etc/di.xml b/app/code/Magento/Analytics/etc/di.xml index 65614c3580356..8a453b96a866a 100644 --- a/app/code/Magento/Analytics/etc/di.xml +++ b/app/code/Magento/Analytics/etc/di.xml @@ -30,7 +30,7 @@ - + Magento\Config\Model\ResourceModel\Config\Data From e914174a5383114aceed5a6be99b8e5b815195b0 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Wed, 29 Mar 2017 11:55:58 +0300 Subject: [PATCH 19/44] MAGETWO-66528: Add response handler Remove rest of subscription class. --- .../Controller/Adminhtml/Subscription/Activate.php | 11 ----------- .../Controller/Adminhtml/Subscription/RetryTest.php | 3 +-- 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php b/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php index e4fa96ccdb9b7..4c82ede27ee3d 100644 --- a/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php +++ b/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php @@ -8,7 +8,6 @@ use Magento\Analytics\Model\Config\Backend\Enabled; use Magento\Analytics\Model\NotificationTime; -use Magento\Analytics\Model\Subscription; use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; use Magento\Config\Model\PreparedValueFactory; @@ -24,13 +23,6 @@ */ class Activate extends Action { - /** - * Resource for managing subscription to Magento BI. - * - * @var Subscription - */ - private $subscription; - /** * @var LoggerInterface */ @@ -64,7 +56,6 @@ class Activate extends Action * Activate constructor. * * @param Context $context - * @param Subscription $subscription * @param LoggerInterface $logger * @param NotificationTime $notificationTime * @param AbstractDb $configValueResource @@ -72,13 +63,11 @@ class Activate extends Action */ public function __construct( Context $context, - Subscription $subscription, LoggerInterface $logger, NotificationTime $notificationTime, AbstractDb $configValueResource, PreparedValueFactory $preparedValueFactory ) { - $this->subscription = $subscription; $this->logger = $logger; $this->notificationTime = $notificationTime; $this->configValueResource = $configValueResource; diff --git a/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/RetryTest.php b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/RetryTest.php index e7c6f0769644f..a8da3c9de5b26 100644 --- a/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/RetryTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Controller/Adminhtml/Subscription/RetryTest.php @@ -8,7 +8,6 @@ use Magento\Analytics\Controller\Adminhtml\Subscription\Retry; use Magento\Analytics\Model\Config\Backend\Enabled\SubscriptionHandler; -use Magento\Analytics\Model\Subscription; use Magento\Framework\Controller\Result\Redirect; use Magento\Framework\Controller\ResultFactory; use Magento\Framework\Exception\LocalizedException; @@ -32,7 +31,7 @@ class RetryTest extends \PHPUnit_Framework_TestCase private $resultRedirectMock; /** - * @var Subscription|\PHPUnit_Framework_MockObject_MockObject + * @var SubscriptionHandler|\PHPUnit_Framework_MockObject_MockObject */ private $subscriptionHandlerMock; From 538a80feef98cad2d10b98d119fd670bd5af6d85 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Wed, 29 Mar 2017 14:35:22 +0300 Subject: [PATCH 20/44] MAGETWO-66528: Add response handler Change preparedValueFactory. --- .../Config/Model/PreparedValueFactory.php | 18 ++++++++++-------- .../Unit/Model/PreparedValueFactoryTest.php | 5 ++++- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/app/code/Magento/Config/Model/PreparedValueFactory.php b/app/code/Magento/Config/Model/PreparedValueFactory.php index b3c3955ca13e2..2d37cf91fbba9 100644 --- a/app/code/Magento/Config/Model/PreparedValueFactory.php +++ b/app/code/Magento/Config/Model/PreparedValueFactory.php @@ -71,14 +71,16 @@ public function create($path, $value, $scope, $scopeCode) { /** @var Structure $structure */ $structure = $this->structureFactory->create(); - /** @var Structure\ElementInterface $field */ - $field = $this->deploymentConfig->isAvailable() - ? $structure->getElement($path) - : null; - /** @var ValueInterface $backendModel */ - $backendModel = $field instanceof Structure\Element\Field && $field->hasBackendModel() - ? $field->getBackendModel() - : $this->valueFactory->create(); + $field = null; + $backendModel = $this->valueFactory->create(); + if ($this->deploymentConfig->isAvailable()) { + /** @var Structure\ElementInterface $field */ + $field = $structure->getElement($path); + if ($field instanceof Structure\Element\Field && $field->hasBackendModel()) { + $backendModel = $field->getBackendModel(); + $path = $field->getConfigPath() ?: $path; + } + } if ($backendModel instanceof Value) { $backendModel->setPath($path); diff --git a/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php b/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php index 6ae9fd0c6e7ee..b5382691285f1 100644 --- a/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php @@ -123,6 +123,9 @@ public function testCreate( ->expects($field['getBackendModel']['expects']) ->method('getBackendModel') ->willReturn($this->valueMock); + $this->fieldMock->expects($this->any()) + ->method('getConfigPath') + ->willReturn(false); $this->valueFactoryMock->expects($valueFactory['expects']) ->method('create') ->willReturn($this->valueMock); @@ -174,7 +177,7 @@ public function createDataProvider() ], 'getBackendModel' => ['expects' => $this->once()] ], - 'valueFactory' => ['expects' => $this->never()] + 'valueFactory' => ['expects' => $this->once()] ], [ 'deploymentConfigIsAvailable' => ['return' => true], From 576455dbc8f1a78a82c046f332ba25f10576ad0c Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Wed, 29 Mar 2017 14:50:55 +0300 Subject: [PATCH 21/44] MAGETWO-66528: Add response handler Fix review comments. --- .../Adminhtml/Subscription/Activate.php | 3 ++- .../Analytics/Model/Config/Backend/Enabled.php | 5 ----- .../Model/Config/Source/Enabledisable.php | 18 +++++++++++++++++- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php b/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php index 4c82ede27ee3d..66420a5b0c292 100644 --- a/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php +++ b/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php @@ -10,6 +10,7 @@ use Magento\Analytics\Model\NotificationTime; use Magento\Backend\App\Action; use Magento\Backend\App\Action\Context; +use Magento\Config\Model\Config\Source\Enabledisable; use Magento\Config\Model\PreparedValueFactory; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\Controller\Result\Json; @@ -96,7 +97,7 @@ public function execute() if ($this->getRequest()->getParam($this->subscriptionApprovedField)) { $configValue = $this->preparedValueFactory->create( Enabled::XML_ENABLED_CONFIG_STRUCTURE_PATH, - Enabled::YES_VALUE, + Enabledisable::ENABLE_VALUE, ScopeConfigInterface::SCOPE_TYPE_DEFAULT, null ); diff --git a/app/code/Magento/Analytics/Model/Config/Backend/Enabled.php b/app/code/Magento/Analytics/Model/Config/Backend/Enabled.php index d563758f1b747..4a36e9b2a5b9b 100644 --- a/app/code/Magento/Analytics/Model/Config/Backend/Enabled.php +++ b/app/code/Magento/Analytics/Model/Config/Backend/Enabled.php @@ -25,11 +25,6 @@ class Enabled extends Value */ const XML_ENABLED_CONFIG_STRUCTURE_PATH = 'analytics/general/enabled'; - /** - * Value which equal Yes for Yesno dropdown. - */ - const YES_VALUE = 1; - /** * Service for processing of activation/deactivation MBI subscription. * diff --git a/app/code/Magento/Config/Model/Config/Source/Enabledisable.php b/app/code/Magento/Config/Model/Config/Source/Enabledisable.php index 70a96c3c832e1..88ecb5b7c72d0 100644 --- a/app/code/Magento/Config/Model/Config/Source/Enabledisable.php +++ b/app/code/Magento/Config/Model/Config/Source/Enabledisable.php @@ -5,13 +5,29 @@ */ namespace Magento\Config\Model\Config\Source; +/** + * Source model for element with enable and disable variants. + */ class Enabledisable implements \Magento\Framework\Option\ArrayInterface { + /** + * Value which equal Enable for Enabledisable dropdown. + */ + const ENABLE_VALUE = 1; + + /** + * Value which equal Disable for Enabledisable dropdown. + */ + const DISABLE_VALUE = 0; + /** * @return array */ public function toOptionArray() { - return [['value' => 1, 'label' => __('Enable')], ['value' => 0, 'label' => __('Disable')]]; + return [ + ['value' => self::ENABLE_VALUE, 'label' => __('Enable')], + ['value' => self::DISABLE_VALUE, 'label' => __('Disable')], + ]; } } From 28943f8780d951fe5471774ff57433a64e31441e Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Wed, 29 Mar 2017 15:57:00 +0300 Subject: [PATCH 22/44] MAGETWO-66528: Add response handler Add case to unit. --- .../Unit/Model/PreparedValueFactoryTest.php | 40 +++++++++++++------ 1 file changed, 28 insertions(+), 12 deletions(-) diff --git a/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php b/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php index b5382691285f1..ce3bb3f149dea 100644 --- a/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php @@ -92,15 +92,16 @@ protected function setUp() * @param array $structureGetElement * @param array $field * @param array $valueFactory + * @param string $configPath * @dataProvider createDataProvider */ public function testCreate( array $deploymentConfigIsAvailable, array $structureGetElement, array $field, - array $valueFactory + array $valueFactory, + $configPath ) { - $path = '/some/path'; $value = 'someValue'; $scope = 'someScope'; $scopeCode = 'someScopeCode'; @@ -123,15 +124,15 @@ public function testCreate( ->expects($field['getBackendModel']['expects']) ->method('getBackendModel') ->willReturn($this->valueMock); - $this->fieldMock->expects($this->any()) + $this->fieldMock->expects($field['getConfigPath']['expects']) ->method('getConfigPath') - ->willReturn(false); + ->willReturn($field['getConfigPath']['return']); $this->valueFactoryMock->expects($valueFactory['expects']) ->method('create') ->willReturn($this->valueMock); $this->valueMock->expects($this->once()) ->method('setPath') - ->with($path) + ->with($configPath) ->willReturnSelf(); $this->valueMock->expects($this->once()) ->method('setScope') @@ -148,7 +149,7 @@ public function testCreate( $this->assertInstanceOf( Value::class, - $this->valueBuilder->create($path, $value, $scope, $scopeCode) + $this->valueBuilder->create($configPath, $value, $scope, $scopeCode) ); } @@ -163,9 +164,14 @@ public function createDataProvider() 'expects' => $this->never(), 'return' => true ], - 'getBackendModel' => ['expects' => $this->never()] + 'getBackendModel' => ['expects' => $this->never()], + 'getConfigPath' => [ + 'expects' => $this->never(), + 'return' => null + ], ], - 'valueFactory' => ['expects' => $this->once()] + 'valueFactory' => ['expects' => $this->once()], + 'configPath' => '/some/path', ], [ 'deploymentConfigIsAvailable' => ['return' => true], @@ -175,9 +181,14 @@ public function createDataProvider() 'expects' => $this->once(), 'return' => true ], - 'getBackendModel' => ['expects' => $this->once()] + 'getBackendModel' => ['expects' => $this->once()], + 'getConfigPath' => [ + 'expects' => $this->once(), + 'return' => 'customPath' + ], ], - 'valueFactory' => ['expects' => $this->once()] + 'valueFactory' => ['expects' => $this->once()], + 'configPath' => 'customPath', ], [ 'deploymentConfigIsAvailable' => ['return' => true], @@ -187,9 +198,14 @@ public function createDataProvider() 'expects' => $this->once(), 'return' => false ], - 'getBackendModel' => ['expects' => $this->never()] + 'getBackendModel' => ['expects' => $this->never()], + 'getConfigPath' => [ + 'expects' => $this->never(), + 'return' => null + ], ], - 'valueFactory' => ['expects' => $this->once()] + 'valueFactory' => ['expects' => $this->once()], + 'configPath' => '/some/path' ], ]; } From 95caaf2f5ef95d12d378f8bbfdf5239c183b3fc6 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Wed, 29 Mar 2017 16:38:01 +0300 Subject: [PATCH 23/44] MAGETWO-66528: Add response handler Add case to unit. --- .../Unit/Model/PreparedValueFactoryTest.php | 186 +++++++++++------- 1 file changed, 115 insertions(+), 71 deletions(-) diff --git a/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php b/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php index ce3bb3f149dea..c9ac25c0312ea 100644 --- a/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php @@ -87,20 +87,56 @@ protected function setUp() ); } + public function testCreateWhenDeploymentConfigIsNotAvailable() + { + $configPath = '/some/path'; + $value = 'someValue'; + $scope = 'someScope'; + $scopeCode = 'someScopeCode'; + $this->structureFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($this->structureMock); + $this->deploymentConfigMock + ->expects($this->once()) + ->method('isAvailable') + ->willReturn(false); + $this->valueFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($this->valueMock); + $this->valueMock->expects($this->once()) + ->method('setPath') + ->with($configPath) + ->willReturnSelf(); + $this->valueMock->expects($this->once()) + ->method('setScope') + ->with($scope) + ->willReturnSelf(); + $this->valueMock->expects($this->once()) + ->method('setScopeId') + ->with($scopeCode) + ->willReturnSelf(); + $this->valueMock->expects($this->once()) + ->method('setValue') + ->with($value) + ->willReturnSelf(); + + $this->assertInstanceOf( + Value::class, + $this->valueBuilder->create($configPath, $value, $scope, $scopeCode) + ); + } + /** - * @param array $deploymentConfigIsAvailable - * @param array $structureGetElement - * @param array $field - * @param array $valueFactory - * @param string $configPath * @dataProvider createDataProvider + * + * @param string $structurePath + * @param string $customPath + * @param string $expectedPath */ - public function testCreate( - array $deploymentConfigIsAvailable, - array $structureGetElement, - array $field, - array $valueFactory, - $configPath + public function testCreateAndSetDataToBackendModel( + $structurePath, + $customPath, + $expectedPath ) { $value = 'someValue'; $scope = 'someScope'; @@ -111,28 +147,28 @@ public function testCreate( $this->deploymentConfigMock ->expects($this->once()) ->method('isAvailable') - ->willReturn($deploymentConfigIsAvailable['return']); + ->willReturn(true); $this->structureMock - ->expects($structureGetElement['expects']) + ->expects($this->once()) ->method('getElement') ->willReturn($this->fieldMock); $this->fieldMock - ->expects($field['hasBackendModel']['expects']) + ->expects($this->once()) ->method('hasBackendModel') - ->willReturn($field['hasBackendModel']['return']); + ->willReturn(true); $this->fieldMock - ->expects($field['getBackendModel']['expects']) + ->expects($this->once()) ->method('getBackendModel') ->willReturn($this->valueMock); - $this->fieldMock->expects($field['getConfigPath']['expects']) - ->method('getConfigPath') - ->willReturn($field['getConfigPath']['return']); - $this->valueFactoryMock->expects($valueFactory['expects']) + $this->valueFactoryMock->expects($this->once()) ->method('create') ->willReturn($this->valueMock); + $this->fieldMock->expects($this->once()) + ->method('getConfigPath') + ->willReturn($customPath); $this->valueMock->expects($this->once()) ->method('setPath') - ->with($configPath) + ->with($expectedPath) ->willReturnSelf(); $this->valueMock->expects($this->once()) ->method('setScope') @@ -149,64 +185,72 @@ public function testCreate( $this->assertInstanceOf( Value::class, - $this->valueBuilder->create($configPath, $value, $scope, $scopeCode) + $this->valueBuilder->create($structurePath, $value, $scope, $scopeCode) ); } + /** + * @return array + */ public function createDataProvider() { return [ - [ - 'deploymentConfigIsAvailable' => ['return' => false], - 'structureGetElement' => ['expects' => $this->never()], - 'field' => [ - 'hasBackendModel' => [ - 'expects' => $this->never(), - 'return' => true - ], - 'getBackendModel' => ['expects' => $this->never()], - 'getConfigPath' => [ - 'expects' => $this->never(), - 'return' => null - ], - ], - 'valueFactory' => ['expects' => $this->once()], - 'configPath' => '/some/path', + 'withCustomConfigPath' => [ + 'structurePath' => '/some/path', + 'customPath' => 'customPath', + 'expectedPath' => 'customPath' ], - [ - 'deploymentConfigIsAvailable' => ['return' => true], - 'structureGetElement' => ['expects' => $this->once()], - 'field' => [ - 'hasBackendModel' => [ - 'expects' => $this->once(), - 'return' => true - ], - 'getBackendModel' => ['expects' => $this->once()], - 'getConfigPath' => [ - 'expects' => $this->once(), - 'return' => 'customPath' - ], - ], - 'valueFactory' => ['expects' => $this->once()], - 'configPath' => 'customPath', - ], - [ - 'deploymentConfigIsAvailable' => ['return' => true], - 'structureGetElement' => ['expects' => $this->once()], - 'field' => [ - 'hasBackendModel' => [ - 'expects' => $this->once(), - 'return' => false - ], - 'getBackendModel' => ['expects' => $this->never()], - 'getConfigPath' => [ - 'expects' => $this->never(), - 'return' => null - ], - ], - 'valueFactory' => ['expects' => $this->once()], - 'configPath' => '/some/path' + 'withOutCustomConfigPath' => [ + 'structurePath' => '/some/path', + 'customPath' => null, + 'expectedPath' => '/some/path' ], ]; } + + public function testCreateAndSetDataWithNewBackendModel() + { + $structurePath = '/some/path'; + $value = 'someValue'; + $scope = 'someScope'; + $scopeCode = 'someScopeCode'; + $this->structureFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($this->structureMock); + $this->deploymentConfigMock + ->expects($this->once()) + ->method('isAvailable') + ->willReturn(true); + $this->structureMock + ->expects($this->once()) + ->method('getElement') + ->willReturn($this->fieldMock); + $this->fieldMock->expects($this->once()) + ->method('hasBackendModel') + ->willReturn(false); + $this->valueFactoryMock->expects($this->once()) + ->method('create') + ->willReturn($this->valueMock); + $this->valueMock->expects($this->once()) + ->method('setPath') + ->with($structurePath) + ->willReturnSelf(); + $this->valueMock->expects($this->once()) + ->method('setScope') + ->with($scope) + ->willReturnSelf(); + $this->valueMock->expects($this->once()) + ->method('setScopeId') + ->with($scopeCode) + ->willReturnSelf(); + $this->valueMock->expects($this->once()) + ->method('setValue') + ->with($value) + ->willReturnSelf(); + + $this->assertSame( + $this->valueMock, + $this->valueBuilder->create($structurePath, $value, $scope, $scopeCode) + ); + } } From 7e2712d4c6788ead3386d30811bc24cb35eceb6f Mon Sep 17 00:00:00 2001 From: olysenko Date: Wed, 29 Mar 2017 18:11:23 +0300 Subject: [PATCH 24/44] MAGETWO-66829: [Performance] Join to product entity table cause locks on order page/api --- .../Model/ResourceModel/Stock.php | 16 ++- .../Unit/Model/ResourceModel/StockTest.php | 99 +++++++++++++++++++ 2 files changed, 112 insertions(+), 3 deletions(-) create mode 100644 app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/StockTest.php diff --git a/app/code/Magento/CatalogInventory/Model/ResourceModel/Stock.php b/app/code/Magento/CatalogInventory/Model/ResourceModel/Stock.php index 1f529818872dd..aed1e25593e48 100644 --- a/app/code/Magento/CatalogInventory/Model/ResourceModel/Stock.php +++ b/app/code/Magento/CatalogInventory/Model/ResourceModel/Stock.php @@ -125,13 +125,23 @@ public function lockProductsStock($productIds, $websiteId) return []; } $itemTable = $this->getTable('cataloginventory_stock_item'); - $productTable = $this->getTable('catalog_product_entity'); $select = $this->getConnection()->select()->from(['si' => $itemTable]) - ->join(['p' => $productTable], 'p.entity_id=si.product_id', ['type_id']) ->where('website_id=?', $websiteId) ->where('product_id IN(?)', $productIds) ->forUpdate(true); - return $this->getConnection()->fetchAll($select); + + $productTable = $this->getTable('catalog_product_entity'); + $selectProducts = $this->getConnection()->select()->from(['p' => $productTable], []) + ->where('entity_id IN (?)', $productIds) + ->columns( + [ + 'product_id' => 'entity_id', + 'type_id' => 'type_id' + ] + ); + $this->getConnection()->query($select); + + return $this->getConnection()->fetchAll($selectProducts); } /** diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/StockTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/StockTest.php new file mode 100644 index 0000000000000..b9894eb39197f --- /dev/null +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/StockTest.php @@ -0,0 +1,99 @@ +contextMock = $this->getMockBuilder(Context::class)->disableOriginalConstructor()->getMock(); + $this->resourceMock = $this->getMockBuilder(ResourceConnection::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->contextMock->expects($this->once())->method('getResources')->willReturn($this->resourceMock); + + $this->stockModel = (new ObjectManager($this))->getObject( + Stock::class, + [ + 'context' => $this->contextMock + ] + ); + } + + public function testLockProductsStock() + { + $productIds = [1, 2]; + $websiteId = 1; + $itemTable = 'item_table'; + $productTable = 'product_table'; + + $connectionMock = $this->getMockBuilder(\Magento\Framework\DB\Adapter\AdapterInterface::class)->getMock(); + $this->resourceMock->method('getConnection')->will($this->returnValue($connectionMock)); + + $this->resourceMock->method('getTableName') + ->withConsecutive(['cataloginventory_stock_item'], ['catalog_product_entity']) + ->willReturnOnConsecutiveCalls($itemTable, $productTable); + + $selectMock = $this->getMockBuilder(\Magento\Framework\DB\Select::class) + ->disableOriginalConstructor() + ->getMock(); + + $selectProductsMock = clone $selectMock; + + $selectMock->expects($this->once())->method('forUpdate')->with(true)->willReturnSelf(); + $selectMock->expects($this->once())->method('from')->with(['si' => $itemTable])->willReturnSelf(); + $selectMock->expects($this->exactly(2)) + ->method('where') + ->withConsecutive(['website_id=?', $websiteId], ['product_id IN(?)', $productIds]) + ->willReturnSelf(); + $connectionMock->expects($this->exactly(2)) + ->method('select') + ->willReturnOnConsecutiveCalls($selectMock, $selectProductsMock); + + $selectProductsMock->expects($this->once())->method('from')->with(['p' => $productTable], [])->willReturnSelf(); + $selectProductsMock->expects($this->once())->method('where') + ->with('entity_id IN (?)', $productIds) + ->willReturnSelf(); + $selectProductsMock->expects($this->once())->method('columns')->willReturnSelf(); + + $connectionMock->expects($this->once())->method('query')->with($selectMock); + $connectionMock->expects($this->once())->method('fetchAll')->with($selectProductsMock)->willReturn([]); + + $this->assertEquals([], $this->stockModel->lockProductsStock($productIds, $websiteId)); + } + + public function testLockNoProductsStock() + { + $productIds = []; + $websiteId = 1; + + $this->assertEquals([], $this->stockModel->lockProductsStock($productIds, $websiteId)); + } +} From 121738e2edac33e341fe93f79b6bd45457acaa23 Mon Sep 17 00:00:00 2001 From: Oleksandr Radchenko Date: Thu, 30 Mar 2017 15:32:44 +0300 Subject: [PATCH 25/44] MAGETWO-66855: [GITHUB] Category tree is slow with many category/product associations #7469 --- .../Magento/Catalog/Setup/UpgradeSchema.php | 36 +++++++++++++++++++ app/code/Magento/Catalog/etc/module.xml | 2 +- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/app/code/Magento/Catalog/Setup/UpgradeSchema.php b/app/code/Magento/Catalog/Setup/UpgradeSchema.php index f31f85be15179..cd620e21d1438 100755 --- a/app/code/Magento/Catalog/Setup/UpgradeSchema.php +++ b/app/code/Magento/Catalog/Setup/UpgradeSchema.php @@ -63,6 +63,10 @@ public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $con $this->recreateCatalogCategoryProductIndexTmpTable($setup); } + if (version_compare($context->getVersion(), '2.1.6', '<')) { + $this->addPathKeyToCategoryEntityTableIfNotExists($setup); + } + $setup->endSetup(); } @@ -449,4 +453,36 @@ private function recreateCatalogCategoryProductIndexTmpTable(SchemaSetupInterfac $setup->getConnection()->createTable($table); } + + /** + * Add key for the path field if not exists + * significantly improves category tree performance + * + * @param SchemaSetupInterface $setup + * @return void + */ + private function addPathKeyToCategoryEntityTableIfNotExists(SchemaSetupInterface $setup) + { + /** + * @var \Magento\Framework\DB\Adapter\AdapterInterface + */ + $connection = $setup->getConnection(); + $tableName = $setup->getTable('catalog_category_entity'); + + $keyName = $setup->getIdxName( + $tableName, + ['path'], + \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_INDEX + ); + + $existingKeys = $connection->getIndexList($tableName); + if (!array_key_exists($keyName, $existingKeys)) { + $connection->addIndex( + $tableName, + $keyName, + ['path'], + \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_INDEX + ); + } + } } diff --git a/app/code/Magento/Catalog/etc/module.xml b/app/code/Magento/Catalog/etc/module.xml index 383ab6dd26625..3fd5d10d72bf1 100644 --- a/app/code/Magento/Catalog/etc/module.xml +++ b/app/code/Magento/Catalog/etc/module.xml @@ -6,7 +6,7 @@ */ --> - + From 3ed7f9297025580e5994970aa4176d3fe0382cc9 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Thu, 30 Mar 2017 16:34:59 +0300 Subject: [PATCH 26/44] MAGETWO-66528: Add response handler Fix scope id for config saving. --- .../Analytics/Controller/Adminhtml/Subscription/Activate.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php b/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php index 66420a5b0c292..ab7ae38b08962 100644 --- a/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php +++ b/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php @@ -99,7 +99,7 @@ public function execute() Enabled::XML_ENABLED_CONFIG_STRUCTURE_PATH, Enabledisable::ENABLE_VALUE, ScopeConfigInterface::SCOPE_TYPE_DEFAULT, - null + 0 ); $this->configValueResource From 3e47dfe7d7c75a2108a069b963cc6da8fc7e3546 Mon Sep 17 00:00:00 2001 From: Oleksandr Radchenko Date: Fri, 31 Mar 2017 17:52:46 +0300 Subject: [PATCH 27/44] MAGETWO-66855: [GITHUB] Category tree is slow with many category/product associations #7469 --- .../Magento/Catalog/Setup/UpgradeSchema.php | 36 +++++++++++++++++++ app/code/Magento/Catalog/etc/module.xml | 2 +- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/app/code/Magento/Catalog/Setup/UpgradeSchema.php b/app/code/Magento/Catalog/Setup/UpgradeSchema.php index 5de47995b3d1b..0a2b89aa8cfd3 100755 --- a/app/code/Magento/Catalog/Setup/UpgradeSchema.php +++ b/app/code/Magento/Catalog/Setup/UpgradeSchema.php @@ -63,6 +63,10 @@ public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $con $this->recreateCatalogCategoryProductIndexTmpTable($setup); } + if (version_compare($context->getVersion(), '2.1.6', '<')) { + $this->addPathKeyToCategoryEntityTableIfNotExists($setup); + } + $setup->endSetup(); } @@ -449,4 +453,36 @@ private function recreateCatalogCategoryProductIndexTmpTable(SchemaSetupInterfac $setup->getConnection()->createTable($table); } + + /** + * Add key for the path field if not exists + * significantly improves category tree performance + * + * @param SchemaSetupInterface $setup + * @return void + */ + private function addPathKeyToCategoryEntityTableIfNotExists(SchemaSetupInterface $setup) + { + /** + * @var \Magento\Framework\DB\Adapter\AdapterInterface + */ + $connection = $setup->getConnection(); + $tableName = $setup->getTable('catalog_category_entity'); + + $keyName = $setup->getIdxName( + $tableName, + ['path'], + \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_INDEX + ); + + $existingKeys = $connection->getIndexList($tableName); + if (!array_key_exists($keyName, $existingKeys)) { + $connection->addIndex( + $tableName, + $keyName, + ['path'], + \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_INDEX + ); + } + } } diff --git a/app/code/Magento/Catalog/etc/module.xml b/app/code/Magento/Catalog/etc/module.xml index ce57994c92477..89e9191ef69f7 100644 --- a/app/code/Magento/Catalog/etc/module.xml +++ b/app/code/Magento/Catalog/etc/module.xml @@ -6,7 +6,7 @@ */ --> - + From 47e3006385176a371b7f02ed3b8324af20bd5ab4 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Fri, 31 Mar 2017 19:14:27 +0300 Subject: [PATCH 28/44] MAGETWO-66528: Add response handler Add handler to notifier. --- .../Model/Connector/NotifyDataChangedCommand.php | 15 +++++++++++++-- app/code/Magento/Analytics/Model/LinkProvider.php | 4 ++-- app/code/Magento/Analytics/etc/di.xml | 12 ++++++++++++ 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/app/code/Magento/Analytics/Model/Connector/NotifyDataChangedCommand.php b/app/code/Magento/Analytics/Model/Connector/NotifyDataChangedCommand.php index f8ead49de1e6b..5b0fd83ce2839 100644 --- a/app/code/Magento/Analytics/Model/Connector/NotifyDataChangedCommand.php +++ b/app/code/Magento/Analytics/Model/Connector/NotifyDataChangedCommand.php @@ -10,6 +10,7 @@ use Magento\Config\Model\Config; use Psr\Log\LoggerInterface; use Magento\Store\Model\Store; +use Magento\Analytics\Model\Connector\Http\ResponseResolver; /** * Command notifies MBI about that data collection was finished. @@ -36,6 +37,11 @@ class NotifyDataChangedCommand implements CommandInterface */ private $config; + /** + * @var ResponseResolver + */ + private $responseResolver; + /** * @var LoggerInterface */ @@ -46,17 +52,20 @@ class NotifyDataChangedCommand implements CommandInterface * @param AnalyticsToken $analyticsToken * @param Http\ClientInterface $httpClient * @param Config $config + * @param ResponseResolver $responseResolver * @param LoggerInterface $logger */ public function __construct( AnalyticsToken $analyticsToken, Http\ClientInterface $httpClient, Config $config, + ResponseResolver $responseResolver, LoggerInterface $logger ) { $this->analyticsToken = $analyticsToken; $this->httpClient = $httpClient; $this->config = $config; + $this->responseResolver = $responseResolver; $this->logger = $logger; } @@ -67,8 +76,9 @@ public function __construct( */ public function execute() { + $result = false; if ($this->analyticsToken->isTokenExist()) { - $this->httpClient->request( + $response = $this->httpClient->request( ZendClient::POST, $this->config->getConfigDataValue($this->notifyDataChangedUrlPath), [ @@ -78,7 +88,8 @@ public function execute() ), ] ); + $result = $this->responseResolver->getResult($response); } - return true; + return $result; } } diff --git a/app/code/Magento/Analytics/Model/LinkProvider.php b/app/code/Magento/Analytics/Model/LinkProvider.php index 5cfd32bfe1cd2..12a7a4718dcc6 100644 --- a/app/code/Magento/Analytics/Model/LinkProvider.php +++ b/app/code/Magento/Analytics/Model/LinkProvider.php @@ -7,8 +7,8 @@ use Magento\Analytics\Api\Data\LinkInterfaceFactory; use Magento\Analytics\Api\LinkProviderInterface; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Framework\UrlInterface; -use Magento\Framework\Webapi\Exception; use Magento\Store\Model\StoreManagerInterface; /** @@ -75,7 +75,7 @@ public function get() { $fileInfo = $this->fileInfoManager->load(); if (!$this->isFileReady($fileInfo)) { - throw new \Magento\Framework\Exception\NotFoundException(__('File is not ready yet.')); + throw new NoSuchEntityException(__('File is not ready yet.')); } return $this->linkFactory->create( [ diff --git a/app/code/Magento/Analytics/etc/di.xml b/app/code/Magento/Analytics/etc/di.xml index 8a453b96a866a..41f882c92201c 100644 --- a/app/code/Magento/Analytics/etc/di.xml +++ b/app/code/Magento/Analytics/etc/di.xml @@ -171,6 +171,13 @@ + + + + Magento\Analytics\Model\Connector\ResponseHandler\ReSignUp + + + SignUpResponseResolver @@ -186,4 +193,9 @@ OtpResponseResolver + + + NotifyDataChangedResponseResolver + + From 206c5714ebca6553f168eae876a82f3b22dfe161 Mon Sep 17 00:00:00 2001 From: Oleksandr Radchenko Date: Mon, 3 Apr 2017 13:32:48 +0300 Subject: [PATCH 29/44] MAGETWO-66855: [GITHUB] Category tree is slow with many category/product associations #7469 --- .../testsuite/Magento/Catalog/Model/CategoryTreeTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryTreeTest.php b/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryTreeTest.php index 5c253c0ac69e3..21ef8e52a2eb6 100644 --- a/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryTreeTest.php +++ b/dev/tests/integration/testsuite/Magento/Catalog/Model/CategoryTreeTest.php @@ -125,7 +125,7 @@ public function testGetParentIds() public function testGetChildren() { $this->_model->load(3); - $this->assertEquals('4,13', $this->_model->getChildren()); + $this->assertEquals(array_diff([4, 13], explode(',', $this->_model->getChildren())), []); } public function testGetPathInStore() From c5886e411772176808fae0b7a816f79b4f793a81 Mon Sep 17 00:00:00 2001 From: olysenko Date: Tue, 4 Apr 2017 12:17:15 +0300 Subject: [PATCH 30/44] MAGETWO-66212: Re-subscribe after M2 token was lost at server-side --- .../Model/Connector/NotifyDataChangedCommandTest.php | 9 ++++++++- .../Analytics/Test/Unit/Model/LinkProviderTest.php | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/NotifyDataChangedCommandTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/NotifyDataChangedCommandTest.php index 42f3d64af6d9d..19c479888a0c9 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/NotifyDataChangedCommandTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/NotifyDataChangedCommandTest.php @@ -6,6 +6,8 @@ namespace Magento\Analytics\Test\Unit\Model\Connector; use Magento\Analytics\Model\AnalyticsToken; +use Magento\Analytics\Model\Connector\Http\JsonConverter; +use Magento\Analytics\Model\Connector\Http\ResponseResolver; use Magento\Framework\HTTP\ZendClient; use Magento\Config\Model\Config; use Psr\Log\LoggerInterface; @@ -56,11 +58,16 @@ protected function setUp() $this->loggerMock = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() ->getMock(); + $successHandler = $this->getMockBuilder(\Magento\Analytics\Model\Connector\Http\ResponseHandlerInterface::class) + ->getMockForAbstractClass(); + $successHandler->method('handleResponse') + ->willReturn(true); $this->notifyDataChangedCommand = new NotifyDataChangedCommand( $this->analyticsTokenMock, $this->httpClientMock, $this->configMock, + new ResponseResolver(new JsonConverter(), [201 => $successHandler]), $this->loggerMock ); } @@ -95,6 +102,6 @@ public function testExecuteWithoutToken() ->willReturn(false); $this->httpClientMock->expects($this->never()) ->method('request'); - $this->assertTrue($this->notifyDataChangedCommand->execute()); + $this->assertFalse($this->notifyDataChangedCommand->execute()); } } diff --git a/app/code/Magento/Analytics/Test/Unit/Model/LinkProviderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/LinkProviderTest.php index bc6d77c114218..7d676b4c2899c 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/LinkProviderTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/LinkProviderTest.php @@ -132,7 +132,7 @@ public function testGet() * @param string|null $fileInitializationVector * * @dataProvider fileNotReadyDataProvider - * @expectedException \Magento\Framework\Exception\NotFoundException + * @expectedException \Magento\Framework\Exception\NoSuchEntityException * @expectedExceptionMessage File is not ready yet. */ public function testFileNotReady($fileInfoPath, $fileInitializationVector) From 516229a6da42d6aa70d047d2a27948a6cd69b255 Mon Sep 17 00:00:00 2001 From: olysenko Date: Tue, 4 Apr 2017 12:35:27 +0300 Subject: [PATCH 31/44] MAGETWO-66829: [Performance] Join to product entity table cause locks on order page/api --- .../Test/Unit/Model/ResourceModel/StockTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/StockTest.php b/app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/StockTest.php index b9894eb39197f..3ca3c24e41bdb 100644 --- a/app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/StockTest.php +++ b/app/code/Magento/CatalogInventory/Test/Unit/Model/ResourceModel/StockTest.php @@ -1,6 +1,6 @@ Date: Tue, 4 Apr 2017 12:44:38 +0300 Subject: [PATCH 32/44] MAGETWO-66783: Expand data provided in Analytics reports --- app/code/Magento/SalesAnalytics/etc/reports.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/SalesAnalytics/etc/reports.xml b/app/code/Magento/SalesAnalytics/etc/reports.xml index 6c3defb863634..bb6bdb800e9bf 100644 --- a/app/code/Magento/SalesAnalytics/etc/reports.xml +++ b/app/code/Magento/SalesAnalytics/etc/reports.xml @@ -1,7 +1,7 @@ From c48c4831795b486a7a78ed0bec0a678ba32a344d Mon Sep 17 00:00:00 2001 From: olysenko Date: Tue, 4 Apr 2017 15:05:11 +0300 Subject: [PATCH 33/44] MAGETWO-66212: Re-subscribe after M2 token was lost at server-side --- .../Analytics/Model/Connector/Http/ConverterInterface.php | 2 +- .../Magento/Analytics/Model/Connector/Http/JsonConverter.php | 2 +- .../Analytics/Model/Connector/Http/ResponseHandlerInterface.php | 2 +- .../Magento/Analytics/Model/Connector/Http/ResponseResolver.php | 2 +- .../Magento/Analytics/Model/Connector/ResponseHandler/OTP.php | 2 +- .../Analytics/Model/Connector/ResponseHandler/ReSignUp.php | 2 +- .../Analytics/Model/Connector/ResponseHandler/SignUp.php | 2 +- .../Analytics/Model/Connector/ResponseHandler/Update.php | 2 +- .../Test/Unit/Model/Connector/Http/JsonConverterTest.php | 2 +- .../Test/Unit/Model/Connector/Http/ResponseResolverTest.php | 2 +- .../Test/Unit/Model/Connector/ResponseHandler/OTPTest.php | 2 +- .../Test/Unit/Model/Connector/ResponseHandler/ReSignUpTest.php | 2 +- .../Test/Unit/Model/Connector/ResponseHandler/SignUpTest.php | 2 +- .../Test/Unit/Model/Connector/ResponseHandler/UpdateTest.php | 2 +- 14 files changed, 14 insertions(+), 14 deletions(-) diff --git a/app/code/Magento/Analytics/Model/Connector/Http/ConverterInterface.php b/app/code/Magento/Analytics/Model/Connector/Http/ConverterInterface.php index 3a3ae66e0fb17..a6ce85cadc62f 100644 --- a/app/code/Magento/Analytics/Model/Connector/Http/ConverterInterface.php +++ b/app/code/Magento/Analytics/Model/Connector/Http/ConverterInterface.php @@ -1,6 +1,6 @@ Date: Tue, 4 Apr 2017 15:58:25 +0300 Subject: [PATCH 34/44] MAGETWO-66484: Analytics Module does not support tables with prefixes --- .../Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php | 1 + 1 file changed, 1 insertion(+) diff --git a/app/code/Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php b/app/code/Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php index a900f9d4df17e..a369672016be3 100644 --- a/app/code/Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php +++ b/app/code/Magento/Analytics/ReportXml/DB/Assembler/JoinAssembler.php @@ -43,6 +43,7 @@ class JoinAssembler implements AssemblerInterface * @param ConditionResolver $conditionResolver * @param ColumnsResolver $columnsResolver * @param NameResolver $nameResolver + * @param ResourceConnection $resourceConnection */ public function __construct( ConditionResolver $conditionResolver, From 7c7c9870ae5be6f0390fd15162c108b6a42ca4c2 Mon Sep 17 00:00:00 2001 From: olysenko Date: Tue, 4 Apr 2017 16:18:00 +0300 Subject: [PATCH 35/44] MAGETWO-66212: Re-subscribe after M2 token was lost at server-side --- app/code/Magento/Analytics/Model/Connector/SignUpRequest.php | 0 app/code/Magento/Analytics/Model/Subscription.php | 0 .../Analytics/Test/Unit/Model/Connector/SignUpRequestTest.php | 0 app/code/Magento/Analytics/Test/Unit/Model/SubscriptionTest.php | 0 4 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 app/code/Magento/Analytics/Model/Connector/SignUpRequest.php delete mode 100644 app/code/Magento/Analytics/Model/Subscription.php delete mode 100644 app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpRequestTest.php delete mode 100644 app/code/Magento/Analytics/Test/Unit/Model/SubscriptionTest.php diff --git a/app/code/Magento/Analytics/Model/Connector/SignUpRequest.php b/app/code/Magento/Analytics/Model/Connector/SignUpRequest.php deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/app/code/Magento/Analytics/Model/Subscription.php b/app/code/Magento/Analytics/Model/Subscription.php deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpRequestTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/SignUpRequestTest.php deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionTest.php b/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionTest.php deleted file mode 100644 index e69de29bb2d1d..0000000000000 From f07f250d51dbf1f8daa0ec510e1f6d0a63c62428 Mon Sep 17 00:00:00 2001 From: olysenko Date: Tue, 4 Apr 2017 16:35:52 +0300 Subject: [PATCH 36/44] MAGETWO-66212: Re-subscribe after M2 token was lost at server-side --- .../Model/Connector/Http/ReSignUpResponseResolverTest.php | 2 +- .../_files/enabled_subscription_with_invalid_token.php | 2 +- .../_files/enabled_subscription_with_invalid_token_rollback.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php b/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php index 492d45606880c..9230afcac355c 100644 --- a/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php +++ b/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php @@ -1,6 +1,6 @@ Date: Tue, 4 Apr 2017 19:02:52 +0300 Subject: [PATCH 37/44] MAGETWO-66798: Create integration test --- .../Model/Connector/Http/ReSignUpResponseResolverTest.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php b/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php index 9230afcac355c..a6484bdb3f152 100644 --- a/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php +++ b/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php @@ -98,7 +98,12 @@ private function getSubscribeSchedule() * @var $scopeConfig ScopeConfigInterface */ $scopeConfig = $objectManager->get(ScopeConfigInterface::class); - return $scopeConfig->getValue(SubscriptionHandler::CRON_STRING_PATH); + + return $scopeConfig->getValue( + SubscriptionHandler::CRON_STRING_PATH, + ScopeConfigInterface::SCOPE_TYPE_DEFAULT, + 0 + ); } /** From 69f2a5779641c7f1ee8a077f5b5fbb29218b48d9 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Wed, 5 Apr 2017 12:23:26 +0300 Subject: [PATCH 38/44] MAGETWO-66798: Create integration test fix cleanup --- dev/tests/integration/phpunit.xml.dist | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev/tests/integration/phpunit.xml.dist b/dev/tests/integration/phpunit.xml.dist index 742eb1d940b2f..7820eb746da5d 100644 --- a/dev/tests/integration/phpunit.xml.dist +++ b/dev/tests/integration/phpunit.xml.dist @@ -47,7 +47,7 @@ - + From 3a1a7f1930f0927c27443481af608df2f820f225 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Wed, 5 Apr 2017 14:00:02 +0300 Subject: [PATCH 39/44] MAGETWO-66798: Create integration test fix cleanup --- .../_files/enabled_subscription_with_invalid_token.php | 2 +- .../_files/enabled_subscription_with_invalid_token_rollback.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token.php b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token.php index 027e788c7f188..0d9ce7a05cd5a 100644 --- a/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token.php +++ b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token.php @@ -13,7 +13,7 @@ $configWriter = $objectManager->get(\Magento\Framework\App\Config\Storage\WriterInterface::class); $configWriter->delete(SubscriptionHandler::CRON_STRING_PATH); -$configWriter->save('default/analytics/subscription/enabled', 1); +$configWriter->save('analytics/subscription/enabled', 1); /** * @var $analyticsToken \Magento\Analytics\Model\AnalyticsToken diff --git a/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php index d3f7eea13b0a2..e90c7b2b3151e 100644 --- a/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php +++ b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php @@ -13,7 +13,7 @@ $configWriter = $objectManager->get(\Magento\Framework\App\Config\Storage\WriterInterface::class); $configWriter->delete(SubscriptionHandler::CRON_STRING_PATH); -$configWriter->save('default/analytics/subscription/enabled', 0); +$configWriter->save('analytics/subscription/enabled', 0); /** * @var $analyticsToken \Magento\Analytics\Model\AnalyticsToken From f960cd60cf31e7a776255dbb19925351c34bb586 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Wed, 5 Apr 2017 18:43:37 +0300 Subject: [PATCH 40/44] MAGETWO-66798: Create integration test revert cleanup --- dev/tests/integration/phpunit.xml.dist | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev/tests/integration/phpunit.xml.dist b/dev/tests/integration/phpunit.xml.dist index 7820eb746da5d..742eb1d940b2f 100644 --- a/dev/tests/integration/phpunit.xml.dist +++ b/dev/tests/integration/phpunit.xml.dist @@ -47,7 +47,7 @@ - + From c1a7729ce207a9d40ee6fe955697d5ed8f442192 Mon Sep 17 00:00:00 2001 From: Vladyslav Shcherbyna Date: Thu, 6 Apr 2017 12:18:03 +0300 Subject: [PATCH 41/44] MAGETWO-66798: Create integration test fix cleanup --- dev/tests/integration/phpunit.xml.dist | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev/tests/integration/phpunit.xml.dist b/dev/tests/integration/phpunit.xml.dist index 742eb1d940b2f..7820eb746da5d 100644 --- a/dev/tests/integration/phpunit.xml.dist +++ b/dev/tests/integration/phpunit.xml.dist @@ -47,7 +47,7 @@ - + From b01631e4a660836afa935353060e2936f47e1500 Mon Sep 17 00:00:00 2001 From: olysenko Date: Thu, 6 Apr 2017 18:12:17 +0300 Subject: [PATCH 42/44] MAGETWO-66212: Re-subscribe after M2 token was lost at server-side --- .../Controller/Adminhtml/Subscription/Activate.php | 3 +-- app/code/Magento/Config/Model/PreparedValueFactory.php | 9 +++++---- .../Config/Test/Unit/Model/PreparedValueFactoryTest.php | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php b/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php index f5ba41c557c48..b5731fc07bb07 100644 --- a/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php +++ b/app/code/Magento/Analytics/Controller/Adminhtml/Subscription/Activate.php @@ -98,8 +98,7 @@ public function execute() $configValue = $this->preparedValueFactory->create( Enabled::XML_ENABLED_CONFIG_STRUCTURE_PATH, Enabledisable::ENABLE_VALUE, - ScopeConfigInterface::SCOPE_TYPE_DEFAULT, - 0 + ScopeConfigInterface::SCOPE_TYPE_DEFAULT ); $this->configValueResource diff --git a/app/code/Magento/Config/Model/PreparedValueFactory.php b/app/code/Magento/Config/Model/PreparedValueFactory.php index 20484f3532c36..322f74406b1ea 100644 --- a/app/code/Magento/Config/Model/PreparedValueFactory.php +++ b/app/code/Magento/Config/Model/PreparedValueFactory.php @@ -75,12 +75,13 @@ public function create($path, $value, $scope, $scopeCode = null) try { /** @var Structure $structure */ $structure = $this->structureFactory->create(); + $backendModel = $this->valueFactory->create(); /** @var Structure\ElementInterface $field */ $field = $structure->getElement($path); - /** @var ValueInterface $backendModel */ - $backendModel = $field instanceof Structure\Element\Field && $field->hasBackendModel() - ? $field->getBackendModel() - : $this->valueFactory->create(); + if ($field instanceof Structure\Element\Field && $field->hasBackendModel()) { + $backendModel = $field->getBackendModel(); + $path = $field->getConfigPath() ?: $path; + } if ($backendModel instanceof Value) { $scopeId = 0; diff --git a/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php b/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php index 2b3b870396da5..de3323bce58de 100644 --- a/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php @@ -146,7 +146,7 @@ public function testCreate( $this->fieldMock->expects($this->once()) ->method('getBackendModel') ->willReturn($this->valueMock); - $this->valueFactoryMock->expects($this->never()) + $this->valueFactoryMock->expects($this->once()) ->method('create') ->willReturn($this->valueMock); $this->valueMock->expects($this->once()) From 0470c5b443c578882005fbe02a1ee532f74c6dea Mon Sep 17 00:00:00 2001 From: Max Lesechko Date: Mon, 10 Apr 2017 12:32:23 +0300 Subject: [PATCH 43/44] MAGETWO-66212: Re-subscribe after M2 token was lost at server-side -- resolve merge conflicts --- .../Backend/Enabled/SubscriptionHandler.php | 2 +- .../Model/Connector/UpdateCommand.php | 2 +- .../Model/SubscriptionStatusProvider.php | 1 + .../Model/Connector/UpdateCommandTest.php | 2 +- .../Model/SubscriptionStatusProviderTest.php | 2 +- .../Config/Model/PreparedValueFactory.php | 35 ++++++++++++++---- .../Unit/Model/PreparedValueFactoryTest.php | 37 +++++++++++++++---- 7 files changed, 61 insertions(+), 20 deletions(-) diff --git a/app/code/Magento/Analytics/Model/Config/Backend/Enabled/SubscriptionHandler.php b/app/code/Magento/Analytics/Model/Config/Backend/Enabled/SubscriptionHandler.php index b9700e433e833..d23f5a7c60d91 100644 --- a/app/code/Magento/Analytics/Model/Config/Backend/Enabled/SubscriptionHandler.php +++ b/app/code/Magento/Analytics/Model/Config/Backend/Enabled/SubscriptionHandler.php @@ -7,10 +7,10 @@ use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\Config\Backend\CollectionTime; -use Magento\Analytics\Model\FlagManager; use Magento\Analytics\Model\NotificationTime; use Magento\Framework\App\Config\ReinitableConfigInterface; use Magento\Framework\App\Config\Storage\WriterInterface; +use Magento\Framework\FlagManager; /** * Class for processing of activation/deactivation MBI subscription. diff --git a/app/code/Magento/Analytics/Model/Connector/UpdateCommand.php b/app/code/Magento/Analytics/Model/Connector/UpdateCommand.php index 92db643759dbf..a2d64a98e0409 100644 --- a/app/code/Magento/Analytics/Model/Connector/UpdateCommand.php +++ b/app/code/Magento/Analytics/Model/Connector/UpdateCommand.php @@ -7,9 +7,9 @@ use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\Connector\Http\ResponseResolver; -use Magento\Analytics\Model\FlagManager; use Magento\Analytics\Model\Plugin\BaseUrlConfigPlugin; use Magento\Config\Model\Config; +use Magento\Framework\FlagManager; use Magento\Framework\HTTP\ZendClient; use Magento\Store\Model\Store; use Psr\Log\LoggerInterface; diff --git a/app/code/Magento/Analytics/Model/SubscriptionStatusProvider.php b/app/code/Magento/Analytics/Model/SubscriptionStatusProvider.php index f5df0c18b43f3..8fe548013c206 100644 --- a/app/code/Magento/Analytics/Model/SubscriptionStatusProvider.php +++ b/app/code/Magento/Analytics/Model/SubscriptionStatusProvider.php @@ -7,6 +7,7 @@ use Magento\Analytics\Model\Config\Backend\Enabled\SubscriptionHandler; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\FlagManager; /** * Provider of subscription status. diff --git a/app/code/Magento/Analytics/Test/Unit/Model/Connector/UpdateCommandTest.php b/app/code/Magento/Analytics/Test/Unit/Model/Connector/UpdateCommandTest.php index a950bb2cf8002..c5f96a96b4432 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/Connector/UpdateCommandTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/Connector/UpdateCommandTest.php @@ -7,7 +7,7 @@ use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\Connector\Http\ResponseResolver; -use Magento\Analytics\Model\FlagManager; +use Magento\Framework\FlagManager; use Magento\Framework\HTTP\ZendClient; use Magento\Config\Model\Config; use Psr\Log\LoggerInterface; diff --git a/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php b/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php index 79e98af08d77a..90707b2db7e1a 100644 --- a/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php +++ b/app/code/Magento/Analytics/Test/Unit/Model/SubscriptionStatusProviderTest.php @@ -7,9 +7,9 @@ use Magento\Analytics\Model\AnalyticsToken; use Magento\Analytics\Model\Config\Backend\Enabled\SubscriptionHandler; -use Magento\Analytics\Model\FlagManager; use Magento\Analytics\Model\SubscriptionStatusProvider; use Magento\Framework\App\Config\ScopeConfigInterface; +use Magento\Framework\FlagManager; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager as ObjectManagerHelper; /** diff --git a/app/code/Magento/Config/Model/PreparedValueFactory.php b/app/code/Magento/Config/Model/PreparedValueFactory.php index 322f74406b1ea..dd19be9af29a2 100644 --- a/app/code/Magento/Config/Model/PreparedValueFactory.php +++ b/app/code/Magento/Config/Model/PreparedValueFactory.php @@ -5,11 +5,12 @@ */ namespace Magento\Config\Model; +use Magento\Config\Model\Config\BackendFactory; use Magento\Config\Model\Config\Structure; use Magento\Config\Model\Config\StructureFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\Config\ValueInterface; use Magento\Framework\App\Config\Value; -use Magento\Framework\App\Config\ValueFactory; use Magento\Framework\App\ScopeInterface; use Magento\Framework\App\ScopeResolverPool; use Magento\Framework\Exception\RuntimeException; @@ -39,23 +40,33 @@ class PreparedValueFactory * The factory for configuration value objects. * * @see ValueInterface - * @var ValueFactory + * @var BackendFactory */ private $valueFactory; + /** + * The scope configuration. + * + * @var ScopeConfigInterface + */ + private $config; + /** * @param ScopeResolverPool $scopeResolverPool The scope resolver pool * @param StructureFactory $structureFactory The manager for system configuration structure - * @param ValueFactory $valueFactory The factory for configuration value objects + * @param BackendFactory $valueFactory The factory for configuration value objects + * @param ScopeConfigInterface $config The scope configuration */ public function __construct( ScopeResolverPool $scopeResolverPool, StructureFactory $structureFactory, - ValueFactory $valueFactory + BackendFactory $valueFactory, + ScopeConfigInterface $config ) { $this->scopeResolverPool = $scopeResolverPool; $this->structureFactory = $structureFactory; $this->valueFactory = $valueFactory; + $this->config = $config; } /** @@ -75,13 +86,21 @@ public function create($path, $value, $scope, $scopeCode = null) try { /** @var Structure $structure */ $structure = $this->structureFactory->create(); - $backendModel = $this->valueFactory->create(); /** @var Structure\ElementInterface $field */ $field = $structure->getElement($path); + $configPath = $path; + /** @var string $backendModelName */ if ($field instanceof Structure\Element\Field && $field->hasBackendModel()) { - $backendModel = $field->getBackendModel(); - $path = $field->getConfigPath() ?: $path; + $backendModelName = $field->getData()['backend_model']; + $configPath = $field->getConfigPath() ?: $path; + } else { + $backendModelName = ValueInterface::class; } + /** @var ValueInterface $backendModel */ + $backendModel = $this->valueFactory->create( + $backendModelName, + ['config' => $this->config] + ); if ($backendModel instanceof Value) { $scopeId = 0; @@ -91,7 +110,7 @@ public function create($path, $value, $scope, $scopeCode = null) $scopeId = $scopeResolver->getScope($scopeCode)->getId(); } - $backendModel->setPath($path); + $backendModel->setPath($configPath); $backendModel->setScope($scope); $backendModel->setScopeId($scopeId); $backendModel->setValue($value); diff --git a/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php b/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php index de3323bce58de..5f7f7ed3532ab 100644 --- a/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php +++ b/app/code/Magento/Config/Test/Unit/Model/PreparedValueFactoryTest.php @@ -5,8 +5,9 @@ */ namespace Magento\Config\Test\Unit\Model; +use Magento\Config\Model\Config\BackendFactory; use Magento\Config\Model\PreparedValueFactory; -use Magento\Framework\App\Config\ValueFactory; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Config\Model\Config\StructureFactory; use Magento\Framework\App\Config\Value; use Magento\Config\Model\Config\Structure; @@ -27,7 +28,7 @@ class PreparedValueFactoryTest extends \PHPUnit_Framework_TestCase private $structureFactoryMock; /** - * @var ValueFactory|Mock + * @var BackendFactory|Mock */ private $valueFactoryMock; @@ -46,6 +47,11 @@ class PreparedValueFactoryTest extends \PHPUnit_Framework_TestCase */ private $fieldMock; + /** + * @var ScopeConfigInterface|Mock + */ + private $configMock; + /** * @var ScopeResolverPool|Mock */ @@ -75,7 +81,7 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); - $this->valueFactoryMock = $this->getMockBuilder(ValueFactory::class) + $this->valueFactoryMock = $this->getMockBuilder(BackendFactory::class) ->disableOriginalConstructor() ->setMethods(['create']) ->getMock(); @@ -89,6 +95,8 @@ protected function setUp() ->disableOriginalConstructor() ->setMethods(['setPath', 'setScope', 'setScopeId', 'setValue']) ->getMock(); + $this->configMock = $this->getMockBuilder(ScopeConfigInterface::class) + ->getMockForAbstractClass(); $this->scopeResolverPoolMock = $this->getMockBuilder(ScopeResolverPool::class) ->disableOriginalConstructor() ->getMock(); @@ -101,12 +109,14 @@ protected function setUp() $this->preparedValueFactory = new PreparedValueFactory( $this->scopeResolverPoolMock, $this->structureFactoryMock, - $this->valueFactoryMock + $this->valueFactoryMock, + $this->configMock ); } /** * @param string $path + * @param string|null $configPath * @param string $value * @param string $scope * @param string|int|null $scopeCode @@ -115,6 +125,7 @@ protected function setUp() */ public function testCreate( $path, + $configPath, $value, $scope, $scopeCode, @@ -143,15 +154,15 @@ public function testCreate( $this->fieldMock->expects($this->once()) ->method('hasBackendModel') ->willReturn(true); - $this->fieldMock->expects($this->once()) - ->method('getBackendModel') - ->willReturn($this->valueMock); + $this->fieldMock + ->method('getConfigPath') + ->willReturn($configPath); $this->valueFactoryMock->expects($this->once()) ->method('create') ->willReturn($this->valueMock); $this->valueMock->expects($this->once()) ->method('setPath') - ->with($path) + ->with($configPath ?: $path) ->willReturnSelf(); $this->valueMock->expects($this->once()) ->method('setScope') @@ -180,6 +191,15 @@ public function createDataProvider() return [ 'standard flow' => [ '/some/path', + null, + 'someValue', + 'someScope', + 'someScopeCode', + 1, + ], + 'standard flow with custom config path' => [ + '/some/path', + '/custom/config_path', 'someValue', 'someScope', 'someScopeCode', @@ -187,6 +207,7 @@ public function createDataProvider() ], 'default scope flow' => [ '/some/path', + null, 'someValue', ScopeInterface::SCOPE_DEFAULT, null, From 671bed07b11beabf2bb6b4115e9a2f6bc3ea8ba8 Mon Sep 17 00:00:00 2001 From: Max Lesechko Date: Mon, 10 Apr 2017 13:57:07 +0300 Subject: [PATCH 44/44] MAGETWO-66212: Re-subscribe after M2 token was lost at server-side -- fix problems with FileManager moving --- app/code/Magento/Analytics/Model/NotificationTime.php | 2 +- .../Model/Connector/Http/ReSignUpResponseResolverTest.php | 2 +- .../_files/enabled_subscription_with_invalid_token.php | 4 ++-- .../enabled_subscription_with_invalid_token_rollback.php | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/app/code/Magento/Analytics/Model/NotificationTime.php b/app/code/Magento/Analytics/Model/NotificationTime.php index 47b9f35cc77b9..9272542f4dedd 100644 --- a/app/code/Magento/Analytics/Model/NotificationTime.php +++ b/app/code/Magento/Analytics/Model/NotificationTime.php @@ -25,7 +25,7 @@ class NotificationTime /** * NotificationTime constructor. * - * @param \Magento\Analytics\Model\FlagManager $flagManager + * @param FlagManager $flagManager */ public function __construct( FlagManager $flagManager diff --git a/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php b/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php index a6484bdb3f152..f69c751e1357f 100644 --- a/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php +++ b/dev/tests/integration/testsuite/Magento/Analytics/Model/Connector/Http/ReSignUpResponseResolverTest.php @@ -6,7 +6,7 @@ namespace Magento\Analytics\Model\Connector\Http; use Magento\Analytics\Model\Config\Backend\Enabled\SubscriptionHandler; -use Magento\Analytics\Model\FlagManager; +use Magento\Framework\FlagManager; use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\TestFramework\Helper\Bootstrap; diff --git a/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token.php b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token.php index 0d9ce7a05cd5a..0106bf6f1bdac 100644 --- a/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token.php +++ b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token.php @@ -22,8 +22,8 @@ $analyticsToken->storeToken('42'); /** - * @var $flagManager \Magento\Analytics\Model\FlagManager + * @var $flagManager \Magento\Framework\FlagManager */ -$flagManager = $objectManager->get(\Magento\Analytics\Model\FlagManager::class); +$flagManager = $objectManager->get(\Magento\Framework\FlagManager::class); $flagManager->deleteFlag(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE); diff --git a/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php index e90c7b2b3151e..3fd3e21e282e0 100644 --- a/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php +++ b/dev/tests/integration/testsuite/Magento/Analytics/_files/enabled_subscription_with_invalid_token_rollback.php @@ -22,8 +22,8 @@ $analyticsToken->storeToken(null); /** - * @var $flagManager \Magento\Analytics\Model\FlagManager + * @var $flagManager \Magento\Framework\FlagManager */ -$flagManager = $objectManager->get(\Magento\Analytics\Model\FlagManager::class); +$flagManager = $objectManager->get(\Magento\Framework\FlagManager::class); $flagManager->deleteFlag(SubscriptionHandler::ATTEMPTS_REVERSE_COUNTER_FLAG_CODE);