]> Raphaƫl G. Git Repositories - userbundle/blob - Utils/Slugger.php
Add manifest, licence, readme and composer files
[userbundle] / Utils / Slugger.php
1 <?php
2
3 namespace Rapsys\UserBundle\Utils;
4
5 class Slugger {
6 //The secret parameter
7 private $secret;
8
9 //The offset reduced from secret
10 private $offset;
11
12 //Retrieve secret and set offset from reduction
13 public function __construct(\Symfony\Component\DependencyInjection\ContainerInterface $container) {
14 //Set secret
15 $this->secret = $container->getParameter('secret');
16
17 //Init rev array
18 $rev = array_flip(array_merge(range('0', '9'), range('a', 'z'), range('A', 'Z'), range('!', '~')));
19
20 //Set offset
21 $this->offset = array_reduce(str_split($this->secret), function ($res, $a) use ($rev) { return $res += $rev[$a]; }, count($this->secret)) % count($rev);
22 }
23
24 //Short the string
25 public function short($string) {
26 //Return string
27 $ret = '';
28
29 //Alphabet
30 $alpha = array_merge(range('0', '9'), range('a', 'z'), range('A', 'Z'), range('!', '~'));
31
32 //Reverse alphabet
33 $rev = array_flip($alpha);
34
35 //Number characters
36 $count = count($alpha);
37
38 //Iterate on each character
39 foreach(str_split($string) as $c) {
40 if (isset($rev[$c]) && isset($alpha[($rev[$c]+$this->offset)%$count])) {
41 $ret .= $alpha[($rev[$c]+$this->offset)%$count];
42 }
43 }
44
45 //Send result
46 return str_replace(array('+','/'), array('-','_'), base64_encode($ret));
47 }
48
49 //Unshort the string
50 public function unshort($string) {
51 //Return string
52 $ret = '';
53
54 //Alphabet
55 $alpha = array_merge(range('0', '9'), range('a', 'z'), range('A', 'Z'), range('!', '~'));
56
57 //Reverse alphabet
58 $rev = array_flip($alpha);
59
60 //Number characters
61 $count = count($alpha);
62
63 //Iterate on each character
64 foreach(str_split(base64_decode(str_replace(array('-','_'), array('+','/'), $string))) as $c) {
65 if (isset($rev[$c]) && isset($alpha[($rev[$c]-$this->offset+$count)%$count])) {
66 $ret .= $alpha[($rev[$c]-$this->offset+$count)%$count];
67 }
68 }
69
70 //Send result
71 return $ret;
72 }
73
74 //Crypt and base64uri encode string
75 public function hash($string) {
76 return str_replace(array('+','/'), array('-','_'), base64_encode(crypt($string, $this->secret)));
77 }
78
79 //Convert string to safe slug
80 function slug($string) {
81 return preg_replace('/[\/_|+ -]+/', '-', strtolower(trim(preg_replace('/[^a-zA-Z0-9\/_|+ -]/', '', str_replace(array('\'', '"'), ' ', iconv('UTF-8', 'ASCII//TRANSLIT', $string))), '-')));
82 }
83
84 }