1<?php 2 3 4use ComboStrap\DokuPath; 5use ComboStrap\MetaManagerForm; 6use ComboStrap\Metadata; 7use ComboStrap\MetadataWikiPath; 8use ComboStrap\PageTitle; 9use ComboStrap\ResourceCombo; 10use ComboStrap\StringUtility; 11 12class Slug extends MetadataWikiPath 13{ 14 15 public const PROPERTY_NAME = "slug"; 16 17 18 public static function createForPage(ResourceCombo $resource) 19 { 20 return (new Slug()) 21 ->setResource($resource); 22 } 23 24 public function getCanonical(): string 25 { 26 return self::PROPERTY_NAME; 27 } 28 29 30 /** 31 * The goal is to get only words that can be interpreted 32 * We could also encode it 33 * @param $string 34 * @return string|null 35 */ 36 public static function toSlugPath($string): ?string 37 { 38 if (empty($string)) return null; 39 $excludedCharacters = array_merge(DokuPath::getReservedWords(), StringUtility::SEPARATORS_CHARACTERS); 40 $excludedCharacters[] = DokuPath::SLUG_SEPARATOR; 41 $parts = explode(DokuPath::PATH_SEPARATOR, $string); 42 $parts = array_map(function ($e) use ($excludedCharacters) { 43 $wordsPart = StringUtility::getWords( 44 $e, 45 $excludedCharacters 46 ); 47 // Implode and Lower case 48 return strtolower(implode(DokuPath::SLUG_SEPARATOR, $wordsPart)); 49 }, $parts); 50 51 $slug = implode(DokuPath::PATH_SEPARATOR, $parts); 52 // Space to separator 53 //$slugWithoutSpace = str_replace(" ", DokuPath::SLUG_SEPARATOR, $slugWithoutSpaceAroundParts); 54 // No double separator 55 //$slugWithoutDoubleSeparator = preg_replace("/" . DokuPath::SLUG_SEPARATOR . "{2,}/", DokuPath::SLUG_SEPARATOR, $slugWithoutSpace); 56 DokuPath::addRootSeparatorIfNotPresent($slug); 57 return $slug; 58 } 59 60 public function getTab(): string 61 { 62 return MetaManagerForm::TAB_REDIRECTION_VALUE; 63 } 64 65 public function getDescription(): string 66 { 67 return "The slug is used in the url of the page (if chosen)"; 68 } 69 70 public function getLabel(): string 71 { 72 return "Slug Path"; 73 } 74 75 public function setFromStoreValue($value): Metadata 76 { 77 return $this->buildFromStoreValue($value); 78 } 79 80 public function setValue($value): Metadata 81 { 82 return $this->buildFromStoreValue($value); 83 } 84 85 public function buildFromStoreValue($value): Metadata 86 { 87 return parent::buildFromStoreValue(self::toSlugPath($value)); 88 } 89 90 91 static public function getName(): string 92 { 93 return self::PROPERTY_NAME; 94 } 95 96 public function getPersistenceType(): string 97 { 98 return Metadata::PERSISTENT_METADATA; 99 } 100 101 public function getMutable(): bool 102 { 103 return true; 104 } 105 106 public function getDefaultValue(): ?string 107 { 108 $title = PageTitle::createForPage($this->getResource()) 109 ->getValueOrDefault(); 110 if ($title === null) { 111 return null; 112 } 113 return self::toSlugPath($title); 114 } 115} 116