<?php
/**人
* クラスに関するユーティリティ
*
* PHP version 5
*
* @package    core
* @author     stk2k <stk2k@sazysoft.com>
* @copyright  2008 stk2k, sazysoft
*/

class ClassUtil
{
	/*
	 * クラス名を検証
	 */
	public static function validateClassName( $class_name )
	{
		return preg_match( "/\A[a-zA-Z]\w*/", "$class_name" );
	}

	/*
	 * クラスをロード
	 */
	public static function loadClass( $class_path, $class_name )
	{
		// パスが未定義
		if ( !$class_path ){
			return FALSE;
		}

		// ソースがなければ例外をスロー
		$include_path_list = explode( PATH_SEPARATOR, get_include_path() );
		$found = FALSE;
		foreach( $include_path_list as $include_path ){
			$path = $include_path . DIRECTORY_SEPARATOR . $class_path;
			if ( is_file($path) ){
				$found = TRUE;
				break;
			}
		}
		if ( !$found ){
			$msg = "Source file path[$class_path] is not file";
			require_once( 'exceptions/ClassNotFoundException.class.php' );
			throw new ClassNotFoundException($class_name,$class_path,$msg);
		}

		// ソース読み込み
		require_once( $class_path );

		// クラスが未定義なら例外をスロー
		if ( !class_exists($class_name,FALSE) && !interface_exists($class_name,FALSE) ){
			$msg = "Class[$class_name] is not defined in source file[$class_path]";
			require_once( 'exceptions/ClassNotFoundException.class.php' );
			throw new ClassNotFoundException($class_name,$class_path,$msg);
		}

		return TRUE;
	}

	/*
	 * クラスのインスタンスを生成する
	 */
	public static function newInstance( String $class_name, $args = NULL )
	{
		$class_name = $class_name->getValue();

		if ( !class_exists($class_name) ){
			throw new ClassNotFoundException( $class_name );
		}

		$reflection = new ReflectionClass( $class_name );

		if ( !$args ){
			$instance = $reflection->newInstance( NULL );
		}
		else if ( is_array($args) ){
			switch ( count($args) ){
			case 0:		$instance = $reflection->newInstance( NULL );															break;
			case 1:		$instance = $reflection->newInstance( $args[0] );														break;
			case 2:		$instance = $reflection->newInstance( $args[0], $args[1] );												break;
			case 3:		$instance = $reflection->newInstance( $args[0], $args[1], $args[2] );									break;
			case 4:		$instance = $reflection->newInstance( $args[0], $args[1], $args[2], $args[3] );							break;
			case 5:		$instance = $reflection->newInstance( $args[0], $args[1], $args[2], $args[3], $args[4] );				break;
			case 6:		$instance = $reflection->newInstance( $args[0], $args[1], $args[2], $args[3], $args[4], $args[5] );		break;
			}
		}
		else{
			$instance = $reflection->newInstance( $args );
		}

		return $instance;
	}

	/*
	 * クラスがインタフェースを実装しているか確認
	 */
	public static function testImplements( $object, $interface_name )
	{
		return ( $object instanceof $interface_name );
	}

}
