Skip to content

Commit

Permalink
feat: add helper function checking empty values in array (#423)
Browse files Browse the repository at this point in the history
  • Loading branch information
wthijmen authored Jul 11, 2022
1 parent 8c8c84d commit f0e6549
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/Helper/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace MyParcelNL\Sdk\src\Helper;

use MyParcelNL\Sdk\src\Support\Arr;
use MyParcelNL\Sdk\src\Support\Str;

class Utils
Expand All @@ -27,4 +28,24 @@ public static function fillObject($object, array $properties): void
}
}
}

/**
* @param array $array
* @param null|array $requiredKeys
*
* @return array $emptyValues
*/
public static function getKeysWithoutValue(array $array, array $requiredKeys = null): array
{
$requiredKeys = $requiredKeys ?? array_keys($array);

$emptyValues = Arr::where(
$array,
static function ($value, $key) use ($requiredKeys) {
return (empty($value) && in_array($key, $requiredKeys, true));
}
);

return array_keys($emptyValues);
}
}
61 changes: 61 additions & 0 deletions test/Helper/UtilsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

declare(strict_types=1);

namespace MyParcelNL\Sdk\Test\Helper;

use MyParcelNL\Sdk\src\Helper\Utils;
use MyParcelNL\Sdk\Test\Bootstrap\TestCase;

class UtilsTest extends TestCase
{
/**
* @return array
*/
public function provideGetKeysWithoutValueData(): array
{
return [
[
[
'person' => null,
'email' => '[email protected]',
'reference' => ''
],
[
'email', 'person', 'reference'
],
[
'person', 'reference'
]
],
[
[
'person' => null,
'email' => '[email protected]',
'reference' => ''
],
[
'email', 'person'
],
[
'person'
]
]
];
}

/**
* @dataProvider provideGetKeysWithoutValueData
* @param $array
* @param $requiredFields
* @param $expected
*
* @return void
*/
public function testGetKeysWithoutValue($array, $requiredFields, $expected): void
{
$emptyValues = Utils::getKeysWithoutValue($array, $requiredFields);
self::assertIsArray($emptyValues);
self::assertEquals($expected, $emptyValues);
}
}

0 comments on commit f0e6549

Please sign in to comment.