diff --git a/README.md b/README.md index 84de644..934ac8e 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,7 @@ All of these methods manipulate the array, but not all of them return an instanc `->shift()` removes the first element from the array and returns it. - `->changeKeyCase()` +- `->chunk(int[, array])` - `->combine(array|Chain, array|Chain)` - `->count()` - `->diff(array|Chain)` diff --git a/src/Chain.php b/src/Chain.php index d445db7..5c42478 100644 --- a/src/Chain.php +++ b/src/Chain.php @@ -3,6 +3,7 @@ namespace Cocur\Chain; use Cocur\Chain\Link\ChangeKeyCase; +use Cocur\Chain\Link\Chunk; use Cocur\Chain\Link\Combine; use Cocur\Chain\Link\Count; use Cocur\Chain\Link\CountValues; @@ -54,6 +55,7 @@ class Chain extends AbstractChain implements Countable { use ChangeKeyCase; + use Chunk; use Combine; use Count; use CountValues; diff --git a/src/Link/Chunk.php b/src/Link/Chunk.php new file mode 100644 index 0000000..822b3ed --- /dev/null +++ b/src/Link/Chunk.php @@ -0,0 +1,36 @@ +array = array_chunk($this->array, $size, $options['preserveKeys']); + } else { + $this->array = array_chunk($this->array, $size); + } + + if (empty($options['decorate']) || true === $options['decorate']) { + foreach ($this->array as $index => $chunk) { + $this->array[$index] = new static($chunk); + } + } + + return $this; + } +} diff --git a/tests/ChainTest.php b/tests/ChainTest.php index 428e221..85f9ce6 100644 --- a/tests/ChainTest.php +++ b/tests/ChainTest.php @@ -77,6 +77,7 @@ public function chainHasTraits(): void $c = new Chain(); $this->assertTrue(method_exists($c, 'changeKeyCase')); + $this->assertTrue(method_exists($c, 'chunk')); $this->assertTrue(method_exists($c, 'combine')); $this->assertTrue(method_exists($c, 'count')); $this->assertTrue(method_exists($c, 'countValues')); diff --git a/tests/Link/ChunkTest.php b/tests/Link/ChunkTest.php new file mode 100644 index 0000000..8f929a1 --- /dev/null +++ b/tests/Link/ChunkTest.php @@ -0,0 +1,27 @@ +getMockForTrait(Chunk::class); + $mock->array = [1, 2, 3, 4]; + $mock->chunk(2); + + $this->assertEquals([1, 2], $mock->array[0]->array); + $this->assertEquals([3, 4], $mock->array[1]->array); + } +}