Skip to content

Commit

Permalink
Merge pull request #623 from magento-api/pull-request
Browse files Browse the repository at this point in the history
[API] Bug Fixes
  • Loading branch information
monkeysee committed May 14, 2016
2 parents b5900bc + ceb7f46 commit 08eebe4
Show file tree
Hide file tree
Showing 38 changed files with 499 additions and 12 deletions.
1 change: 1 addition & 0 deletions app/code/Magento/Backend/Block/Widget/Grid/Export.php
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ public function _exportIterateCollection($callback, array $args)
$break = false;

while ($break !== true) {
$originalCollection->clear();
$originalCollection->setPageSize($this->getExportPageSize());
$originalCollection->setCurPage($page);
$originalCollection->load();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public function testSetCookiePathNonDefault()
public function testSetSessionSettingsByConstructor($secureRequest)
{
$sessionName = 'admin';
$this->requestMock->expects($this->once())->method('isSecure')->willReturn($secureRequest);
$this->requestMock->expects($this->exactly(2))->method('isSecure')->willReturn($secureRequest);

$validatorMock = $this->getMockBuilder('Magento\Framework\Validator\ValidatorInterface')
->disableOriginalConstructor()
Expand Down
8 changes: 6 additions & 2 deletions app/code/Magento/Customer/Api/CustomerRepositoryInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
interface CustomerRepositoryInterface
{
/**
* Create customer.
* Create or update a customer.
*
* @api
* @param \Magento\Customer\Api\Data\CustomerInterface $customer
Expand All @@ -38,7 +38,7 @@ public function save(\Magento\Customer\Api\Data\CustomerInterface $customer, $pa
public function get($email, $websiteId = null);

/**
* Retrieve customer.
* Get customer by customer ID.
*
* @api
* @param int $customerId
Expand All @@ -51,6 +51,10 @@ public function getById($customerId);
/**
* Retrieve customers which match a specified criteria.
*
* This call returns an array of objects, but detailed information about each object’s attributes might not be
* included. See http://devdocs.magento.com/codelinks/attributes.html#CustomerRepositoryInterface to determine
* which call to use to get detailed information about all attributes for an object.
*
* @api
* @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
* @return \Magento\Customer\Api\Data\CustomerSearchResultsInterface
Expand Down
4 changes: 4 additions & 0 deletions app/code/Magento/Customer/Api/GroupRepositoryInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ public function getById($id);
* The list of groups can be filtered to exclude the NOT_LOGGED_IN group using the first parameter and/or it can
* be filtered by tax class.
*
* This call returns an array of objects, but detailed information about each object’s attributes might not be
* included. See http://devdocs.magento.com/codelinks/attributes.html#GroupRepositoryInterface to determine
* which call to use to get detailed information about all attributes for an object.
*
* @api
* @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
* @return \Magento\Customer\Api\Data\GroupSearchResultsInterface
Expand Down
7 changes: 5 additions & 2 deletions app/code/Magento/Directory/Model/Currency/Import/FixerIo.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,11 @@ private function convertBatch($data, $currencyFrom, $currenciesTo)
$url = str_replace('{{CURRENCY_TO}}', $currenciesStr, $url);

set_time_limit(0);
$response = $this->getServiceResponse($url);
ini_restore('max_execution_time');
try {
$response = $this->getServiceResponse($url);
} finally {
ini_restore('max_execution_time');
}

foreach ($currenciesTo as $currencyTo) {
if ($currencyFrom == $currencyTo) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ protected function _convert($currencyFrom, $currencyTo, $retry = 0)
)->getBody();

$xml = simplexml_load_string($response, null, LIBXML_NOERROR);
if (!$xml) {
if (!$xml || (isset($xml[0]) && $xml[0] == -1)) {
$this->_messages[] = __('We can\'t retrieve a rate from %1.', $url);
return null;
}
Expand Down
183 changes: 183 additions & 0 deletions app/code/Magento/Directory/Model/Currency/Import/YahooFinance.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Directory\Model\Currency\Import;

/**
* Currency rate import model (From http://query.yahooapis.com/)
*/
class YahooFinance extends \Magento\Directory\Model\Currency\Import\AbstractImport
{
/**
* Currency converter url string
*
* @var string
*/
private $currencyConverterUrl = 'http://query.yahooapis.com/v1/public/yql?format=json&q={{YQL_STRING}}'
.'&env=store://datatables.org/alltableswithkeys';

/**
* Config path for service timeout
*
* @var string
*/
private $timeoutConfigPath = 'currency/yahoofinance/timeout';

/**
* Http Client Factory
*
* @var \Magento\Framework\HTTP\ZendClientFactory
*/
protected $httpClientFactory;

/**
* Core scope config
*
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
private $scopeConfig;

/**
* Initialize dependencies
*
* @param \Magento\Directory\Model\CurrencyFactory $currencyFactory
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
* @param \Magento\Framework\HTTP\ZendClientFactory $httpClientFactory
*/
public function __construct(
\Magento\Directory\Model\CurrencyFactory $currencyFactory,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\HTTP\ZendClientFactory $httpClientFactory
) {
parent::__construct($currencyFactory);
$this->scopeConfig = $scopeConfig;
$this->httpClientFactory = $httpClientFactory;
}

/**
* {@inheritdoc}
*/
public function fetchRates()
{
$data = [];
$currencies = $this->_getCurrencyCodes();
$defaultCurrencies = $this->_getDefaultCurrencyCodes();

foreach ($defaultCurrencies as $currencyFrom) {
if (!isset($data[$currencyFrom])) {
$data[$currencyFrom] = [];
}
$data = $this->convertBatch($data, $currencyFrom, $currencies);
ksort($data[$currencyFrom]);
}
return $data;
}

/**
* Return currencies convert rates in batch mode
*
* @param array $data
* @param string $currencyFrom
* @param array $currenciesTo
* @return array
*/
private function convertBatch($data, $currencyFrom, $currenciesTo)
{
$url = $this->buildUrl($currencyFrom, $currenciesTo);
set_time_limit(0);
try {
$response = $this->getServiceResponse($url);
} finally {
ini_restore('max_execution_time');
}

foreach ($currenciesTo as $currencyTo) {
if ($currencyFrom == $currencyTo) {
$data[$currencyFrom][$currencyTo] = $this->_numberFormat(1);
} else {
if (empty($response[$currencyFrom . $currencyTo])) {
$this->_messages[] = __('We can\'t retrieve a rate from %1 for %2.', $url, $currencyTo);
$data[$currencyFrom][$currencyTo] = null;
} else {
$data[$currencyFrom][$currencyTo] = $this->_numberFormat(
(double)$response[$currencyFrom . $currencyTo]
);
}
}
}
return $data;
}

/**
* Get Fixer.io service response
*
* @param string $url
* @param int $retry
* @return array
*/
private function getServiceResponse($url, $retry = 0)
{
/** @var \Magento\Framework\HTTP\ZendClient $httpClient */
$httpClient = $this->httpClientFactory->create();
$response = [];
try {
$jsonResponse = $httpClient->setUri(
$url
)->setConfig(
[
'timeout' => $this->scopeConfig->getValue(
$this->timeoutConfigPath,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
),
]
)->request(
'GET'
)->getBody();

$jsonResponse = json_decode($jsonResponse, true);
if (!empty($jsonResponse['query']['results']['rate'])) {
$response = array_column($jsonResponse['query']['results']['rate'], 'Rate', 'id');
}
} catch (\Exception $e) {
if ($retry == 0) {
$response = $this->getServiceResponse($url, 1);
}
}
return $response;
}

/**
* {@inheritdoc}
*/
protected function _convert($currencyFrom, $currencyTo)
{
}

/**
* Build url for Currency Service
*
* @param string $currencyFrom
* @param string[] $currenciesTo
* @return string
*/
private function buildUrl($currencyFrom, $currenciesTo)
{
$query = urlencode('select ') . '*' . urlencode(' from yahoo.finance.xchange where pair in (');
$query .=
urlencode(
implode(
',',
array_map(
function ($currencyTo) use ($currencyFrom) {
return '"' . $currencyFrom . $currencyTo . '"';
},
$currenciesTo
)
)
);
$query .= ')';
return str_replace('{{YQL_STRING}}', $query, $this->currencyConverterUrl);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php
/**
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/

namespace Magento\Directory\Test\Unit\Model\Currency\Import;

class YahooFinanceTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \Magento\Directory\Model\Currency\Import\YahooFinance
*/
private $model;

/**
* @var \Magento\Directory\Model\CurrencyFactory|\PHPUnit_Framework_MockObject_MockObject
*/
private $currencyFactoryMock;

/**
* @var \Magento\Framework\HTTP\ZendClientFactory|\PHPUnit_Framework_MockObject_MockObject
*/
private $httpClientFactoryMock;

protected function setUp()
{
$objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);

$this->currencyFactoryMock = $this->getMockBuilder('Magento\Directory\Model\CurrencyFactory')
->disableOriginalConstructor()
->setMethods(['create'])
->getMock();
$this->httpClientFactoryMock = $this->getMockBuilder('Magento\Framework\HTTP\ZendClientFactory')
->disableOriginalConstructor()
->setMethods(['create'])
->getMock();
$scopeMock = $this->getMockBuilder('Magento\Framework\App\Config\ScopeConfigInterface')
->disableOriginalConstructor()
->setMethods([])
->getMock();

$this->model = $objectManagerHelper->getObject(
'Magento\Directory\Model\Currency\Import\YahooFinance',
[
'currencyFactory' => $this->currencyFactoryMock,
'scopeConfig' => $scopeMock,
'httpClientFactory' => $this->httpClientFactoryMock
]
);
}

public function testFetchRates()
{
$currencyFromList = ['USD'];
$currencyToList = ['EUR', 'UAH'];
$responseBody = '{"query":{"count":7,"created":"2016-04-05T16:46:55Z","lang":"en-US","results":{"rate":'
. '[{"id":"USDEUR","Name":"USD/EUR","Rate":"0.9022","Date":"4/5/2016"}]}}}';
$expectedCurrencyRateList = ['USD' => ['EUR' => 0.9022, 'UAH' => null]];
$message = "We can't retrieve a rate from http://query.yahooapis.com/v1/public/yql?format=json"
. "&q=select+*+from+yahoo.finance.xchange+where+pair+in+%28%22USDEUR%22%2C%22USDUAH%22)"
. "&env=store://datatables.org/alltableswithkeys for UAH.";

/** @var \Magento\Directory\Model\Currency|\PHPUnit_Framework_MockObject_MockObject $currencyMock */
$currencyMock = $this->getMockBuilder('Magento\Directory\Model\Currency')
->disableOriginalConstructor()
->setMethods([])
->getMock();
/** @var \Magento\Framework\HTTP\ZendClient|\PHPUnit_Framework_MockObject_MockObject $currencyMock */
$httpClientMock = $this->getMockBuilder('Magento\Framework\HTTP\ZendClient')
->disableOriginalConstructor()
->setMethods([])
->getMock();
/** @var \Zend_Http_Response|\PHPUnit_Framework_MockObject_MockObject $currencyMock */
$httpResponseMock = $this->getMockBuilder('Zend_Http_Response')
->disableOriginalConstructor()
->setMethods([])
->getMock();
$this->currencyFactoryMock->expects($this->any())->method('create')->willReturn($currencyMock);
$currencyMock->expects($this->once())->method('getConfigBaseCurrencies')->willReturn($currencyFromList);
$currencyMock->expects($this->once())->method('getConfigAllowCurrencies')->willReturn($currencyToList);
$this->httpClientFactoryMock->expects($this->any())->method('create')->willReturn($httpClientMock);
$httpClientMock->expects($this->atLeastOnce())->method('setUri')->willReturnSelf();
$httpClientMock->expects($this->atLeastOnce())->method('setConfig')->willReturnSelf();
$httpClientMock->expects($this->atLeastOnce())->method('request')->willReturn($httpResponseMock);
$httpResponseMock->expects($this->any())->method('getBody')->willReturn($responseBody);

$this->assertEquals($expectedCurrencyRateList, $this->model->fetchRates());
$messages = $this->model->getMessages();
$this->assertNotEmpty($messages);
$this->assertTrue(is_array($messages));
$this->assertEquals($message, (string)$messages[0]);
}
}
12 changes: 12 additions & 0 deletions app/code/Magento/Directory/etc/adminhtml/system.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,18 @@
<can_be_empty>1</can_be_empty>
</field>
</group>
<group id="yahoofinance" translate="label" sortOrder="33" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Yahoo Finance Exchange</label>
<field id="timeout" translate="label" type="text" sortOrder="0" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Connection Timeout in Seconds</label>
</field>
</group>
<group id="fixerio" translate="label" sortOrder="35" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Fixer.io</label>
<field id="timeout" translate="label" type="text" sortOrder="0" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Connection Timeout in Seconds</label>
</field>
</group>
<group id="webservicex" translate="label" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Webservicex</label>
<field id="timeout" translate="label" type="text" sortOrder="0" showInDefault="1" showInWebsite="0" showInStore="0" canRestore="1">
Expand Down
6 changes: 6 additions & 0 deletions app/code/Magento/Directory/etc/config.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@
<base>USD</base>
<default>USD</default>
</options>
<yahoofinance>
<timeout>100</timeout>
</yahoofinance>
<fixerio>
<timeout>100</timeout>
</fixerio>
<webservicex>
<timeout>100</timeout>
</webservicex>
Expand Down
Loading

0 comments on commit 08eebe4

Please sign in to comment.