Skip to content

Refactor Field Type Declaration from Property to Constant in Field Classes #6

@ogorzalka

Description

@ogorzalka

Currently, the type of input field in our Field class hierarchy is managed as a protected property, which allows for dynamic modification of the field type at runtime. This is observed in the Text class as follows:

class Text extends Field
{
    /**
     * The type of input field. Defaults to 'text'.
     */
    protected string $type = 'text';
}

Additionally, there's functionality to modify this type through a setter method:

public function type(string|InputTextType $type): static
{
    $this->type = OptionValidation::check($type, InputTextType::class);
    return $this;
}

This design, while flexible, does not enforce type immutability which might be desirable for certain field types like text, url, or email.

Proposed Change

To ensure type safety and immutability, it is proposed to define the type of each field class using constants rather than properties. This would also involve the use of an interface to enforce the declaration of this constant in all field subclasses.

Step 1: Define an Interface

interface FieldType
{
    public const TYPE = '';
}

Step 2: Modify Existing Classes

Each field class, such as Text, Email, and URL, would implement the FieldType interface and define their own TYPE constant:

class Text extends Field implements FieldType
{
    public const TYPE = 'text';
}
class Email extends Field implements FieldType
{
    public const TYPE = 'email';
}
class URL extends Field implements FieldType
{
    public const TYPE = 'url';
}

Step 3: Remove Setter Method

Since the field type will now be immutable and defined at compile-time, the setter method type() would be removed from these classes.

Impact

This change will:

  • Enhance the type safety of the field classes.
  • Ensure the immutability of field types, aligning with best practices for constant usage.
  • Simplify the class design by removing unnecessary runtime type checks and modifications.

This approach does, however, reduce the flexibility of changing the field type dynamically but increases reliability and predictability of field behavior across our application.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions