Passed
Pull Request — master (#324)
by Philippe
54:56 queued 21:29
created

BaseUrlSegment   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 22.22%

Importance

Changes 0
Metric Value
wmc 8
eloc 16
dl 0
loc 46
ccs 4
cts 18
cp 0.2222
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A prepend() 0 8 2
A all() 0 13 3
A strip() 0 13 3
1
<?php
2
3
namespace Thinktomorrow\Chief\Urls\ProvidesUrl;
4
5
use Thinktomorrow\Chief\Management\Managers;
6
7
class BaseUrlSegment
8
{
9
    /**
10
     * @param ProvidesUrl $model
11
     * @param string $slug
12
     * @param $locale
13
     * @return string
14
     */
15 72
    public static function prepend(ProvidesUrl $model, string $slug, $locale): string
16
    {
17 72
        $slugWithBaseSegment = $model->baseUrlSegment($locale) . '/' . $slug;
18 72
        $slugWithBaseSegment = trim($slugWithBaseSegment, '/');
19
20
        // If slug with base segment is empty string, it means that the passed slug was probably a "/" character.
21
        // so we'll want to return it in case the base segment is not added.
22 72
        return $slugWithBaseSegment ?: '/';
23
    }
24
25
    public static function strip($value)
26
    {
27
        $originalValue = $value = trim($value, '/');
28
29
        $segments = static::all();
30
31
        foreach ($segments as $segment) {
32
            if (0 === strpos($originalValue, $segment)) {
33
                $value = substr($value, strlen($segment));
34
            }
35
        }
36
37
        return trim($value, '/');
38
    }
39
40
    private static function all(): array
41
    {
42
        $segments = [];
43
44
        $managers = app(Managers::class)->all();
45
46
        foreach ($managers as $manager) {
47
            if (contract($manager->model(), ProvidesUrl::class)) {
48
                $segments[] = $manager->model()->baseUrlSegment();
49
            }
50
        }
51
52
        return array_unique($segments);
53
    }
54
}
55