Skip to content

POC: Data objects #37

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

Closed
wants to merge 6 commits into from
Closed
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
5 changes: 3 additions & 2 deletions src/Actions/Component/CreateComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,16 @@

namespace Cachet\Actions\Component;

use Cachet\Data\ComponentData;
use Cachet\Models\Component;
use Lorisleiva\Actions\Concerns\AsAction;

class CreateComponent
{
use AsAction;

public function handle(array $component): Component
public function handle(ComponentData $data): Component
{
return Component::create($component);
return Component::create($data->toArray());
}
}
7 changes: 5 additions & 2 deletions src/Actions/Component/UpdateComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Cachet\Actions\Component;

use Cachet\Data\ComponentData;
use Cachet\Events\Components\ComponentStatusWasChanged;
use Cachet\Models\Component;
use Lorisleiva\Actions\Concerns\AsAction;
Expand All @@ -10,11 +11,13 @@ class UpdateComponent
{
use AsAction;

public function handle(Component $component, array $data): Component
public function handle(Component $component, ComponentData $data): Component
{
$oldStatus = $component->status;

$component->update($data);
$component->update(array_filter(
$data->toArray(),
));
Comment on lines +18 to +20
Copy link
Collaborator Author

@joelbutcher joelbutcher Sep 21, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not too happy about the use of array_filter here. This assumes that you shouldn't be allowed to update a columns value to null. Might have to think about this a bit more…

Removing array_filter means that columns that aren't passed in the request (e.g. status) are returned as 'status' => null when calling $data->toArray(). This doesn't necessarily indicate that the value we want to set in the DB is null, it just indicates that the data was not sent.

This raises the discussion around the appropriateness of PUT versus PATCH requests for the API... @jbrooksuk correct me if I'm wrong, but a PUT request should send all attributes, even if they've not changed and PATCH only sends the ones we want to update?


if ($component->wasChanged('status')) {
ComponentStatusWasChanged::dispatch($component, $oldStatus, $component->status);
Expand Down
19 changes: 19 additions & 0 deletions src/Data/ComponentData.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace Cachet\Data;

use Cachet\Enums\ComponentStatusEnum;

final class ComponentData extends Data
{
public function __construct(
public readonly string $name,
public readonly ?string $description = null,
public readonly ?ComponentStatusEnum $status = null,
public readonly ?string $link = null,
public readonly ?int $order = null,
public readonly ?int $componentGroupId = null,
public readonly bool $enabled = true,
) {
}
}
111 changes: 111 additions & 0 deletions src/Data/Data.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<?php

namespace Cachet\Data;

use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Str;

abstract class Data implements Arrayable, \ArrayAccess, \JsonSerializable, \Stringable
{
/**
* Create a new data object from a form request.
*/
final public static function fromRequest(FormRequest $request): static
{
return static::fromArray(array_filter($request->validated()));
}

/**
* Create a new data object from an array.
*/
public static function fromArray(array $data): static
{
return new static(
...collect($data)->mapWithKeys(
fn ($value, $key) => [
Str::of($key)->camel()->toString() => $value,
]
)
->all()
);
}

/**
* Create a new data object from a JSON string.
*/
public static function fromJson(string $json): static
{
return static::fromArray(
json_decode($json, associative: true, flags: JSON_THROW_ON_ERROR),
);
}

/**
* Determine if a given index exists on the data object.
*/
public function offsetExists(mixed $offset): bool
{
return isset($this->toArray()[$offset]);
}

/**
* Retrieve the value of the given index.
*/
public function offsetGet(mixed $offset): mixed
{
return $this->toArray()[$offset];
}

/**
* Set the value of the given index.
*/
public function offsetSet(mixed $offset, mixed $value): void
{
$klass = static::class;

throw new \Error("Cannot modify readonly property $klass::\${$offset}", code: 2);
}

/**
* Remove the given index from the data object.
*/
public function offsetUnset(mixed $offset): void
{
$klass = static::class;

throw new \Error("Cannot modify readonly property $klass::\${$offset}", code: 2);
}

/**
* Get the array representation of the data object.
*/
final public function toArray(): array
{
$properties = (new \ReflectionClass($this))->getProperties(
\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_READONLY
);

return collect($properties)->mapWithKeys(
fn (\ReflectionProperty $property) => [
Str::of($property->getName())->snake()->toString() => $property->getValue($this),
]
)->all();
}

/**
* Get the data to be serialized into JSON.
*/
public function jsonSerialize(): string
{
return json_encode($this->toArray());
}

/**
* JSON serialize the object into a string.
*/
public function __toString(): string
{
return $this->jsonSerialize();
}
}
7 changes: 5 additions & 2 deletions src/Http/Controllers/Api/ComponentController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Cachet\Actions\Component\CreateComponent;
use Cachet\Actions\Component\DeleteComponent;
use Cachet\Actions\Component\UpdateComponent;
use Cachet\Data\ComponentData;
use Cachet\Http\Requests\CreateComponentRequest;
use Cachet\Http\Requests\UpdateComponentRequest;
use Cachet\Http\Resources\Component as ComponentResource;
Expand Down Expand Up @@ -34,7 +35,9 @@ public function index()
*/
public function store(CreateComponentRequest $request)
{
$component = CreateComponent::run($request->validated());
$component = CreateComponent::run(
ComponentData::fromRequest($request),
);

return ComponentResource::make($component);
}
Expand All @@ -54,7 +57,7 @@ public function show(Component $component)
*/
public function update(UpdateComponentRequest $request, Component $component)
{
UpdateComponent::run($component, $request->validated());
UpdateComponent::run($component, ComponentData::fromRequest($request));

return ComponentResource::make($component->fresh());
}
Expand Down
9 changes: 9 additions & 0 deletions src/Http/Requests/CreateComponentRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

/**
* @property string $name
* @property ?string $description
* @property ?ComponentStatusEnum $status
* @property ?string $link
* @property ?int $order
* @property ?bool $enabled
* @property ?int $component_group_id
*/
class CreateComponentRequest extends FormRequest
{
/**
Expand Down
12 changes: 12 additions & 0 deletions tests/Architecture/DataTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

namespace Cachet\Tests\Architecture;

use Cachet\Data\Data;

test('data objects test')
->expect('Cachet\Data')
->toBeClasses()
->toBeFinal()
->ignoring(Data::class)
->toExtend(Data::class);
29 changes: 15 additions & 14 deletions tests/Unit/Actions/Component/CreateComponentTest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?php

use Cachet\Actions\Component\CreateComponent;
use Cachet\Data\ComponentData;
use Cachet\Enums\ComponentStatusEnum;
use Cachet\Events\Components\ComponentCreated;
use Illuminate\Support\Facades\Event;
Expand All @@ -10,33 +11,33 @@
});

it('can create a component', function () {
$data = [
'name' => 'My Component',
'description' => 'My component description',
];
$data = new ComponentData(
name: 'My Component',
description: 'My component description',
);

$component = CreateComponent::run($data);

expect($component)
->name->toBe($data['name'])
->description->toBe($data['description']);
->name->toBe($data->name)
->description->toBe($data->description);

Event::assertDispatched(ComponentCreated::class, fn ($event) => $event->component->is($component));
});

it('can create a component with a given status', function () {
$data = [
'name' => 'My Component',
'description' => 'My component description',
'status' => ComponentStatusEnum::performance_issues,
];
$data = new ComponentData(
name: 'My Component',
description: 'My component description',
status: ComponentStatusEnum::performance_issues,
);

$component = CreateComponent::run($data);

expect($component)
->name->toBe($data['name'])
->description->toBe($data['description'])
->status->toBe($data['status']);
->name->toBe($data->name)
->description->toBe($data->description)
->status->toBe($data->status);

Event::assertDispatched(ComponentCreated::class, fn ($event) => $event->component->is($component));
});
Loading