Skip to content

Entity ID can be object #672

Open
@JanFridrich

Description

@JanFridrich

Is your feature request related to a problem? Please describe.

  • We want to use stringable object as id for entity instead of normal string
  • Motivation behind this is so you can be 100% sure everywhere with which entity ID you are working
  • And it works most cases but when you have these entities in OneHasMany or ManyHasMany relation (where you are making collection from them) it will cause error Cannot access offset of type EntityId on array when you are trying to get one from other

Describe the solution you'd like.

  • Create EntityId class which can be then extended and it will be ready everywhere for use in those relations
  • Example of EntityId
    /**
     * @param T $id
     */
    final protected function __construct(private mixed $id)
    {
    }

    /**
     * @return T
     */
    public function toScalar(): mixed
    {
        return $this->id;
    }

    public function __toString(): string
    {
        return (string) $this->toScalar();
    }

    public static function fromScalar(mixed $scalar): static
    {
        return new static($scalar);
    }
  • And IdWrapper:
class IdWrapper extends ImmutableValuePropertyWrapper
{
    private string $className;

    public function __construct(PropertyMetadata $propertyMetadata)
    {
        parent::__construct($propertyMetadata);

        \assert(\count($propertyMetadata->types) === 1);
        $this->className = \key($propertyMetadata->types);
        \assert(\class_exists($this->className));
    }

    /**
     * @param Id $value
     */
    public function convertToRawValue($value)
    {
        return $value->toScalar();
    }

    public function convertFromRawValue($value)
    {
        /** @var Id $className */
        $className = $this->className;

        return $className::fromScalar($value);
    }
}
  • So it can be used in Entity for example like this: * @property-read EntityId $id {primary} {wrapper \App\Infrastructure\Shared\Nextras\Wrapper\IdWrapper}
  • Or indexes will have to be tested if its object so something like this: $index = \is_object(index) ? (string) $index : $index

Describe alternatives you've considered.

  • For now we're just using string as ID

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions