Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy arguments validation in php

Tags:

validation

php

Every time you write some php functions or class methods, it's good practice to check input arguments and throw an exceptions, or trigger errors or warnings etc...

For example

<?php

function send_email($email, $subject, $body)
{
    if (empty($email)) {
        throw new InvalidArgumentException('Email should not be empty');
    }
    if (!is_string($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
        throw new InvalidArgumentException('Email format is invalid');
    }
    if (empty($subject)) {
        throw new InvalidArgumentException('Subject should not be empty');
    }
    if (!is_string($subject)) {
        throw new InvalidArgumentException('Subject must be a string');
    }
    if (empty($body)) {
        throw new InvalidArgumentException('Body should not be empty');
    }
    if (!is_string($body)) {
        throw new InvalidArgumentException('Body must be a string');
    }

    return mail($email, $subject, $body);
}

As you can see most of this example contains validation code, whereas only one helpful line which do the job. You actually need to write a lot of code if you want to reliably protect your functions. And this is tediously.

My question is - does anybody know some good way to validate code easily? Is there any libraries that validate depends on PHP-DOC? For example:

<?php

/**
 * @param email $email
 * @param string $subject
 * @param string $body
 */
function send_email($email, $subject, $body)
{
    return mail($email, $subject, $body);
}

Thank you.

like image 686
Eugeniy Petrov Avatar asked Dec 07 '13 14:12

Eugeniy Petrov


People also ask

How many types of validation are there in PHP?

There are 2 kinds of validation available in PHP: Client-Side Validation: This type of validation is done on the web browser of the client machine. Server-Side Validation: The data on submission is then sent to the server machine to perform validation checks there.

What is $params in PHP?

PHP Parameterized functions They are declared inside the brackets, after the function name. A parameter is a value you pass to a function or strategy. It can be a few value put away in a variable, or a literal value you pass on the fly. They are moreover known as arguments.


1 Answers

The easiest way in pure PHP is to simplify the check by using assertions:

class Assert {

    public static function isString($var) {
        if (!is_string($var)) {
            throw new InvalidArgumentException('Argument is not a string');
        }
    }

}

function foo($string) {
    Assert::isString($string);
    ...
}

You can spruce this up with introspection and/or debug backtraces to include more information in the thrown exception.

like image 189
deceze Avatar answered Oct 12 '22 22:10

deceze