<?php

/*
 * @copyright NetMonsters <team@netmonsters.ru>
 * @link http://netmonsters.ru
 * @package Majestic
 * @subpackage UnitTests
 * @since 2011-10-07
 * 
 * Unit tests for RegexValdator class
 */

require_once dirname(__FILE__) . '/../../validator/iValidator.php';
require_once dirname(__FILE__) . '/../../validator/Validator.php';
require_once dirname(__FILE__) . '/../../validator/RegexValidator.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';

class RegexValidatorTest extends PHPUnit_Framework_TestCase
{

    public function testIsValid()
    {
        $validator = new RegexValidator('/^[a-z]*$/i');
        
        $this->assertTrue($validator->isValid('anTon', array(1,2,3)));
        $this->assertFalse($validator->isValid('12ejkas,.21'));        
    }
    
    public function testGetMessage()
    {
        $validator = new RegexValidator('/^[a-z0-9]*$/i');
        $this->assertTrue($validator->isValid('ton342ad21y'));
        $this->assertEmpty($validator->getMessage());
        $this->assertFalse($validator->isValid('!!#asd'));
        $this->assertNotEmpty($validator->getMessage());  
    }
    
    public function testSetMessage()
    {
        $validator = new RegexValidator('/a/i');
        $validator->isValid('2sa131');
        $this->assertEmpty($validator->getMessage());
        $validator->setMessage('i am ok');
        $validator->isValid('2131');
        $this->assertSame('i am ok', $validator->getMessage());
    }
    

    public function testNullMessage()
    {
        $validator = new RegexValidator('/a/i');
        $validator->setMessage(null, null);

        $this->setExpectedException('GeneralException', 'Message template "regex_not_match" unknown.');

        $validator->isValid('1212');
    }
    
    /**
     * @TODO: RegexValidator - wrong regex throws an error. Check this.
     */
    public function testWrongRegexp()
    {
        $validator = new RegexValidator('/^[a-z][0-9]$*/i');
        $this->setExpectedException('PHPUnit_Framework_Error');
        $this->assertFalse($validator->isValid('to423$%ny'));
    }
    
    public function testRegexReturnsFalse()
    {
        $validator = new RegexValidator('/(?:\D+|<\d+>)*[!?]/');
        $this->setExpectedException('GeneralException', 'regex');
        $this->assertFalse($validator->isValid('foobar foobar foobar'));
    }
}