Skip to content

Commit

Permalink
Merge pull request #2 from PBXg33k/feature/ArrayTraits
Browse files Browse the repository at this point in the history
ArrayTraits
  • Loading branch information
PBXg33k committed Mar 21, 2017
2 parents 29ed04f + f66f11d commit eed71b0
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 1 deletion.
2 changes: 1 addition & 1 deletion .travis.yml
Expand Up @@ -12,6 +12,6 @@ matrix:
before_script:
- mkdir -p build/logs
after_script:
- travis_retry php bin/coveralls -v
- travis_retry php vendor/bin/coveralls -v
- php: 7.0
fast_finish: true
37 changes: 37 additions & 0 deletions src/ArrayTrait.php
@@ -0,0 +1,37 @@
<?php

namespace Pbxg33k\Traits;

trait ArrayTrait
{
/**
* Recusively implodes an array
*
* @param array $array
* @param string $glue
*
* @return string
*/
public function recusiveImplode(array $array, $glue = ',')
{
foreach($array as $key => $element) {
if(is_array($element)) {
$array[$key] = $this->recusiveImplode($element, $glue);
}
}

return implode($glue, $array);
}

/**
* Alias for recursiveImplode
*
* @param array $array
* @param string $glue
* @return string
*/
public function recursiveJoin(array $array, $glue = ',')
{
return $this->recusiveImplode($array, $glue);
}
}
60 changes: 60 additions & 0 deletions tests/ArrayTraitTest.php
@@ -0,0 +1,60 @@
<?php
use Pbxg33k\Traits\ArrayTrait;

require_once('stubs/ArrayTraitClass.php');

class ArrayTraitTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ArrayTraitClass
*/
protected $testClass;

public function setUp()
{
$this->testClass = new ArrayTraitClass();
}

/**
* @test
*/
public function simpleImplodeReturnString()
{
$arr = [
'testKey' => 'testValue',
'testKey2' => 'testValue2'
];

$this->assertSame(implode(',', $arr), $this->testClass->recusiveImplode($arr, ','));
}

/**
* @test
*/
public function implodingMultiDimensionalArrayReturnsString()
{
$arr = [
'testKey' => 'testValue',
'testArr' => [
'subKey' => 'subValue'
]
];

$expectedOutput = "testValue,subValue";

$this->assertSame($expectedOutput, $this->testClass->recusiveImplode($arr, ','));
}

/**
* @test
*/
public function joinIsAliasingImplode()
{
$arr = [
'testKey' => 'testValue',
'testKey2' => 'testValue2'
];

$this->assertSame(implode(',', $arr), $this->testClass->recursiveJoin($arr, ','));
}
}
8 changes: 8 additions & 0 deletions tests/stubs/ArrayTraitClass.php
@@ -0,0 +1,8 @@
<?php

use Pbxg33k\Traits\ArrayTrait;

class ArrayTraitClass
{
use ArrayTrait;
}

0 comments on commit eed71b0

Please sign in to comment.