<?php

class domainName 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
     */
    protected $pattern = '/^(^[\*]\.|[a-z0-9_]+(-[a-z0-9_]+)*\\.)+[a-z]{2,}$/';

    protected function validateAttribute($object, $attribute)
    {
        // extract the attribute value from it's model object
        $value = $object->$attribute;
        if ($value === '') {
            return true;
        }
        if ($value != '') {
            $this->checkHostName($object, $attribute, $value);
        }
        return true;
    }

    protected function checkHostName($object, $attribute, $value)
    {
        if (!preg_match($this->pattern, $value)) {
            if (!$this->checkHostNameWithZone($object, $value)) {
                $this->addError($object, $attribute, __('GLOBAL_DOMAIN_NAME_VALIDATION_ERROR_MESSAGE'));
                return false;
            }
        }
        return true;
    }

    protected function checkHostNameWithZone($object, $value)
    {
        if (get_class($object) === 'DNSRecord') {
            $model = DNSZone::model()->findByPk($object->dnsZone);
            if ($model) {
                $searchFor = $value . '.' . $model->fqdn;
                if (preg_match($this->pattern, $searchFor)) {
                    return true;
                }
            }
        }
        return false;
    }
}
