Skip to content

Commit

Permalink
Merge pull request #147 from dystcz/feature/fix-attribute-data-dropdo…
Browse files Browse the repository at this point in the history
…wn-values

Fix getting dropdown values for attribute data field
  • Loading branch information
repl6669 authored May 13, 2024
2 parents 050be0c + 79b820d commit 54501af
Showing 1 changed file with 18 additions and 21 deletions.
39 changes: 18 additions & 21 deletions src/Domain/JsonApi/Eloquent/Fields/AttributeData.php
Original file line number Diff line number Diff line change
Expand Up @@ -155,11 +155,11 @@ protected function mapAttributes(Collection $attributes, object $model): Collect
{
return $attributes->mapWithKeys(function (AttributeModel $attribute) use ($model) {
$value = match ($attribute->type) {
Dropdown::class => $this->getDropdownValue($attribute, $model, $this->modelAttributes),
Dropdown::class => $this->getDropdownValue($attribute, $model),
default => null
};

$value = $value ?? $this->getOtherValue($attribute, $model, $this->modelAttributes);
$value = $value ?? $this->getAttributeValue($model, $attribute->handle);
$addPlaintext = $this->plaintextValues && ($attribute->configuration['richtext'] ?? false);

return [
Expand All @@ -172,37 +172,34 @@ protected function mapAttributes(Collection $attributes, object $model): Collect
});
}

/**
* Get other field type value.
*/
protected function getOtherValue(AttributeModel $attribute, object $model, bool $useModelAttributes): mixed
{
$value = $useModelAttributes
? $model->getAttribute($attribute->handle) ?? $model->attr($attribute->handle)
: $model->attr($attribute->handle);

return $value;
}

/**
* Get the dropdown field type value.
*/
protected function getDropdownValue(AttributeModel $attribute, object $model, bool $useModelAttributes): mixed
protected function getDropdownValue(AttributeModel $attribute, object $model): mixed
{
$value = Arr::first(Arr::where(
$value = Arr::first(
$attribute->configuration['lookups'] ?? [],
fn ($lookup) => $lookup['value'] === $useModelAttributes
? $model->getAttribute($attribute->handle) ?? $model->attr($attribute->handle)
: $model->attr($attribute->handle)
));
fn ($lookup) => $lookup['value'] === $this->getAttributeValue($model, $attribute->handle)
|| $lookup['label'] === $this->getAttributeValue($model, $attribute->handle)
);

if ($value && $value['label']) {
if ($value && (! $value['value'] && $value['label'])) {
$value = $value['label'];
}

return $value;
}

/**
* Get the attribute value from model.
*/
protected function getAttributeValue(object $model, string $handle): mixed
{
return $this->modelAttributes
? $model->getAttribute($handle) ?? $model->attr($handle)
: $model->attr($handle);
}

/**
* {@inheritDoc}
*/
Expand Down

0 comments on commit 54501af

Please sign in to comment.