From 610e41a05753bf273d108206ff449079af148a03 Mon Sep 17 00:00:00 2001 From: Marc Jauvin Date: Sat, 11 Jul 2020 10:08:47 -0400 Subject: [PATCH] add flexibility to Post setUrl method (#506) * allow passing parameters when calling setUrl; use current category to build post url * Update components/Posts.php * Fix minor code smell * Update models/Post.php * Update models/Post.php * do not make unnecessary queries * Update models/Post.php Co-authored-by: Ben Thomson Co-authored-by: Ben Thomson Co-authored-by: Luke Towers --- components/Posts.php | 5 +++-- models/Post.php | 13 ++++++++----- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/components/Posts.php b/components/Posts.php index 2746744..9f3bb13 100644 --- a/components/Posts.php +++ b/components/Posts.php @@ -195,6 +195,7 @@ protected function prepareVars() protected function listPosts() { $category = $this->category ? $this->category->id : null; + $categorySlug = $this->category ? $this->category->slug : null; /* * List all the posts, eager load their categories @@ -219,8 +220,8 @@ protected function listPosts() /* * Add a "url" helper attribute for linking to each post and category */ - $posts->each(function($post) { - $post->setUrl($this->postPage, $this->controller); + $posts->each(function($post) use ($categorySlug) { + $post->setUrl($this->postPage, $this->controller, ['category' => $categorySlug]); $post->categories->each(function($category) { $category->setUrl($this->categoryPage, $this->controller); diff --git a/models/Post.php b/models/Post.php index aa5ab8b..4b81258 100644 --- a/models/Post.php +++ b/models/Post.php @@ -152,17 +152,20 @@ public function beforeSave() * Sets the "url" attribute with a URL to this object. * @param string $pageName * @param Controller $controller + * @param array $params Override request URL parameters * * @return string */ - public function setUrl($pageName, $controller) + public function setUrl($pageName, $controller, $params = []) { - $params = [ + $params = array_merge([ 'id' => $this->id, - 'slug' => $this->slug - ]; + 'slug' => $this->slug, + ], $params); - $params['category'] = $this->categories->count() ? $this->categories->first()->slug : null; + if (!$params['category']) { + $params['category'] = $this->categories->count() ? $this->categories->first()->slug : null; + } // Expose published year, month and day as URL parameters. if ($this->published) {