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

Type Conversion for method/function parameters #14580

Closed
GokhanKR opened this issue Jun 16, 2024 · 4 comments
Closed

Type Conversion for method/function parameters #14580

GokhanKR opened this issue Jun 16, 2024 · 4 comments

Comments

@GokhanKR
Copy link

GokhanKR commented Jun 16, 2024

Description

A feature for the object methods. As you know we can declare types in a method. But we can't determine a variable conversion into it.

For example:

class MyString
{
    public static function isNickName( $text ) {
        return preg_match( ... $text );
    }
}
public function myFunction( string{MyString::isNickName} $nickName ) ...

The code above is an example. This is just an idea.

@damianwadley
Copy link
Member

Sounds very magical. What's wrong with calling MyString::isNickName yourself? Or using a Nickname class?

@GokhanKR
Copy link
Author

GokhanKR commented Jun 17, 2024

I attempt a new approach to managing a method in a class. By employing Reflections, I construct a Restful API that defines the structure of its methods and generates a new file for each one. Clients can pass method parameters when making a request.

I've thought about different ways to handle this.

    namespace MyProject\Controller\Types;

    class DefaultTypes {
        public static function notEmty(string $text) {
            return preg_replace('/\s/', '', $text) !== '';
        }
    }


    namespace MyProject\Controller\Types;

    class MyTypes extends DefaultTypes {
        public static function isUserName(string $userName) 
        {
            return preg_match('/az-AZ-09/', $userName);
        }

        public static function isUserNickName(string $nickName) 
        {
            return preg_match('/az-AZ-09_-/', $nickName);
        }
    }

    // MyController
    class MyController {
        public function updateUser(int $userID, MyTypes{isUserName} $name, MyTypes{isUserNickName, notEmpty} $nickName, string $email, int|string $group, ?array $params = [])
        {
            ...
        }
    }

I utilize ReflectionMethod to oversee property types. I validate each parameter type against the parameter provided.

@damianwadley
Copy link
Member

Sounds like a use case for attributes.

@GokhanKR
Copy link
Author

Sounds like a use case for attributes.

Yes, it is a useful feature for me. 😄

@damianwadley damianwadley closed this as not planned Won't fix, can't repro, duplicate, stale Jun 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants