Boris Bär
Boris Bär

Reputation: 99

How to merge two PHP methods into one?

I’d like to merge both of these methods into a single one:

public function addRoute( string $httpMethod, string $route, callable|array $handler ): self
{
    $this->routes[$httpMethod][$route] = $handler;
    return $this;
}

public function addRouteByAttribute( array $controllers )
{
    foreach( $controllers as $controller ) {
        $reflector = new \ReflectionClass($controller);
        foreach($reflector->getMethods() as $method) {
            $attributes = $method -> getAttributes( \Core\Attributes\Router::class, \ReflectionAttribute::IS_INSTANCEOF );
            foreach( $attributes as $attribute ) {
                $route = $attribute -> newInstance();
                $this -> addRoute( $route -> httpMethod, $route -> route, [ $controller, $method -> getName() ] );
            }
        }
    }
}

Bsically the functionality of addRoute() should be inside addRouteByAttribute().

How could I achieve this?

Upvotes: 0

Views: 67

Answers (1)

StepUp
StepUp

Reputation: 38094

It is not good idea to create one big method which can do many things. It is violation of Single Responsibility principle of SOLID principles. So one method should have one goal.

So if you keep with two methods, your code will be simple, methods will be shorter and it will be easier to edit code and write unit tests.

It is not good idea to merge these methods, but code could look like this:

public function addRouteByAttribute( array $controllers )
{
    foreach( $controllers as $controller ) {
        $reflector = new \ReflectionClass( $controller );
        foreach( $reflector -> getMethods() as $method ) {
            $attributes = $method -> 
                getAttributes( \Core\Attributes\Router::class, 
                               \ReflectionAttribute::IS_INSTANCEOF );
            foreach( $attributes as $attribute ) {
                $route = $attribute -> newInstance();
                $this -> addRoute( 
                    $route -> httpMethod, 
                    $route -> route, 
                    [ $controller, $method -> getName() ] );
                $this -> routes[$route -> httpMethod]
                   [$route -> route] = $method -> getName();
            }
        }
    }
}

Upvotes: 1

Related Questions