3
* @link https://www.yiiframework.com/
4
* @copyright Copyright (c) 2008 Yii Software LLC
5
* @license https://www.yiiframework.com/license/
8
namespace yii\behaviors;
11
use yii\base\InvalidConfigException;
12
use yii\db\BaseActiveRecord;
13
use yii\helpers\ArrayHelper;
14
use yii\helpers\Inflector;
15
use yii\validators\UniqueValidator;
18
* SluggableBehavior automatically fills the specified attribute with a value that can be used a slug in a URL.
20
* Note: This behavior relies on php-intl extension for transliteration. If it is not installed it
21
* falls back to replacements defined in [[\yii\helpers\Inflector::$transliteration]].
23
* To use SluggableBehavior, insert the following code to your ActiveRecord class:
26
* use yii\behaviors\SluggableBehavior;
28
* public function behaviors()
32
* 'class' => SluggableBehavior::class,
33
* 'attribute' => 'title',
34
* // 'slugAttribute' => 'slug',
40
* By default, SluggableBehavior will fill the `slug` attribute with a value that can be used a slug in a URL
41
* when the associated AR object is being validated.
43
* Because attribute values will be set automatically by this behavior, they are usually not user input and should therefore
44
* not be validated, i.e. the `slug` attribute should not appear in the [[\yii\base\Model::rules()|rules()]] method of the model.
46
* If your attribute name is different, you may configure the [[slugAttribute]] property like the following:
49
* public function behaviors()
53
* 'class' => SluggableBehavior::class,
54
* 'slugAttribute' => 'alias',
60
* @author Alexander Kochetov <creocoder@gmail.com>
61
* @author Paul Klimov <klimov.paul@gmail.com>
64
class SluggableBehavior extends AttributeBehavior
67
* @var string the attribute that will receive the slug value
69
public $slugAttribute = 'slug';
71
* @var string|array|null the attribute or list of attributes whose value will be converted into a slug
72
* or `null` meaning that the `$value` property will be used to generate a slug.
76
* @var callable|string|null the value that will be used as a slug. This can be an anonymous function
77
* or an arbitrary value or null. If the former, the return value of the function will be used as a slug.
78
* If `null` then the `$attribute` property will be used to generate a slug.
79
* The signature of the function should be as follows,
90
* @var bool whether to generate a new slug if it has already been generated before.
91
* If true, the behavior will not generate a new slug even if [[attribute]] is changed.
94
public $immutable = false;
96
* @var bool whether to ensure generated slug value to be unique among owner class records.
97
* If enabled behavior will validate slug uniqueness automatically. If validation fails it will attempt
98
* generating unique slug value from based one until success.
100
public $ensureUnique = false;
102
* @var bool whether to skip slug generation if [[attribute]] is null or an empty string.
103
* If true, the behaviour will not generate a new slug if [[attribute]] is null or an empty string.
106
public $skipOnEmpty = false;
108
* @var array configuration for slug uniqueness validator. Parameter 'class' may be omitted - by default
109
* [[UniqueValidator]] will be used.
110
* @see UniqueValidator
112
public $uniqueValidator = [];
114
* @var callable|null slug unique value generator. It is used in case [[ensureUnique]] enabled and generated
115
* slug is not unique. This should be a PHP callable with following signature:
118
* function ($baseSlug, $iteration, $model)
120
* // return uniqueSlug
124
* If not set unique slug will be generated adding incrementing suffix to the base slug.
126
public $uniqueSlugGenerator;
132
public function init()
136
if (empty($this->attributes)) {
137
$this->attributes = [BaseActiveRecord::EVENT_BEFORE_VALIDATE => $this->slugAttribute];
140
if ($this->attribute === null && $this->value === null) {
141
throw new InvalidConfigException('Either "attribute" or "value" property must be specified.');
148
protected function getValue($event)
150
if (!$this->isNewSlugNeeded()) {
151
return $this->owner->{$this->slugAttribute};
154
if ($this->attribute !== null) {
156
foreach ((array) $this->attribute as $attribute) {
157
$part = ArrayHelper::getValue($this->owner, $attribute);
158
if ($this->skipOnEmpty && $this->isEmpty($part)) {
159
return $this->owner->{$this->slugAttribute};
161
$slugParts[] = $part;
163
$slug = $this->generateSlug($slugParts);
165
$slug = parent::getValue($event);
168
return $this->ensureUnique ? $this->makeUnique($slug) : $slug;
172
* Checks whether the new slug generation is needed
173
* This method is called by [[getValue]] to check whether the new slug generation is needed.
174
* You may override it to customize checking.
178
protected function isNewSlugNeeded()
180
if (empty($this->owner->{$this->slugAttribute})) {
184
if ($this->immutable) {
188
if ($this->attribute === null) {
192
foreach ((array) $this->attribute as $attribute) {
193
if ($this->owner->isAttributeChanged($attribute)) {
202
* This method is called by [[getValue]] to generate the slug.
203
* You may override it to customize slug generation.
204
* The default implementation calls [[\yii\helpers\Inflector::slug()]] on the input strings
205
* concatenated by dashes (`-`).
206
* @param array $slugParts an array of strings that should be concatenated and converted to generate the slug value.
207
* @return string the conversion result.
209
protected function generateSlug($slugParts)
211
return Inflector::slug(implode('-', $slugParts));
215
* This method is called by [[getValue]] when [[ensureUnique]] is true to generate the unique slug.
216
* Calls [[generateUniqueSlug]] until generated slug is unique and returns it.
217
* @param string $slug basic slug value
218
* @return string unique slug
220
* @see generateUniqueSlug
223
protected function makeUnique($slug)
227
while (!$this->validateSlug($uniqueSlug)) {
229
$uniqueSlug = $this->generateUniqueSlug($slug, $iteration);
236
* Checks if given slug value is unique.
237
* @param string $slug slug value
238
* @return bool whether slug is unique.
240
protected function validateSlug($slug)
242
/* @var $validator UniqueValidator */
243
/* @var $model BaseActiveRecord */
244
$validator = Yii::createObject(array_merge(
246
'class' => UniqueValidator::className(),
248
$this->uniqueValidator
251
$model = clone $this->owner;
252
$model->clearErrors();
253
$model->{$this->slugAttribute} = $slug;
255
$validator->validateAttribute($model, $this->slugAttribute);
256
return !$model->hasErrors();
260
* Generates slug using configured callback or increment of iteration.
261
* @param string $baseSlug base slug value
262
* @param int $iteration iteration number
263
* @return string new slug value
264
* @throws \yii\base\InvalidConfigException
266
protected function generateUniqueSlug($baseSlug, $iteration)
268
if (is_callable($this->uniqueSlugGenerator)) {
269
return call_user_func($this->uniqueSlugGenerator, $baseSlug, $iteration, $this->owner);
272
return $baseSlug . '-' . ($iteration + 1);
276
* Checks if $slugPart is empty string or null.
278
* @param string $slugPart One of attributes that is used for slug generation.
279
* @return bool whether $slugPart empty or not.
282
protected function isEmpty($slugPart)
284
return $slugPart === null || $slugPart === '';