Skip to content

Commit

Permalink
Add optionItems method to improve performance ...
Browse files Browse the repository at this point in the history
This method gets an array of Item instances that would be used for each option.

To make it backwards compatible, a method is added to the abstract class. It's not performant, but it works.

The BasicDictionary class overrides it to make it performant.

If someone is making a dictionary that extends the base class, they don't have to override it, but they can if they want to improve the performance.

This is all done because ->options() would get the options, then calling ->get() is happening for each option, which would end up getting all the options for each one. In the case of the file dictionary for example, this means the file is read and parsed for each line in the file.
  • Loading branch information
jasonvarga committed Oct 4, 2024
1 parent 55caaf3 commit b76304b
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 3 deletions.
8 changes: 7 additions & 1 deletion src/Dictionaries/BasicDictionary.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,17 @@ public function get(string $key): ?Item
}

public function options(?string $search = null): array
{
return collect($this->optionItems($search))
->mapWithKeys(fn (Item $item) => [$item->value() => $item->label()])
->all();
}

public function optionItems(?string $search = null): array
{
return $this
->getFilteredItems()
->when($search, fn ($collection) => $collection->filter(fn ($item) => $this->matchesSearchQuery($search, $item)))
->mapWithKeys(fn (Item $item) => [$item->value() => $item->label()])
->all();
}

Expand Down
7 changes: 7 additions & 0 deletions src/Dictionaries/Dictionary.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,11 @@ private function getInferredGqlType($value)

return GraphQL::string();
}

public function optionItems(?string $search = null): array
{
return collect($this->options($search))
->map(fn ($label, $value) => new Item($value, $label, $this->get($value)->extra()))
->all();
}
}
4 changes: 2 additions & 2 deletions src/Tags/Dictionary/Dictionary.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ private function loop($handle)
throw new DictionaryNotFoundException($handle);
}

$options = (new DataCollection($dictionary->options($search)))
->map(fn ($label, $value) => new DictionaryItem($dictionary->get($value)->toArray()))
$options = (new DataCollection($dictionary->optionItems($search)))
->map(fn ($item) => new DictionaryItem($item->toArray()))
->values();

$query = (new ItemQueryBuilder)->withItems($options);
Expand Down

0 comments on commit b76304b

Please sign in to comment.