From 0c85d708204c72fc80dcfc07344036eaf10e4d08 Mon Sep 17 00:00:00 2001 From: Daniel Rudolf Date: Sun, 13 Dec 2015 22:01:25 +0100 Subject: [PATCH] Adding $queryData parameter to Pico::getPageUrl() method This allows developers to easily add custom query data to an page URL without the need to check enabled URL rewriting on their own. Since Twigs `link` filter is just an alias for Pico::getPageUrl(), theme designers can do the same with e.g. `{{ "index"|link("foo=bar&baz=42") }}`. Theme designers, heads up! Don't forget that the result of the `link` filter is never escaped, so the result could contain unescaped ampersands when passing custom query data. You should pass the result to Twigs `escape` filter when using custom query data. --- CHANGELOG.md | 1 + lib/Pico.php | 27 +++++++++++++++++++++------ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fe5acbc..3b0877a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Released: - ``` * [New] This is Picos first stable release! The Pico Community wants to thank all contributors and users which made this possible! +* [New] Adding `$queryData` parameter to `Pico::getPageUrl()` method * [Changed] Moving `LICENSE` to `LICENSE.md` ``` diff --git a/lib/Pico.php b/lib/Pico.php index bcdb5e6..30de7be 100644 --- a/lib/Pico.php +++ b/lib/Pico.php @@ -1234,17 +1234,32 @@ class Pico /** * Returns the URL to a given page * - * @param string $page identifier of the page to link to - * @return string URL + * @param string $page identifier of the page to link to + * @param array|string $queryData either an array containing properties to + * create a URL-encoded query string from, or a already encoded string + * @return string URL */ - public function getPageUrl($page) + public function getPageUrl($page, $queryData = null) { + if (is_array($queryData)) { + $queryData = http_build_query($queryData, '', '&'); + } elseif (($queryData !== null) && !is_string($queryData)) { + throw new InvalidArgumentException( + 'Argument 2 passed to ' . get_called_class() . '::getPageUrl() must be of the type array or string, ' + . (is_object($queryData) ? get_class($queryData) : gettype($queryData)) . ' given' + ); + } + if (!empty($queryData)) { + $page = (!empty($page) || $this->isUrlRewritingEnabled()) ? $page : 'index'; + $queryData = $this->isUrlRewritingEnabled() ? '?' . $queryData : '&' . $queryData; + } + if (empty($page)) { - return $this->getBaseUrl(); + return $this->getBaseUrl() . $queryData; } elseif (!$this->isUrlRewritingEnabled()) { - return $this->getBaseUrl() . '?' . rawurlencode($page); + return $this->getBaseUrl() . '?' . rawurlencode($page) . $queryData; } else { - return $this->getBaseUrl() . implode('/', array_map('rawurlencode', explode('/', $page))); + return $this->getBaseUrl() . implode('/', array_map('rawurlencode', explode('/', $page))) . $queryData; } }