<?php
/**
 * core.framework
 *
 * @category  Core
 * @package   Core_Validate
 * @copyright Copyright (c) 2011. Burza d.o.o. (http://web.burza.hr/en/)
 * @license   proprietary
 */

/**
 * Validates if a value is a valid OIB or not, defined by
 * http://www.regos.hr/UserDocsImages/KONTROLA%20OIB-a.pdf
 *
 * Uses ISO 7064 as the checksum mechanism, so called (MOD 11, 10) system.
 *
 * @category   Core
 * @package    Core_Validate
 * @subpackage Oib
 * @copyright  Copyright (c) 2011. Burza d.o.o. (http://web.burza.hr/en/)
 * @license    proprietary
 */
class Core_Validate_Oib extends Core_Validate_Abstract
{
    /**
     * @var string Default error message.
     */
    protected $_defaultErrorMessage = 'Neispravan OIB!';

    /**
     * @param int $value Value to evaluate.
     *
     * @return boolean
     */
    protected function _isValid($value)
    {
        // simple checks
        if (!is_numeric($value)) {
            return false;
        } else if (11 !== strlen($value)) {
            return false;
        }

        // the control character
        $control  = intval(substr($value, 10, 1), 10);

        // first digit gets added to 10
        $checksum = 10;

        // we go through all the chars except the control one
        for ($idx = 0; $idx < (strlen($value) - 1); $idx++) {
            $checksum += intval(substr($value, $idx, 1), 10);
            $checksum %= 10;

            if (0 === $checksum) {
                $checksum = 10;
            }

            $checksum *= 2;
            $checksum %= 11;
        }

        $checksum = 11 - $checksum;

        if (10 === $checksum) {
            $checksum = 0;
        }

        return ($checksum === $control);
    }
}
