Sluggable::onBeforeWrite()   A
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 40
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 21
dl 0
loc 40
rs 9.2728
c 4
b 0
f 0
cc 5
nc 6
nop 0
1
<?php declare(strict_types = 1);
2
3
namespace Suilven\Sluggable\Extension;
4
5
use SilverStripe\ORM\DataExtension;
6
use Suilven\Sluggable\Helper\SluggableHelper;
7
8
// @phpcs:disable SlevomatCodingStandard.Commenting.DisallowCommentAfterCode.DisallowedCommentAfterCode
9
class Sluggable extends DataExtension
10
{
11
    /** @var array<string,string> $db Slug is where the slug is stored */
12
    private static $db = [
13
        'Slug' => 'Varchar(255)',
14
    ];
15
16
    /** @var array<string, array<string, array<int, string>|string>> */
17
    private static $indexes = [
18
        'SlugIndex' => [
19
            'type' => 'unique',
20
            'columns' => ['Slug'],
21
        ],
22
    ];
23
24
25
    /**
26
     * Convert the configured field and it's associated value into a slug
27
     * e.g. Liverpool Football Club => liverpool-football-club
28
     */
29
    public function onBeforeWrite(): void
30
    {
31
        parent::onBeforeWrite();
32
33
        /** @var \SilverStripe\Core\Config\Config_ForClass $config */
34
        $config = $this->getOwner()->config();
35
36
        /** @var string $fieldName */
37
        $fieldName = $config->get('slug');
38
39
        /** @var string $fieldValue */
40
        $fieldValue = $this->getOwner()->$fieldName; // @phpstan-ignore-line
41
42
        $helper = new SluggableHelper();
43
44
        /** @var string $slug */
45
        $slug = $helper->getSlug($fieldValue);
46
        $count = $this->getOwner()->get()->filter([$fieldName => $fieldValue])->count();
47
48
        if ($count >= 1) {
49
            $i = 0;
50
51
            // @todo make this configurable
52
            while ($i < 1000) {
53
                $suffix = $i === 0
54
                    ? ''
55
                    : '-' . $i;
56
                $slugToSave = $slug . $suffix;
57
58
                $existing = $this->getOwner()->get()->filter(['Slug' => $slugToSave])->first();
59
                if (!isset($existing)) {
60
                    $this->getOwner()->Slug = $slugToSave;
61
62
                    break;
63
                }
64
65
                $i++;
66
            }
67
        } else {
68
            $this->getOwner()->Slug = $slug;
69
        }
70
    }
71
}
72