Repository navigation
Expand file tree
/
Copy pathSlugify.php
More file actions
65 lines (50 loc) · 1.74 KB
/
Copy pathSlugify.php
File metadata and controls
65 lines (50 loc) · 1.74 KB
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
<?php if (!defined('BASEPATH')) {exit('No direct script access allowed');}
class Slugify
{
public function create($obj = null, $field = 'name')
{
if (!$obj) {
return false;
}
$string = call_user_func(array($obj, 'get'.ucwords($field)));
$slug = $this->processString($string);
// Trim it if it's greater than 32 characters (minus 3 for suffix)
if (mb_strlen($slug) > (32 - 3)) {
$slug = mb_substr($slug, 0, (32 - 3));
}
$increment = 0;
while (true)
{
$slug2 = $increment ? $slug . '-' . $increment : $slug;
$slugExists = $this->check($obj, $slug2);
if ($slugExists) {
$increment++;
} else {
return $slug2;
}
}
return null;
}
public function check($obj = null, $slug, $class = null)
{
if ($class) {
$obj = new $class;
}
return ($obj->getRepository()->findOneBySlug($slug)) ? true : false;
}
public function simple($string)
{
$string = utf8_encode($string);
return $this->processString($string);
}
protected function processString($text)
{
$slug = iconv('utf-8', 'us-ascii//TRANSLIT', $text); // transliterate
$slug = mb_strtolower($slug); // lowercase
$slug = str_replace(array('\'', '`', '^'), '', $slug); // remove accents resulting from OSX's iconv
$slug = preg_replace('/\W+/', '-', $slug); // replace non letter or digits with separator
$slug = trim($slug, '-'); // trim
$slug = $slug ? $slug : 'n-a';
return $slug;
}
}