One minute
Determine missing required parameters
Frequently checking for required parameters is needed. Locating the missing parameters helps in creating a helpful message for the client.
Test
<?php
declare(strict_types=1);
namespace AppTest\Validator;
use PHPUnit\Framework\TestCase;
use function array_diff_key;
use function array_flip;
use function array_keys;
class RequiredParameterTest extends TestCase
{
public function testGetMissingParameters(): void
{
$required = [
'requiredParameterA',
'requiredParameterB',
'requiredParameterC',
'requiredParameterD',
];
$data = [
'requiredParameterA' => 'foo',
'requiredParameterD' => null,
];
$missing = [
'requiredParameterB',
'requiredParameterC',
];
$result = array_keys(array_diff_key(array_flip($required), $data));
$this->assertEquals($missing, $result);
}
}
“Validator”
<?php
declare(strict_types=1);
namespace App\Validator;
use function array_diff_key;
use function array_flip;
use function array_keys;
class RequiredParameter
{
public function getMissingParameters(array $required, array $data): array
{
return array_keys(array_diff_key(array_flip($required), $data));
}
}
Read other posts