silverstripe-blog/code/extensions/URLSegmentExtension.php

79 lines
2.0 KiB
PHP
Raw Normal View History

2015-05-09 16:33:12 +02:00
<?php
/**
* Adds URLSegment functionality to Tags & Categories.
*
* @package silverstripe
* @subpackage blog
*/
2015-11-21 07:17:29 +01:00
class URLSegmentExtension extends DataExtension
{
/**
* @var array
*/
private static $db = array(
'URLSegment' => 'Varchar(255)',
);
/**
* {@inheritdoc}
*/
public function onBeforeWrite()
{
if ($this->owner->BlogID) {
$this->owner->generateURLSegment();
}
2015-11-21 07:17:29 +01:00
}
/**
* Generates a unique URLSegment from the title.
*
* @param int $increment
*
* @return string
*/
public function generateURLSegment($increment = null)
{
$filter = new URLSegmentFilter();
// Setting this to on. Because of the UI flow, it would be quite a lot of work
// to support turning this off. (ie. the add by title flow would not work).
// If this becomes a problem we can approach it then.
// @see https://github.com/silverstripe/silverstripe-blog/issues/376
$filter->setAllowMultibyte(true);
2015-11-21 07:17:29 +01:00
$this->owner->URLSegment = $filter->filter($this->owner->Title);
if (is_int($increment)) {
$this->owner->URLSegment .= '-' . $increment;
}
// Postgres use '' instead of 0 as an emtpy blog ID
// Without this all the tests fail
if (!$this->owner->BlogID) {
$this->owner->BlogID = 0;
}
2015-11-21 07:17:29 +01:00
$duplicate = DataList::create($this->owner->ClassName)->filter(array(
'URLSegment' => $this->owner->URLSegment,
'BlogID' => $this->owner->BlogID,
));
if ($this->owner->ID) {
$duplicate = $duplicate->exclude('ID', $this->owner->ID);
}
if ($duplicate->count() > 0) {
if (is_int($increment)) {
$increment += 1;
} else {
$increment = 0;
}
$this->owner->generateURLSegment((int) $increment);
}
return $this->owner->URLSegment;
}
2015-05-09 16:33:12 +02:00
}