From 77dc88a0b5f426348f27de619f4d54f0e598ea5a Mon Sep 17 00:00:00 2001 From: Duncan McClean Date: Mon, 18 Nov 2024 21:55:36 +0000 Subject: [PATCH] Add support for Dictionary fields --- src/ServiceProvider.php | 3 +- src/Transformers/DictionaryTransformer.php | 35 +++++++++++++ .../DictionaryTransformerTest.php | 51 +++++++++++++++++++ 3 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 src/Transformers/DictionaryTransformer.php create mode 100644 tests/Transformers/DictionaryTransformerTest.php diff --git a/src/ServiceProvider.php b/src/ServiceProvider.php index 9ef9107..5814d04 100644 --- a/src/ServiceProvider.php +++ b/src/ServiceProvider.php @@ -11,10 +11,11 @@ class ServiceProvider extends AddonServiceProvider { - public array $transformers = [ + protected array $transformers = [ 'assets' => Transformers\AssetsTransformer::class, 'bard' => Transformers\BardTransformer::class, 'date' => Transformers\DateTransformer::class, + 'dictionary' => Transformers\DictionaryTransformer::class, 'entries' => Transformers\EntriesTransformer::class, 'terms' => Transformers\TermsTransformer::class, 'toggle' => Transformers\ToggleTransformer::class, diff --git a/src/Transformers/DictionaryTransformer.php b/src/Transformers/DictionaryTransformer.php new file mode 100644 index 0000000..b9b7639 --- /dev/null +++ b/src/Transformers/DictionaryTransformer.php @@ -0,0 +1,35 @@ +join('|'); + } + + $options = collect(explode('|', $value))->map(function ($value) { + return $this->dictionary()->get($value)?->value(); + })->filter()->values(); + + return $this->field->get('max_items') === 1 ? $options->first() : $options->all(); + } + + private function dictionary(): Dictionary + { + $dictionary = $this->field->get('dictionary'); + + if (is_string($dictionary)) { + return Facades\Dictionary::find($dictionary); + } + + return Facades\Dictionary::find($dictionary['type']); + } +} diff --git a/tests/Transformers/DictionaryTransformerTest.php b/tests/Transformers/DictionaryTransformerTest.php new file mode 100644 index 0000000..756695b --- /dev/null +++ b/tests/Transformers/DictionaryTransformerTest.php @@ -0,0 +1,51 @@ +collection = tap(Collection::make('pages'))->save(); + + $this->blueprint = $this->collection->entryBlueprint(); + $this->blueprint->ensureField('countries', ['type' => 'dictionary', 'dictionary' => 'countries'])->save(); + + $this->field = $this->blueprint->field('countries'); + + $this->import = Import::make(); + } + + #[Test] + public function it_returns_keys() + { + $transformer = new DictionaryTransformer( + import: $this->import, + blueprint: $this->blueprint, + field: $this->field, + config: [] + ); + + $output = $transformer->transform('USA|CAN|FOO|DEU|GBR'); + + $this->assertEquals(['USA', 'CAN', 'DEU', 'GBR'], $output); + } +}