<?php

class portInRange extends CValidator
{

    /**
     * Validates the attribute of the object.
     * If there is any error, the error message is added to the object.
     * @param CModel $object the object being validated
     * @param string $attribute the attribute being validated
     */
    public $min = 1;
    public $max = 65535;

    protected function validateAttribute($object, $attribute)
    {
        // extract the attribute value from it's model object
        $value = $object->$attribute;

        $result = true;
        if (!empty($value)) {

            if (strpos($value, '-') !== false) {
                $result = $this->checkIfStringPortIsInRange($value);
            } else if (strpos($value, '*') !== false) {
                $result = $this->checkPortAllScenario($value);
            } else {
                $result = $this->checkIfIntPortIsInRange($value);
            }
        }
        if (!$result) {
            $errorTxt = 'GLOBAL_PORT_IN_RANGE_VALIDATION_ERROR_MESSAGE_NOT_IN_RANGE';
            $errorMsg = __($errorTxt, true, 'messages', array(
                "{attribute}" => $object->getAttributeLabel($attribute),
                "{min}" => $this->min,
                "{max}" => $this->max
                    ));
            $this->addError($object, $attribute, $errorMsg);
        }
        return $result;
    }

    protected function checkIfStringPortIsInRange($value)
    {
        $valueRange = explode('-', $value);
        $valueMin = @$valueRange[0];
        $valueMax = @$valueRange[1];

        if (!isset($valueMin) && !isset($valueMax)) {
            return false;
        }
        if (!$this->checkIfIntPortIsInRange($valueMin)) {
            return false;
        }

        if (!$this->checkIfIntPortIsInRange($valueMax)) {
            return false;
        }
        return true;
    }

    protected function checkPortAllScenario($value)
    {
        if (strlen($value) > 1) {
            return false;
        }
        return true;
    }

    protected function checkIfIntPortIsInRange($value)
    {
        $intValue = (int) $value;
        if (($intValue >= $this->min && $intValue <= $this->max)) {
            return true;
        }
        return false;
    }
}
