#672·orm

Entity ID can be object

Author: JanFridrichCreated Jun 14, 2024Updated Nov 9, 2024
Labelspriority-high

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
php
    /**
     * @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:
php
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