Skip to content

Commit

Permalink
Merge pull request #3 from stellarwp/bugfix/undot
Browse files Browse the repository at this point in the history
Fix & Add Tests for Arr::undot()
  • Loading branch information
tarecord committed Jun 12, 2024
2 parents eab0916 + 429b2d0 commit fc2199a
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Arrays/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -1317,7 +1317,7 @@ public static function undot( $array ) {
$results = [];

foreach ( $array as $key => $value ) {
static::set( $results, $key, $value );
$results = static::set( $results, explode( '.', $key ), $value );
}

return $results;
Expand Down
105 changes: 105 additions & 0 deletions tests/wpunit/UndotTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php

use StellarWP\Arrays\Arr;
use StellarWP\Arrays\Tests\ArraysTestCase;

class UndotTest extends ArraysTestCase
{

public function setUp()
{
// before
parent::setUp();
}

public function tearDown()
{
parent::tearDown();
}

/**
* @test
*/
public function it_properly_expands_array()
{
$dotted = [
'one.two.three.five.eight' => 'fibonacci',
];

$expected = [
'one' => [
'two' => [
'three' => [
'five' => [
'eight' => 'fibonacci'
]
]
]
],
];

$this->assertSame($expected, Arr::undot($dotted));
}

/**
* @test
*/
public function it_expands_array_with_leaves()
{
$dotted = [
'one.first_leaf' => true,
'one.two.second_leaf' => true,
'one.two.three.third_leaf' => true,
'one.two.three.five.fifth_leaf' => true,
'one.two.three.five.eight' => 'fibonacci',
];

$expected = [
'one' => [
'first_leaf' => true,
'two' => [
'second_leaf' => true,
'three' => [
'third_leaf' => true,
'five' => [
'fifth_leaf' => true,
'eight' => 'fibonacci'
]
]
]
],
];

$this->assertSame($expected, Arr::undot($dotted));
}

/**
* @test
*/
public function it_expands_nested_arrays_with_numerical_keys()
{
$dotted = [
'first_array.0' => 'bacon',
'first_array.1' => 'ham',
'first_array.2' => 'cheese',
'second_array.0' => 'bacon',
'second_array.1' => 'egg',
'second_array.2' => 'cheese',
];

$expected = [
'first_array' => [
'bacon',
'ham',
'cheese',
],
'second_array' => [
'bacon',
'egg',
'cheese'
]
];

$this->assertSame($expected, Arr::undot($dotted));
}
}

0 comments on commit fc2199a

Please sign in to comment.