Skip to content

Commit

Permalink
Fix normalized model for laravel 10
Browse files Browse the repository at this point in the history
  • Loading branch information
rubenvanassche committed Oct 4, 2024
1 parent 592b930 commit 24552dc
Showing 1 changed file with 32 additions and 2 deletions.
34 changes: 32 additions & 2 deletions src/Normalizers/Normalized/NormalizedModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,20 @@

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use ReflectionProperty;
use Spatie\LaravelData\Attributes\LoadRelation;
use Spatie\LaravelData\Support\DataProperty;

class NormalizedModel implements Normalized
{
protected array $properties = [];

protected ReflectionProperty $castsProperty;

protected ReflectionProperty $attributesProperty;

public function __construct(
protected Model $model
protected Model $model,
) {
}

Expand All @@ -33,7 +38,7 @@ public function getProperty(string $name, DataProperty $dataProperty): mixed

protected function fetchNewProperty(string $name, DataProperty $dataProperty): mixed
{
if ($this->model->hasAttribute($name)) {
if ($this->hasModelAttribute($name)) {
return $this->properties[$name] = $this->model->getAttributeValue($name);
}

Expand All @@ -56,4 +61,29 @@ protected function fetchNewProperty(string $name, DataProperty $dataProperty): m

return $this->properties[$name] = UnknownProperty::create();
}

protected function hasModelAttribute(string $name): bool
{
if (method_exists($this->model, 'hasAttribute')) {
return $this->model->hasAttribute($name);
}

// TODO: to use that one once we stop supporting Laravel 10

if (! isset($this->attributesProperty)) {
$this->attributesProperty = new ReflectionProperty($this->model, 'attributes');
$this->attributesProperty->setAccessible(true);
}

if (! isset($this->castsProperty)) {
$this->castsProperty = new ReflectionProperty($this->model, 'casts');
$this->castsProperty->setAccessible(true);
}

return array_key_exists($name, $this->attributesProperty->getValue($this->model)) ||
array_key_exists($name, $this->castsProperty->getValue($this->model)) ||
$this->model->hasGetMutator($name) ||
$this->model->hasAttributeMutator($name) ||
$this->model->isClassCastable($name);

Check failure on line 87 in src/Normalizers/Normalized/NormalizedModel.php

View workflow job for this annotation

GitHub Actions / phpstan

Call to protected method isClassCastable() of class Illuminate\Database\Eloquent\Model.
}
}

0 comments on commit 24552dc

Please sign in to comment.