Ok, after this lightweight brief I am going to present you fat-ass Router method o'mine which main function is to make possible to load correct Action method although it is misspelled or shorten.
For example, this URL is requested:
http://www.mypage.com/Book/Shoooww/69/php-for-dummies
Router parses URL, and find that Book is controller, Shoooww should be action, 69 and php-for-dummies are parameters.
This questioned method makes checks for available actions and based on similarity picks one (Show). Code is well commented so I will explain no more
Here is the method code:
Code: Select all
/**
* This method searches over provided array of possible methods and based on
* percent of similarity returns the closest match. If percent is lower than 30%
* default method name is returned
* @param string $action Provided action name via URL
* @param array $methodArray Array of controller methods
* @param string $defaultMethod Default method if match is not found
* @access private
*/
private function getClosestMatchMethod( $action, $methodArray, $defaultMethod ){
// Check if provided parameters are valid
if( is_string( $action ) && !empty( $action ) && is_array( $methodArray ) && is_string( $defaultMethod ) && !empty( $defaultMethod ) ){
// Initialize match array
$matchArray = array();
// Foreach of possible controller methods...
foreach( $methodArray as $method ){
// Check if method contains some 'magic' substrings
if( !strstr( $method, "__" ) || !strstr( $method, "_" ) ) {
// If method name is valid, calculate similarity between
// provided action candidate and possible controller methods
similar_text( $action, $method, $result );
// Store only matches that are over 30% similar
if( $result > 30 ) $matchArray[$method] = $result;
// Otherwise, continue
} else continue;
}
// Check if any matches are founded
if ( !empty( $matchArray ) ){
// If founded, get maximum value in the string
$maximum =& max( $matchArray );
// Return method name ( index key ) based on it's value
return array_search( $maximum, $matchArray, true );
// Otherwise return default method name
} else return $defaultMethod;
// Otherwise, throw exception
} else throw new Exception("Invalid parameter(s) in " . __METHOD__ );
}