Skip to content

Commit

Permalink
Merge pull request #44 from smartbooster/add_array_utils
Browse files Browse the repository at this point in the history
Add `ArrayUtils::toIndexedArray` + fix qa
  • Loading branch information
mathieu-ducrot authored Nov 13, 2024
2 parents 4758545 + e6d7612 commit e5085f8
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGELOG_add_array_utils.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
### Added
- `ArrayUtils::toIndexedArray` + tests Delete keys of array and multidimensional array
24 changes: 24 additions & 0 deletions src/Utils/ArrayUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -272,4 +272,28 @@ public static function hasDuplicateValue(array $array): bool
{
return count($array) !== count(array_flip($array));
}

/**
* Delete keys of array and multidimensional array
*
* <pre>
* <?php
* toIndexedArray(['john' => 1, 'doe' => ['smart' => 100, 'booster' => 200]);
* ?>
* </pre>
* The above example will output:
* <pre>
* [1, [100, 200]]
* </pre>
*/
public static function toIndexedArray(array $array): array
{
foreach ($array as $key => $value) {
if (is_array($value)) {
$array[$key] = self::toIndexedArray($value);
}
}

return array_values($array);
}
}
2 changes: 1 addition & 1 deletion src/Utils/DateUtils.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public static function getMonthChoices(string $locale = 'fr_FR'): array
{
$formatter = new \IntlDateFormatter(locale: $locale, dateType: \IntlDateFormatter::FULL, timeType: \IntlDateFormatter::FULL, pattern: 'MMMM');
for ($i = 1; $i <= 12; $i++) {
$month = $formatter->format(strtotime("2000-$i")); // @phpstan-ignore-line MDT the year is arbitrary and does not impact the month
$month = $formatter->format(strtotime("2000-$i")); // MDT the year is arbitrary and does not impact the month
$toReturn[ucfirst((string) $month)] = $i;
}

Expand Down
18 changes: 18 additions & 0 deletions tests/Utils/ArrayUtilsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -606,4 +606,22 @@ public function hasDuplicateProvider(): array
],
];
}

/**
* @dataProvider toIndexedArrayProvider
*/
public function testToIndexedArray(array $expected, array $array): void
{
$this->assertSame($expected, ArrayUtils::toIndexedArray($array));
}

public function toIndexedArrayProvider(): array
{
return [
'simple_associative_array' => [[1, 2, 3], ['3' => 1, '2' => 2, '1' => 3]],
'simple_indexed_array_no_chagnes' => [[1, 2, 3], [1, 2, 3]],
'multidimensional_associative_array' => [[[1, 2], [3, 4]], [['dummy' => 1, 'test' => 2], ['8' => 3, '1' => 4]]],
'multidimensional_indexed_array_no_changes' => [[[1, 2], [3, 4]], [[1, 2], [3, 4]]],
];
}
}

0 comments on commit e5085f8

Please sign in to comment.