Passed
Push — ft/package ( 5ee474...180175 )
by Philippe
05:16 queued 12s
created

UniqueSlug   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 82.35%

Importance

Changes 0
Metric Value
dl 0
loc 45
ccs 14
cts 17
cp 0.8235
rs 10
c 0
b 0
f 0
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A make() 0 3 1
A __construct() 0 3 1
A get() 0 11 2
B isSlugUnique() 0 9 5
1
<?php
2
3
namespace Thinktomorrow\Chief\Common;
4
5
use Thinktomorrow\Chief\Common\Contracts\SluggableContract;
6
use Illuminate\Support\Str;
7
8
class UniqueSlug
9
{
10
    /**
11
     * @var SluggableContract
12
     */
13
    private $model;
14
15 2
    public function __construct(SluggableContract $model)
16
    {
17 2
        $this->model = $model;
18 2
    }
19
20 2
    public static function make($model)
21
    {
22 2
        return new static($model);
23
    }
24
25 2
    public function get($title, SluggableContract $entity = null)
26
    {
27 2
        $slug = $originalslug = Str::slug($title);
28 2
        $i = 1;
29
30 2
        while (!$this->isSlugUnique($slug, $entity)) {
31
            $slug = $originalslug.'-'.$i;
32
            $i++;
33
        }
34
35 2
        return $slug;
36
    }
37
38
    /**
39
     *
40
     * @param $slug
41
     * @param SluggableContract $entity
42
     * @return bool
43
     */
44 2
    private function isSlugUnique($slug, SluggableContract $entity = null)
45
    {
46 2
        $model = $this->model->findBySlug($slug);
47
48 2
        if (!$model || ($entity && $entity->id && $model->id == $entity->id)) {
0 ignored issues
show
Bug introduced by
Accessing id on the interface Thinktomorrow\Chief\Comm...racts\SluggableContract suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
49 2
            return true;
50
        }
51
52
        return false;
53
    }
54
}
55