Slugger::getSluggableSeparator()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 4
ccs 0
cts 4
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
/*
3
 * This file is part of the Laravel Platfourm package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Longman\Platfourm\Database\Eloquent\Traits;
12
13
use Exception;
14
15
trait Slugger
16
{
17
    /**
18
     * @var array List of attributes to automatically generate unique URL names (slugs) for.
19
     *
20
     * protected $slugs = [];
21
     */
22
    protected $slugs = [];
23
24
    /**
25
     * Boot the sluggable trait for a model.
26
     *
27
     * @return void
28
     */
29
    public static function bootSlugger()
30
    {
31
        if (!property_exists(get_called_class(), 'slugs')) {
32
            throw new Exception(sprintf(
33
                'You must define a $slugs property in %s to use the Sluggable trait.',
34
                get_called_class()
35
            ));
36
        }
37
38
        /*
39
         * Set slugged attributes on new records
40
         */
41
        static::creating(function ($model) {
42
            $model->slugAttributes();
43
        });
44
    }
45
46
    /**
47
     * Adds slug attributes to the dataset, used before saving.
48
     *
49
     * @return void
50
     */
51
    public function slugAttributes()
52
    {
53
        foreach ($this->slugs as $slugAttribute => $sourceAttributes) {
54
            $this->setSluggedValue($slugAttribute, $sourceAttributes);
55
        }
56
    }
57
58
    /**
59
     * Sets a single slug attribute value.
60
     *
61
     * @param string $slugAttribute    Attribute to populate with the slug.
62
     * @param mixed  $sourceAttributes Attribute(s) to generate the slug from.
63
     *                                 Supports dotted notation for relations.
64
     * @param int    $maxLength        Maximum length for the slug not including the counter.
65
     *
66
     * @return string The generated value.
67
     */
68
    public function setSluggedValue($slugAttribute, $sourceAttributes, $maxLength = 240)
69
    {
70
        if (!isset($this->{$slugAttribute}) || !strlen($this->{$slugAttribute})) {
71
            if (!is_array($sourceAttributes)) {
72
                $sourceAttributes = [$sourceAttributes];
73
            }
74
75
            $slugArr = [];
76
            foreach ($sourceAttributes as $attribute) {
77
                $slugArr[] = $this->getSluggableSourceAttributeValue($attribute);
78
            }
79
80
            $slug = implode(' ', $slugArr);
81
            $slug = substr($slug, 0, $maxLength);
82
            $slug = str_slug($slug, $this->getSluggableSeparator());
83
        } else {
84
            $slug = $this->{$slugAttribute};
85
        }
86
87
        return $this->{$slugAttribute} = $this->getSluggableUniqueAttributeValue($slugAttribute, $slug);
88
    }
89
90
    /**
91
     * Ensures a unique attribute value, if the value is already used a counter suffix is added.
92
     *
93
     * @param string $name  The database column name.
94
     * @param value  $value The desired column value.
95
     *
96
     * @return string A safe value that is unique.
97
     */
98
    protected function getSluggableUniqueAttributeValue($name, $value)
99
    {
100
        $counter   = 1;
101
        $separator = $this->getSluggableSeparator();
102
103
        // Remove any existing suffixes
104
        $_value = preg_replace('/' . preg_quote($separator) . '[0-9]+$/', '', trim($value));
105
106
        while ($this->newQuery()->where($name, $_value)->count() > 0) {
0 ignored issues
show
Bug introduced by
It seems like newQuery() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
107
            $counter++;
108
            $_value = $value . $separator . $counter;
109
        }
110
111
        return $_value;
112
    }
113
114
    /**
115
     * Get an attribute relation value using dotted notation.
116
     * Eg: author.name.
117
     *
118
     * @return mixed
119
     */
120
    protected function getSluggableSourceAttributeValue($key)
121
    {
122
        if (strpos($key, '.') === false) {
123
            return $this->getAttribute($key);
0 ignored issues
show
Bug introduced by
It seems like getAttribute() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
124
        }
125
126
        $keyParts = explode('.', $key);
127
        $value    = $this;
128
        foreach ($keyParts as $part) {
129
            if (!isset($value[$part])) {
130
                return;
131
            }
132
133
            $value = $value[$part];
134
        }
135
136
        return $value;
137
    }
138
139
    /**
140
     * Override the default slug separator.
141
     *
142
     * @return string
143
     */
144
    public function getSluggableSeparator()
145
    {
146
        return defined('static::SLUG_SEPARATOR') ? static::SLUG_SEPARATOR : '-';
147
    }
148
}
149