nette / schema

📐 Validating data structures against a given Schema.
https://doc.nette.org/schema
Other
905 stars 26 forks source link

Schema: added possibility to instantiate object using reflection #47

Closed vitek-dev closed 1 year ago

vitek-dev commented 2 years ago

While using Nette/Schema I found little discomfort when using PHP 8 features - specifically Constructor property promotion.

Let's imagine following class:

class Foo
{
  public function __construct(
    public int $a,
    public int $b,
  ) {
  }
}

Casting to this class will result in ArgumentCountError because Schema is instantiating the class using new keyword. This can be solved with instantiating the class using Reflection and it's newInstanceWithoutConstructor method.

I solved this with adding second argument to castTo: castTo(string $type, bool $usingReflection = false): self - default behavior is not changed so it's not causing BC break.

Tests included and passing.