I'm working on an integration for Magento 2 with a 3rd party. This class will fetch the articledata resource. This resource contains multiple items, with a maximum of 750 per call. The class is designed to be used like do load() while next()
.
If there are more items than the current 750, there will be a value next_resultset
. For example /app/api/v3/articledata/750-1-36/
. I only need the last part 750-1-36/
to append it to the resource.
This class works fine, but I'm not happy with how all the logic is being handled. Part of me tells that the API I'm using is not designed so well and another part of me tells that the code could be better regardless.
<?php
class ArticleData
{
const RESULT_SET_LIMIT = 750;
/**
* @var RestClient
*/
protected $client;
/**
* @var ConfigProviderFactory
*/
protected $configProviderFactory;
/**
* @var array
*/
protected $data = [];
/**
* @var \Magento\Framework\Json\Decoder
*/
protected $jsonDecoder;
/**
* ArticleData constructor.
* @param ConfigProviderFactory $configProviderFactory
* @param RestClient $client
* @param \Magento\Framework\Json\Decoder $jsonDecoder
*/
public function __construct(
ConfigProviderFactory $configProviderFactory,
RestClient $client,
\Magento\Framework\Json\Decoder $jsonDecoder
) {
$this->configProviderFactory = $configProviderFactory;
$this->client = $client;
$this->jsonDecoder = $jsonDecoder;
}
/**
* Load first set
*/
public function load()
{
$resultSet = '';
if ($this->next()) {
$resultSet = $this->getResultSet();
}
$response = $this->client->get('articledata/' . $resultSet);
$decoded = $this->jsonDecoder->decode($response->getBody());
$decoded['items'] = $decoded['data'];
unset($decoded['data']);
$this->data = $decoded;
}
/**
* @return bool
*/
public function next(): bool
{
return !empty($this->data['results']) && $this->data['results'] >= self::RESULT_SET_LIMIT
&& !empty($this->data['next_resultset']);
}
/**
* @return string
*/
public function getResultSet(): string
{
$matches = [];
return preg_match('/articledata\/([0-9\-]+\/)/', $this->data['next_resultset'], $matches) ? $matches[1] : '';
}
}