Passed
Push — master ( af4f7a...04c811 )
by Elf
02:38
created

AppIdentifier::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 0
dl 0
loc 9
ccs 6
cts 6
cp 1
crap 2
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
namespace ElfSundae\Laravel\Apps;
4
5
class AppIdentifier
6
{
7
    /**
8
     * The key registered in the container for the application identifier.
9
     */
10
    const IDENTIFIER_KEY = 'apps.identifier';
11
12
    /**
13
     * Get the current application identifier.
14
     *
15
     * @return string
16
     */
17 3
    public static function get()
18
    {
19 3
        if (app()->bound(static::IDENTIFIER_KEY)) {
20 2
            return app()->make(static::IDENTIFIER_KEY);
21
        }
22
23 1
        return app()->instance(
24 1
            static::IDENTIFIER_KEY,
25 1
            static::getIdentifierForUrl(app('request')->getUri())
26
        );
27
    }
28
29
    /**
30
     * Get application identifier for the given URL.
31
     *
32
     * @param  string  $url
33
     * @return string
34
     */
35 1
    protected static function getIdentifierForUrl($url)
36
    {
37 1
        $identifier = null;
38
39 1
        foreach (config('apps.url') as $id => $root) {
40 1
            $root = preg_replace('#^https?://#', '', $root);
41 1
            $pattern = '#^https?://'.preg_quote($root, '#').'([\?/].*)?$#';
42 1
            if (preg_match($pattern, $url)) {
43 1
                $len = strlen($root);
44 1
                if (! isset($length) || $length < $len) {
45 1
                    $length = $len;
46 1
                    $identifier = $id;
47
                }
48
            }
49
        }
50
51 1
        return $identifier;
52
    }
53
54
    /**
55
     * Refresh the current application identifier.
56
     *
57
     * @return void
58
     */
59 1
    public static function refresh()
60
    {
61 1
        app()->forgetInstance(static::IDENTIFIER_KEY);
62 1
    }
63
}
64