Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add sometimes rule & undefined concept #79

Merged
merged 1 commit into from
Jan 26, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/Attributes/Validation/Sometimes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Spatie\LaravelData\Attributes\Validation;

use Attribute;

#[Attribute(Attribute::TARGET_PROPERTY)]
class Sometimes extends ValidationAttribute
{
public function getRules(): array
{
return ['sometimes'];
}
}
7 changes: 6 additions & 1 deletion src/Resolvers/DataFromArrayResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Spatie\LaravelData\Lazy;
use Spatie\LaravelData\Support\DataConfig;
use Spatie\LaravelData\Support\DataProperty;
use Spatie\LaravelData\Undefined;

class DataFromArrayResolver
{
Expand Down Expand Up @@ -41,12 +42,16 @@ private function shouldIgnoreProperty(DataProperty $property, array $values): bo

private function resolveValue(DataProperty $property, array $values): mixed
{
$value = $values[$property->name()] ?? null;
$value = array_key_exists($property->name(), $values) ? $values[$property->name()] ?? null : Undefined::make();

if ($value === null) {
return $value;
}

if ($value instanceof Undefined) {
return $value;
}

if ($value instanceof Lazy) {
return $value;
}
Expand Down
17 changes: 17 additions & 0 deletions src/RuleInferrers/SometimesRuleInferrer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Spatie\LaravelData\RuleInferrers;

use Spatie\LaravelData\Support\DataProperty;

class SometimesRuleInferrer implements RuleInferrer
{
public function handle(DataProperty $property, array $rules): array
{
if ($property->isUndefinable() && ! in_array('sometimes', $rules)) {
$rules[] = 'sometimes';
}

return $rules;
}
}
17 changes: 17 additions & 0 deletions src/Support/DataProperty.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Spatie\LaravelData\Exceptions\CannotFindDataTypeForProperty;
use Spatie\LaravelData\Exceptions\InvalidDataPropertyType;
use Spatie\LaravelData\Lazy;
use Spatie\LaravelData\Undefined;
use TypeError;

class DataProperty
Expand All @@ -23,6 +24,8 @@ class DataProperty

protected bool $isNullable;

protected bool $isUndefinable;

protected bool $isData;

protected bool $isDataCollection;
Expand Down Expand Up @@ -75,6 +78,11 @@ public function isNullable(): bool
return $this->isNullable;
}

public function isUndefinable(): bool
{
return $this->isUndefinable;
}

public function isPromoted(): bool
{
return $this->property->isPromoted();
Expand Down Expand Up @@ -177,6 +185,7 @@ private function processNoType(): void
{
$this->isLazy = false;
$this->isNullable = true;
$this->isUndefinable = false;
$this->isData = false;
$this->isDataCollection = false;
$this->types = new DataPropertyTypes();
Expand All @@ -194,13 +203,15 @@ private function processNamedType(ReflectionNamedType $type)
$this->isData = is_a($name, Data::class, true);
$this->isDataCollection = is_a($name, DataCollection::class, true);
$this->isNullable = $type->allowsNull();
$this->isUndefinable = is_a($name, Undefined::class, true);
$this->types = new DataPropertyTypes([$name]);
}

private function processListType(ReflectionUnionType|ReflectionIntersectionType $type)
{
$this->isLazy = false;
$this->isNullable = false;
$this->isUndefinable = false;
$this->isData = false;
$this->isDataCollection = false;
$this->types = new DataPropertyTypes();
Expand All @@ -214,6 +225,12 @@ private function processListType(ReflectionUnionType|ReflectionIntersectionType
continue;
}

if ($name === Undefined::class) {
$this->isUndefinable = true;

continue;
}

if ($name === Lazy::class) {
$this->isLazy = true;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ protected function typeProcessors(): array
$this->config->getDefaultTypeReplacements()
),
new RemoveLazyTypeProcessor(),
new RemoveUndefinedTypeProcessor(),
new DtoCollectionTypeProcessor(),
];
}
Expand Down
48 changes: 48 additions & 0 deletions src/Support/TypeScriptTransformer/RemoveUndefinedTypeProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?php

namespace Spatie\LaravelData\Support\TypeScriptTransformer;

use Exception;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\Compound;
use phpDocumentor\Reflection\Types\Object_;
use ReflectionMethod;
use ReflectionParameter;
use ReflectionProperty;
use Spatie\LaravelData\Lazy;
use Spatie\LaravelData\Undefined;
use Spatie\TypeScriptTransformer\Structures\MissingSymbolsCollection;
use Spatie\TypeScriptTransformer\TypeProcessors\TypeProcessor;

class RemoveUndefinedTypeProcessor implements TypeProcessor
{
public function process(
Type $type,
ReflectionParameter | ReflectionMethod | ReflectionProperty $reflection,
MissingSymbolsCollection $missingSymbolsCollection
): ?Type {
if (! $type instanceof Compound) {
return $type;
}

/** @var \Illuminate\Support\Collection $types */
$types = collect(iterator_to_array($type->getIterator()))
->reject(function (Type $type) {
if (! $type instanceof Object_) {
return false;
}

return is_a((string)$type->getFqsen(), Undefined::class, true);
});

if ($types->isEmpty()) {
throw new Exception("Type {$reflection->getDeclaringClass()->name}:{$reflection->getName()} cannot be only Undefined");
}

if ($types->count() === 1) {
return $types->first();
}

return new Compound($types->all());
}
}
5 changes: 5 additions & 0 deletions src/Transformers/DataTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Spatie\LaravelData\Support\DataConfig;
use Spatie\LaravelData\Support\DataProperty;
use Spatie\LaravelData\Support\TransformationType;
use Spatie\LaravelData\Undefined;

class DataTransformer
{
Expand Down Expand Up @@ -71,6 +72,10 @@ protected function shouldIncludeProperty(
?array $allowedIncludes,
?array $allowedExcludes,
): bool {
if ($value instanceof Undefined) {
return false;
}

if (! $value instanceof Lazy) {
return true;
}
Expand Down
12 changes: 12 additions & 0 deletions src/Undefined.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

namespace Spatie\LaravelData;


class Undefined
{
public static function make(): Undefined
{
return new self();
}
}
6 changes: 6 additions & 0 deletions tests/Attributes/Validation/RulesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
use Spatie\LaravelData\Attributes\Validation\Rule;
use Spatie\LaravelData\Attributes\Validation\Same;
use Spatie\LaravelData\Attributes\Validation\Size;
use Spatie\LaravelData\Attributes\Validation\Sometimes;
use Spatie\LaravelData\Attributes\Validation\StartsWith;
use Spatie\LaravelData\Attributes\Validation\StringType;
use Spatie\LaravelData\Attributes\Validation\Timezone;
Expand Down Expand Up @@ -373,6 +374,11 @@ public function attributesDataProvider(): Generator
'attribute' => new Uuid(),
'expected' => ['uuid'],
];

yield [
'attribute' => new Sometimes(),
'expected' => ['sometimes'],
];
}

public function acceptedIfAttributesDataProvider(): Generator
Expand Down
22 changes: 22 additions & 0 deletions tests/DataTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Spatie\LaravelData\Tests\Factories\DataBlueprintFactory;
use Spatie\LaravelData\Tests\Factories\DataPropertyBlueprintFactory;
use Spatie\LaravelData\Tests\Fakes\DefaultLazyData;
use Spatie\LaravelData\Tests\Fakes\DefaultUndefinedData;
use Spatie\LaravelData\Tests\Fakes\DummyDto;
use Spatie\LaravelData\Tests\Fakes\DummyModel;
use Spatie\LaravelData\Tests\Fakes\DummyModelWithCasts;
Expand Down Expand Up @@ -773,4 +774,25 @@ public function it_can_construct_a_data_object_with_default_values_and_overwrite
$this->assertEquals('Test', $data->default_property);
$this->assertEquals('Test Again', $data->default_promoted_property);
}


/** @test */
public function it_excludes_undefined_values_data()
{
$data = DefaultUndefinedData::from([]);

$this->assertEquals([], $data->toArray());
}

/** @test */
public function it_includes_value_if_not_undefined_data()
{
$data = DefaultUndefinedData::from([
'name' => 'Freek'
]);

$this->assertEquals([
'name' => 'Freek'
], $data->toArray());
}
}
2 changes: 2 additions & 0 deletions tests/Fakes/ComplicatedData.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Spatie\LaravelData\Casts\DateTimeInterfaceCast;
use Spatie\LaravelData\Data;
use Spatie\LaravelData\DataCollection;
use Spatie\LaravelData\Undefined;

class ComplicatedData extends Data
{
Expand All @@ -19,6 +20,7 @@ public function __construct(
public string $string,
public array $array,
public ?int $nullable,
public int|Undefined $undefinable,
public mixed $mixed,
#[WithCast(DateTimeInterfaceCast::class, format: 'd-m-Y', type: CarbonImmutable::class)]
public $explicitCast,
Expand Down
14 changes: 14 additions & 0 deletions tests/Fakes/DefaultUndefinedData.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Spatie\LaravelData\Tests\Fakes;

use Spatie\LaravelData\Data;
use Spatie\LaravelData\Undefined;

class DefaultUndefinedData extends Data
{
public function __construct(
public string | Undefined $name
) {
}
}
2 changes: 2 additions & 0 deletions tests/Resolvers/DataFromArrayResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Spatie\LaravelData\Tests\Fakes\NestedModelData;
use Spatie\LaravelData\Tests\Fakes\SimpleData;
use Spatie\LaravelData\Tests\TestCase;
use Spatie\LaravelData\Undefined;

class DataFromArrayResolverTest extends TestCase
{
Expand Down Expand Up @@ -69,6 +70,7 @@ public function it_maps_default_types()
$this->assertEquals('Hello world', $data->string);
$this->assertEquals([1, 1, 2, 3, 5, 8], $data->array);
$this->assertNull($data->nullable);
$this->assertInstanceOf(Undefined::class, $data->undefinable);
$this->assertEquals(42, $data->mixed);
$this->assertEquals(DateTime::createFromFormat(DATE_ATOM, '1994-05-16T12:00:00+01:00'), $data->defaultCast);
$this->assertEquals(CarbonImmutable::createFromFormat('d-m-Y', '16-06-1994'), $data->explicitCast);
Expand Down
52 changes: 52 additions & 0 deletions tests/Resolvers/EmptyDataResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Spatie\LaravelData\Resolvers\EmptyDataResolver;
use Spatie\LaravelData\Tests\Fakes\SimpleData;
use Spatie\LaravelData\Tests\TestCase;
use Spatie\LaravelData\Undefined;

class EmptyDataResolverTest extends TestCase
{
Expand Down Expand Up @@ -105,6 +106,37 @@ public function it_will_return_the_base_type_for_lazy_types_that_can_be_null()
});
}

public function it_will_return_the_base_type_for_lazy_types_that_can_be_undefined()
{
$this->assertEmptyPropertyValue(null, new class () {
public Lazy | string | Undefined $property;
});

$this->assertEmptyPropertyValue([], new class () {
public Lazy | array | Undefined $property;
});

$this->assertEmptyPropertyValue(['string' => null], new class () {
public Lazy | SimpleData | Undefined $property;
});
}

/** @test */
public function it_will_return_the_base_type_for_undefinable_types()
{
$this->assertEmptyPropertyValue(null, new class() {
public Undefined | string $property;
});

$this->assertEmptyPropertyValue([], new class () {
public Undefined | array $property;
});

$this->assertEmptyPropertyValue(['string' => null], new class () {
public Undefined | SimpleData $property;
});
}

/** @test */
public function it_cannot_have_multiple_types()
{
Expand Down Expand Up @@ -135,6 +167,26 @@ public function it_cannot_have_multiple_types_with_a_nullable_lazy()
});
}

/** @test */
public function it_cannot_have_multiple_types_with_a_undefined()
{
$this->expectException(DataPropertyCanOnlyHaveOneType::class);

$this->assertEmptyPropertyValue(null, new class () {
public int | string | Undefined $property;
});
}

/** @test */
public function it_cannot_have_multiple_types_with_a_nullable_undefined()
{
$this->expectException(DataPropertyCanOnlyHaveOneType::class);

$this->assertEmptyPropertyValue(null, new class () {
public int | string | Undefined | null $property;
});
}

/** @test */
public function it_can_overwrite_empty_properties()
{
Expand Down
Loading