Skip to content

Update encode method to use type hinting for string|Response object#1150

Draft
joanhey wants to merge 16 commits intowalkor:masterfrom
joanhey:type-hint
Draft

Update encode method to use type hinting for string|Response object#1150
joanhey wants to merge 16 commits intowalkor:masterfrom
joanhey:type-hint

Conversation

@joanhey
Copy link
Copy Markdown
Contributor

@joanhey joanhey commented Apr 4, 2026

Available from PHP 8.0.

EDIT: string|Response|ServerSentEvents string|Stringable
With only type hint string, any class that implements stringable can be passed, so we are not limiting the classes. And we can simplify the send() code as always is string. But for now it's OK.

PD: later we need to check the TcpConnection::send() why the $sendBuffer receive null. This variable now is mixed need to be limited to string|Stringable.
For now use a fast fix $sendBuffer ??= '';

@joanhey joanhey marked this pull request as draft April 4, 2026 13:03
@joanhey joanhey marked this pull request as ready for review April 4, 2026 18:24
@joanhey joanhey marked this pull request as draft April 4, 2026 18:54
@joanhey joanhey marked this pull request as ready for review April 4, 2026 19:01
@joanhey joanhey marked this pull request as draft April 4, 2026 19:27
@joanhey
Copy link
Copy Markdown
Contributor Author

joanhey commented Apr 4, 2026

Interesting journey with this code.

Testing string|Stringable type hint.

With only string we can pass strings or any class that implements Stringable without any problem.

class str implements stringable {
    function __tostring(){
        return 'Hola';
    }
}

$b = new str();

function test(string $input = '') {
    if (is_string($input)) echo "String";
    if (is_a($input, 'Stringable')) echo "Object";
    var_dump($input);
}

test($b);

// Return:
Stringstring(4) "Hola"

With string|Stringable the same, but change:

class str implements stringable {
    function __tostring(){
        return 'Hola';
    }
}

$b = new str();

function test(string|Stringable $input = '') {
    if (is_string($input)) echo "String";
    if (is_a($input, 'Stringable')) echo "Object";  // or is_a($input, 'str')
    var_dump($input);
    echo $input;
}

test($b);

// Return:
Objectobject(str)#1 (0) {
}
Hola

Here only change to string when echo or (string).

And seems that phpstan fail with this code.

@joanhey joanhey marked this pull request as ready for review April 5, 2026 09:32
@joanhey
Copy link
Copy Markdown
Contributor Author

joanhey commented Apr 5, 2026

@joanhey joanhey marked this pull request as draft April 6, 2026 12:12
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