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

UniqueSlug::isSlugUnique()   B

Complexity

Conditions 5
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 5.2

Importance

Changes 0
Metric Value
cc 5
eloc 4
nc 2
nop 2
dl 0
loc 9
ccs 4
cts 5
cp 0.8
crap 5.2
rs 8.8571
c 0
b 0
f 0
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