<?php

class Eppe_Validate_PolishNipNumber extends Zend_Validate_Abstract {

	const INVALID_NIP_NUMBER = 'invalidNipNumber';

	protected $_messageTemplates = array(
		self::INVALID_NIP_NUMBER => "'%value%' is not a valid polish NIP code.",
	);
	
	public function __construct($options = null) {
		Eppe_Validate::setupConstructorOptions($this, $options);
	}
	
	/**
	 * @param type $value
	 * @return boolean
	 */
	public function isValid($value) {
		$valueString = (string) $value;
		$this->_setValue($valueString);

		if (!$this->NIPIsValid($value)) {
			$this->_error(self::INVALID_NIP_NUMBER);
			return false;
		}
		return true;
	}

	/**
	 * Sprawdza poprawność podanego numeru NIP
	 * @param type $pNip
	 * @return boolean
	 */
	public function NIPIsValid($pNip) {
		if (!empty($pNip)) {
			$weights = array(6, 5, 7, 2, 3, 4, 5, 6, 7);
			$nip = preg_replace('/[\s-]/', '', $pNip);
			if (strlen($nip) == 10 && is_numeric($nip)) {
				$sum = 0;
				for ($i = 0; $i < 9; $i++)
					$sum += $nip[$i] * $weights[$i];
				return ($sum % 11) == $nip[9];
			}
		}
		return false;
	}

}

?>
