Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a data validation class, which I would like to return errors in many languages. I'm not writing the whole class, just the needed parts as my question only refers to that.

<?php

class Validator {

    public $error = null;

    private $options = null;
    private $errors = [
            'isArray' => [
                    'en' => "Data passed cannot be an array.",
                    'es' => "Los datos proporcionados no pueden ser un array."
            ],
            'notArray' => [
                    'en' => "Data is not an Array.",
                    'es' => "Los datos no son de tipo Array."
            ],
            'emptyArray' => [
                    'en' => "Array is empty.",
                    'es' => "El array esta vacio."
            ],
            'emptyData' => [
                    'en' => "Data passed is empty.",
                    'es' => "Los datos proporcionados estan vacios."
            ],
            'notAlphanumData' => [
                    'en' => "Data is not alpha or numeric.",
                    'es' => "Los datos no son texto o números."
            ],
            'rangeNotArray' => [
                    'en' => "Numeric range must be passed as an array.",
                    'es' => "El rango numerico debe ser pasado en un array."
            ],
            'isNot12Hours' => [
                    'en' => "Data could not be validated as an hour in 12-Hours format.",
                    'es' => "Los datos no pudieron ser validados como una hora en formato de 12 Horas."
            ],
            'isNot24Hours' => [
                    'en' => "Data could not be validated as an hour in 24-Hours format.",
                    'es' => "Los datos no pudieron ser validados como una hora en formato de 24 Horas."
            ],
            'isNotDate' => [
                    'en' => "Data could not be validated as a date.",
                    'es' => "Los datos no pudieron ser validados como una fecha."
            ],
            'noDateGiven' => [
                    'en' => "No date is given in data.",
                    'es' => "No se encontro una fecha en los datos."
            ],
            'noHourGiven' => [
                    'en' => "No hour is given in data.",
                    'es' => "No se encontro una hora en los datos."
            ],
            'notEmail' => [
                    'en' => "Data could not be validated as an E-mail.",
                    'es' => "Los datos no pudieron ser validados como un E-mail."
            ]
    ];

    private function _initErrors() {

        $options = &$this->options;

        $rangeMin = isset($options->range[0]) ? $options->range[0] : 0;
        $rangeMax = isset($options->range[1]) ? $options->range[1] : 0;

        $options->errors['minGtMax'] = 
        [
                'en' => "Minimum length of: $options->min, can not be greater than max length of: $options->max",
                'es' => "La longitud minima de: $options->min, no puede ser mayor a la longitud maxima de: $options->max"
        ];
        $options->errors['lengthLtMin'] =
        [
                'en' => "Data length is lower than minimum length of: $options->min characters.",
                'es' => "La longitud de los datos no cumple el minimo de $options->min caracteres."
        ];
        $options->errors['lengthGtMax'] =
        [
                'en' => "Data length is greater than maximum length of: $options->max characters.",
                'es' => "La longitud de los datos sobrepasa el maximo de $options->max caracteres."
        ];
        $options->errors['rangeMinGtMax'] = 
        [
                'en' => "Data minimum range of $rangeMin, is greater than maximum range of $rangeMax.",
                'es' => "El rango minimo de $rangeMin, es mayor que el rango maximo de $rangeMax"
        ];
        $options->errors['rangeLtMin'] = 
        [
                'en' => "Data is below minimum range of $rangeMin.",
                'es' => "Los datos estan por debjo del rango minimo de $rangeMin."
        ];
        $options->errors['rangeGtMax'] = 
        [
                'en' => "Data is higher than maximum range of $rangeMax.",
                'es' => "Los datos estan por encima del rango minimo de $rangeMax."
        ];          
    }

    private function _init($options) {

        $optns = &$this->options;
        $optns = new stdClass();

        $optns->data = isset($options['data']) ? $options['data'] : null;
        $optns->space = isset($options['space']) ? $options['space'] : false;
        $optns->min = isset($options['min']) ? $options['min'] : null;
        $optns->max = isset($options['max']) ? $options['max'] : null;
        $optns->range = isset($options['range']) ? $options['range'] : null;
        $optns->format = isset($options['format']) ? $options['format'] : null;
        $optns->encode = isset($options['encode']) ? $options['encode'] : true;
        $optns->lang = isset($options['lang']) ? $options['lang'] : 'es';

        self::_initErrors();

        if ( isset($optns->data) && !is_array($optns->data) ) {
            self::_decode();
        }
    }

    private function _close() {

        $result = new stdClass();

        $result->error = $this->error;
        $result->data = $this->options->data;

        $this->error = null;
        $this->options = null;

        return $result;
    }

    private function _setError($error) {

        $lang = $this->options->lang;

        if ( array_key_exists($lang, $this->errors[$error]) ) {

            $this->error = $this->errors[$error][$lang];
        }

        else {

            $this->error = $this->errors[$error][0];
        }           
    }

    private function _checkData($is_array = null) {

        $data = &$this->options->data;

        if ( isset($is_array) && $is_array === true) {

            if ( !is_array($data)  ) {
                self::_setError('notArray');
                return false;
            }

            else if ( empty(array_filter($data)) ) {
                self::_setError('emptyArray');
                return false;
            }

            return true;
        }

        else {

            if ( empty($data) ) {
                self::_setError('emptyData');
                return false;
            }

            else if ( !is_string($data) && !is_numeric($data) ) {
                self::_setError('notAlphanumData');
                return false;
            }

            return true;
        }

    }

    public function example($options) {

         self::_init($options);

        if ( !self::_checkData() ) {
            return self::_close();
        }
    }
}
?>

As you can see the error list is long, and I do hate too look at that. I know I can write those errors into an ini file and load them, but I think that may slow the class.

I have more classes which uses the same error reporting approach. So my question, is there a better way of handling all classes errors?


As a side note, I was thinking to only return the 'error code' (e.g: 'arrayEmpty') and let people display their own error message. But I still would need to maintain a list of the errors code meaning. To people to know what to show.

share|improve this question
    
I have previously seen errors report an error code, and then a separate file/handler matches the error code to the user's error message in their preferred language. This keeps translations and controlling code separate. – Alex L Jan 23 at 6:28
    
@AlexL Thanks for your comment, so I would do something like $errorMsg = $errorHandler->getFriendlyError($validation->error_code); ? – Victor Tello Jan 23 at 23:17
    
Essentially yes, however I can't find anything listing the pros/cons of this method, and I'm not a credible source on translating websites so take that advice with a grain of salt :) – Alex L Jan 23 at 23:30
    
Hehe it's ok, I really appreciate the advice. I have think of a method of doing this based on your comment, but I think I should do another question for that. – Victor Tello Jan 23 at 23:36

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.