Skip to content

Instantly share code, notes, and snippets.

@erandirjunior
Last active January 27, 2019 23:30
Show Gist options
  • Save erandirjunior/bf6fbe2226778ebe1720e0c013176ab5 to your computer and use it in GitHub Desktop.
Save erandirjunior/bf6fbe2226778ebe1720e0c013176ab5 to your computer and use it in GitHub Desktop.
Lógica das rotas dinâmicas
<?php
/*Métodos de PlugHelper*/
public static function getMatch($route, $pattern = '{(.*?)}')
{
$pattern = "/{$pattern}/";
preg_match($pattern, $route, $matches);
return !empty($matches[1]) ? $matches[1] : null;
}
public static function getMatchAll($route, $pattern = '{(.*?)}')
{
preg_match_all("/{$pattern}/", $route, $match);
return $match[0];
}
/*FIM Métodos*/
$route = '/teste/{id}';
// Faço uma match que me retorna uma array dos dados dinâmicos. ex: {id}
$matches = PlugHelper::getMatchAll($route, '({.+?(?:\:.*?)?})');
$routePrepared = $route;
$matchPrepared = [];
foreach ($matches as $key => $match) {
// pego o pattern para aquele valor dinâmico, se tiver um pattern
$getMatchRoute = PlugHelper::getMatch($match, ':(.*?)}');
// Recebe o pattern ou um pattern default
$matchPrepared[] = is_null($getMatchRoute) ? '.+' : $getMatchRoute;
// cria um identificador
$identifiers[] = "|##{$key}##|";
// Substitui a parte dinâmica pelo indentificador
$routePrepared = str_replace($match, $identifiers[$key], $routePrepared);
}
// escapa as barras para não quebrar a regex
$routePrepared = str_replace('/', '\/', $routePrepared);
// substitui os identificadores pelos patterns
$urlPrepared = str_replace($identifiers, $matchPrepared, $routePrepared);
// retorna a match da rota pela url ou nulo se não fez match
return PlugHelper::getMatch($url, "({$urlPrepared})");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment