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

Updated with spelling fixes, return types, parameter types and property types #1

Open
MichelJonkman opened this issue Oct 10, 2023 · 0 comments

Comments

@MichelJonkman
Copy link

I used PHPStorm to add return types, parameter types and property types; and do a bunch of spelling fixes! I'd do a pull request but I feel like this is a lot faster.

Note that this is untested as of right nowand I also automatically formatted the file which may have changed a bunch of formatting, hopefully for the better!

<?php

/**
 * @link https://github.com/devwithkunal/php-validator-class
 * @license https://github.com/devwithkunal/php-validator-class/blob/main/LICENSE
 */
class Validator
{

    /**
     * @var array $data - Data to validate.
     */
    private array $data;

    /**
     * @var string $current_field - Current selected key/field to validate data.
     */
    private string $current_field;

    /**
     * @var string $current_alias - Alias use on error messages instead of field name.
     */
    private string $current_alias;

    /**
     * @var array $response_messages - Error messages to show user.
     *
     * You can change messages from here. User "{field}" to refer the field name.
     */
    private array $response_messages = [
        "required" => "{field} is required.",
        "alpha" => "{field} must contains alphabetic characters only.",
        "alpha_num" => "{field} must contains alphabetic characters & numbers only.",
        "numeric" => "{field} must contains numbers only.",
        "email" => "{field} is invalid.",
        "max_len" => "{field} is too long.",
        "min_len" => "{field} is too short.",
        "max_val" => "{field} is too high.",
        "min_val" => "{field} is too low.",
        "enum" => "{field} is invalid.",
        "equals" => "{field} does not match.",
        "must_contain" => "{field} must contains {chars}.",
        "match" => "{field} is invalid.",
        "date" => "{field} is invalid.",
        "date_after" => "{field} date is not valid.",
        "date_before" => "{field} date is not valid.",
    ];

    /**
     * @var array $error_messages - Error message generated after validation of each field.
     */
    public array $error_messages = [];

    /**
     * @var boolean $next - Check if next validation on the field should run or not.
     */
    private bool $next = true;

    /**
     * Validator - Create new instance of Validator class.
     *
     * @param array $data - Data to validate.
     */
    function __construct(array $data)
    {
        $this->data = $data;
    }

    /**
     * add_error_message - Create and add error message after each validation failed.
     *
     * @param string $type - Key of $response_messages array.
     * @return void
     */
    private function add_error_message(string $type, $others = [])
    {
        $field_name = $this->current_alias ? ucfirst($this->current_alias) : ucfirst($this->current_field);
        $msg = str_replace('{field}', $field_name, $this->response_messages[$type]);
        foreach ($others as $key => $val) {
            $msg = str_replace('{' . $key . '}', $val, $msg);
        }
        $this->error_messages[$this->current_field] = $msg;
    }

    /**
     * exists - Check if the current field or field value exists or not.
     *
     * @return boolean
     */
    private function exists(): bool
    {
        if (!isset($this->data[$this->current_field]) || !$this->data[$this->current_field]) {
            return false;
        }
        return true;
    }

    /**
     * set_response_messages - Function to set/extend custom error response messages.
     *
     * @param array $messages
     * @return void
     */
    function set_response_messages(array $messages)
    {
        foreach ($messages as $key => $val) {
            $this->response_messages[$key] = $val;
        }
    }

    /**
     * field - Set the field name to start validation.
     *
     * @param string $name - Name of the field/key as on data to validate.
     * @param string|null $alias - (optional) Alias use on error messages instead of field name.
     * @return self
     */
    function field(string $name, string $alias = null): Validator
    {
        $this->current_field = $name;
        $this->next = true;
        $this->current_alias = $alias;
        return $this;
    }

    /**
     * required - Check if the value exists.
     *
     * @return self
     */
    function required(): Validator
    {
        if (!$this->exists()) {
            $this->add_error_message('required');
            $this->next = false;
        }
        return $this;
    }

    /**
     * alpha - Check if the value is alpha only.
     *
     * @param array $ignore - (Optional) add characters to allow.
     * @return self
     */
    function alpha(array $ignore = []): Validator
    {
        if ($this->next && $this->exists() && !ctype_alpha(str_replace($ignore, '', $this->data[$this->current_field]))) {
            $this->add_error_message('alpha');
            $this->next = false;
        }
        return $this;
    }

    /**
     * alpha_num - Check if the value is alphanumeric only.
     *
     * @param array $ignore - (Optional) add characters to allow.
     * @return self
     */
    function alpha_num(array $ignore = []): Validator
    {
        if ($this->next && $this->exists() && !ctype_alnum(str_replace($ignore, '', $this->data[$this->current_field]))) {
            $this->add_error_message('alpha_num');
            $this->next = false;
        }
        return $this;
    }

    /**
     * numeric - Check if the value is numeric only.
     *
     * @return self
     */
    function numeric(): Validator
    {
        if ($this->next && $this->exists() && !is_numeric($this->data[$this->current_field])) {
            $this->add_error_message('numeric');
            $this->next = false;
        }
        return $this;
    }

    /**
     * email - Check if the value is a valid email.
     *
     * @return self
     */
    function email(): Validator
    {
        if ($this->next && $this->exists() && !filter_var($this->data[$this->current_field], FILTER_VALIDATE_EMAIL)) {
            $this->add_error_message('email');
            $this->next = false;
        }
        return $this;
    }

    /**
     * max_len - Check if length of the value is larger than the limit.
     *
     * @param int $size - Max length of characters of the value.
     * @return self
     */
    function max_len(int $size): Validator
    {
        if ($this->next && $this->exists() && strlen($this->data[$this->current_field]) > $size) {
            $this->add_error_message('max_len');
            $this->next = false;
        }
        return $this;
    }

    /**
     * min_len - Check if length of the value is smaller than the limit.
     *
     * @param int $size - Min length of characters of the value.
     * @return self
     */
    function min_len(int $size): Validator
    {
        if ($this->next && $this->exists() && strlen($this->data[$this->current_field]) < $size) {
            $this->add_error_message('min_len');
            $this->next = false;
        }
        return $this;
    }

    /**
     * max_val - Check if the value of integer/number is not larger than limit.
     *
     * @param int $val - Max value of the number.
     * @return self
     */
    function max_val(int $val): Validator
    {
        if ($this->next && $this->exists() && $this->data[$this->current_field] > $val) {
            $this->add_error_message('max_val');
            $this->next = false;
        }
        return $this;
    }

    /**
     * min_val - Check if the value of integer/number is not smaller than limit.
     *
     * @param int $val - Min value of the number.
     * @return self
     */
    function min_val(int $val): Validator
    {
        if ($this->next && $this->exists() && $this->data[$this->current_field] < $val) {
            $this->add_error_message('min_val');
            $this->next = false;
        }
        return $this;
    }

    /**
     * enum - Check if the value is in the list.
     *
     * @param array $list - List of valid values.
     * @return self
     */
    function enum(array $list): Validator
    {
        if ($this->next && $this->exists() && !in_array($this->data[$this->current_field], $list)) {
            $this->add_error_message('enum');
            $this->next = false;
        }
        return $this;
    }

    /**
     * equals - Check if the value is equal.
     *
     * @param mixed $value - Value to match equal.
     * @return self
     */
    function equals($value): Validator
    {
        if ($this->next && $this->exists() && !$this->data[$this->current_field] == $value) {
            $this->add_error_message('equals');
            $this->next = false;
        }
        return $this;
    }

    /**
     * date - Check if the value is a valid date.
     *
     * @param mixed $format - format of the date. (ex. Y-m-d) Check out https://www.php.net/manual/en/datetime.format.php for more.
     * @return self
     */
    function date($format = 'Y-m-d'): Validator
    {
        if ($this->next && $this->exists()) {
            $dateTime = \DateTime::createFromFormat($format, $this->data[$this->current_field]);
            if (!($dateTime && $dateTime->format($format) == $this->data[$this->current_field])) {
                $this->add_error_message('date');
                $this->next = false;
            }
        }
        return $this;
    }

    /**
     * date_after - Check if the date appeared after the specified date.
     *
     * @param mixed $date - Use format Y-m-d (ex. 2023-01-15).
     * @return self
     */
    function date_after($date): Validator
    {
        if ($this->next && $this->exists() && strtotime($date) >= strtotime($this->data[$this->current_field])) {
            $this->add_error_message('date_after');
            $this->next = false;
        }
        return $this;
    }

    /**
     * date_before - Check if the date appeared before the specified date.
     *
     * @param mixed $date - Use format Y-m-d (ex. 2023-01-15).
     * @return self
     */
    function date_before($date): Validator
    {
        if ($this->next && $this->exists() && strtotime($date) <= strtotime($this->data[$this->current_field])) {
            $this->add_error_message('date_before');
            $this->next = false;
        }
        return $this;
    }

    /**
     * must_contain - Check if the value must contain some characters.
     *
     * @param string $chars - Set of chars in one string ex. "@#$&abc123".
     * @return self
     */
    function must_contain(string $chars): Validator
    {
        if ($this->next && $this->exists() && !preg_match("/[" . $chars . "]/i", $this->data[$this->current_field])) {
            $this->add_error_message('must_contain', ['chars' => $chars]);
            $this->next = false;
        }
        return $this;
    }

    /**
     * match - Check if the value matches a pattern.
     *
     * @param string $pattern - Regex pattern to match.
     * @return self
     */
    function match(string $pattern): Validator
    {
        if ($this->next && $this->exists() && !preg_match($pattern, $this->data[$this->current_field])) {
            $this->add_error_message('match');
            $this->next = false;
        }
        return $this;
    }

    /**
     * is_valid - Check if all validations is successful.
     *
     * @return boolean
     */
    function is_valid(): bool
    {
        return count($this->error_messages) == 0;
    }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant