Skip to content

Commit

Permalink
feat: chunker
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejhlavacek committed Dec 6, 2018
1 parent 23f82f3 commit d7b8ba1
Show file tree
Hide file tree
Showing 3 changed files with 109 additions and 0 deletions.
1 change: 1 addition & 0 deletions phpunit.xml.dist
Expand Up @@ -15,6 +15,7 @@
<testsuite name="common">
<directory>tests/Common</directory>
<directory>tests/Options</directory>
<directory>tests/S3Uploader</directory>
</testsuite>

<testsuite name="backend-redshift-part-1">
Expand Down
56 changes: 56 additions & 0 deletions src/Keboola/StorageApi/S3Uploader/Chunker.php
@@ -0,0 +1,56 @@
<?php
namespace Keboola\StorageApi\S3Uploader;

class Chunker
{
/**
* @var int
*/
protected $size;

/**
* Chunker constructor.
* @param int $size
*/
public function __construct($size = 50)
{
$this->setSize($size);
}

/**
* @return int
*/
public function getSize()
{
return $this->size;
}

/**
* @param int $size
* @return $this
*/
public function setSize($size)
{
$this->size = (int) $size;
return $this;
}

/**
* @param array $items
* @return array
*/
public function makeChunks($items)
{
$chunkCount = ceil(count($items) / $this->getSize());
$chunks = [];
for ($i = 0; $i < $chunkCount; $i++) {
$currentChunk = array_slice(
$items,
$i * $this->getSize(),
$this->getSize()
);
$chunks[] = $currentChunk;
}
return $chunks;
}
}
52 changes: 52 additions & 0 deletions tests/S3Uploader/ChunkerTest.php
@@ -0,0 +1,52 @@
<?php

namespace Keboola\Test\S3Uploader;

use Keboola\StorageApi\S3Uploader\Chunker;
use Keboola\Test\StorageApiTestCase;

class ChunkerTest extends StorageApiTestCase
{

public function testSettersAndGetters()
{
$chunker = new Chunker();
$this->assertEquals(50, $chunker->getSize());
$chunker->setSize(10);
$this->assertEquals(10, $chunker->getSize());
$chunker = new Chunker(5);
$this->assertEquals(5, $chunker->getSize());
}

public function testSimpleChunker()
{
$chunker = new Chunker(3);
$items = [1, 2, 3, 4, 5];
$expected = [[1, 2, 3], [4, 5]];
$this->assertEquals($expected, $chunker->makeChunks($items));
}

public function testAssociativeArrayChunker()
{
$chunker = new Chunker(3);
$items = [
"item1" => 1,
"item2" => 2,
"item3" => 3,
"item4" => 4,
"item5" => 5
];
$expected = [
[
"item1" => 1,
"item2" => 2,
"item3" => 3
],
[
"item4" => 4,
"item5" => 5
]
];
$this->assertEquals($expected, $chunker->makeChunks($items));
}
}

0 comments on commit d7b8ba1

Please sign in to comment.