Completed
Pull Request — master (#59)
by
unknown
01:36
created

TaxonomyTermUrlExtension::onBeforeWrite()   B

Complexity

Conditions 8
Paths 8

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 12
nc 8
nop 0
dl 0
loc 21
rs 8.4444
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\Taxonomy\Extensions;
4
5
use SilverStripe\Forms\FieldList;
6
use SilverStripe\ORM\DataExtension;
7
use SilverStripe\Taxonomy\TaxonomyTerm;
8
use SilverStripe\View\Parsers\URLSegmentFilter;
9
10
/**
11
* Adds a URLSegment to TaxonomyTerm that gets
12
* generated from the name if not specified.
13
*
14
* @package taxonomy
15
*/
16
class TaxonomyTermUrlExtension extends DataExtension
17
{
18
    private static $db = array(
0 ignored issues
show
introduced by
The private property $db is not used, and could be removed.
Loading history...
19
        'URLSegment' => 'Varchar(255)',
20
    );
21
22
    public function updateCMSFields(FieldList $fields)
23
    {
24
        $field = $fields->dataFieldByName('URLSegment');
25
        if ($field) {
0 ignored issues
show
introduced by
$field is of type SilverStripe\Forms\FormField, thus it always evaluated to true.
Loading history...
26
            $field->setDescription(_t(
27
                __CLASS__ . '.LeaveBlankLabel',
28
                'Leave blank to generate from name'
29
            ));
30
            $fields->insertAfter('Name', $field);
31
        }
32
    }
33
34
    /**
35
     *  Set the URL segment allowing filtering by url slug
36
     *
37
     *  {@inheritDoc}
38
     */
39
    public function onBeforeWrite()
40
    {
41
        parent::onBeforeWrite();
42
        // Write the URLSegment to allow for Taxonomy navigation only if one is not supplied
43
        if ($this->owner->Name && $this->owner->URLSegment == null) {
44
            $filter = URLSegmentFilter::create();
45
            $filteredTitle = $filter->filter($this->owner->Name);
46
47
            // Fallback to generic name if path is empty (= no valid, convertable characters)
48
            if (!$filteredTitle || $filteredTitle == '-' || $filteredTitle == '-1') {
49
                $id = $this->owner->ID ? $this->owner->ID : 1;
50
                $filteredTitle = "term-$id";
51
            }
52
53
            $this->owner->setField('URLSegment', $filteredTitle);
54
        }
55
        // Ensure that this object has a non-conflicting URLSegment value.
56
        $count = 2;
57
        while (TaxonomyTerm::get()->filter(['URLSegment' => $this->owner->URLSegment])->exclude(array('ID' => $this->owner->ID))->exists()) {
58
            $this->owner->setField('URLSegment', preg_replace('/-[0-9]+$/', null, $this->owner->URLSegment) . '-' . $count);
59
            $count++;
60
        }
61
    }
62
}
63