CuyZ / Valinor

PHP library that helps to map any input into a strongly-typed value object structure.

Home Page:https://valinor.cuyz.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use valinor for a assert() function use case

staabm opened this issue · comments

to encapsulate valinor I want to create a few static methods, which make use of valinors super power but hides the library for the caller.

something like

// utility
final class Typer {
    /**
     * @param mixed $var
     * @param literal-string $type
     *
     * @throws RuntimeException
     */
    static public function assert(string $type, $var): void {
        try {
            (new MapperBuilder())
                ->mapper()
                ->map($type, $var);
        } catch (\CuyZ\Valinor\Mapper\MappingError $e) {
            throw new RuntimeException($e->getMessage());
        }
    }
}

// caller
Typer::assert('non-empty-string', $email);
Typer::assert('array<int, string>', $addresses);

as you can see the idea is to narrow the type of $var, like other assertion libraries do.

it would be great if the PHPStan typing logic in TreeMapperPHPStanExtension could be extracted so I can re-use it for a TypeSpecifyingExtension, without the need of duplicating valinors internal PHPStan typing logic.

I think my request does not fit valinor. I will create a separate lib to implement my idea.

Hi @staabm, I agree that your request goes beyond Valinor's scope. I'm interested in the solution you will provide, would you mind sharing it here when it's done? Do you think this kind of logic (inferring type directly from a variable/parameter content) could fit in PHPStan's core, somehow?

I also want to express my gratitude towards your work on OSS projects in general, I feel honored that you give Valinor a try. 🙂