Skip to content

Instantly share code, notes, and snippets.

@josephzidell
Last active January 3, 2016 17:59
Show Gist options
  • Save josephzidell/8498917 to your computer and use it in GitHub Desktop.
Save josephzidell/8498917 to your computer and use it in GitHub Desktop.
Pathify CakePHP routes
<?php
function root_path() {
return '/';
}
function pathify() {
foreach ( Router::$routes as $route ) {
$parts = [];
if ( isset( $route->defaults['prefix'] ) && !is_null( $route->defaults['prefix'] ) ) {
$parts[] = $route->defaults['prefix'];
}
if ( !is_null( $route->defaults['plugin'] ) ) {
$parts[] = $route->defaults['plugin'];
}
$parts[] = $route->defaults['controller'];
$parts[] = $route->defaults['action'];
// root
if ( $route->template == '/' ) {
$parts = ['root'];
}
$functionNamePath = implode('_', $parts) . '_path';
if ( !function_exists($functionNamePath) ) {
$$functionNamePath = function() use ($route, $functionNamePath) {
$argsRequired = substr_count($route->template, ':');
if ( $argsRequired !== func_num_args() ) {
throw new InvalidArgumentException('Invalid parameters for ' . $functionNamePath . '()');
}
if ( $argsRequired == 0 ) {
return $route->template;
} else {
$template = $route->template;
foreach ( func_get_args() as $arg ) {
$template = preg_replace('/:[A-Za-z_-]+/', func_get_arg($a), $template);
}
return $template;
}
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment