Address / class / method validations

2

Scenario

I use a method to instantiate classes and methods dynamically.

Properties received:

  • modulo = name of folder with files .class.php
  • ferramenta = name of file .class.php
  • acao = name of method

Method that executes the request:

private function executar()
{
    try {
        # Monta o patch e faz require da classe
        $classe     = DIR_MODULOS . $this -> modulo . DS . $this -> ferramenta . '.class.php';
        require_once $classe;
        # Instancia o objeto e executa o método
        $obj        = new $this -> ferramenta();
        $resposta   = $obj -> {$this -> acao}($this -> dados);
        # Retorna a resposta
        $this -> retorno = $resposta;

        } catch (Exception $e) {

            $this -> error =  $e->getMessage();
    }
}

Problems

  • If the modulo property is incorrect, it will not find the folder path.
    • Error: Warning and Fatal Error require .
  • If the ferramenta property is incorrect, it will not find the class file.
    • Error: Warning and Fatal Error require .
  • If the% cos_de% property is incorrect, you will not find the method in the class.
    • Error: Call method error: Fatal error: Call to undefined method

Doubt

  • What is the best way to treat errors since acao does not treat them?

    (preferably native functions)

Objective

The idea is to return only a simple string as the error.

Example:

  • "Invalid module"
  • "Invalid tool"
  • "Invalid action"
asked by anonymous 04.12.2018 / 12:57

2 answers

0

I was able to resolve using file_exists , class_exists and method_exists .

PS: As mentioned by Maniero, being dynamic may bring security breaches. In my case handled before reaching this method, but security is never much.

How it was:

private function executar()
{
    # Verifica ...
    if (...) {

        # Verifica propriedades mínimas
        if (...) {

            # Monta o path do diretório
            $dir  = DIR_MODULOS . $this -> modulo;
            # Verifica se existe o diretório
            if (file_exists($dir)) {

                # Monta o path do arquivo
                $classe  = DIR_MODULOS . $this -> modulo . DS . $this -> ferramenta . '.class.php';
                # Verifica se existe o arquivo
                if (file_exists($classe)) {

                    # Inclui a classe
                    require_once $classe;
                    # Verifica se existe a classe no arquivo
                    if (class_exists($this -> ferramenta)) {

                        # Cria objeto
                        $obj = new $this -> ferramenta();
                        # Verifica se o método existe
                        if (method_exists($obj, $this -> acao)) {

                            # Executa o método
                            $retorno = $obj -> {$this -> acao}($this -> dados);
                            # Retorna a resposta
                            $this -> retorno = $retorno;

                        } else {
                            $this -> error = "Ação inexistente.";
                        }

                    } else {
                        $this -> error = "Ferramenta inválida 2.";
                    }

                } else {
                    $this -> error = "Ferramenta inválida 1.";
                }

            } else {
                $this -> error = "Módulo inválido.";
            }

        } else {
            $this -> error = "Erro na estrutura JSON.";
        }

    } else {
        $this -> error = "Erro ...!";
    }

}

Useful links:

file_exists

class_exists

method_exists

    
04.12.2018 / 13:27
2

The use of try-catch there is already wrong. I answer this at various questions here at SOpt (I strongly recommend following the links strongly). Do not capture Exception other than the final output of the code and do not catch an exception to do anything useful.

What you are reporting is a programming error, and programming errors we fix and do not try to recover. Exception is to recover from an unexpected failure, but not a programming error.

In dynamic type codes, and in dynamic typing language everything is more or less dynamic in nature, you should check what you are going to use before using it. Verification does not just have to be done where it is guaranteed to work.

The programming error there is not to consider that the data can go wrong. So before using something with the potential to be wrong make sure you are right and decide what to do if you are wrong. Only perform if everything is correct. Almost always if is your friend.

Maybe one day I'll write a book about it. Yes, to dominate exception and error handling needs a book. That is why most people will not learn, almost everyone today does not want to read, does not want to spend time learning, does what is simple, even if it is wrong and if it works, okay. It is quite complicated to treat errors correctly, and even more to use exception. One thing I always say is that if you do not master a resource, do not use it, and this is the case of the exception, so I have a talk called "Exception - the goto of the 21st century" since it is the mechanism that causes the most problems for people, causes much more than goto that everyone knows is not to use.

    
04.12.2018 / 13:09