Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow casters to parse null values and provide default or Injected values #62

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

Robertbaelde
Copy link
Contributor

@Robertbaelde Robertbaelde commented Mar 1, 2024

In my project I'm using the ObjectHydrator in order to parse api calls to commands and queries.

One caster that would really improve DX would be a "AuthenticatedUser" caster, providing the UserId that is authenticated in the session.

In code, usage of it would look like this:

/** @implements Query<array<Organization>> */
#[ApiQuery]
final readonly class GetUserOrganisations implements Query
{
    public function __construct(
        #[AuthenticatedUser]
        public UserId $userId,
        public int $limit = 10,
    ) {}
}

And the "caster" itself would look something like this:

#[Attribute(Attribute::TARGET_PARAMETER)]
final readonly class AuthenticatedUser implements PropertyCaster
{
    public function cast(mixed $value, ObjectMapper $hydrator): mixed
    {
        $user = \Auth::user();
        if($user === null) {
            throw new \Exception("User not authenticated");
        }

        return UserId::fromString($user->id);
    }
}

In order for this to work, we need to skip the null check before casters are triggered, and allow casters to process a value of null. This PR enables that.

Technically we could discuss if providing the Authenticated User ID is a "caster". However I wouldn't know what else to call it, and it seems a bit heavy to introduce a lot of code to support this simple use-case. Open to suggestions though!

Note, this is a breaking change, since current casters might not expect to handle null as value.
See the change I had to make to src/PropertyCasters/CastToDateTimeImmutable.php as example.

@frankdejonge
Copy link
Member

Sorry for the long delay... but: unless I'm mistaken, this introduces a behavioural breaking change for existing casters that do not expect to receive a null value. We could introduce an interface that ... when it' null we only go into the caster if the marker interface is present on the caster. WDYT?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants