<?php

class isSubDomain 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 $topLevelDomain;
    
    protected function validateAttribute($object, $attribute)
    {
        // extract the attribute value from it's model object
        $value = $object->$attribute;
        
        if (!empty($value))
        {
            if ($this->endswith($value, $this->topLevelDomain)) {
                return true;
            }
            
            $this->addError($object, $attribute, __('GLOBAL_DOMAIN_NAME_VALIDATION_ERROR_MESSAGE_NO_SUB_DOMAIN_FROM'). $this->topLevelDomain);
            return false;
        }
        return true;
    }
    
    
    protected function endswith($haystack, $needle)
    {
        $strlen = strlen($haystack);
        $testlen = strlen($needle);
    
        if ($testlen > $strlen) {
               return false;
        }
        return substr_compare($haystack, $needle, $strlen - $testlen, $testlen) === 0;
    }
}