Skip to content

Commit 58dc2e8

Browse files
committed
array_of new rule created
1 parent c6068d1 commit 58dc2e8

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

src/Providers/ValidatorServiceProvider.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Fintech\Core\Providers;
44

5+
use Fintech\Core\Rules\ArrayOfRule;
56
use Fintech\Core\Rules\Base64File;
67
use Fintech\Core\Rules\CurrentPin;
78
use Fintech\Core\Rules\Locale;
@@ -74,5 +75,16 @@ function ($message) use ($validator, $attribute) {
7475
return !$validator->errors()->has($attribute);
7576
});
7677

78+
Validator::extend('array_of', function ($attribute, $value, $parameters, $validator) {
79+
(new ArrayOfRule(...$parameters))->validate(
80+
$attribute,
81+
$value,
82+
function ($message) use ($validator, $attribute) {
83+
$validator->errors()->add($attribute, __($message, ['attribute' => $attribute]));
84+
}
85+
);
86+
return !$validator->errors()->has($attribute);
87+
});
88+
7789
}
7890
}

src/Rules/ArrayOfRule.php

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?php
2+
3+
namespace Fintech\Core\Rules;
4+
5+
use Closure;
6+
use Illuminate\Contracts\Validation\ValidationRule;
7+
use Illuminate\Translation\PotentiallyTranslatedString;
8+
use Spatie\MediaLibrary\MediaCollections\Exceptions\InvalidBase64Data;
9+
use Spatie\MediaLibrary\MediaCollections\Exceptions\MimeTypeNotAllowed;
10+
11+
class ArrayOfRule implements ValidationRule
12+
{
13+
private array $allowedTypes;
14+
15+
public function __construct(...$types)
16+
{
17+
$this->allowedTypes = $types;
18+
}
19+
20+
/**
21+
* Run the validation rule.
22+
*
23+
* @param Closure(string): PotentiallyTranslatedString $fail
24+
*/
25+
public function validate(string $attribute, mixed $value, Closure $fail): void
26+
{
27+
if (is_array($value)) {
28+
foreach ($value as $item) {
29+
if(!in_array(gettype($item), $this->allowedTypes)) {
30+
$fail('The :attribute item is not a valid data type of ['.json_encode($this->allowedTypes).'].');
31+
}
32+
}
33+
} else {
34+
if(!in_array(gettype($value), $this->allowedTypes)) {
35+
$fail('The :attribute item is not a valid data type of ['.json_encode($this->allowedTypes).'].');
36+
}
37+
}
38+
}
39+
}

0 commit comments

Comments
 (0)