/** * Check that a slug can be updated for a page and update if so * * @param Page $page * @param Slug $slug */ public function updateSlug(Page $page, Slug $slug) { if ($slug->getFull() === $page->slug->getFull()) { return; } $newSlug = $slug->getLastSegment(); $slugSegments = $page->slug->getSegments(); array_pop($slugSegments); $slugSegments[] = $newSlug; $slug = '/' . implode('/', $slugSegments); $this->_checkRoute($slug); $this->_checkSlugExists($page, $slug); // If the slug has changed then update the slug $this->_pageEdit->removeHistoricalSlug($slug); try { $this->_pageEdit->updateSlug($page, $newSlug); } catch (Exception\InvalidSlugException $e) { throw new Exception\SlugUpdateException($e->getMessage(), 'ms.cms.feedback.force-slug.failure.generic', ['%message%' => $e->getMessage()]); } }
/** * Generate a slug. * * If the generated slug already exists on a page, a flag is appended to the * end to try and make the slug unique and generation is attempted again. * The first time a conflict is found, -1 is appended. The second time, -2 * is appended, and so on until a unique slug is found. * * If the slug originally requested to be generated exists in the history of * page slugs, a special exception is thrown to inform the user that the * slug exists historically so they can optionally delete the historical * slug. * * @param string $title The page title to use for slug generation * @param Page|null $parent The parent page, or null if it's a top level page * @param integer $attempt Attempt number, this needn't be set except * when called internally * * @return Slug The generated slug instance */ public function generate($title, Page $parent = null, $attempt = 1) { // Get the parent slug and add the title to the end $segments = $parent ? $parent->slug->getSegments() : array(); $segments[] = $title; $slug = new Slug($segments); // Sanitize the new slug if ($this->_substitutions) { $slug->sanitize($this->_substitutions); } else { $slug->sanitize(); } // Check to see if this slug exists in the history $redirectPage = $this->_loader->checkSlugHistory($slug->getFull()); // If the generated slug exists either historically or on a live page, // try again with a flag for uniqueness if ($redirectPage || $this->_loader->getBySlug($slug->getFull(), false)) { $newTitle = $attempt > 1 ? substr($title, 0, strrpos($title, '-')) : $title; $newTitle .= '-' . $attempt; return $this->generate($newTitle, $parent, $attempt + 1); } // Otherwise, return the slug as it's good to use! return $slug; }
public function testGetLastSegment() { $fullSlug = '/secret/place/in/the/website'; $slug = new Slug($fullSlug); $this->assertSame($slug->getLastSegment(), 'website'); }