Issues (35)

src/SlugGenerator.php (1 issue)

Labels
Severity
1
<?php
2
3
namespace Fomvasss\SlugMaker;
4
5
/**
6
 * Class SlugGenerator
7
 *
8
 * @package \Fomvasss\SlugGenerator
9
 */
10
trait SlugGenerator
11
{
12
    /**
13
     * @param string $str
14
     * @return string
15
     */
16
    public function getSlug(string $str)
17
    {
18
        $nonUniqueSlug = $this->makeNonUniqueSlug($str);
19
20
        return $this->makeUniqueSlug($nonUniqueSlug);
21
    }
22
23
    /**
24
     * @param string $str
25
     * @return string
26
     */
27
    protected function makeNonUniqueSlug(string $str): string
28
    {
29
        return str_slug($this->getClippedSlugWithPrefixSuffix($str), $this->slugConfig['separator']);
30
    }
31
32
    /**
33
     * @param string $slugSourceString
34
     * @return string
35
     */
36
    public function getClippedSlugWithPrefixSuffix(string $slugSourceString): string
37
    {
38
        $prefix = $this->slugConfig['prefix'];
39
        $suffix = $this->slugConfig['suffix'];
40
41
        $maximumLength= $this->slugConfig['maximum_length'];
42
43
        if ($strLen = strlen($prefix) + strlen($suffix)) {
44
            $limitWithoutPrefixSuffix = $maximumLength - ($strLen + 2);
45
46
            if ($limitWithoutPrefixSuffix < 1) {
47
                return str_limit($prefix.' '.$suffix, $maximumLength);
48
            }
49
50
            return $prefix.' '.str_limit($slugSourceString, $limitWithoutPrefixSuffix, '').' '.$suffix;
51
        }
52
53
        return str_limit($slugSourceString, $maximumLength);
54
    }
55
56
    /**
57
     * @param string $slug
58
     * @return string
59
     */
60
    protected function makeUniqueSlug(string $slug): string
61
    {
62
        $originalSlug = $slug;
63
        $i = 1;
64
        while ($this->otherRecordExistsWithSlug($slug) || $slug === '') {
65
            $slug = $originalSlug.'-'.$i++;
66
        }
67
68
        return $slug;
69
    }
70
71
    /**
72
     * @param string $slug
73
     * @return bool
74
     */
75
    protected function otherRecordExistsWithSlug(string $slug): bool
76
    {
77
        $classModel = app()->make($this->slugConfig['model']);
0 ignored issues
show
The function app was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

77
        $classModel = /** @scrutinizer ignore-call */ app()->make($this->slugConfig['model']);
Loading history...
78
79
        return (bool) $classModel::where('name', $slug)
80
            ->where('id', '<>', optional($this->currentSlugModel)->id)
81
            ->withoutGlobalScopes()
82
            ->first();
83
    }
84
}
85