Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle array property as nested or object #1936

Open
mpiot opened this issue Feb 5, 2024 · 0 comments
Open

Handle array property as nested or object #1936

mpiot opened this issue Feb 5, 2024 · 0 comments

Comments

@mpiot
Copy link

mpiot commented Feb 5, 2024

Hi,
In some case an entity can have a property of type array, and we should want to store it in Elasticsearch as nested or object depending the kind of search we want.

But, if we configure the bundle to store the property as type: nested for example we have an error because the Transformer do not handle the case of a non-object.

Actually I've a workarround:

<?php

declare(strict_types=1);

namespace App\SearchRepository\Transformer;

use FOS\ElasticaBundle\Transformer\ModelToElasticaAutoTransformer;
use Symfony\Component\DependencyInjection\Attribute\Autoconfigure;

#[Autoconfigure(
    calls: [
        ['setPropertyAccessor' => ['@fos_elastica.property_accessor']],
    ]
)]
class NestedArrayModelToElasticaAutoTransformer extends ModelToElasticaAutoTransformer
{
    protected function transformNested($objects, array $fields): ?array
    {
        if (is_iterable($objects)) {
            foreach ($objects as &$object) {
                $object = \is_array($object) ? (object) $object : $object;
            }
        } elseif (null !== $objects) {
            $objects = \is_array($objects) ? (object) $objects : $objects;
        }

        return parent::transformNested($objects, $fields);
    }
}

In the config, I just set:

model_to_elastica_transformer:
    service: App\SearchRepository\Transformer\NestedArrayModelToElasticaAutoTransformer

Do you think, it will be accepted to do a change in the original transformer ?
The main document should be an object, but all fields and subfields should be what we want, I don't know if the best way is:

  • keep this workarround directly in the Transformer (pro: do not redesign all, cons: this is a little weird)
  • do a redefine the functions type hints to handle object or array ? (pro: better design, cons: update the transformer design for a edge-case)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant