bigcommerce-api-php icon indicating copy to clipboard operation
bigcommerce-api-php copied to clipboard

Issue with products with more than 50 Skus

Open bham1586 opened this issue 9 years ago • 3 comments

When getting product SKUs, the bigcommerce API limits the response to 50 by default and uses pagination. In Resources/Product.php the function skus() needs to take pagination into account.

This is a quick solution I wrote, could probably be improved upon.

public function skus()
{
	$allSkus = [];
	$limit = 250;
	$page = 1;
	do {
		$filter = [
			'limit' => $limit,
			'page'  => $page,
		];
		$filter = Filter::create($filter);
		$skus = Client::getCollection($this->fields->skus->resource . $filter->toQuery(), 'Sku');
		$page++;
		$allSkus = array_merge($allSkus, $skus);
	} while(count($skus) >= $limit);
	return $allSkus;
}

for this to work you also need to add the following at the top of the file.

use Bigcommerce\Api\Filter;

bham1586 avatar Nov 01 '16 19:11 bham1586

$skus can be null, which will make the array_merge cause a warning

MagicTrixor avatar Dec 07 '16 02:12 MagicTrixor

@MagicTrixor Good point. As I said, my solution could be improved upon. This should fix it.

        public function skus()
	{
		$allSkus = [];
		$limit = 250;
		$page = 1;
		do {
			$filter = [
				'limit' => $limit,
				'page'  => $page,
			];
			$filter = Filter::create($filter);
			$skus = Client::getCollection($this->fields->skus->resource . $filter->toQuery(), 'Sku');
			$page++;
			if(!empty($skus)) {
				$allSkus = array_merge($allSkus, $skus);
			}
		} while(count($skus) >= $limit);
		return $allSkus;
	}

bham1586 avatar Dec 13 '16 02:12 bham1586

Perhaps if $product->skus is null you can use the new PHP null coalesce features?

$skus = $product->skus ?? [];

Also for the do while loop, the condition should be $skuCount == $limit. It should never be able to return a greater number than the $limit unless there is a serious problem with the API.

Lewiscowles1986 avatar Mar 20 '17 15:03 Lewiscowles1986