forked from cviebrock/sluggable
/
sluggable.php
127 lines (79 loc) · 2.18 KB
/
sluggable.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<?php
/**
* Easy slugging for your Eloquent models.
*
* @package Sluggable
* @version 1.0
* @author Colin Viebrock <colin@viebrock.ca>
* @link http://github.com/cviebrock/sluggable
*/
class Sluggable {
/**
* Method that gets fired when the eloquent model is saved.
* Handles the slugging.
*
* @param Model $model
* @return bool
*/
public static function make( $model, $force = false )
{
// skip if the model isn't sluggable
if ( !isset( $model::$sluggable ) ) {
return true;
}
$model_config = $model::$sluggable;
// read the default config:
// 1. application/config/sluggable.php
// 2. bundles/sluggable/config/sluggable.php
$default_config = Config::get('sluggable', Config::get('sluggable::sluggable', array() ));
$config = array_merge( $default_config, $model_config );
// nicer variables for readability
$build_from = $save_to = $style = $separator = $unique = $on_update = null;
extract( $config, EXTR_IF_EXISTS );
// skip slug generation if the model exists or the slug field is already populated,
// and on_update is false ... unless we are forcing things!
if (!$force) {
if ( ( $model->exists || !empty($model->{$save_to}) ) && !$on_update ) {
return true;
}
}
// build the slug string
if ( $build_from ) {
if ( !is_array( $build_from ) ) {
$build_from = array( $build_from );
}
$string = '';
foreach( $build_from as $field ) {
$string .= $model->{$field} . ' ';
}
} else {
$string = $model->__toString();
}
$string = trim( $string );
// build slug using given slug style
switch ($config['style']) {
case 'slug':
default:
$slug = Str::slug( $string, $config['separator'] );
break;
}
// check for uniqueness?
if ( $unique ) {
$class = get_class($model);
$last = $class::where( $save_to, 'LIKE', $slug.'%' )
->order_by( $save_to, 'DESC' )
->first();
if ( $last ) {
$idx = substr( $last->{$save_to} , strlen($slug) );
$idx = ltrim( $idx, $separator );
$idx = intval( $idx );
$idx++;
$slug .= $separator . $idx;
}
}
// update the slug field
$model->{$save_to} = $slug;
// done!
return true;
}
}