Skip to content

Instantly share code, notes, and snippets.

@lukaskleinschmidt
Last active May 9, 2019 11:59
Show Gist options
  • Save lukaskleinschmidt/bc87e6030a5c5761a96429ebaa26de90 to your computer and use it in GitHub Desktop.
Save lukaskleinschmidt/bc87e6030a5c5761a96429ebaa26de90 to your computer and use it in GitHub Desktop.
Kirby 3 uuid

You would need to install https://github.com/ramsey/uuid to make it work. Depending on the use case it could also make sense to implement those as traits.

<?php

class ArticlePage extends UuidPage
{
  
}
<?php

class BlogPage extends UuidParentPage
{
  
}
<?php
use Kirby\Exception\NotFoundException;
use Kirby\Cms\Page;
use Kirby\Toolkit\Str;
class UuidPage extends Page
{
/**
* Changes the slug/uid of the page
*
* @param string $slug
* @param string $languageCode
* @return Page
*/
public function changeSlug(string $slug, string $languageCode = null): Page
{
// always sanitize the slug
$slug = Str::slug($slug);
if ($language = $this->kirby()->language($languageCode)) {
if (!$language) {
throw new NotFoundException('The language: "' . $languageCode . '" does not exist');
}
}
return $this->commit('changeSlug', [$this, $slug, $languageCode], function ($page, $slug, $languageCode) {
// remove the slug if it's the same as the folder name
if ($slug === $page->uid()) {
$slug = null;
}
return $page->save(['slug' => $slug], $languageCode);
});
}
}
<?php
use Kirby\Exception\DuplicateException;
use Kirby\Cms\Page;
use Kirby\Toolkit\Str;
use Ramsey\Uuid\Uuid;
class UuidParentPage extends Page
{
/**
* Creates and stores a new page
*
* @param array $props
* @return Page
*/
public static function create(array $props): Page
{
kirby()->extend([
'hooks' => [
'page.create:before' => function (Page $page) {
$languageCode = $page->kirby()->defaultLanguage()->code();
$children = $page->parentModel()->childrenAndDrafts();
$slug = $page->content()->slug();
foreach ($children as $p) {
if ($p->uid() == $slug) {
throw new DuplicateException([
'key' => 'page.duplicate',
'data' => ['slug' => $slug]
]);
}
if ($p->slug() == $slug) {
throw new DuplicateException([
'key' => 'page.duplicate',
'data' => ['slug' => $slug]
]);
}
if ($p->slug($languageCode) == $slug) {
throw new DuplicateException([
'key' => 'page.duplicate',
'data' => ['slug' => $slug]
]);
}
}
}
]
]);
$slug = Str::slug($props['slug'] ?? $props['content']['title'] ?? null);
$props['content']['slug'] = $slug;
$props['slug'] = (string) Uuid::uuid4();
return parent::create($props);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment