From ba562f0486c8e1de6545b7677ee46e541801f123 Mon Sep 17 00:00:00 2001 From: Andy Miller Date: Sat, 20 May 2017 22:16:53 -0600 Subject: [PATCH] Added Utils::getPagePathFromToken() --- system/src/Grav/Common/Utils.php | 52 ++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/system/src/Grav/Common/Utils.php b/system/src/Grav/Common/Utils.php index 8ceddd366..6c8898103 100644 --- a/system/src/Grav/Common/Utils.php +++ b/system/src/Grav/Common/Utils.php @@ -851,4 +851,56 @@ abstract class Utils public static function isApache() { return strpos($_SERVER["SERVER_SOFTWARE"], 'Apache') !== false; } + + /** + * Get's path based on a token + * + * @param $path + * @param null $page + * @return string + */ + public static function getPagePathFromToken($path, $page = null) + { + $path_parts = pathinfo($path); + $grav = Grav::instance(); + + $basename = ''; + if (isset($path_parts['extension'])) { + $basename = '/' . $path_parts['basename']; + $path = rtrim($path_parts['dirname'], ':'); + } + + $regex = '/(@self|self@)|((?:@page|page@):(?:.*))|((?:@theme|theme@):(?:.*))/'; + preg_match($regex, $path, $matches); + + if ($matches) { + if ($matches[1]) { + if (is_null($page)) { + throw new \RuntimeException('Page not available for this self@ reference'); + } + } elseif ($matches[2]) { + // page@ + $parts = explode(':', $path); + $route = $parts[1]; + $page = $grav['page']->find($route); + } elseif ($matches[3]) { + // theme@ + $parts = explode(':', $path); + $route = $parts[1]; + $theme = str_replace(ROOT_DIR, '', $grav['locator']->findResource("theme://")); + + return $theme . $route . $basename; + } + } else { + return $path . $basename; + } + + if (!$page) { + throw new \RuntimeException('Page route not found: ' . $path); + } + + $path = str_replace($matches[0], rtrim($page->relativePagePath(), '/'), $path); + + return $path . $basename; + } }