Skip to content

Commit cd96296

Browse files
committed
added params validator
1 parent 8396b7c commit cd96296

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Dcblogdev\MsGraph\Validators;
6+
7+
use InvalidArgumentException;
8+
9+
class GraphQueryValidator
10+
{
11+
/**
12+
* Allowed query parameters for Microsoft Graph API requests.
13+
*/
14+
protected static array $allowedParams = [
15+
'$top', '$skip', '$filter', '$orderby', '$select', '$expand', '$count', '$search', '$format',
16+
];
17+
18+
/**
19+
* Validate and filter query parameters.
20+
*
21+
* @param array $params Query parameters to validate.
22+
* @return array Valid query parameters.
23+
*
24+
* @throws InvalidArgumentException If invalid parameters are present.
25+
*/
26+
public static function validate(array $params): array
27+
{
28+
// Filter out invalid parameters
29+
$validParams = array_intersect_key($params, array_flip(self::$allowedParams));
30+
31+
// Identify invalid parameters
32+
$invalidParams = array_diff_key($params, $validParams);
33+
if (! empty($invalidParams)) {
34+
throw new InvalidArgumentException(sprintf(
35+
"Invalid query parameters: %s. Allowed parameters: %s.",
36+
implode(', ', array_keys($invalidParams)),
37+
implode(', ', self::$allowedParams)
38+
));
39+
}
40+
41+
return $validParams;
42+
}
43+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php
2+
3+
use Dcblogdev\MsGraph\Validators\GraphQueryValidator;
4+
5+
test('can validate', function () {
6+
$response = GraphQueryValidator::validate([
7+
'$top' => 10,
8+
'$skip' => 5,
9+
'$filter' => 'name eq \'test\'',
10+
'$orderby' => 'name asc',
11+
'$select' => 'name',
12+
'$expand' => 'children',
13+
'$count' => 'true',
14+
'$search' => 'test',
15+
'$format' => 'pdf',
16+
]);
17+
18+
expect($response)->toEqual([
19+
'$top' => 10,
20+
'$skip' => 5,
21+
'$filter' => 'name eq \'test\'',
22+
'$orderby' => 'name asc',
23+
'$select' => 'name',
24+
'$expand' => 'children',
25+
'$count' => 'true',
26+
'$search' => 'test',
27+
'$format' => 'pdf',
28+
]);
29+
});
30+
31+
test('cannot validate none existing params', function () {
32+
$response = GraphQueryValidator::validate([
33+
'$tops' => 10,
34+
'$skip' => 5,
35+
'$filter' => 'name eq \'test\'',
36+
'$orderby' => 'name asc',
37+
'$select' => 'name',
38+
'$expand' => 'children',
39+
'$count' => 'true',
40+
'$search' => 'test',
41+
'$format' => 'pdf',
42+
]);
43+
})->throws(InvalidArgumentException::class, 'Invalid query parameters: $tops. Allowed parameters: $top, $skip, $filter, $orderby, $select, $expand, $count, $search, $format.');

0 commit comments

Comments
 (0)