Passed
Pull Request — master (#59)
by
unknown
01:23
created

TaxonomyTermUrlExtension::updateCMSFields()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\Taxonomy\Extensions;
4
5
use SilverStripe\CMS\Model\SiteTree;
0 ignored issues
show
Bug introduced by
The type SilverStripe\CMS\Model\SiteTree was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use SilverStripe\Forms\FieldList;
7
use SilverStripe\ORM\DataExtension;
8
use SilverStripe\Taxonomy\TaxonomyTerm;
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
            $this->owner->setField('URLSegment', SiteTree::singleton()->generateURLSegment($this->owner->Name));
45
             // Ensure that this object has a non-conflicting URLSegment value.
46
            $count = 2;
47
            while (TaxonomyTerm::get()->filter(['URLSegment' => $this->owner->URLSegment])->exclude(array('ID' => $this->owner->ID))->exists()) {
48
                $this->owner->setField('URLSegment', preg_replace('/-[0-9]+$/', null, $this->owner->URLSegment) . '-' . $count);
49
                $count++;
50
            }
51
        }
52
    }
53
}
54