Skip to content

Commit 12b76a2

Browse files
serious-angelserious-art
authored andcommitted
Set validation during a cast to be optional
1. Added parameter for optional validation during a cast 2. Since we except the data to be arrayable, let's change the type from BaseData to Data
1 parent 09fcdfa commit 12b76a2

File tree

1 file changed

+19
-8
lines changed

1 file changed

+19
-8
lines changed

src/SettingsCasts/ArrayDataCast.php

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,44 +3,55 @@
33
namespace Spatie\LaravelSettings\SettingsCasts;
44

55
use Exception;
6-
use Spatie\LaravelData\Contracts\BaseData;
6+
use Spatie\LaravelData\Data;
77
use Spatie\LaravelSettings\SettingsCasts\SettingsCast;
88

99
class ArrayDataCast implements SettingsCast
1010
{
1111
protected string $type;
1212

13-
public function __construct(?string $type)
13+
protected bool $validate;
14+
15+
public function __construct(?string $type, string $validate = 'true')
1416
{
15-
$this->type = $this->ensureDataTypeExists($type);
17+
$this->type = $this->ensureDataTypeExists($type);
18+
$this->validate = !in_array($validate, ['false', '0'], true);
1619
}
1720

1821
/**
1922
* @param array<array> $payload
2023
*
21-
* @return BaseData[]
24+
* @return Data[]
2225
*/
2326
public function get($payload): array
2427
{
2528
return array_map(
26-
fn ($data) => $this->type::validateAndCreate($data),
29+
fn ($data) => $this->createData($data),
2730
$payload
2831
);
2932
}
3033

3134
/**
32-
* @param array<array|BaseData> $payload
35+
* @param array<array|Data> $payload
3336
*
3437
* @return array<array>
3538
*/
3639
public function set($payload): array
3740
{
3841
return array_map(
39-
fn ($data) => $this->type::validateAndCreate($data)->toArray(),
42+
fn ($data) => $this->createData($data)->toArray(),
4043
$payload
4144
);
4245
}
4346

47+
/**
48+
* @param array|Data $data
49+
*/
50+
protected function createData($data): Data
51+
{
52+
return $this->validate ? $this->type::validateAndCreate($data) : $this->type::from($data);
53+
}
54+
4455
protected function ensureDataTypeExists(?string $type): string
4556
{
4657
if ($type === null) {
@@ -51,7 +62,7 @@ protected function ensureDataTypeExists(?string $type): string
5162
throw new Exception("Cannot create a data cast for `$type` because the data does not exist");
5263
}
5364

54-
if (!class_implements($type, BaseData::class)) {
65+
if (!class_implements($type, Data::class)) {
5566
throw new Exception("Cannot create a data cast for `$type` because the class does not implement data");
5667
}
5768

0 commit comments

Comments
 (0)