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

Instantiate message via late static binding #69

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

Conversation

grzegorz-rozycki
Copy link

Currently the Message class uses instantiation via its class name. The class isn't final, so extending it is possible.
A use case demonstrating the issue:

<?php

namespace App\Http\Controllers\Webhooks;

use Aws\Sns\Message;

/**
 * These annotation are added so that we enforce the right return type.
 * @method static self fromRawPostData()
 * @method static self fromPsrRequest()
 */
final class SnsMessage extends Message
{
    public function isSubscriptionConfirmation(): bool
    {
        return $this['Type'] === SnsNotificationType::SubscriptionConfirmation->value;
    }

    public function isNotification(): bool
    {
        return $this['Type'] === SnsNotificationType::Notification->value;
    }

    // We override the method so the correct type is returned.
    // PHP doesn't support upcasting, so using static in non-final classes would make it so much easier.
    #[\Override]
    public static function fromJsonString($requestBody): self
    {
        $baseMessage = parent::fromJsonString($requestBody);

        return new self($baseMessage->toArray());
    }
}

The class above adds some helper methods, but also has to redefine fromJsonString to specify the right class to instantiate.
With this change overriding fromJsonString and adding the class annotations isn't required, reducing the boilerplate a lot.

Another option would be making the Message class final.

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

Successfully merging this pull request may close these issues.

1 participant