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.