Skip to content

[TwigComponent] Missleading doc between Passing & Rendering Attributes and PreMount validation #1704

Closed
@cavasinf

Description

@cavasinf

Rendering "extra" Attributes with a PreMount hook + OptionsResolver will not work if followed as the doc explains it.

As from the example, if the Alert component looks like this:

#[AsTwigComponent]
final class Alert
{
    public string $message;
    public string $type = 'success';

    #[PreMount]
    public function preMount(array $data): array
    {
        // validate data
        $resolver = new OptionsResolver();
        $resolver->setDefaults(['type' => 'success']);
        $resolver->setAllowedValues('type', ['success', 'danger']);
        $resolver->setRequired('message');
        $resolver->setAllowedTypes('message', 'string');

        return $resolver->resolve($data);
    }
}

Calling it like this:

<twig:Alert id="alert_id" message="My message"/>

Will throw an UndefinedOptionsException error:

Caution

Error rendering "Alert" component: The option "id" does not exist. Defined options are: "message", "type".

We may need to resolve this incoherence by:

  1. Add an extra paragraph in the PreMount hook part, to explain how to do it with extra attributes.
  2. Re-write the "example" preMount function doc like this:
#[PreMount]
public function preMount(array $data): array
{
    // validate data
    $resolver = new OptionsResolver();
+   $resolver->setIgnoreUndefined();
+
    $resolver->setDefaults(['type' => 'success']);
    $resolver->setAllowedValues('type', ['success', 'danger']);
    $resolver->setRequired('message');
    $resolver->setAllowedTypes('message', 'string');

-   return $resolver->resolve($data);
+   return array_merge($data, $resolver->resolve($data));
}

I could have done a PR directly, but I want to talk about it first and discuss if it is necessary or not.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions