Skip to content

Commit

Permalink
Improvement: Utilizing the method-chaining nature of `Model.setAttrib…
Browse files Browse the repository at this point in the history
…ute` adds support for external model mutations and polymorphism.
  • Loading branch information
yvo-niedrich committed Jul 23, 2024
1 parent 165bb17 commit e7dfb5c
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 8 deletions.
12 changes: 5 additions & 7 deletions src/Drivers/EloquentEntitySet.php
Original file line number Diff line number Diff line change
Expand Up @@ -187,14 +187,12 @@ public function read(PropertyValue $key): Entity
*/
protected function setModelAttributes(Model $model, PropertyValues $propertyValues): Model
{
foreach ($propertyValues->getDeclaredPropertyValues() as $propertyValue) {
$model->setAttribute(
$this->getPropertySourceName($propertyValue->getProperty()),
$propertyValue->getPrimitive()->toMixed()
return $propertyValues->getDeclaredPropertyValues()->reduce(function(Model $model, PropertyValue $value) {
return $model->setAttribute(
$this->getPropertySourceName($value->getProperty()),
$value->getPrimitive()->toMixed(),
);
}

return $model;
}, $model);
}

/**
Expand Down
4 changes: 3 additions & 1 deletion src/EntityType.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Flat3\Lodata;

use Flat3\Lodata\Annotation\Core\V1\Computed;
use Flat3\Lodata\Annotation\Core\V1\Immutable;
use Flat3\Lodata\Controller\Transaction;
use Flat3\Lodata\Exception\Internal\PathNotHandledException;
use Flat3\Lodata\Facades\Lodata;
Expand Down Expand Up @@ -98,7 +99,8 @@ public function getOpenAPIUpdateSchema(): array
'type' => Constants::oapiObject,
'title' => __('lodata:::name (Update schema)', ['name' => $this->getName()]),
'properties' => (object) $this->getDeclaredProperties()->filter(function (DeclaredProperty $property) {
return $property->getAnnotations()->sliceByClass([Computed::class])->isEmpty() && $property !== $this->getKey();
return $property->getAnnotations()->sliceByClass([Computed::class, Immutable::class])->isEmpty()
&& $property !== $this->getKey();
})->map(function (DeclaredProperty $property) {
return $property->getOpenAPISchema();
})
Expand Down
13 changes: 13 additions & 0 deletions src/Helper/ObjectArray.php
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,19 @@ public function map(callable $callback)
return array_map($callback, $this->array);
}

/**
* @param callable(mixed $initial, mixed $value, mixed $key): mixed $callback
* @param $initial
* @return mixed|null
*/
public function reduce(callable $callback, $initial = null)
{
foreach ($this->array as $key => $value) {
$initial = $callback($initial, $value, $key);
}
return $initial;
}

/**
* Sort the objects in the array
* @param callable $callback
Expand Down

0 comments on commit e7dfb5c

Please sign in to comment.