Completed
Push — master ( 612227...7394c2 )
by Dev
14:55
created

UniqueSluggifier::slugify()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 8
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 14
rs 10
1
<?php
2
3
/**
4
 * PHP TableOfContents Library.
5
 *
6
 * @license http://opensource.org/licenses/MIT
7
 *
8
 * @see https://github.com/caseyamcl/toc
9
 *
10
 * @version 2
11
 *
12
 * @author Casey McLaughlin <[email protected]>
13
 *
14
 * For the full copyright and license information, please view the LICENSE.md
15
 * file that was distributed with this source code.
16
 *
17
 * ------------------------------------------------------------------
18
 */
19
20
declare(strict_types=1);
21
22
namespace PiedWeb\CMSBundle\Service\toc;
23
24
use Cocur\Slugify\Slugify;
25
26
/**
27
 * UniqueSluggifier creates slugs from text without repeating the same slug twice per instance.
28
 *
29
 * @author Casey McLaughlin <[email protected]>
30
 */
31
class UniqueSluggifier
32
{
33
    /**
34
     * @var Slugify
35
     */
36
    private $slugify;
37
38
    /**
39
     * @var array
40
     */
41
    private $used;
42
43
    /**
44
     * Constructor.
45
     *
46
     * @param Slugify $slugify
47
     */
48
    public function __construct(Slugify $slugify = null)
49
    {
50
        $this->used = [];
51
        $this->slugify = $slugify ?: new Slugify();
52
    }
53
54
    /**
55
     * Slugify.
56
     */
57
    public function slugify(string $text): string
58
    {
59
        $slugged = $this->slugify->slugify($text);
60
61
        $count = 1;
62
        $orig = $slugged;
63
        while (in_array($slugged, $this->used)) {
64
            $slugged = $orig.'-'.$count;
65
            ++$count;
66
        }
67
68
        $this->used[] = $slugged;
69
70
        return $slugged;
71
    }
72
}
73